fix: agent selfupdate rename .bak error

This commit is contained in:
engigu
2025-12-29 20:36:58 +08:00
parent d75bbfd020
commit 25d8155d02
+23 -5
View File
@@ -1110,26 +1110,38 @@ func (a *Agent) selfUpdate() {
return return
} }
// 备份旧版本 - 先去掉已有的 .bak 后缀,避免不断追加 // 计算基础路径(去掉所有 .bak 后缀
basePath := exePath basePath := exePath
for strings.HasSuffix(basePath, ".bak") { for strings.HasSuffix(basePath, ".bak") {
basePath = strings.TrimSuffix(basePath, ".bak") basePath = strings.TrimSuffix(basePath, ".bak")
} }
backupFile := basePath + ".bak" backupFile := basePath + ".bak"
// 如果当前运行的就是 .bak 文件,直接删除它(更新后会用新版本)
// 否则需要备份当前文件
if exePath != backupFile {
os.Remove(backupFile) os.Remove(backupFile)
if err := os.Rename(exePath, backupFile); err != nil { if err := os.Rename(exePath, backupFile); err != nil {
log.Errorf("备份旧版本失败: %v", err) log.Errorf("备份旧版本失败: %v", err)
os.Remove(tmpFile) os.Remove(tmpFile)
return return
} }
}
// 替换为新版本 // 替换为新版本(放到 basePath,即不带 .bak 的路径)
if err := os.Rename(tmpFile, exePath); err != nil { if err := os.Rename(tmpFile, basePath); err != nil {
log.Errorf("替换新版本失败: %v", err) log.Errorf("替换新版本失败: %v", err)
if exePath != backupFile {
os.Rename(backupFile, exePath) // 恢复旧版本 os.Rename(backupFile, exePath) // 恢复旧版本
}
return return
} }
// 如果之前运行的是 .bak 文件,现在可以删除它了
if exePath == backupFile {
os.Remove(exePath)
}
log.Info("更新完成,正在重启...") log.Info("更新完成,正在重启...")
// 重启服务 // 重启服务
@@ -1140,13 +1152,19 @@ func (a *Agent) selfUpdate() {
func (a *Agent) restart() { func (a *Agent) restart() {
exePath, _ := os.Executable() exePath, _ := os.Executable()
// 计算基础路径(去掉所有 .bak 后缀),确保启动的是正确的可执行文件
basePath := exePath
for strings.HasSuffix(basePath, ".bak") {
basePath = strings.TrimSuffix(basePath, ".bak")
}
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
// Windows: 启动新进程后退出 // Windows: 启动新进程后退出
cmd := exec.Command(exePath, "start") cmd := exec.Command(basePath, "start")
cmd.Start() cmd.Start()
os.Exit(0) os.Exit(0)
} else { } else {
// Linux/macOS: 使用 exec 替换当前进程 // Linux/macOS: 使用 exec 替换当前进程
syscall.Exec(exePath, []string{exePath, "start"}, os.Environ()) syscall.Exec(basePath, []string{basePath, "start"}, os.Environ())
} }
} }