An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add kernel exit stage diagnostics https://github.com/siyuan-note/siyuan/issues/20191
Daniel908f10068bde
diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex aae34eacbe..e1d6bba0cf 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -1039,24 +1039,33 @@ var exitLock = sync.Mutex{}// 当 force 为 true(强制退出)并且 execInstallPkg 为 0(默认检查更新)并且新版本安装包已经准备就绪时,将安装包路径返回给桌面宿主// https://github.com/siyuan-note/siyuan/issues/10288func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, installPkgPath string) {+ diagnostic := util.WatchOperationWithTiming("exit kernel", "wait for exit lock")+ defer diagnostic.Finish()exitLock.Lock()defer exitLock.Unlock()logging.LogInfof("exiting kernel [force=%v, setCurrentWorkspace=%v, execInstallPkg=%d]", force, setCurrentWorkspace, execInstallPkg)- defer stopLANSyncManager()+ defer func() {+ diagnostic.Stage("stop LAN sync manager")+ stopLANSyncManager()+ }()+ diagnostic.Stage("flush editing transactions")util.PushMsg(Conf.Language(95), 10000*60)FlushTxQueue()+ diagnostic.Stage("cancel purge")cancelPurge()if !force {if OnKernelPluginsStop != nil {+ diagnostic.Stage("stop kernel plugins")OnKernelPluginsStop()}if Conf.Sync.Enabled && 3 != Conf.Sync.Mode &&((IsSubscriber() && conf.ProviderSiYuan == Conf.Sync.Provider) || conf.ProviderSiYuan != Conf.Sync.Provider) {+ diagnostic.Stage("exit sync")syncData(true, false)if 0 != ExitSyncSucc {exitCode = 1@@ -1069,15 +1078,19 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, i}// Close the user guide when exiting https://github.com/siyuan-note/siyuan/issues/10322+ diagnostic.Stage("close user guide")closeUserGuide()// Improve indexing completeness when exiting https://github.com/siyuan-note/siyuan/issues/12039+ diagnostic.Stage("flush database index")sql.FlushQueue()util.IsExiting.Store(true)// 等待正在执行的路径批次退出,未完成任务保留在配置目录供下次启动恢复。+ diagnostic.Stage("wait for path refresh")hpathRefresh.Lock()hpathRefresh.Unlock()+ diagnostic.Stage("check install package")newVerInstallPkgPath := getNewVerInstallPkgPath()if !skipNewVerInstallPkg() && "" != newVerInstallPkgPath {if 2 == execInstallPkg || (force && 0 == execInstallPkg) { // 将新版本安装包交给桌面宿主执行@@ -1091,6 +1104,7 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, i}}+ diagnostic.Stage("save configuration")Conf.Close()// 退出前关闭已打开的加密笔记本并推送 closeBox,让前端关闭对应的明文文档标签页,避免重启后泄密。// 走 Unmount:落盘 Closed=true + 生成历史 + 锁定清 DEK + 广播 closeBox。@@ -1098,17 +1112,25 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, i// 放在 BroadcastByType("exit")(第 933 行)之前推送,随后的 time.Sleep(500ms) 留给前端处理事件。for _, box := range Conf.GetOpenedBoxes() {if IsEncryptedBox(box.ID) && !IsUserGuide(box.ID) {+ diagnostic.Stage("unmount encrypted notebook " + box.ID)Unmount(box.ID)}}+ diagnostic.Stage("close databases")sql.CloseDatabase()+ diagnostic.Stage("close push queue")closePushQueue()+ diagnostic.Stage("save asset texts")util.SaveAssetsTexts()+ diagnostic.Stage("clear workspace temp")clearWorkspaceTemp(installPkgPath)+ diagnostic.Stage("clear corrupted notebooks")clearCorruptedNotebooks()+ diagnostic.Stage("clear port file")clearPortJSON()if setCurrentWorkspace {+ diagnostic.Stage("save workspace paths")// 将当前工作空间放到工作空间列表的最后一个// Open the last workspace by default https://github.com/siyuan-note/siyuan/issues/10570workspacePaths, err := util.ReadWorkspacePaths()@@ -1121,21 +1143,28 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, i}}+ diagnostic.Stage("unlock workspace")util.UnlockWorkspace()+ diagnostic.Stage("wait for frontend events")time.Sleep(500 * time.Millisecond)+ diagnostic.Stage("close sync websocket")closeSyncWebSocket()go func() {+ diagnostic := util.WatchOperationWithTiming("exit kernel servers", "wait for exit response")time.Sleep(500 * time.Millisecond)logging.LogInfof("exited kernel")if nil != util.WebSocketServer {+ diagnostic.Stage("close frontend websockets")util.WebSocketServer.Close()}if nil != util.HttpServer {+ diagnostic.Stage("close HTTP server")util.HttpServer.Close()}util.HttpServing = false+ diagnostic.Finish()if util.IsMobileContainer() {returndiff --git a/kernel/sql/database.go b/kernel/sql/database.goindex af9fafaab8..badba9f301 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -1447,20 +1447,28 @@ func cleanupInvalidRefs(database *sql.DB) (err error) {}func CloseDatabase() {+ diagnostic := util.WatchOperationWithTiming("close databases", "close index queue")+ defer diagnostic.Finish()closeIndexQueue()// 退出时删除所有已打开的加密 db 文件:加密索引可由 box.Index() 全量重建,// 文件无需持久化,删除可避免重启后残留旧索引数据导致下次解锁叠加重复行。+ diagnostic.Stage("remove encrypted indexes")RemoveAllEncryptedDBFiles()+ diagnostic.Stage("remove encrypted block tree indexes")treenode.RemoveAllEncryptedBlockTreeDBFiles()+ diagnostic.Stage("close block database")if err := db.Close(); err != nil {logging.LogErrorf("close database failed: %s", err)}+ diagnostic.Stage("close history database")if err := historyDB.Close(); err != nil {logging.LogErrorf("close history database failed: %s", err)}+ diagnostic.Stage("close asset content database")if err := assetContentDB.Close(); err != nil {logging.LogErrorf("close asset content database failed: %s", err)}+ diagnostic.Stage("close block tree database")treenode.CloseDatabase()logging.LogInfof("closed database")}diff --git a/kernel/util/operation_watchdog.go b/kernel/util/operation_watchdog.goindex 3f13a28886..c159e6fc38 100644--- a/kernel/util/operation_watchdog.go+++ b/kernel/util/operation_watchdog.go@@ -17,12 +17,14 @@ const operationStallThreshold = 10 * time.Second// OperationWatchdog 在操作仍未返回时记录阶段和调用栈,不取消操作、不改变数据写入顺序。type OperationWatchdog struct {- mu sync.Mutex- name string- stage string- started time.Time- done bool- timer *time.Timer+ mu sync.Mutex+ name string+ stage string+ started time.Time+ stageStarted time.Time+ logTiming bool+ done bool+ timer *time.Timer}type operationStall struct {@@ -39,8 +41,19 @@ func WatchOperation(name, stage string) *OperationWatchdog {})}+// WatchOperationWithTiming 记录每个阶段的开始、耗时和操作总耗时,并保留慢操作调用栈。+func WatchOperationWithTiming(name, stage string) *OperationWatchdog {+ w := WatchOperation(name, stage)+ w.mu.Lock()+ w.logTiming = true+ w.mu.Unlock()+ logging.LogInfof("operation [%s], stage [%s] started", name, stage)+ return w+}+func watchOperation(name, stage string, threshold time.Duration, report func(operationStall)) *OperationWatchdog {- w := &OperationWatchdog{name: name, stage: stage, started: time.Now()}+ now := time.Now()+ w := &OperationWatchdog{name: name, stage: stage, started: now, stageStarted: now}w.timer = time.AfterFunc(threshold, func() {w.mu.Lock()if w.done {@@ -56,8 +69,15 @@ func watchOperation(name, stage string, threshold time.Duration, report func(opefunc (w *OperationWatchdog) Stage(stage string) {w.mu.Lock()+ previous, elapsed, total := w.stage, time.Since(w.stageStarted), time.Since(w.started)+ logTiming := w.logTimingw.stage = stage+ w.stageStarted = time.Now()w.mu.Unlock()+ if logTiming {+ logging.LogInfof("operation [%s], stage [%s] finished, elapsed [%s], total [%s]", w.name, previous, elapsed, total)+ logging.LogInfof("operation [%s], stage [%s] started", w.name, stage)+ }}func (w *OperationWatchdog) Finish() {@@ -65,7 +85,12 @@ func (w *OperationWatchdog) Finish() {w.done = truew.timer.Stop()elapsed, stage := time.Since(w.started), w.stage+ stageElapsed, logTiming := time.Since(w.stageStarted), w.logTimingw.mu.Unlock()+ if logTiming {+ logging.LogInfof("operation [%s], stage [%s] finished, elapsed [%s], total [%s]", w.name, stage, stageElapsed, elapsed)+ return+ }if elapsed >= operationStallThreshold {logging.LogInfof("slow operation finished [%s], stage [%s], elapsed [%s]", w.name, stage, elapsed)}