working.go 16 KB

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