Skip to content

Commit

Permalink
add update_config and fix small bugs
Browse files Browse the repository at this point in the history
Switch to use update_config instead of save_config in Config.update
function to ensure charm configs are updated and not overwritten.
Fix wiring lines in _save_config function.
Raise ApplyError if grub-mkconfig command failed, since it is failing
also if there is wrong validation.
  • Loading branch information
rgildein committed Aug 4, 2023
1 parent abf0d95 commit d54a893
Show file tree
Hide file tree
Showing 2 changed files with 259 additions and 123 deletions.
21 changes: 16 additions & 5 deletions lib/charms/operator_libs_linux/v0/grub.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def _on_remove(self, _):

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 2
LIBPATCH = 3

GRUB_DIRECTORY = Path("/etc/default/grub.d/")
CHARM_CONFIG_PREFIX = "90-juju"
Expand Down Expand Up @@ -161,13 +161,24 @@ def _save_config(path: Path, config: Dict[str, str], header: str = CONFIG_HEADER
if path.exists():
logger.debug("GRUB config %s already exist and it will overwritten", path)

context = [f"{key}={shlex.quote(value)}" for key, value in config.items()]
with open(path, "w", encoding="UTF-8") as file:
file.writelines([header, *context])
file.write(f"{header}{os.linesep}")
for key, value in config.items():
file.write(f"{key}={shlex.quote(value)}{os.linesep}")

logger.info("GRUB config file %s was saved", path)


def _update_config(path: Path, config: Dict[str, str], header: str = CONFIG_HEADER) -> None:
"""Update existing GRUB config file."""
if path.exists():
original_config = _load_config(path)
original_config.update(config)
config = original_config.copy()

_save_config(path, config, header)


def check_update_grub() -> bool:
"""Report whether an update to /boot/grub/grub.cfg is available."""
main_grub_cfg = Path("/boot/grub/grub.cfg")
Expand All @@ -178,7 +189,7 @@ def check_update_grub() -> bool:
)
except subprocess.CalledProcessError as error:
logger.exception(error)
raise
raise ApplyError from error

return not filecmp.cmp(main_grub_cfg, tmp_path)

Expand Down Expand Up @@ -378,5 +389,5 @@ def update(self, config: Dict[str, str], apply: bool = True) -> Set[str]:
raise

logger.debug("[%s] saving copy of charm config to %s", self.charm_name, GRUB_DIRECTORY)
_save_config(self.path, config)
_update_config(self.path, config)
return changed_keys
Loading

0 comments on commit d54a893

Please sign in to comment.