CyberStrikeAI/internal/app/instance_lock.go

39 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package app
import (
"fmt"
"os"
"path/filepath"
"sync"
)
// lockDatabaseInstance acquires a non-blocking OS kernel lock for dbPath before
// startup recovery mutates SQLite tables (such as hitl_interrupts, messages,
// mcp_executions, or deep_assessments). If a second server process is started
// accidentally while the primary server is still bound and running tasks, the
// second process fails fast without corrupting the live server's task state.
func lockDatabaseInstance(dbPath string) (func(), error) {
absPath, err := filepath.Abs(dbPath)
if err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
return nil, fmt.Errorf("创建数据库目录失败: %w", err)
}
lockPath := absPath + ".instance.lock"
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return nil, fmt.Errorf("打开实例锁文件失败 (%s): %w", lockPath, err)
}
if err := tryLockInstanceFile(f); err != nil {
_ = f.Close()
return nil, fmt.Errorf("另一个 CyberStrikeAI 服务实例正在运行并占用数据库 %s(请先停止旧进程,或在系统设置中使用一键更新)", dbPath)
}
var once sync.Once
return func() {
once.Do(func() {
_ = f.Close()
})
}, nil
}