working.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. // SiYuan - Build Your Eternal Digital Garden
  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. "bytes"
  19. "flag"
  20. "log"
  21. "math/rand"
  22. "mime"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/88250/gulu"
  31. figure "github.com/common-nighthawk/go-figure"
  32. goPS "github.com/mitchellh/go-ps"
  33. "github.com/siyuan-note/httpclient"
  34. "github.com/siyuan-note/logging"
  35. )
  36. // var Mode = "dev"
  37. var Mode = "prod"
  38. const (
  39. Ver = "2.4.5"
  40. IsInsider = false
  41. )
  42. var (
  43. bootProgress float64 // 启动进度,从 0 到 100
  44. bootDetails string // 启动细节描述
  45. HttpServing = false // 是否 HTTP 伺服已经可用
  46. )
  47. func Boot() {
  48. IncBootProgress(3, "Booting...")
  49. rand.Seed(time.Now().UTC().UnixNano())
  50. initMime()
  51. workspacePath := flag.String("workspace", "", "dir path of the workspace, default to ~/Documents/SiYuan/")
  52. wdPath := flag.String("wd", WorkingDir, "working directory of SiYuan")
  53. servePath := flag.String("servePath", "", "obsoleted https://github.com/siyuan-note/siyuan/issues/4647")
  54. _ = servePath
  55. resident := flag.Bool("resident", true, "resident memory even if no active session")
  56. readOnly := flag.Bool("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. Resident = *resident
  70. ReadOnly = *readOnly
  71. AccessAuthCode = *accessAuthCode
  72. Container = ContainerStd
  73. if isRunningInDockerContainer() {
  74. Container = ContainerDocker
  75. }
  76. msStoreFilePath := filepath.Join(WorkingDir, "ms-store")
  77. ISMicrosoftStore = gulu.File.IsExist(msStoreFilePath)
  78. UserAgent = UserAgent + " " + Container
  79. httpclient.SetUserAgent(UserAgent)
  80. initWorkspaceDir(*workspacePath)
  81. SSL = *ssl
  82. LogPath = filepath.Join(TempDir, "siyuan.log")
  83. logging.SetLogPath(LogPath)
  84. AppearancePath = filepath.Join(ConfDir, "appearance")
  85. if "dev" == Mode {
  86. ThemesPath = filepath.Join(WorkingDir, "appearance", "themes")
  87. IconsPath = filepath.Join(WorkingDir, "appearance", "icons")
  88. } else {
  89. ThemesPath = filepath.Join(AppearancePath, "themes")
  90. IconsPath = filepath.Join(AppearancePath, "icons")
  91. }
  92. initPathDir()
  93. checkPort()
  94. go initPandoc()
  95. bootBanner := figure.NewColorFigure("SiYuan", "isometric3", "green", true)
  96. logging.LogInfof("\n" + bootBanner.String())
  97. logBootInfo()
  98. go cleanOld()
  99. }
  100. func setBootDetails(details string) {
  101. bootDetails = "v" + Ver + " " + details
  102. }
  103. func SetBootDetails(details string) {
  104. if 100 <= bootProgress {
  105. return
  106. }
  107. setBootDetails(details)
  108. }
  109. func IncBootProgress(progress float64, details string) {
  110. if 100 <= bootProgress {
  111. return
  112. }
  113. bootProgress += progress
  114. setBootDetails(details)
  115. }
  116. func IsBooted() bool {
  117. return 100 <= bootProgress
  118. }
  119. func GetBootProgressDetails() (float64, string) {
  120. return bootProgress, bootDetails
  121. }
  122. func GetBootProgress() float64 {
  123. return bootProgress
  124. }
  125. func SetBooted() {
  126. setBootDetails("Finishing boot...")
  127. bootProgress = 100
  128. logging.LogInfof("kernel booted")
  129. }
  130. var (
  131. HomeDir, _ = gulu.OS.Home()
  132. WorkingDir, _ = os.Getwd()
  133. WorkspaceDir string // 工作空间目录路径
  134. ConfDir string // 配置目录路径
  135. DataDir string // 数据目录路径
  136. RepoDir string // 仓库目录路径
  137. HistoryDir string // 数据历史目录路径
  138. TempDir string // 临时目录路径
  139. LogPath string // 配置目录下的日志文件 siyuan.log 路径
  140. DBName = "siyuan.db" // SQLite 数据库文件名
  141. DBPath string // SQLite 数据库文件路径
  142. HistoryDBPath string // SQLite 历史数据库文件路径
  143. BlockTreePath string // 区块树文件路径
  144. PandocBinPath string // Pandoc 可执行文件路径
  145. AppearancePath string // 配置目录下的外观目录 appearance/ 路径
  146. ThemesPath string // 配置目录下的外观目录下的 themes/ 路径
  147. IconsPath string // 配置目录下的外观目录下的 icons/ 路径
  148. AndroidNativeLibDir string // Android 库路径
  149. AndroidPrivateDataDir string // Android 私有数据路径
  150. UIProcessIDs = sync.Map{} // UI 进程 ID
  151. IsNewbie bool // 是否是第一次安装
  152. )
  153. func initWorkspaceDir(workspaceArg string) {
  154. userHomeConfDir := filepath.Join(HomeDir, ".config", "siyuan")
  155. workspaceConf := filepath.Join(userHomeConfDir, "workspace.json")
  156. if !gulu.File.IsExist(workspaceConf) {
  157. IsNewbie = ContainerStd == Container // 只有桌面端需要设置新手标识,前端自动挂载帮助文档
  158. if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
  159. log.Printf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
  160. os.Exit(ExitCodeCreateConfDirErr)
  161. }
  162. }
  163. defaultWorkspaceDir := filepath.Join(HomeDir, "Documents", "SiYuan")
  164. if gulu.OS.IsWindows() {
  165. // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622
  166. if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {
  167. defaultWorkspaceDir = filepath.Join(userProfile, "Documents", "SiYuan")
  168. }
  169. }
  170. var workspacePaths []string
  171. if !gulu.File.IsExist(workspaceConf) {
  172. WorkspaceDir = defaultWorkspaceDir
  173. if "" != workspaceArg {
  174. WorkspaceDir = workspaceArg
  175. }
  176. if !gulu.File.IsDir(WorkspaceDir) {
  177. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  178. WorkspaceDir = defaultWorkspaceDir
  179. }
  180. workspacePaths = append(workspacePaths, WorkspaceDir)
  181. } else {
  182. data, err := os.ReadFile(workspaceConf)
  183. if err = gulu.JSON.UnmarshalJSON(data, &workspacePaths); nil != err {
  184. log.Printf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
  185. }
  186. tmp := workspacePaths[:0]
  187. for _, d := range workspacePaths {
  188. if gulu.File.IsDir(d) {
  189. tmp = append(tmp, d)
  190. }
  191. }
  192. workspacePaths = tmp
  193. if 0 < len(workspacePaths) {
  194. WorkspaceDir = workspacePaths[len(workspacePaths)-1]
  195. if "" != workspaceArg {
  196. WorkspaceDir = workspaceArg
  197. }
  198. if !gulu.File.IsDir(WorkspaceDir) {
  199. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  200. WorkspaceDir = defaultWorkspaceDir
  201. }
  202. workspacePaths[len(workspacePaths)-1] = WorkspaceDir
  203. } else {
  204. WorkspaceDir = defaultWorkspaceDir
  205. if "" != workspaceArg {
  206. WorkspaceDir = workspaceArg
  207. }
  208. if !gulu.File.IsDir(WorkspaceDir) {
  209. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  210. WorkspaceDir = defaultWorkspaceDir
  211. }
  212. workspacePaths = append(workspacePaths, WorkspaceDir)
  213. }
  214. }
  215. if data, err := gulu.JSON.MarshalJSON(workspacePaths); nil == err {
  216. if err = os.WriteFile(workspaceConf, data, 0644); nil != err {
  217. log.Fatalf("write workspace conf [%s] failed: %s", workspaceConf, err)
  218. }
  219. } else {
  220. log.Fatalf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
  221. }
  222. ConfDir = filepath.Join(WorkspaceDir, "conf")
  223. DataDir = filepath.Join(WorkspaceDir, "data")
  224. RepoDir = filepath.Join(WorkspaceDir, "repo")
  225. HistoryDir = filepath.Join(WorkspaceDir, "history")
  226. TempDir = filepath.Join(WorkspaceDir, "temp")
  227. osTmpDir := filepath.Join(TempDir, "os")
  228. os.RemoveAll(osTmpDir)
  229. if err := os.MkdirAll(osTmpDir, 0755); nil != err {
  230. log.Fatalf("create os tmp dir [%s] failed: %s", osTmpDir, err)
  231. }
  232. os.RemoveAll(filepath.Join(TempDir, "repo"))
  233. os.Setenv("TMPDIR", osTmpDir)
  234. os.Setenv("TEMP", osTmpDir)
  235. os.Setenv("TMP", osTmpDir)
  236. DBPath = filepath.Join(TempDir, DBName)
  237. HistoryDBPath = filepath.Join(TempDir, "history.db")
  238. BlockTreePath = filepath.Join(TempDir, "blocktree.msgpack")
  239. }
  240. var (
  241. Resident bool
  242. ReadOnly bool
  243. AccessAuthCode string
  244. Lang = ""
  245. Container string // docker, android, ios, std
  246. ISMicrosoftStore bool // 桌面端是否是微软商店版
  247. )
  248. const (
  249. ContainerStd = "std" // 桌面端
  250. ContainerDocker = "docker" // Docker 容器端
  251. ContainerAndroid = "android" // Android 端
  252. ContainerIOS = "ios" // iOS 端
  253. )
  254. func initPathDir() {
  255. if err := os.MkdirAll(ConfDir, 0755); nil != err && !os.IsExist(err) {
  256. log.Fatalf("create conf folder [%s] failed: %s", ConfDir, err)
  257. }
  258. if err := os.MkdirAll(DataDir, 0755); nil != err && !os.IsExist(err) {
  259. log.Fatalf("create data folder [%s] failed: %s", DataDir, err)
  260. }
  261. if err := os.MkdirAll(TempDir, 0755); nil != err && !os.IsExist(err) {
  262. log.Fatalf("create temp folder [%s] failed: %s", TempDir, err)
  263. }
  264. assets := filepath.Join(DataDir, "assets")
  265. if err := os.MkdirAll(assets, 0755); nil != err && !os.IsExist(err) {
  266. log.Fatalf("create data assets folder [%s] failed: %s", assets, err)
  267. }
  268. templates := filepath.Join(DataDir, "templates")
  269. if err := os.MkdirAll(templates, 0755); nil != err && !os.IsExist(err) {
  270. log.Fatalf("create data templates folder [%s] failed: %s", templates, err)
  271. }
  272. widgets := filepath.Join(DataDir, "widgets")
  273. if err := os.MkdirAll(widgets, 0755); nil != err && !os.IsExist(err) {
  274. log.Fatalf("create data widgets folder [%s] failed: %s", widgets, err)
  275. }
  276. emojis := filepath.Join(DataDir, "emojis")
  277. if err := os.MkdirAll(emojis, 0755); nil != err && !os.IsExist(err) {
  278. log.Fatalf("create data emojis folder [%s] failed: %s", widgets, err)
  279. }
  280. }
  281. // TODO: v2.2.0 移除
  282. func cleanOld() {
  283. dirs, _ := os.ReadDir(WorkingDir)
  284. for _, dir := range dirs {
  285. if strings.HasSuffix(dir.Name(), ".old") {
  286. old := filepath.Join(WorkingDir, dir.Name())
  287. os.RemoveAll(old)
  288. }
  289. }
  290. }
  291. func checkPort() {
  292. portOpened := isPortOpen(ServerPort)
  293. if !portOpened {
  294. return
  295. }
  296. logging.LogInfof("port [%s] is opened, try to check version of running kernel", ServerPort)
  297. result := NewResult()
  298. _, err := httpclient.NewBrowserRequest().
  299. SetResult(result).
  300. SetHeader("User-Agent", UserAgent).
  301. Get("http://127.0.0.1:" + ServerPort + "/api/system/version")
  302. if nil != err || 0 != result.Code {
  303. logging.LogErrorf("connect to port [%s] for checking running kernel failed", ServerPort)
  304. KillByPort(ServerPort)
  305. return
  306. }
  307. if nil == result.Data {
  308. logging.LogErrorf("connect ot port [%s] for checking running kernel failed", ServerPort)
  309. os.Exit(ExitCodeUnavailablePort)
  310. }
  311. runningVer := result.Data.(string)
  312. if runningVer == Ver {
  313. logging.LogInfof("version of the running kernel is the same as this boot [%s], exit this boot", runningVer)
  314. os.Exit(ExitCodeOk)
  315. }
  316. logging.LogInfof("found kernel [%s] is running, try to exit it", runningVer)
  317. processes, err := goPS.Processes()
  318. if nil != err {
  319. logging.LogErrorf("close kernel [%s] failed: %s", runningVer, err)
  320. os.Exit(ExitCodeUnavailablePort)
  321. }
  322. currentPid := os.Getpid()
  323. for _, p := range processes {
  324. name := p.Executable()
  325. if strings.Contains(strings.ToLower(name), "siyuan-kernel") || strings.Contains(strings.ToLower(name), "siyuan kernel") {
  326. kernelPid := p.Pid()
  327. if currentPid != kernelPid {
  328. pid := strconv.Itoa(kernelPid)
  329. Kill(pid)
  330. logging.LogInfof("killed kernel [name=%s, pid=%s, ver=%s], continue to boot", name, pid, runningVer)
  331. }
  332. }
  333. }
  334. if !tryToListenPort() {
  335. os.Exit(ExitCodeUnavailablePort)
  336. }
  337. }
  338. func initMime() {
  339. // 在某版本的 Windows 10 操作系统上界面样式异常问题
  340. // https://github.com/siyuan-note/siyuan/issues/247
  341. // https://github.com/siyuan-note/siyuan/issues/3813
  342. mime.AddExtensionType(".css", "text/css")
  343. mime.AddExtensionType(".js", "application/x-javascript")
  344. mime.AddExtensionType(".json", "application/json")
  345. mime.AddExtensionType(".html", "text/html")
  346. }
  347. func KillByPort(port string) {
  348. if pid := PidByPort(port); "" != pid {
  349. pidInt, _ := strconv.Atoi(pid)
  350. proc, _ := goPS.FindProcess(pidInt)
  351. var name string
  352. if nil != proc {
  353. name = proc.Executable()
  354. }
  355. Kill(pid)
  356. logging.LogInfof("killed process [name=%s, pid=%s]", name, pid)
  357. }
  358. }
  359. func Kill(pid string) {
  360. var kill *exec.Cmd
  361. if gulu.OS.IsWindows() {
  362. kill = exec.Command("cmd", "/c", "TASKKILL /F /PID "+pid)
  363. } else {
  364. kill = exec.Command("kill", "-9", pid)
  365. }
  366. gulu.CmdAttr(kill)
  367. kill.CombinedOutput()
  368. }
  369. func PidByPort(port string) (ret string) {
  370. if gulu.OS.IsWindows() {
  371. cmd := exec.Command("cmd", "/c", "netstat -ano | findstr "+port)
  372. gulu.CmdAttr(cmd)
  373. data, err := cmd.CombinedOutput()
  374. if nil != err {
  375. logging.LogErrorf("netstat failed: %s", err)
  376. return
  377. }
  378. output := string(data)
  379. lines := strings.Split(output, "\n")
  380. for _, l := range lines {
  381. if strings.Contains(l, "LISTENING") {
  382. l = l[strings.Index(l, "LISTENING")+len("LISTENING"):]
  383. l = strings.TrimSpace(l)
  384. ret = l
  385. return
  386. }
  387. }
  388. return
  389. }
  390. cmd := exec.Command("lsof", "-Fp", "-i", ":"+port)
  391. gulu.CmdAttr(cmd)
  392. data, err := cmd.CombinedOutput()
  393. if nil != err {
  394. logging.LogErrorf("lsof failed: %s", err)
  395. return
  396. }
  397. output := string(data)
  398. lines := strings.Split(output, "\n")
  399. for _, l := range lines {
  400. if strings.HasPrefix(l, "p") {
  401. l = l[1:]
  402. ret = l
  403. return
  404. }
  405. }
  406. return
  407. }
  408. func initPandoc() {
  409. if ContainerStd != Container {
  410. return
  411. }
  412. pandocDir := filepath.Join(TempDir, "pandoc")
  413. if gulu.OS.IsWindows() {
  414. PandocBinPath = filepath.Join(pandocDir, "bin", "pandoc.exe")
  415. } else if gulu.OS.IsDarwin() || gulu.OS.IsLinux() {
  416. PandocBinPath = filepath.Join(pandocDir, "bin", "pandoc")
  417. }
  418. pandocVer := getPandocVer(PandocBinPath)
  419. if "" != pandocVer {
  420. logging.LogInfof("built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)
  421. return
  422. }
  423. pandocZip := filepath.Join(WorkingDir, "pandoc.zip")
  424. if "dev" == Mode {
  425. if gulu.OS.IsWindows() {
  426. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-windows-amd64.zip")
  427. } else if gulu.OS.IsDarwin() {
  428. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-darwin-amd64.zip")
  429. } else if gulu.OS.IsLinux() {
  430. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-linux-amd64.zip")
  431. }
  432. }
  433. if err := gulu.Zip.Unzip(pandocZip, pandocDir); nil != err {
  434. logging.LogErrorf("unzip pandoc failed: %s", err)
  435. return
  436. }
  437. if gulu.OS.IsDarwin() || gulu.OS.IsLinux() {
  438. exec.Command("chmod", "+x", PandocBinPath).CombinedOutput()
  439. }
  440. pandocVer = getPandocVer(PandocBinPath)
  441. logging.LogInfof("initialized built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)
  442. }
  443. func getPandocVer(binPath string) (ret string) {
  444. if "" == binPath {
  445. return
  446. }
  447. cmd := exec.Command(binPath, "--version")
  448. gulu.CmdAttr(cmd)
  449. data, err := cmd.CombinedOutput()
  450. if nil == err && strings.HasPrefix(string(data), "pandoc") {
  451. parts := bytes.Split(data, []byte("\n"))
  452. if 0 < len(parts) {
  453. ret = strings.TrimPrefix(string(parts[0]), "pandoc")
  454. ret = strings.ReplaceAll(ret, ".exe", "")
  455. ret = strings.TrimSpace(ret)
  456. }
  457. return
  458. }
  459. return
  460. }
  461. func IsValidPandocBin(binPath string) bool {
  462. if "" == binPath {
  463. return false
  464. }
  465. cmd := exec.Command(binPath, "--version")
  466. gulu.CmdAttr(cmd)
  467. data, err := cmd.CombinedOutput()
  468. if nil == err && strings.HasPrefix(string(data), "pandoc") {
  469. return true
  470. }
  471. return false
  472. }
  473. func GetDataAssetsAbsPath() (ret string) {
  474. ret = filepath.Join(DataDir, "assets")
  475. var err error
  476. stat, err := os.Lstat(ret)
  477. if nil != err {
  478. logging.LogErrorf("stat assets failed: %s", err)
  479. return
  480. }
  481. if 0 != stat.Mode()&os.ModeSymlink {
  482. // 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480
  483. ret, err = os.Readlink(ret)
  484. if nil != err {
  485. logging.LogErrorf("read assets link failed: %s", err)
  486. }
  487. }
  488. return
  489. }