diff --git a/simplyblock_core/snode_client.py b/simplyblock_core/snode_client.py index 803afcd4cf..07eb17b1da 100644 --- a/simplyblock_core/snode_client.py +++ b/simplyblock_core/snode_client.py @@ -204,6 +204,15 @@ def spdk_proxy_restart(self,rpc_port=None): def set_hugepages(self): return self._request("POST", "set_hugepages") + def persist_node_config(self, max_lvol, huge_page_memory, numa_node, ssd_list): + payload = { + "max_lvol": max_lvol, + "huge_page_memory": huge_page_memory, + "numa_node": numa_node, + "ssd_list": ssd_list, + } + return self._request("POST", "persist_node_config", payload) + def ifc_is_roce(self, nic): params = {"nic": nic} return self._request("GET", "ifc_is_roce", params) diff --git a/simplyblock_core/storage_node_ops.py b/simplyblock_core/storage_node_ops.py index 2ac9acb5da..9c4f11c37f 100755 --- a/simplyblock_core/storage_node_ops.py +++ b/simplyblock_core/storage_node_ops.py @@ -2546,7 +2546,8 @@ def _restart_storage_node_impl( logger.info("Restarting SPDK") - if max_lvol: + lvol_changed = bool(max_lvol) and max_lvol != snode.max_lvol + if lvol_changed: snode.max_lvol = max_lvol if max_snap: snode.max_snap = max_snap @@ -2644,6 +2645,8 @@ def _restart_storage_node_impl( snode.ssd_pcie.append(new_ssd) fdb_connection = cluster.db_connection + if lvol_changed: + snode_api.persist_node_config(snode.max_lvol, minimum_hp_memory, snode.socket, snode.ssd_pcie) snode_api.set_hugepages() results, err = snode_api.spdk_process_start( snode.l_cores, snode.spdk_mem, snode.spdk_image, spdk_debug, cluster_ip, fdb_connection, @@ -4134,7 +4137,7 @@ def start_storage_node_api_container(node_ip, cluster_ip=None): # has to fall through to dockerd, which can stall for 60-80s # during post-outage Swarm reconciliation (incident 2026-04-24). '/mnt/ramdisk:/mnt/ramdisk', - '/tmp/simplyblock:/tmp/simplyblock'], + '/var/run/simplyblock:/var/run/simplyblock'], restart_policy={"Name": "always"}, environment=[ f"DOCKER_IP={node_ip}", diff --git a/simplyblock_core/utils/__init__.py b/simplyblock_core/utils/__init__.py index 4bf94c2d56..82fc5ee151 100644 --- a/simplyblock_core/utils/__init__.py +++ b/simplyblock_core/utils/__init__.py @@ -1996,7 +1996,7 @@ def format_device_with_4k(pci_device): logger.error(f"Failed to format device with 4K {e}") -_HUGEPAGES_BASELINE_DIR = "/tmp/simplyblock" +_HUGEPAGES_BASELINE_DIR = "/var/run/simplyblock" def _get_user_hugepages_baseline(node, current_hugepages): @@ -2004,8 +2004,8 @@ def _get_user_hugepages_baseline(node, current_hugepages): On first call for a given NUMA node (no baseline file), the current allocatable hugepage count is the user's reservation — simplyblock hasn't touched it yet. - That value is written to /tmp/simplyblock/hugepages_baseline_node{N}. - On subsequent calls the file is read directly; /tmp/simplyblock is cleared on + That value is written to /var/run/simplyblock/hugepages_baseline_node{N}. + On subsequent calls the file is read directly; /var/run/simplyblock is cleared on reboot (host tmpfs / Docker/K8s hostPath volume) so the baseline is always fresh after a reboot. """ @@ -2032,8 +2032,45 @@ def _get_user_hugepages_baseline(node, current_hugepages): return current_hugepages +def _get_sb_hugepages_allocation(node): + """Return the simplyblock hugepage allocation stored from the previous deploy, or None.""" + sb_file = os.path.join(_HUGEPAGES_BASELINE_DIR, f"hugepages_sb_node{node}") + if os.path.exists(sb_file): + try: + with open(sb_file) as f: + val = int(f.read().strip()) + logger.debug(f"Node {node}: previous simplyblock hugepage allocation from cache: {val}") + return val + except Exception as e: + logger.warning(f"Node {node}: could not read sb allocation file {sb_file}: {e}") + return None + + +def _save_sb_hugepages_allocation(node, hugepages_needed) -> bool: + sb_file = os.path.join(_HUGEPAGES_BASELINE_DIR, f"hugepages_sb_node{node}") + try: + os.makedirs(_HUGEPAGES_BASELINE_DIR, exist_ok=True) + with open(sb_file, "w") as f: + f.write(str(hugepages_needed)) + return True + except Exception as e: + logger.warning(f"Node {node}: could not save sb allocation to {sb_file}: {e}") + return False + + +def _save_user_hugepages_baseline(node, baseline): + baseline_file = os.path.join(_HUGEPAGES_BASELINE_DIR, f"hugepages_baseline_node{node}") + try: + os.makedirs(_HUGEPAGES_BASELINE_DIR, exist_ok=True) + with open(baseline_file, "w") as f: + f.write(str(baseline)) + logger.debug(f"Node {node}: saved updated hugepage baseline: {baseline} -> {baseline_file}") + except Exception as e: + logger.warning(f"Node {node}: could not save hugepage baseline to {baseline_file}: {e}") + + def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048): - """Set hugepages for a specific NUMA node if current number is less than needed.""" + """Set hugepages for a specific NUMA node, adjusting up or down based on previous allocation.""" hugepage_path = f"/sys/devices/system/node/node{node}/hugepages/hugepages-{page_size_kb}kB/nr_hugepages" try: @@ -2041,16 +2078,56 @@ def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048): current_hugepages = int(f.read().strip()) user_baseline = _get_user_hugepages_baseline(node, current_hugepages) - required = user_baseline + hugepages_needed - - if current_hugepages >= required: - logger.debug(f"Node {node}: already has {current_hugepages} hugepages >= required {required}, no change needed.") + prev_sb = _get_sb_hugepages_allocation(node) + + if prev_sb is not None: + # prev_sb is the adjusted total last written to the kernel, so the + # delta from that value captures manual user changes since the last + # deploy (rounding overhead is not mistaken for user additions). + user_delta = current_hugepages - prev_sb + if user_delta > 0: + # nr_hugepages grew beyond what we last set — the user added + # hugepages. Absorb it into the baseline so it persists across + # every future restart, not just the next one. + current_user = user_baseline + user_delta + _save_user_hugepages_baseline(node, current_user) + logger.info(f"Node {node}: user hugepage baseline updated {user_baseline} -> {current_user} (delta={user_delta:+d})") + else: + # user_delta <= 0: nr_hugepages is at or BELOW what we last + # wrote. This is almost always a reset (a reboot zeroes the + # runtime allocation while the persisted prev_sb survives), NOT + # a deliberate user removal. Treating it as a removal drove the + # user baseline negative and produced a negative nr_hugepages + # write that failed with "Invalid argument", looping forever + # (observed 2026-07-07: baseline 0 -> -7168 -> -14336 -> ...). + # Keep the established user baseline and simply re-apply. + current_user = user_baseline + if user_delta < 0: + logger.info(f"Node {node}: nr_hugepages ({current_hugepages}) below last-set ({prev_sb}); " + f"treating as reset, keeping user baseline {user_baseline}") else: - required = adjust_hugepages(required) - logger.debug(f"Node {node}: setting to {required} (user baseline={user_baseline} + simplyblock={hugepages_needed})...") + # First deploy: use the captured pre-deploy baseline + current_user = user_baseline + + # Never write a negative or below-requirement value: the user baseline + # is clamped to >= 0, and the final total can never drop below what + # simplyblock itself needs. + current_user = max(current_user, 0) + required = adjust_hugepages(current_user + hugepages_needed) + required = max(required, hugepages_needed) + logger.debug(f"Node {node}: setting to {required} (user={current_user} + simplyblock={hugepages_needed})") + + if current_hugepages != required: cmd = f"echo {required} | sudo tee /sys/devices/system/node/node{node}/hugepages/hugepages-2048kB/nr_hugepages" subprocess.run(cmd, shell=True, check=True) logger.debug(f"Node {node}: hugepages updated to {required}.") + else: + logger.debug(f"Node {node}: already has {current_hugepages} hugepages == required {required}, no change needed.") + + # Store the adjusted total (what was actually written to the kernel) so + # the next deploy computes user_delta = current - prev_total correctly. + if not _save_sb_hugepages_allocation(node, required): + logger.error(f"Node {node}: failed to persist hugepage allocation — delta tracking will be incorrect on next restart") except FileNotFoundError: logger.error(f"Node {node}: Hugepage path not found. Is hugepage support enabled?") diff --git a/simplyblock_web/api/internal/storage_node/docker.py b/simplyblock_web/api/internal/storage_node/docker.py index d31c01c5ce..45265c3a3f 100644 --- a/simplyblock_web/api/internal/storage_node/docker.py +++ b/simplyblock_web/api/internal/storage_node/docker.py @@ -766,6 +766,44 @@ def bind_device_to_spdk(body: utils.DeviceParams): return utils.get_response(True) +class PersistNodeConfigParams(BaseModel): + max_lvol: Optional[int] = Field(None, ge=0) + huge_page_memory: Optional[int] = Field(None, ge=0) + numa_node: Optional[int] = Field(None, ge=0) + ssd_list: Optional[List[str]] = Field(None) + + +@api.post('/persist_node_config', responses={ + 200: {'content': {'application/json': {'schema': utils.response_schema({ + 'type': 'boolean' + })}}}, +}) +def persist_node_config(body: PersistNodeConfigParams): + node_info = core_utils.load_config(constants.NODES_CONFIG_FILE) + if not node_info.get("nodes"): + return utils.get_response(False, "Config not found") + + ssd_set = set(body.ssd_list) if body.ssd_list is not None else None + matched = False + for node_config in node_info["nodes"]: + if body.numa_node is not None and node_config["socket"] != body.numa_node: + continue + if ssd_set is not None and not ssd_set.intersection(set(node_config.get("ssd_pcis", []))): + continue + if body.max_lvol is not None: + node_config["max_lvol"] = body.max_lvol + if body.huge_page_memory is not None: + node_config["huge_page_memory"] = body.huge_page_memory + matched = True + break + + if not matched: + return utils.get_response(False, "No matching node found for given numa_node and ssd_list") + + core_utils.store_config_file(node_info, constants.NODES_CONFIG_FILE) + return utils.get_response(True) + + @api.post('/set_hugepages', responses={ 200: {'content': {'application/json': {'schema': utils.response_schema({ 'type': 'boolean' diff --git a/simplyblock_web/api/internal/storage_node/kubernetes.py b/simplyblock_web/api/internal/storage_node/kubernetes.py index b0abd91c09..3e717646b4 100644 --- a/simplyblock_web/api/internal/storage_node/kubernetes.py +++ b/simplyblock_web/api/internal/storage_node/kubernetes.py @@ -670,6 +670,15 @@ def get_firewall(): return utils.get_response(False, "deprecated bath get snode/get_firewall") +@api.post('/persist_node_config', responses={ + 200: {'content': {'application/json': {'schema': utils.response_schema({ + 'type': 'boolean' + })}}}, +}) +def persist_node_config(body: snode_ops.PersistNodeConfigParams): + return snode_ops.persist_node_config(body) + + @api.post('/set_hugepages', responses={ 200: {'content': {'application/json': {'schema': utils.response_schema({ 'type': 'boolean' diff --git a/simplyblock_web/templates/storage_deploy_spdk.yaml.j2 b/simplyblock_web/templates/storage_deploy_spdk.yaml.j2 index 0b65007322..0b3758bef3 100755 --- a/simplyblock_web/templates/storage_deploy_spdk.yaml.j2 +++ b/simplyblock_web/templates/storage_deploy_spdk.yaml.j2 @@ -41,7 +41,7 @@ spec: path: /var/simplyblock - name: tmp-simplyblock hostPath: - path: /tmp/simplyblock + path: /var/run/simplyblock type: DirectoryOrCreate - name: host-modules hostPath: @@ -147,7 +147,7 @@ spec: - name: socket-dir mountPath: /mnt/ramdisk - name: tmp-simplyblock - mountPath: /tmp/simplyblock + mountPath: /var/run/simplyblock {% if TLS_SERVE or TLS_CONNECT != "disabled" %} - name: tls mountPath: /etc/simplyblock/tls diff --git a/simplyblock_web/templates/storage_init_job.yaml.j2 b/simplyblock_web/templates/storage_init_job.yaml.j2 index df34351201..b563b37f84 100755 --- a/simplyblock_web/templates/storage_init_job.yaml.j2 +++ b/simplyblock_web/templates/storage_init_job.yaml.j2 @@ -23,7 +23,7 @@ spec: path: /proc - name: tmp-simplyblock hostPath: - path: /tmp/simplyblock + path: /var/run/simplyblock type: DirectoryOrCreate {% if TLS_CONNECT == "authenticated" %} - name: tls @@ -39,7 +39,7 @@ spec: - name: host-proc mountPath: /proc - name: tmp-simplyblock - mountPath: /tmp/simplyblock + mountPath: /var/run/simplyblock {% if TLS_CONNECT == "authenticated" %} - name: tls mountPath: /etc/simplyblock/tls @@ -68,7 +68,7 @@ spec: hp_path="${numa_dir}hugepages/hugepages-2048kB/nr_hugepages" if [ -f "$hp_path" ]; then hp_count=$(cat "$hp_path") - baseline_file="/tmp/simplyblock/hugepages_baseline_node${node_id}" + baseline_file="/var/run/simplyblock/hugepages_baseline_node${node_id}" if [ ! -f "$baseline_file" ]; then echo "$hp_count" > "$baseline_file" echo "[INFO] NUMA ${node_id}: wrote hugepage baseline ${hp_count}" diff --git a/tests/test_hugepages_baseline.py b/tests/test_hugepages_baseline.py new file mode 100644 index 0000000000..bb42ce88a8 --- /dev/null +++ b/tests/test_hugepages_baseline.py @@ -0,0 +1,236 @@ +# coding=utf-8 +"""Regression tests for hugepage reservation across node restarts. + +`set_hugepages_if_needed` writes an *absolute* `nr_hugepages` computed as +"the user's own pre-existing reservation + what simplyblock needs". The user's +reservation is not observable once simplyblock has written to the node, so it +is remembered in two files under `_HUGEPAGES_BASELINE_DIR`: + + hugepages_baseline_node{N} the user's reservation + hugepages_sb_node{N} the total simplyblock last wrote to the kernel + +If either is lost, the already-inflated `nr_hugepages` is mistaken for the +user's reservation and simplyblock's requirement is added on top of itself -- +every `sn restart` then grows the reservation by the full requirement. That is +what these tests pin down: a restart must be a no-op, and the state must live +somewhere that survives a container restart (a host tmpfs, not `/tmp`). +""" + +import inspect +import pathlib +import re +import subprocess + +import pytest + +from simplyblock_core import storage_node_ops, utils + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] +TEMPLATE_DIR = REPO_ROOT / "simplyblock_web" / "templates" + + +NEEDED = 7168 # 14 GiB of 2 MiB pages, a typical single-node requirement +NEEDED_TOTAL = 7680 # adjust_hugepages(7168) -- rounded up with headroom + + +class FakeHost: + """A single-NUMA-node host whose nr_hugepages lives in a temp file.""" + + def __init__(self, tmp_path, monkeypatch, nr_hugepages=0): + self.state_dir = tmp_path / "run" / "simplyblock" + self._nr_file = tmp_path / "nr_hugepages" + self._nr_file.write_text(str(nr_hugepages)) + self.writes: list = [] + + real_open = open + + def _open(path, *args, **kwargs): + if isinstance(path, str) and path.startswith("/sys/devices/system/node/"): + return real_open(self._nr_file, *args, **kwargs) + return real_open(path, *args, **kwargs) + + # `open` and `subprocess` are shadowed in the utils module namespace + # only, so the real sysfs is never touched and the `tee` shell-out is + # intercepted instead of executed. + monkeypatch.setattr(utils, "open", _open, raising=False) + monkeypatch.setattr(utils, "subprocess", self, raising=True) + monkeypatch.setattr(utils, "_HUGEPAGES_BASELINE_DIR", str(self.state_dir)) + + def run(self, cmd, shell=False, check=False): + """Stand in for `subprocess.run("echo N | sudo tee ")`.""" + match = re.match(r"echo (-?\d+) \| sudo tee (\S+)", cmd) + assert match is not None, f"unexpected command: {cmd}" + value = int(match.group(1)) + self.writes.append(value) + if value < 0: + # The kernel rejects a negative write with "Invalid argument". + raise subprocess.CalledProcessError(1, cmd) + self._nr_file.write_text(str(value)) + + @property + def nr_hugepages(self): + return int(self._nr_file.read_text().strip()) + + def set_nr_hugepages(self, value): + self._nr_file.write_text(str(value)) + + def state(self, name): + path = self.state_dir / name + return int(path.read_text().strip()) if path.exists() else None + + def drop_state(self): + """Simulate losing the state directory (container restart, /tmp sweep).""" + for path in self.state_dir.glob("hugepages_*"): + path.unlink() + + +@pytest.fixture +def host(tmp_path, monkeypatch): + return FakeHost(tmp_path, monkeypatch) + + +def test_state_dir_survives_a_container_restart(): + """The state must not live in the container or in a swept directory. + + `/tmp` is pruned by systemd-tmpfiles-clean (10-day TTL on RHEL family), and + a path the storage-node API pod does not host-mount is destroyed with the + container. Either loses the baseline while nr_hugepages stays inflated. + """ + assert utils._HUGEPAGES_BASELINE_DIR == "/var/run/simplyblock" + + +@pytest.mark.parametrize( + "template", + ["storage_init_job.yaml.j2", "storage_deploy_spdk.yaml.j2"], +) +def test_k8s_templates_host_mount_the_state_dir(template): + """The k8s pods must bind the state dir to the same path on the host. + + The storage-node init job captures the user's baseline and the API pod + reads it back. If either resolves `_HUGEPAGES_BASELINE_DIR` inside its own + container instead of on the host, the two never see the same file and the + baseline is re-captured -- from an already-inflated nr_hugepages -- on the + next restart. + """ + text = (TEMPLATE_DIR / template).read_text() + state_dir = utils._HUGEPAGES_BASELINE_DIR + + assert f"path: {state_dir}\n" in text, f"{template} does not hostPath {state_dir}" + assert f"mountPath: {state_dir}\n" in text, f"{template} does not mount {state_dir}" + + +def test_init_job_writes_the_baseline_into_the_mounted_state_dir(): + text = (TEMPLATE_DIR / "storage_init_job.yaml.j2").read_text() + match = re.search(r'baseline_file="([^"]+)"', text) + + assert match is not None, "init job no longer captures a hugepage baseline" + assert match.group(1).startswith(utils._HUGEPAGES_BASELINE_DIR + "/") + + +def test_docker_snode_api_container_bind_mounts_the_state_dir(): + """Docker mounts are fixed for a container's lifetime, and `cluster upgrade` + never recreates SNodeAPI -- so a wrong path here is only fixed by `sn deploy`. + """ + source = inspect.getsource(storage_node_ops.start_storage_node_api_container) + state_dir = utils._HUGEPAGES_BASELINE_DIR + + assert f"'{state_dir}:{state_dir}'" in source + + +def test_first_deploy_treats_the_current_reservation_as_the_user_s(host): + utils.set_hugepages_if_needed(0, NEEDED) + + assert host.nr_hugepages == NEEDED_TOTAL + assert host.state("hugepages_baseline_node0") == 0 + assert host.state("hugepages_sb_node0") == NEEDED_TOTAL + + +def test_restart_does_not_grow_the_reservation(host): + """The reported fault: every `sn restart` added the requirement again.""" + utils.set_hugepages_if_needed(0, NEEDED) + after_deploy = host.nr_hugepages + + for _ in range(3): + utils.set_hugepages_if_needed(0, NEEDED) + assert host.nr_hugepages == after_deploy + + # Only the initial deploy should have written to the kernel at all. + assert host.writes == [NEEDED_TOTAL] + + +def test_sb_file_records_the_written_total_not_the_raw_requirement(host): + """Drift guard: the delta on the next run is measured against what we wrote. + + Storing the unrounded requirement made the rounding headroom look like a + manual user addition on the following restart. + """ + utils.set_hugepages_if_needed(0, NEEDED) + + assert host.state("hugepages_sb_node0") == NEEDED_TOTAL + assert host.state("hugepages_sb_node0") != NEEDED + + +def test_a_pre_existing_user_reservation_is_added_once(tmp_path, monkeypatch): + host = FakeHost(tmp_path, monkeypatch, nr_hugepages=2000) + + utils.set_hugepages_if_needed(0, NEEDED) + assert host.state("hugepages_baseline_node0") == 2000 + after_deploy = host.nr_hugepages + assert after_deploy > 2000 + NEEDED + + utils.set_hugepages_if_needed(0, NEEDED) + assert host.nr_hugepages == after_deploy + + +def test_manual_user_addition_survives_repeated_restarts(host): + """A user adding pages between restarts must not be reverted or re-added.""" + utils.set_hugepages_if_needed(0, NEEDED) + host.set_nr_hugepages(host.nr_hugepages + 1000) + + utils.set_hugepages_if_needed(0, NEEDED) + assert host.state("hugepages_baseline_node0") == 1000 + absorbed = host.nr_hugepages + assert absorbed > NEEDED_TOTAL + + # Second restart: the addition is already in the baseline, so it is neither + # dropped (reverting the user's change) nor counted twice. + utils.set_hugepages_if_needed(0, NEEDED) + assert host.nr_hugepages == absorbed + assert host.state("hugepages_baseline_node0") == 1000 + + +def test_reboot_reapplies_the_requirement_without_a_negative_write(host): + """A reboot zeroes nr_hugepages while the state files survive. + + Reading that as "the user removed pages" drove the baseline negative, and + `echo -512 | tee nr_hugepages` fails, so the node never got its pages. + """ + utils.set_hugepages_if_needed(0, NEEDED) + host.set_nr_hugepages(0) # reboot: runtime allocation gone, state kept + + utils.set_hugepages_if_needed(0, NEEDED) + + assert host.nr_hugepages == NEEDED_TOTAL + assert host.state("hugepages_baseline_node0") == 0 + assert all(value >= 0 for value in host.writes) + + +def test_a_smaller_requirement_shrinks_the_reservation(host): + """Over-provisioned nodes must be able to give pages back.""" + utils.set_hugepages_if_needed(0, NEEDED) + assert host.nr_hugepages == NEEDED_TOTAL + + utils.set_hugepages_if_needed(0, 3000) + + assert host.nr_hugepages < NEEDED_TOTAL + assert host.nr_hugepages >= 3000 + + +def test_the_written_total_never_drops_below_the_requirement(host): + utils.set_hugepages_if_needed(0, NEEDED) + host.drop_state() + host.set_nr_hugepages(0) + + utils.set_hugepages_if_needed(0, NEEDED) + + assert host.nr_hugepages >= NEEDED