working.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package util
  17. import (
  18. "errors"
  19. "flag"
  20. "fmt"
  21. "math/rand"
  22. "mime"
  23. "net/url"
  24. "os"
  25. "path/filepath"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "github.com/88250/gulu"
  33. figure "github.com/common-nighthawk/go-figure"
  34. "github.com/gofrs/flock"
  35. "github.com/siyuan-note/filelock"
  36. "github.com/siyuan-note/httpclient"
  37. "github.com/siyuan-note/logging"
  38. )
  39. // var Mode = "dev"
  40. var Mode = "prod"
  41. const (
  42. Ver = "3.1.8"
  43. IsInsider = false
  44. )
  45. var (
  46. RunInContainer = false // 是否运行在容器中
  47. SiyuanAccessAuthCodeBypass = false // 是否跳过空访问授权码检查
  48. )
  49. func initEnvVars() {
  50. RunInContainer = isRunningInDockerContainer()
  51. var err error
  52. if SiyuanAccessAuthCodeBypass, err = strconv.ParseBool(os.Getenv("SIYUAN_ACCESS_AUTH_CODE_BYPASS")); err != nil {
  53. SiyuanAccessAuthCodeBypass = false
  54. }
  55. }
  56. var (
  57. bootProgress = atomic.Int32{} // 启动进度,从 0 到 100
  58. bootDetails string // 启动细节描述
  59. HttpServing = false // 是否 HTTP 伺服已经可用
  60. )
  61. func Boot() {
  62. initEnvVars()
  63. IncBootProgress(3, "Booting kernel...")
  64. rand.Seed(time.Now().UTC().UnixNano())
  65. initMime()
  66. initHttpClient()
  67. workspacePath := flag.String("workspace", "", "dir path of the workspace, default to ~/SiYuan/")
  68. wdPath := flag.String("wd", WorkingDir, "working directory of SiYuan")
  69. port := flag.String("port", "0", "port of the HTTP server")
  70. readOnly := flag.String("readonly", "false", "read-only mode")
  71. accessAuthCode := flag.String("accessAuthCode", "", "access auth code")
  72. ssl := flag.Bool("ssl", false, "for https and wss")
  73. lang := flag.String("lang", "", "zh_CN/zh_CHT/en_US/fr_FR/es_ES/ja_JP/it_IT/de_DE/he_IL/ru_RU/pl_PL")
  74. mode := flag.String("mode", "prod", "dev/prod")
  75. flag.Parse()
  76. if "" != *wdPath {
  77. WorkingDir = *wdPath
  78. }
  79. if "" != *lang {
  80. Lang = *lang
  81. }
  82. Mode = *mode
  83. ServerPort = *port
  84. ReadOnly, _ = strconv.ParseBool(*readOnly)
  85. AccessAuthCode = *accessAuthCode
  86. Container = ContainerStd
  87. if RunInContainer {
  88. Container = ContainerDocker
  89. if "" == AccessAuthCode {
  90. interruptBoot := true
  91. // Set the env `SIYUAN_ACCESS_AUTH_CODE_BYPASS=true` to skip checking empty access auth code https://github.com/siyuan-note/siyuan/issues/9709
  92. if SiyuanAccessAuthCodeBypass {
  93. interruptBoot = false
  94. fmt.Println("bypass access auth code check since the env [SIYUAN_ACCESS_AUTH_CODE_BYPASS] is set to [true]")
  95. }
  96. if interruptBoot {
  97. // The access authorization code command line parameter must be set when deploying via Docker https://github.com/siyuan-note/siyuan/issues/9328
  98. fmt.Printf("the access authorization code command line parameter (--accessAuthCode) must be set when deploying via Docker")
  99. os.Exit(1)
  100. }
  101. }
  102. }
  103. if ContainerStd != Container {
  104. ServerPort = FixedPort
  105. }
  106. msStoreFilePath := filepath.Join(WorkingDir, "ms-store")
  107. ISMicrosoftStore = gulu.File.IsExist(msStoreFilePath)
  108. UserAgent = UserAgent + " " + Container + "/" + runtime.GOOS
  109. httpclient.SetUserAgent(UserAgent)
  110. initWorkspaceDir(*workspacePath)
  111. SSL = *ssl
  112. LogPath = filepath.Join(TempDir, "siyuan.log")
  113. logging.SetLogPath(LogPath)
  114. // 工作空间仅允许被一个内核进程伺服
  115. tryLockWorkspace()
  116. AppearancePath = filepath.Join(ConfDir, "appearance")
  117. if "dev" == Mode {
  118. ThemesPath = filepath.Join(WorkingDir, "appearance", "themes")
  119. IconsPath = filepath.Join(WorkingDir, "appearance", "icons")
  120. } else {
  121. ThemesPath = filepath.Join(AppearancePath, "themes")
  122. IconsPath = filepath.Join(AppearancePath, "icons")
  123. }
  124. initPathDir()
  125. bootBanner := figure.NewColorFigure("SiYuan", "isometric3", "green", true)
  126. logging.LogInfof("\n" + bootBanner.String())
  127. logBootInfo()
  128. }
  129. var bootDetailsLock = sync.Mutex{}
  130. func setBootDetails(details string) {
  131. bootDetailsLock.Lock()
  132. bootDetails = "v" + Ver + " " + details
  133. bootDetailsLock.Unlock()
  134. }
  135. func SetBootDetails(details string) {
  136. if 100 <= bootProgress.Load() {
  137. return
  138. }
  139. setBootDetails(details)
  140. }
  141. func IncBootProgress(progress int32, details string) {
  142. if 100 <= bootProgress.Load() {
  143. return
  144. }
  145. bootProgress.Add(progress)
  146. setBootDetails(details)
  147. }
  148. func IsBooted() bool {
  149. return 100 <= bootProgress.Load()
  150. }
  151. func GetBootProgressDetails() (progress int32, details string) {
  152. progress = bootProgress.Load()
  153. bootDetailsLock.Lock()
  154. details = bootDetails
  155. bootDetailsLock.Unlock()
  156. return
  157. }
  158. func GetBootProgress() int32 {
  159. return bootProgress.Load()
  160. }
  161. func SetBooted() {
  162. setBootDetails("Finishing boot...")
  163. bootProgress.Store(100)
  164. logging.LogInfof("kernel booted")
  165. }
  166. var (
  167. HomeDir, _ = gulu.OS.Home()
  168. WorkingDir, _ = os.Getwd()
  169. WorkspaceDir string // 工作空间目录路径
  170. WorkspaceName string // 工作空间名称
  171. WorkspaceLock *flock.Flock // 工作空间锁
  172. ConfDir string // 配置目录路径
  173. DataDir string // 数据目录路径
  174. RepoDir string // 仓库目录路径
  175. HistoryDir string // 数据历史目录路径
  176. TempDir string // 临时目录路径
  177. LogPath string // 配置目录下的日志文件 siyuan.log 路径
  178. DBName = "siyuan.db" // SQLite 数据库文件名
  179. DBPath string // SQLite 数据库文件路径
  180. HistoryDBPath string // SQLite 历史数据库文件路径
  181. AssetContentDBPath string // SQLite 资源文件内容数据库文件路径
  182. BlockTreeDBPath string // 区块树数据库文件路径
  183. AppearancePath string // 配置目录下的外观目录 appearance/ 路径
  184. ThemesPath string // 配置目录下的外观目录下的 themes/ 路径
  185. IconsPath string // 配置目录下的外观目录下的 icons/ 路径
  186. SnippetsPath string // 数据目录下的 snippets/ 路径
  187. UIProcessIDs = sync.Map{} // UI 进程 ID
  188. )
  189. func initWorkspaceDir(workspaceArg string) {
  190. userHomeConfDir := filepath.Join(HomeDir, ".config", "siyuan")
  191. workspaceConf := filepath.Join(userHomeConfDir, "workspace.json")
  192. logging.SetLogPath(filepath.Join(userHomeConfDir, "kernel.log"))
  193. if !gulu.File.IsExist(workspaceConf) {
  194. if err := os.MkdirAll(userHomeConfDir, 0755); err != nil && !os.IsExist(err) {
  195. logging.LogErrorf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
  196. os.Exit(logging.ExitCodeInitWorkspaceErr)
  197. }
  198. }
  199. defaultWorkspaceDir := filepath.Join(HomeDir, "SiYuan")
  200. if gulu.OS.IsWindows() {
  201. // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622
  202. if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {
  203. defaultWorkspaceDir = filepath.Join(userProfile, "SiYuan")
  204. }
  205. }
  206. var workspacePaths []string
  207. if !gulu.File.IsExist(workspaceConf) {
  208. WorkspaceDir = defaultWorkspaceDir
  209. } else {
  210. workspacePaths, _ = ReadWorkspacePaths()
  211. if 0 < len(workspacePaths) {
  212. WorkspaceDir = workspacePaths[len(workspacePaths)-1]
  213. } else {
  214. WorkspaceDir = defaultWorkspaceDir
  215. }
  216. }
  217. if "" != workspaceArg {
  218. WorkspaceDir = workspaceArg
  219. }
  220. if !gulu.File.IsDir(WorkspaceDir) {
  221. logging.LogWarnf("use the default workspace [%s] since the specified workspace [%s] is not a dir", defaultWorkspaceDir, WorkspaceDir)
  222. if err := os.MkdirAll(defaultWorkspaceDir, 0755); err != nil && !os.IsExist(err) {
  223. logging.LogErrorf("create default workspace folder [%s] failed: %s", defaultWorkspaceDir, err)
  224. os.Exit(logging.ExitCodeInitWorkspaceErr)
  225. }
  226. WorkspaceDir = defaultWorkspaceDir
  227. }
  228. workspacePaths = append(workspacePaths, WorkspaceDir)
  229. if err := WriteWorkspacePaths(workspacePaths); err != nil {
  230. logging.LogErrorf("write workspace conf [%s] failed: %s", workspaceConf, err)
  231. os.Exit(logging.ExitCodeInitWorkspaceErr)
  232. }
  233. WorkspaceName = filepath.Base(WorkspaceDir)
  234. ConfDir = filepath.Join(WorkspaceDir, "conf")
  235. DataDir = filepath.Join(WorkspaceDir, "data")
  236. RepoDir = filepath.Join(WorkspaceDir, "repo")
  237. HistoryDir = filepath.Join(WorkspaceDir, "history")
  238. TempDir = filepath.Join(WorkspaceDir, "temp")
  239. osTmpDir := filepath.Join(TempDir, "os")
  240. os.RemoveAll(osTmpDir)
  241. if err := os.MkdirAll(osTmpDir, 0755); err != nil {
  242. logging.LogErrorf("create os tmp dir [%s] failed: %s", osTmpDir, err)
  243. os.Exit(logging.ExitCodeInitWorkspaceErr)
  244. }
  245. os.RemoveAll(filepath.Join(TempDir, "repo"))
  246. os.Setenv("TMPDIR", osTmpDir)
  247. os.Setenv("TEMP", osTmpDir)
  248. os.Setenv("TMP", osTmpDir)
  249. DBPath = filepath.Join(TempDir, DBName)
  250. HistoryDBPath = filepath.Join(TempDir, "history.db")
  251. AssetContentDBPath = filepath.Join(TempDir, "asset_content.db")
  252. BlockTreeDBPath = filepath.Join(TempDir, "blocktree.db")
  253. SnippetsPath = filepath.Join(DataDir, "snippets")
  254. }
  255. func ReadWorkspacePaths() (ret []string, err error) {
  256. ret = []string{}
  257. workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
  258. data, err := os.ReadFile(workspaceConf)
  259. if err != nil {
  260. msg := fmt.Sprintf("read workspace conf [%s] failed: %s", workspaceConf, err)
  261. logging.LogErrorf(msg)
  262. err = errors.New(msg)
  263. return
  264. }
  265. if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil {
  266. msg := fmt.Sprintf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
  267. logging.LogErrorf(msg)
  268. err = errors.New(msg)
  269. return
  270. }
  271. var tmp []string
  272. for _, d := range ret {
  273. d = strings.TrimRight(d, " \t\n") // 去掉工作空间路径尾部空格 https://github.com/siyuan-note/siyuan/issues/6353
  274. if gulu.File.IsDir(d) {
  275. tmp = append(tmp, d)
  276. }
  277. }
  278. ret = tmp
  279. ret = gulu.Str.RemoveDuplicatedElem(ret)
  280. return
  281. }
  282. func WriteWorkspacePaths(workspacePaths []string) (err error) {
  283. workspacePaths = gulu.Str.RemoveDuplicatedElem(workspacePaths)
  284. workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
  285. data, err := gulu.JSON.MarshalJSON(workspacePaths)
  286. if err != nil {
  287. msg := fmt.Sprintf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
  288. logging.LogErrorf(msg)
  289. err = errors.New(msg)
  290. return
  291. }
  292. if err = filelock.WriteFile(workspaceConf, data); err != nil {
  293. msg := fmt.Sprintf("write workspace conf [%s] failed: %s", workspaceConf, err)
  294. logging.LogErrorf(msg)
  295. err = errors.New(msg)
  296. return
  297. }
  298. return
  299. }
  300. var (
  301. ServerURL *url.URL // 内核服务 URL
  302. ServerPort = "0" // HTTP/WebSocket 端口,0 为使用随机端口
  303. ReadOnly bool
  304. AccessAuthCode string
  305. Lang = ""
  306. Container string // docker, android, ios, std
  307. ISMicrosoftStore bool // 桌面端是否是微软商店版
  308. )
  309. const (
  310. ContainerStd = "std" // 桌面端
  311. ContainerDocker = "docker" // Docker 容器端
  312. ContainerAndroid = "android" // Android 端
  313. ContainerIOS = "ios" // iOS 端
  314. LocalHost = "127.0.0.1" // 伺服地址
  315. FixedPort = "6806" // 固定端口
  316. )
  317. func initPathDir() {
  318. if err := os.MkdirAll(ConfDir, 0755); err != nil && !os.IsExist(err) {
  319. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create conf folder [%s] failed: %s", ConfDir, err)
  320. }
  321. if err := os.MkdirAll(DataDir, 0755); err != nil && !os.IsExist(err) {
  322. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data folder [%s] failed: %s", DataDir, err)
  323. }
  324. if err := os.MkdirAll(TempDir, 0755); err != nil && !os.IsExist(err) {
  325. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create temp folder [%s] failed: %s", TempDir, err)
  326. }
  327. assets := filepath.Join(DataDir, "assets")
  328. if err := os.MkdirAll(assets, 0755); err != nil && !os.IsExist(err) {
  329. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data assets folder [%s] failed: %s", assets, err)
  330. }
  331. templates := filepath.Join(DataDir, "templates")
  332. if err := os.MkdirAll(templates, 0755); err != nil && !os.IsExist(err) {
  333. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data templates folder [%s] failed: %s", templates, err)
  334. }
  335. widgets := filepath.Join(DataDir, "widgets")
  336. if err := os.MkdirAll(widgets, 0755); err != nil && !os.IsExist(err) {
  337. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data widgets folder [%s] failed: %s", widgets, err)
  338. }
  339. plugins := filepath.Join(DataDir, "plugins")
  340. if err := os.MkdirAll(plugins, 0755); err != nil && !os.IsExist(err) {
  341. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data plugins folder [%s] failed: %s", widgets, err)
  342. }
  343. emojis := filepath.Join(DataDir, "emojis")
  344. if err := os.MkdirAll(emojis, 0755); err != nil && !os.IsExist(err) {
  345. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data emojis folder [%s] failed: %s", widgets, err)
  346. }
  347. // Support directly access `data/public/*` contents via URL link https://github.com/siyuan-note/siyuan/issues/8593
  348. public := filepath.Join(DataDir, "public")
  349. if err := os.MkdirAll(public, 0755); err != nil && !os.IsExist(err) {
  350. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data public folder [%s] failed: %s", widgets, err)
  351. }
  352. }
  353. func initMime() {
  354. // 在某版本的 Windows 10 操作系统上界面样式异常问题
  355. // https://github.com/siyuan-note/siyuan/issues/247
  356. // https://github.com/siyuan-note/siyuan/issues/3813
  357. mime.AddExtensionType(".css", "text/css")
  358. mime.AddExtensionType(".js", "application/x-javascript")
  359. mime.AddExtensionType(".json", "application/json")
  360. mime.AddExtensionType(".html", "text/html")
  361. // 某些系统上下载资源文件后打开是 zip https://github.com/siyuan-note/siyuan/issues/6347
  362. mime.AddExtensionType(".doc", "application/msword")
  363. mime.AddExtensionType(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
  364. mime.AddExtensionType(".xls", "application/vnd.ms-excel")
  365. mime.AddExtensionType(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  366. mime.AddExtensionType(".dwg", "image/x-dwg")
  367. mime.AddExtensionType(".dxf", "image/x-dxf")
  368. mime.AddExtensionType(".dwf", "drawing/x-dwf")
  369. mime.AddExtensionType(".pdf", "application/pdf")
  370. // 某些系统上无法显示 SVG 图片 SVG images cannot be displayed on some systems https://github.com/siyuan-note/siyuan/issues/9413
  371. mime.AddExtensionType(".svg", "image/svg+xml")
  372. // 文档数据文件
  373. mime.AddExtensionType(".sy", "application/json")
  374. }
  375. func GetDataAssetsAbsPath() (ret string) {
  376. ret = filepath.Join(DataDir, "assets")
  377. if IsSymlinkPath(ret) {
  378. // 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480
  379. var err error
  380. ret, err = filepath.EvalSymlinks(ret)
  381. if err != nil {
  382. logging.LogErrorf("read assets link failed: %s", err)
  383. }
  384. }
  385. return
  386. }
  387. func tryLockWorkspace() {
  388. WorkspaceLock = flock.New(filepath.Join(WorkspaceDir, ".lock"))
  389. ok, err := WorkspaceLock.TryLock()
  390. if ok {
  391. return
  392. }
  393. if err != nil {
  394. logging.LogErrorf("lock workspace [%s] failed: %s", WorkspaceDir, err)
  395. } else {
  396. logging.LogErrorf("lock workspace [%s] failed", WorkspaceDir)
  397. }
  398. os.Exit(logging.ExitCodeWorkspaceLocked)
  399. }
  400. func IsWorkspaceLocked(workspacePath string) bool {
  401. if !gulu.File.IsDir(workspacePath) {
  402. return false
  403. }
  404. lockFilePath := filepath.Join(workspacePath, ".lock")
  405. if !gulu.File.IsExist(lockFilePath) {
  406. return false
  407. }
  408. f := flock.New(lockFilePath)
  409. defer f.Unlock()
  410. ok, _ := f.TryLock()
  411. if ok {
  412. return false
  413. }
  414. return true
  415. }
  416. func UnlockWorkspace() {
  417. if nil == WorkspaceLock {
  418. return
  419. }
  420. if err := WorkspaceLock.Unlock(); err != nil {
  421. logging.LogErrorf("unlock workspace [%s] failed: %s", WorkspaceDir, err)
  422. return
  423. }
  424. if err := os.Remove(filepath.Join(WorkspaceDir, ".lock")); err != nil {
  425. logging.LogErrorf("remove workspace lock failed: %s", err)
  426. return
  427. }
  428. }