mirror of
https://github.com/DullJZ/s3-balance.git
synced 2026-09-09 09:56:39 +08:00
Fix: Modify config fails in Docker
This commit is contained in:
+19
-21
@@ -1,6 +1,7 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
@@ -366,39 +367,36 @@ func (m *Manager) backupConfigFile() error {
|
|||||||
|
|
||||||
// writeConfigFile 将配置写入 YAML 文件
|
// writeConfigFile 将配置写入 YAML 文件
|
||||||
func (m *Manager) writeConfigFile(cfg *Config) error {
|
func (m *Manager) writeConfigFile(cfg *Config) error {
|
||||||
// 临时文件,确保原子性
|
// 先编码到缓冲区,避免在写入过程中损坏原文件
|
||||||
tmpFile := m.configFile + ".tmp"
|
var buf bytes.Buffer
|
||||||
|
encoder := yaml.NewEncoder(&buf)
|
||||||
file, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create temp config file: %w", err)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
encoder := yaml.NewEncoder(file)
|
|
||||||
encoder.SetIndent(2)
|
encoder.SetIndent(2)
|
||||||
|
|
||||||
if err := encoder.Encode(cfg); err != nil {
|
if err := encoder.Encode(cfg); err != nil {
|
||||||
file.Close()
|
|
||||||
os.Remove(tmpFile)
|
|
||||||
return fmt.Errorf("failed to encode config: %w", err)
|
return fmt.Errorf("failed to encode config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := encoder.Close(); err != nil {
|
if err := encoder.Close(); err != nil {
|
||||||
file.Close()
|
|
||||||
os.Remove(tmpFile)
|
|
||||||
return fmt.Errorf("failed to close encoder: %w", err)
|
return fmt.Errorf("failed to close encoder: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := file.Close(); err != nil {
|
file, err := os.OpenFile(m.configFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||||
os.Remove(tmpFile)
|
if err != nil {
|
||||||
return fmt.Errorf("failed to close temp file: %w", err)
|
return fmt.Errorf("failed to open config file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 原子性替换原文件
|
if _, err := file.Write(buf.Bytes()); err != nil {
|
||||||
if err := os.Rename(tmpFile, m.configFile); err != nil {
|
file.Close()
|
||||||
os.Remove(tmpFile)
|
return fmt.Errorf("failed to write config file: %w", err)
|
||||||
return fmt.Errorf("failed to replace config file: %w", err)
|
}
|
||||||
|
|
||||||
|
if err := file.Sync(); err != nil {
|
||||||
|
file.Close()
|
||||||
|
return fmt.Errorf("failed to sync config file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
return fmt.Errorf("failed to close config file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
Reference in New Issue
Block a user