Skip to content

Commit 7e76786

Browse files
committed
taking it a few commits back to resolve errors
1 parent febf2a0 commit 7e76786

File tree

2 files changed

+78
-50
lines changed

2 files changed

+78
-50
lines changed

scripts/hostcfgd

Lines changed: 71 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1694,44 +1694,83 @@ class FipsCfg(object):
16941694
syslog.syslog(syslog.LOG_INFO, f'FipsCfg: update the FIPS enforce option {self.enforce}.')
16951695
loader.set_fips(image, self.enforce)
16961696

1697-
class Memory_StatisticsCfg:
1697+
class Memory_StatisticsCfg(object):
1698+
"""
1699+
Memory Stats Config Daemon
1700+
Handles changes in MEMORY_STATS table.
1701+
1) Handle enabling or disabling the feature
1702+
2) Handle change of retention period
1703+
3) Handle change of sampling interval
1704+
"""
1705+
16981706
def __init__(self):
1699-
self.enabled = False
1700-
self.retention_time = 0
1701-
self.sampling_interval = 0
1707+
self.cache = {}
1708+
self.memory_statistics_defaults = {
1709+
"enabled": "false",
1710+
"retention_time": "15 days",
1711+
"sampling_interval": "5 minutes"
1712+
}
17021713

1703-
def load_config(self, config_data):
1704-
try:
1705-
config = json.loads(config_data)
1706-
self.enabled = config.get("enabled", self.enabled)
1707-
self.retention_time = config.get("retention_time", self.retention_time)
1708-
self.sampling_interval = config.get("sampling_interval", self.sampling_interval)
1709-
except json.JSONDecodeError:
1710-
raise ValueError("Invalid JSON format for configuration data")
1711-
1712-
def apply_config(self):
1713-
if self.enabled:
1714-
self._run_shell_command(f"set_memory_statistics --enable --retention-time {self.retention_time} --sampling-interval {self.sampling_interval}")
1715-
else:
1716-
self._run_shell_command("set_memory_statistics --disable")
1717-
1718-
def update_config(self, key, value):
1719-
if key == "enabled":
1720-
self.enabled = value
1721-
elif key == "retention_time":
1722-
self.retention_time = value
1723-
elif key == "sampling_interval":
1724-
self.sampling_interval = value
1714+
def load(self, memory_stats_config: dict):
1715+
"""
1716+
Load memory statistics configuration when the daemon starts.
1717+
Args:
1718+
memory_stats_config: Configured memory statistics settings.
1719+
"""
1720+
syslog.syslog(syslog.LOG_INFO, "Memory_StatisticsCfg init ...")
1721+
memory_statistics_conf = memory_stats_config.get("config", {})
1722+
1723+
# Apply default configurations if not present
1724+
for row, value in self.memory_statistics_defaults.items():
1725+
if not memory_statistics_conf.get(row):
1726+
self.config_db.mod_entry("MEMORY_STATISTICS", "config", {row: value})
1727+
1728+
# Apply configurations to ensure they are set correctly on startup
1729+
self.apply_configuration(memory_statistics_conf)
1730+
1731+
def apply_configuration(self, config):
1732+
"""
1733+
Apply the memory statistics configuration settings.
1734+
Args:
1735+
config: Configuration data for memory statistics.
1736+
"""
1737+
# Determine if the feature is enabled or disabled
1738+
enabled = config.get("enabled", self.memory_statistics_defaults["enabled"]).lower() == "true"
1739+
retention_time = config.get("retention_time", self.memory_statistics_defaults["retention_time"])
1740+
sampling_interval = config.get("sampling_interval", self.memory_statistics_defaults["sampling_interval"])
1741+
1742+
# Enable or disable memory statistics
1743+
if enabled:
1744+
self.run_cmd(["sonic-memory_statistics-config", "--enable"])
17251745
else:
1726-
raise ValueError(f"Unknown configuration key: {key}")
1746+
self.run_cmd(["sonic-memory_statistics-config", "--disable"])
17271747

1728-
self.apply_config()
1748+
# Set retention time and sampling interval
1749+
self.run_cmd(["sonic-memory_statistics-config", "--retention_time", retention_time])
1750+
self.run_cmd(["sonic-memory_statistics-config", "--sampling_interval", sampling_interval])
17291751

1730-
def _run_shell_command(self, command):
1731-
result = subprocess.run(command, shell=True, text=True, capture_output=True)
1732-
if result.returncode != 0:
1733-
raise RuntimeError(f"Shell command failed with error: {result.stderr}")
1752+
def memory_statistics_update(self, key, data):
1753+
"""
1754+
Handle updates to the memory statistics configuration.
1755+
Args:
1756+
key: Key identifying the config type.
1757+
data: Updated configuration data.
1758+
"""
1759+
syslog.syslog(syslog.LOG_INFO, "Memory_Statistics global configuration update")
1760+
if key == "config":
1761+
self.apply_configuration(data)
17341762

1763+
def run_cmd(self, cmd):
1764+
"""
1765+
Execute a shell command and return the output.
1766+
Args:
1767+
cmd: List of command arguments.
1768+
"""
1769+
try:
1770+
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
1771+
syslog.syslog(syslog.LOG_INFO, output.decode('utf-8'))
1772+
except subprocess.CalledProcessError as e:
1773+
syslog.syslog(syslog.LOG_ERR, e.output.decode('utf-8'))
17351774
class HostConfigDaemon:
17361775
def __init__(self):
17371776
self.state_db_conn = DBConnector(STATE_DB, 0)

tests/hostcfgd/hostcfgd_test.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -295,21 +295,11 @@ def test_dns_events(self):
295295
mocked_run_cmd.assert_has_calls([call(['systemctl', 'restart', 'resolv-config'], True, False)])
296296

297297
def test_memory_statistics_event(self):
298-
HOSTCFG_DAEMON_CFG_DB = {
299-
'MEMORY_STATISTICS': {
300-
'config': {
301-
'enabled': 'true',
302-
'retention_time': '15 days',
303-
'sampling_interval': '5 minutes'
304-
}
305-
}
306-
}
307-
308298
MockConfigDb.set_config_db(HOSTCFG_DAEMON_CFG_DB)
309299
daemon = hostcfgd.HostConfigDaemon()
310300
daemon.register_callbacks()
311301
MockConfigDb.event_queue = [('MEMORY_STATISTICS', 'config')]
312-
302+
313303
with mock.patch('hostcfgd.subprocess') as mocked_subprocess:
314304
popen_mock = mock.Mock()
315305
attrs = {'communicate.return_value': ('output', 'error')}
@@ -322,15 +312,14 @@ def test_memory_statistics_event(self):
322312
except TimeoutError:
323313
pass
324314

325-
expected_calls = [
315+
expected = [
326316
mock.call(['sonic-memory_statistics-config', '--enable']),
327-
mock.call(['sonic-memory_statistics-config', '--retention_time', '15 days']),
328-
mock.call(['sonic-memory_statistics-config', '--sampling_interval', '5 minutes'])
317+
mock.call(['sonic-memory_statistics-config', '--retention_time', '15']),
318+
mock.call(['sonic-memory_statistics-config', '--sampling_interval', '5'])
329319
]
330-
331-
mocked_subprocess.check_call.assert_has_calls(expected_calls, any_order=True)
332-
333-
320+
321+
mocked_subprocess.check_call.assert_has_calls(expected, any_order=True)
322+
334323
class TestDnsHandler:
335324

336325
@mock.patch('hostcfgd.run_cmd')

0 commit comments

Comments
 (0)