Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions simplyblock_core/snode_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 5 additions & 2 deletions simplyblock_core/storage_node_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}",
Expand Down
97 changes: 87 additions & 10 deletions simplyblock_core/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1996,16 +1996,16 @@ 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):
"""Return the per-NUMA user hugepage baseline, persisted across calls within a boot.

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.
"""
Expand All @@ -2032,25 +2032,102 @@ 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:
with open(hugepage_path, "r") as f:
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?")
Expand Down
38 changes: 38 additions & 0 deletions simplyblock_web/api/internal/storage_node/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
9 changes: 9 additions & 0 deletions simplyblock_web/api/internal/storage_node/kubernetes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
4 changes: 2 additions & 2 deletions simplyblock_web/templates/storage_deploy_spdk.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions simplyblock_web/templates/storage_init_job.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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}"
Expand Down
Loading
Loading