Skip to content

Commit

Permalink
change type of Config value to str
Browse files Browse the repository at this point in the history
  • Loading branch information
zmraul committed Jul 19, 2023
1 parent 7257317 commit aa727f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
32 changes: 22 additions & 10 deletions lib/charms/operator_libs_linux/v0/sysctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@

"""Handler for the sysctl config.
This library allows your charm to create and update sysctl config options to the machine.
Validation and merge capabilities are added, for situations where more than one application
are setting values. The following files can be created:
- /etc/sysctl.d/90-juju-<app-name>
Requirements from one application requesting to update the values.
- /etc/sysctl.d/95-juju-sysctl.conf
Merged file resulting from all other `90-juju-*` application files.
A charm using the sysctl lib will need a data structure like the following:
```yaml
vm.swappiness:
Expand Down Expand Up @@ -56,6 +68,7 @@ def _on_install(self, _):
def _on_remove(self, _):
self.sysctl.remove()
```
"""

import logging
Expand Down Expand Up @@ -135,7 +148,7 @@ def __iter__(self):
"""Iterate over config."""
return iter(self._data)

def __getitem__(self, key: str) -> int:
def __getitem__(self, key: str) -> str:
"""Get value for key form config."""
return self._data[key]

Expand All @@ -155,8 +168,7 @@ def update(self, config: Dict[str, dict]) -> None:
"""
self._parse_config(config)

# NOTE: case where own charm calls update() more than once. Remove first so
# we don't get validation errors.
# NOTE: case where own charm calls update() more than once.
if self.charm_filepath.exists():
self._merge(add_own_charm=False)

Expand Down Expand Up @@ -237,11 +249,11 @@ def _apply(self) -> None:
logger.error(msg)
raise SysctlPermissionError(msg)

def _create_snapshot(self) -> Dict[str, int]:
def _create_snapshot(self) -> Dict[str, str]:
"""Create a snaphot of config options that are going to be set."""
return {key: int(self._sysctl([key, "-n"])[0]) for key in self._desired_config.keys()}

def _restore_snapshot(self, snapshot: Dict[str, int]) -> None:
def _restore_snapshot(self, snapshot: Dict[str, str]) -> None:
"""Restore a snapshot to the machine."""
values = [f"{key}={value}" for key, value in snapshot.items()]
self._sysctl(values)
Expand All @@ -261,10 +273,10 @@ def _parse_config(self, config: Dict[str, dict]) -> None:
"""Parse a config passed to the lib."""
result = {}
for key, value in config.items():
result[key] = int(value["value"])
self._desired_config: Dict[str, int] = result
result[key] = value["value"]
self._desired_config: Dict[str, str] = result

def _load_data(self) -> Dict[str, int]:
def _load_data(self) -> Dict[str, str]:
"""Get merged config."""
config = {}
if not SYSCTL_FILENAME.exists():
Expand All @@ -276,10 +288,10 @@ def _load_data(self) -> Dict[str, int]:

return config

def _parse_line(self, line: str) -> Dict[str, int]:
def _parse_line(self, line: str) -> Dict[str, str]:
"""Parse a line from juju-sysctl.conf file."""
if line.startswith("#") or line == "\n":
return {}

param, value = line.split("=")
return {param.strip(): int(value.strip())}
return {param.strip(): value.strip()}
4 changes: 2 additions & 2 deletions tests/unit/test_sysctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def test_load_data(self, mock_file, mock_exist):

mock_exist.assert_called()
mock_file.assert_called_with(Path("/etc/sysctl.d/95-juju-sysctl.conf"), "r")
assert config._data == {"vm.swappiness": 0, "vm.max_map_count": 262144}
assert config._data == {"vm.swappiness": "0", "vm.max_map_count": "262144"}

@patch("pathlib.Path.exists")
def test_load_data_no_path(self, mock_exist):
Expand Down Expand Up @@ -314,7 +314,7 @@ def test_parse_config(self, _):

config._parse_config({"key1": {"value": "10"}, "key2": {"value": "20"}})

self.assertEqual(config._desired_config, {"key1": 10, "key2": 20})
self.assertEqual(config._desired_config, {"key1": "10", "key2": "20"})

@patch("charms.operator_libs_linux.v0.sysctl.Config._load_data")
def test_class_methods(self, mock_load):
Expand Down

0 comments on commit aa727f2

Please sign in to comment.