Skip to content

Commit

Permalink
improve spliting line of GRUB config
Browse files Browse the repository at this point in the history
  • Loading branch information
rgildein committed Jul 19, 2023
1 parent 2520e22 commit d8242de
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 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 @@ -37,13 +37,13 @@ def __init__(self, *args):
def _on_install(self, _):
try:
self.grub.update(
{"GRUB_CMDLINE_LINUX_DEFAULT": '"$GRUB_CMDLINE_LINUX_DEFAULT hugepagesz=1G"'}
{"GRUB_CMDLINE_LINUX_DEFAULT": "$GRUB_CMDLINE_LINUX_DEFAULT hugepagesz=1G"}
)
except grub.ValidationError as error:
self.unit.status = BlockedStatus(f"[{error.key}] {error.message}")
def _on_update_status(self, _):
if self.grub["GRUB_CMDLINE_LINUX_DEFAULT"] != '"$GRUB_CMDLINE_LINUX_DEFAULT hugepagesz=1G"':
if self.grub["GRUB_CMDLINE_LINUX_DEFAULT"] != "$GRUB_CMDLINE_LINUX_DEFAULT hugepagesz=1G":
self.unit.status = BlockedStatus("wrong GRUB configuration")
def _on_remove(self, _):
Expand All @@ -58,7 +58,7 @@ def _on_remove(self, _):
import shlex
import subprocess
from pathlib import Path
from typing import Dict, Mapping, Optional, Set
from typing import Dict, Mapping, Optional, Set, Tuple

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -114,6 +114,17 @@ class ApplyError(Exception):
"""Exception if applying new config failed."""


def _split_config_line(line: str) -> Tuple[str, str]:
"""Split GRUB config line to obtain key and value."""
key, raw_value = line.split("=", 1)
value, *not_expected_values = shlex.split(raw_value)
if not_expected_values:
logger.error("unexpected value %s for %s key", raw_value, key)
raise ValueError(f"unexpected value {raw_value} for {key} key")

return key, value


def _parse_config(stream: io.TextIOWrapper) -> Dict[str, str]:
"""Parse config file lines."""
config = {}
Expand All @@ -123,11 +134,11 @@ def _parse_config(stream: io.TextIOWrapper) -> Dict[str, str]:
logger.debug("skipping line `%s`", line)
continue

key, value = line.split("=", 1)
key, value = _split_config_line(line)
if key in config:
logger.warning("key %s is duplicated in config", key)

config[key], *_ = shlex.split(value)
config[key] = value

return config

Expand Down
11 changes: 11 additions & 0 deletions tests/unit/test_grub.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ def setUp(self) -> None:


class TestGrubUtils(BaseTestGrubLib):
def test_split_config_line(self):
"""Tets splitting single line."""
key, value = grub._split_config_line('test="1234"')
assert key == "test"
assert value == "1234"

def test_split_config_line_failed(self):
"""Tets splitting single line."""
with self.assertRaises(ValueError):
grub._split_config_line('test="1234" "5678"')

def test_parse_config(self):
"""Test parsing example GRUB config with skipping duplicated key."""
stream = io.StringIO(GRUB_CONFIG_EXAMPLE)
Expand Down

0 comments on commit d8242de

Please sign in to comment.