working.go 15 KB

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