working.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. "flag"
  19. "log"
  20. "math/rand"
  21. "mime"
  22. "os"
  23. "os/exec"
  24. "path/filepath"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "time"
  29. "github.com/88250/gulu"
  30. figure "github.com/common-nighthawk/go-figure"
  31. goPS "github.com/mitchellh/go-ps"
  32. "github.com/siyuan-note/httpclient"
  33. "github.com/siyuan-note/logging"
  34. )
  35. //var Mode = "dev"
  36. //
  37. var Mode = "prod"
  38. const (
  39. Ver = "2.1.6"
  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 = "std"
  73. if isRunningInDockerContainer() {
  74. Container = "docker"
  75. }
  76. UserAgent = UserAgent + " " + Container
  77. httpclient.SetUserAgent(UserAgent)
  78. initWorkspaceDir(*workspacePath)
  79. SSL = *ssl
  80. LogPath = filepath.Join(TempDir, "siyuan.log")
  81. logging.SetLogPath(LogPath)
  82. AppearancePath = filepath.Join(ConfDir, "appearance")
  83. if "dev" == Mode {
  84. ThemesPath = filepath.Join(WorkingDir, "appearance", "themes")
  85. IconsPath = filepath.Join(WorkingDir, "appearance", "icons")
  86. } else {
  87. ThemesPath = filepath.Join(AppearancePath, "themes")
  88. IconsPath = filepath.Join(AppearancePath, "icons")
  89. }
  90. initPathDir()
  91. checkPort()
  92. bootBanner := figure.NewColorFigure("SiYuan", "isometric3", "green", true)
  93. logging.LogInfof("\n" + bootBanner.String())
  94. logBootInfo()
  95. go cleanOld()
  96. }
  97. func setBootDetails(details string) {
  98. bootDetails = "v" + Ver + " " + details
  99. }
  100. func SetBootDetails(details string) {
  101. if 100 <= bootProgress {
  102. return
  103. }
  104. setBootDetails(details)
  105. }
  106. func IncBootProgress(progress float64, details string) {
  107. if 100 <= bootProgress {
  108. return
  109. }
  110. bootProgress += progress
  111. setBootDetails(details)
  112. }
  113. func IsBooted() bool {
  114. return 100 <= bootProgress
  115. }
  116. func GetBootProgressDetails() (float64, string) {
  117. return bootProgress, bootDetails
  118. }
  119. func GetBootProgress() float64 {
  120. return bootProgress
  121. }
  122. func SetBooted() {
  123. setBootDetails("Finishing boot...")
  124. bootProgress = 100
  125. logging.LogInfof("kernel booted")
  126. }
  127. func GetHistoryDir(suffix string) (ret string, err error) {
  128. ret = filepath.Join(HistoryDir, time.Now().Format("2006-01-02-150405")+"-"+suffix)
  129. if err = os.MkdirAll(ret, 0755); nil != err {
  130. logging.LogErrorf("make history dir failed: %s", err)
  131. return
  132. }
  133. return
  134. }
  135. var (
  136. HomeDir, _ = gulu.OS.Home()
  137. WorkingDir, _ = os.Getwd()
  138. WorkspaceDir string // 工作空间目录路径
  139. ConfDir string // 配置目录路径
  140. DataDir string // 数据目录路径
  141. RepoDir string // 仓库目录路径
  142. HistoryDir string // 数据历史目录路径
  143. TempDir string // 临时目录路径
  144. LogPath string // 配置目录下的日志文件 siyuan.log 路径
  145. DBName = "siyuan.db" // SQLite 数据库文件名
  146. DBPath string // SQLite 数据库文件路径
  147. BlockTreePath string // 区块树文件路径
  148. AppearancePath string // 配置目录下的外观目录 appearance/ 路径
  149. ThemesPath string // 配置目录下的外观目录下的 themes/ 路径
  150. IconsPath string // 配置目录下的外观目录下的 icons/ 路径
  151. AndroidNativeLibDir string // Android 库路径
  152. AndroidPrivateDataDir string // Android 私有数据路径
  153. UIProcessIDs = sync.Map{} // UI 进程 ID
  154. IsNewbie bool // 是否是第一次安装
  155. )
  156. func initWorkspaceDir(workspaceArg string) {
  157. userHomeConfDir := filepath.Join(HomeDir, ".config", "siyuan")
  158. workspaceConf := filepath.Join(userHomeConfDir, "workspace.json")
  159. if !gulu.File.IsExist(workspaceConf) {
  160. IsNewbie = "std" == Container // 只有桌面端需要设置新手标识,前端自动挂载帮助文档
  161. if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
  162. log.Printf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
  163. os.Exit(ExitCodeCreateConfDirErr)
  164. }
  165. }
  166. defaultWorkspaceDir := filepath.Join(HomeDir, "Documents", "SiYuan")
  167. if gulu.OS.IsWindows() {
  168. // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622
  169. if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {
  170. defaultWorkspaceDir = filepath.Join(userProfile, "Documents", "SiYuan")
  171. }
  172. }
  173. var workspacePaths []string
  174. if !gulu.File.IsExist(workspaceConf) {
  175. WorkspaceDir = defaultWorkspaceDir
  176. if "" != workspaceArg {
  177. WorkspaceDir = workspaceArg
  178. }
  179. if !gulu.File.IsDir(WorkspaceDir) {
  180. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  181. WorkspaceDir = defaultWorkspaceDir
  182. }
  183. workspacePaths = append(workspacePaths, WorkspaceDir)
  184. } else {
  185. data, err := os.ReadFile(workspaceConf)
  186. if err = gulu.JSON.UnmarshalJSON(data, &workspacePaths); nil != err {
  187. log.Printf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
  188. }
  189. tmp := workspacePaths[:0]
  190. for _, d := range workspacePaths {
  191. if gulu.File.IsDir(d) {
  192. tmp = append(tmp, d)
  193. }
  194. }
  195. workspacePaths = tmp
  196. if 0 < len(workspacePaths) {
  197. WorkspaceDir = workspacePaths[len(workspacePaths)-1]
  198. if "" != workspaceArg {
  199. WorkspaceDir = workspaceArg
  200. }
  201. if !gulu.File.IsDir(WorkspaceDir) {
  202. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  203. WorkspaceDir = defaultWorkspaceDir
  204. }
  205. workspacePaths[len(workspacePaths)-1] = WorkspaceDir
  206. } else {
  207. WorkspaceDir = defaultWorkspaceDir
  208. if "" != workspaceArg {
  209. WorkspaceDir = workspaceArg
  210. }
  211. if !gulu.File.IsDir(WorkspaceDir) {
  212. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  213. WorkspaceDir = defaultWorkspaceDir
  214. }
  215. workspacePaths = append(workspacePaths, WorkspaceDir)
  216. }
  217. }
  218. if data, err := gulu.JSON.MarshalJSON(workspacePaths); nil == err {
  219. if err = os.WriteFile(workspaceConf, data, 0644); nil != err {
  220. log.Fatalf("write workspace conf [%s] failed: %s", workspaceConf, err)
  221. }
  222. } else {
  223. log.Fatalf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
  224. }
  225. ConfDir = filepath.Join(WorkspaceDir, "conf")
  226. DataDir = filepath.Join(WorkspaceDir, "data")
  227. RepoDir = filepath.Join(WorkspaceDir, "repo")
  228. HistoryDir = filepath.Join(WorkspaceDir, "history")
  229. TempDir = filepath.Join(WorkspaceDir, "temp")
  230. osTmpDir := filepath.Join(TempDir, "os")
  231. os.RemoveAll(osTmpDir)
  232. if err := os.MkdirAll(osTmpDir, 0755); nil != err {
  233. log.Fatalf("create os tmp dir [%s] failed: %s", osTmpDir, err)
  234. }
  235. os.Setenv("TMPDIR", osTmpDir)
  236. os.Setenv("TEMP", osTmpDir)
  237. os.Setenv("TMP", osTmpDir)
  238. DBPath = filepath.Join(TempDir, DBName)
  239. BlockTreePath = filepath.Join(TempDir, "blocktree.msgpack")
  240. }
  241. var (
  242. Resident bool
  243. ReadOnly bool
  244. AccessAuthCode string
  245. Lang = ""
  246. Container string // docker, android, ios, std
  247. )
  248. func initPathDir() {
  249. if err := os.MkdirAll(ConfDir, 0755); nil != err && !os.IsExist(err) {
  250. log.Fatalf("create conf folder [%s] failed: %s", ConfDir, err)
  251. }
  252. if err := os.MkdirAll(DataDir, 0755); nil != err && !os.IsExist(err) {
  253. log.Fatalf("create data folder [%s] failed: %s", DataDir, err)
  254. }
  255. if err := os.MkdirAll(TempDir, 0755); nil != err && !os.IsExist(err) {
  256. log.Fatalf("create temp folder [%s] failed: %s", TempDir, err)
  257. }
  258. assets := filepath.Join(DataDir, "assets")
  259. if err := os.MkdirAll(assets, 0755); nil != err && !os.IsExist(err) {
  260. log.Fatalf("create data assets folder [%s] failed: %s", assets, err)
  261. }
  262. templates := filepath.Join(DataDir, "templates")
  263. if err := os.MkdirAll(templates, 0755); nil != err && !os.IsExist(err) {
  264. log.Fatalf("create data templates folder [%s] failed: %s", templates, err)
  265. }
  266. widgets := filepath.Join(DataDir, "widgets")
  267. if err := os.MkdirAll(widgets, 0755); nil != err && !os.IsExist(err) {
  268. log.Fatalf("create data widgets folder [%s] failed: %s", widgets, err)
  269. }
  270. emojis := filepath.Join(DataDir, "emojis")
  271. if err := os.MkdirAll(emojis, 0755); nil != err && !os.IsExist(err) {
  272. log.Fatalf("create data emojis folder [%s] failed: %s", widgets, err)
  273. }
  274. }
  275. // TODO: v2.2.0 移除
  276. func cleanOld() {
  277. dirs, _ := os.ReadDir(WorkingDir)
  278. for _, dir := range dirs {
  279. if strings.HasSuffix(dir.Name(), ".old") {
  280. old := filepath.Join(WorkingDir, dir.Name())
  281. os.RemoveAll(old)
  282. }
  283. }
  284. }
  285. func checkPort() {
  286. portOpened := isPortOpen(ServerPort)
  287. if !portOpened {
  288. return
  289. }
  290. logging.LogInfof("port [%s] is opened, try to check version of running kernel", ServerPort)
  291. result := NewResult()
  292. _, err := httpclient.NewBrowserRequest().
  293. SetResult(result).
  294. SetHeader("User-Agent", UserAgent).
  295. Get("http://127.0.0.1:" + ServerPort + "/api/system/version")
  296. if nil != err || 0 != result.Code {
  297. logging.LogErrorf("connect to port [%s] for checking running kernel failed", ServerPort)
  298. KillByPort(ServerPort)
  299. return
  300. }
  301. if nil == result.Data {
  302. logging.LogErrorf("connect ot port [%s] for checking running kernel failed", ServerPort)
  303. os.Exit(ExitCodeUnavailablePort)
  304. }
  305. runningVer := result.Data.(string)
  306. if runningVer == Ver {
  307. logging.LogInfof("version of the running kernel is the same as this boot [%s], exit this boot", runningVer)
  308. os.Exit(ExitCodeOk)
  309. }
  310. logging.LogInfof("found kernel [%s] is running, try to exit it", runningVer)
  311. processes, err := goPS.Processes()
  312. if nil != err {
  313. logging.LogErrorf("close kernel [%s] failed: %s", runningVer, err)
  314. os.Exit(ExitCodeUnavailablePort)
  315. }
  316. currentPid := os.Getpid()
  317. for _, p := range processes {
  318. name := p.Executable()
  319. if strings.Contains(strings.ToLower(name), "siyuan-kernel") || strings.Contains(strings.ToLower(name), "siyuan kernel") {
  320. kernelPid := p.Pid()
  321. if currentPid != kernelPid {
  322. pid := strconv.Itoa(kernelPid)
  323. Kill(pid)
  324. logging.LogInfof("killed kernel [name=%s, pid=%s, ver=%s], continue to boot", name, pid, runningVer)
  325. }
  326. }
  327. }
  328. if !tryToListenPort() {
  329. os.Exit(ExitCodeUnavailablePort)
  330. }
  331. }
  332. func initMime() {
  333. // 在某版本的 Windows 10 操作系统上界面样式异常问题
  334. // https://github.com/siyuan-note/siyuan/issues/247
  335. // https://github.com/siyuan-note/siyuan/issues/3813
  336. mime.AddExtensionType(".css", "text/css")
  337. mime.AddExtensionType(".js", "application/x-javascript")
  338. mime.AddExtensionType(".json", "application/json")
  339. mime.AddExtensionType(".html", "text/html")
  340. }
  341. func KillByPort(port string) {
  342. if pid := PidByPort(port); "" != pid {
  343. pidInt, _ := strconv.Atoi(pid)
  344. proc, _ := goPS.FindProcess(pidInt)
  345. var name string
  346. if nil != proc {
  347. name = proc.Executable()
  348. }
  349. Kill(pid)
  350. logging.LogInfof("killed process [name=%s, pid=%s]", name, pid)
  351. }
  352. }
  353. func Kill(pid string) {
  354. var kill *exec.Cmd
  355. if gulu.OS.IsWindows() {
  356. kill = exec.Command("cmd", "/c", "TASKKILL /F /PID "+pid)
  357. } else {
  358. kill = exec.Command("kill", "-9", pid)
  359. }
  360. CmdAttr(kill)
  361. kill.CombinedOutput()
  362. }
  363. func PidByPort(port string) (ret string) {
  364. if gulu.OS.IsWindows() {
  365. cmd := exec.Command("cmd", "/c", "netstat -ano | findstr "+port)
  366. CmdAttr(cmd)
  367. data, err := cmd.CombinedOutput()
  368. if nil != err {
  369. logging.LogErrorf("netstat failed: %s", err)
  370. return
  371. }
  372. output := string(data)
  373. lines := strings.Split(output, "\n")
  374. for _, l := range lines {
  375. if strings.Contains(l, "LISTENING") {
  376. l = l[strings.Index(l, "LISTENING")+len("LISTENING"):]
  377. l = strings.TrimSpace(l)
  378. ret = l
  379. return
  380. }
  381. }
  382. return
  383. }
  384. cmd := exec.Command("lsof", "-Fp", "-i", ":"+port)
  385. CmdAttr(cmd)
  386. data, err := cmd.CombinedOutput()
  387. if nil != err {
  388. logging.LogErrorf("lsof failed: %s", err)
  389. return
  390. }
  391. output := string(data)
  392. lines := strings.Split(output, "\n")
  393. for _, l := range lines {
  394. if strings.HasPrefix(l, "p") {
  395. l = l[1:]
  396. ret = l
  397. return
  398. }
  399. }
  400. return
  401. }