fix(config): never autosave defaults over an unreadable config file

Additional changes
The migration copies the old file to the backup instead of moving it and replaces the file atomically, only after the migration succeeded.
An explicit save keeps a copy of a file that could not be loaded and serializes the configuration before it opens the file.
The configuration guide describes the migration backup and what happens to a file that cannot be loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-20 18:39:14 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent 887bae551b
commit f3773de8f8
5 changed files with 236 additions and 32 deletions
+38 -6
View File
@@ -11,6 +11,7 @@ Key features:
import json
import os
import shutil
import sys
import tempfile
from copy import deepcopy
@@ -463,6 +464,9 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
"with_file_secret_settings": True,
}
_config_file_path: ClassVar[Optional[Path]] = None
# Why the configuration file could not be loaded, None if it was loaded. The automatic save
# never replaces such a file by the default configuration EOS falls back to.
_config_file_load_error: ClassVar[Optional[str]] = None
_config_autosave: ClassVar[str] = ""
# Settings provided at runtime, e.g. by the REST interface. Highest priority after CLI.
_runtime_settings: ClassVar[dict[str, Any]] = {}
@@ -707,6 +711,7 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
Ensures the config file exists and creates a backup if necessary.
"""
cls._config_file_load_error = None
if not cls._init_config_eos.get("with_file_settings", True):
logger.debug("Config initialisation with file settings is disabled.")
return {}
@@ -724,9 +729,17 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
settings = pydantic_settings.JsonConfigSettingsSource(
settings_cls, json_file=config_file
)()
else:
cls._config_file_load_error = "the file could not be read or migrated"
except Exception as ex:
cls._config_file_load_error = str(ex)
if cls._config_file_load_error is not None:
logger.error(
f"Error reading config file '{config_file}' (falling back to default config): {ex}"
f"Error reading config file '{config_file}' (falling back to default config): "
f"{cls._config_file_load_error}. The configuration is not saved automatically "
"until the file is loaded, so the file is kept. Fix the file and reload it "
"(POST /v1/config/reset or restart EOS), or save the current configuration "
"explicitly (PUT /v1/config/file), which keeps a copy of the file."
)
return settings
@@ -1227,24 +1240,43 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
def to_config_file(self) -> None:
"""Saves the current configuration to the configuration file.
Also updates the configuration file settings.
Also updates the configuration file settings. If the configuration file could not be
loaded, a copy of it is kept as ``<stem>.unreadable.<timestamp>`` next to it.
Raises:
ValueError: If the configuration file path is not specified or can not be written to.
OSError: If the copy of a configuration file that could not be loaded fails.
"""
if not self.general.config_file_path:
config_file_path = self.general.config_file_path
if not config_file_path:
raise ValueError("Configuration file path unknown.")
with self.general.config_file_path.open("w", encoding="utf-8", newline="\n") as f_out:
f_out.write(self.to_config_json())
logger.info(f"Saved configuration to '{self.general.config_file_path}'.")
config_json = self.to_config_json()
if ConfigEOS._config_file_load_error is not None and config_file_path.exists():
# The current configuration does not hold the content of the file - keep it.
unreadable_file_path = config_file_path.with_name(
f"{config_file_path.stem}.unreadable.{to_datetime(as_string='YYYYMMDDHHmmss')}"
)
shutil.copy2(config_file_path, unreadable_file_path)
logger.warning(
f"Kept a copy of the configuration file that could not be loaded "
f"as '{unreadable_file_path}'."
)
with config_file_path.open("w", encoding="utf-8", newline="\n") as f_out:
f_out.write(config_json)
ConfigEOS._config_file_load_error = None
logger.info(f"Saved configuration to '{config_file_path}'.")
def autosave(self) -> None:
"""Saves the current configuration if AUTOMATIC save mode is configured.
Tries to avoid save operation if there are no changes between last and actual save.
A configuration file that could not be loaded is never saved automatically: the current
configuration fell back to the defaults and would replace the content of the file.
"""
if self.general.config_save_mode != ConfigSaveMode.AUTOMATIC:
return
if ConfigEOS._config_file_load_error is not None:
return
config_str = self.to_config_json()
if config_str != ConfigEOS._config_autosave:
+56 -26
View File
@@ -1,7 +1,10 @@
"""Migrate config file to actual version."""
import json
import os
import shutil
import stat
import tempfile
import types
from pathlib import Path
from typing import (
@@ -611,9 +614,41 @@ def remove_empty(obj: dict) -> dict:
return obj
def _replace_config_file(config_file: Path, content: str) -> None:
"""Replace the configuration file atomically.
The content is written to a temporary file next to the configuration file, which then
replaces it. If writing fails, the configuration file is left untouched. The new file keeps
the permission bits of the old one.
Args:
config_file (Path): The existing configuration file.
content (str): The new content of the configuration file.
Raises:
OSError: If the temporary file can not be written or can not replace the file.
"""
fd, tmp_name = tempfile.mkstemp(
dir=config_file.parent, prefix=f".{config_file.name}.", suffix=".tmp"
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f_out:
f_out.write(content)
f_out.flush()
os.fsync(f_out.fileno())
os.chmod(tmp_name, stat.S_IMODE(config_file.stat().st_mode))
os.replace(tmp_name, config_file)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raise
def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
"""Migrate configuration file to the current version.
Only a successful migration replaces the file; the old file is copied to the backup file
right before. A failed migration leaves the file untouched and makes no backup.
Returns:
bool: True if up-to-date or successfully migrated, False on failure.
"""
@@ -643,21 +678,6 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
)
try:
# Backup existing file - we already know it is existing
try:
config_file.replace(backup_file)
logger.info(f"Backed up old configuration to '{backup_file}'.")
except Exception as e_replace:
try:
shutil.copy(config_file, backup_file)
logger.info(
f"Could not replace; copied old configuration to '{backup_file}' instead."
)
except Exception as e_copy:
logger.warning(
f"Failed to backup existing config (replace: {e_replace}; copy: {e_copy}). Continuing without backup."
)
from akkudoktoreos.config.config import SettingsEOSDefaults
# Strip computed fields
@@ -666,19 +686,29 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
# Migrate config data
new_config = migrate_config_data(config_data)
# Need model_dump_json (not model_dump) because of special serialisation.
json_str = new_config.model_dump_json(
exclude_computed_fields=True,
exclude_defaults=True,
exclude_none=True,
by_alias=True,
)
cleaned = remove_empty(json.loads(json_str))
json_str = json.dumps(cleaned, indent=4, ensure_ascii=False)
# Backup existing file - we already know it is existing. Copy it: the file stays in
# place until the migrated configuration replaces it.
try:
shutil.copy2(config_file, backup_file)
logger.info(f"Backed up old configuration to '{backup_file}'.")
except Exception as e_copy:
logger.warning(
f"Failed to backup existing config ({e_copy}). Continuing without backup."
)
# Write migrated configuration
try:
with config_file.open("w", encoding="utf-8", newline=None) as f_out:
# Need model_dump_json (not model_dump) because of special serialisation.
json_str = new_config.model_dump_json(
exclude_computed_fields=True,
exclude_defaults=True,
exclude_none=True,
by_alias=True,
)
cleaned = remove_empty(json.loads(json_str))
json_str = json.dumps(cleaned, indent=4, ensure_ascii=False)
f_out.write(json_str)
_replace_config_file(config_file, json_str)
except Exception as e_write:
logger.error(f"Failed to write migrated configuration to '{config_file}': {e_write}")
return False