Skip to content
Open
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
50 changes: 50 additions & 0 deletions simplyblock_core/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,41 @@ def get_config_var(name, default=None):
# released, the volume replicates on its ordinary cadence, and the endgame is
# retried after this long (the abandon burns one attempt of the task's budget).
REPL_CUTOVER_ENDGAME_BACKOFF_SEC = 300
# --- a migration must not fill its source cluster (bed bf29, 2026-11-20) ---
# Five endgames of one source cluster at once, under sustained overwrite, took
# a shrink snapshot every 15-30 s each; every one pinned what the client
# overwrote after it, and their deletions fell behind: 41% -> 99% in 16 min.
# See simplyblock_core/migration_space.py. These hold back only the
# migration's own snapshots -- never client IO or client volume creation.
#
# Cutover endgames (shrink-round phase) running at once per SOURCE cluster.
# The others replicate on their ordinary cadence while they wait for a slot.
REPL_CUTOVER_MAX_ENDGAMES_PER_CLUSTER = 1
# An endgame takes its next round snapshot only once none of the volume's
# snapshots is still in deletion -- for at most this long per wait: a deletion
# that is stuck (no leader, a clone in deletion) must not stall the endgame
# into its shrink deadline on its own. The free-space check still applies.
REPL_ENDGAME_DELETION_WAIT_MAX_SEC = 300
# A migration snapshot needs this many times the bytes written to the volume
# since its last snapshot free on the source (the snapshot pins them, and the
# client overwrites about as much again while the round transfers) ...
REPL_MIGRATION_HEADROOM_FACTOR = 2
# ... and never less than this share of the cluster (other volumes' writes,
# and the capacity record being up to a collector interval old).
REPL_MIGRATION_MIN_FREE_PCT = 5
# A cluster capacity record older than this is no reading (the collector
# writes one every DEV_STAT_COLLECTOR_INTERVAL_SEC).
REPL_MIGRATION_CAPACITY_STALE_SEC = 120
# Without a usable capacity reading a migration snapshot waits this long, then
# goes ahead without the check (logged): a broken stats collector must not
# stop migrations for good.
REPL_MIGRATION_CAPACITY_UNKNOWN_WAIT_SEC = 120
# A cutover endgame whose target node is down before its clone exists cannot
# progress, and holds its volume out of ordinary replication while it waits
# (bed bf29 R3b: RPO 1280 s). After this long it is given up -- no attempt
# burned, no back-off -- and the volume replicates on its cadence until the
# target is back.
REPL_CUTOVER_TARGET_DOWN_GRACE_SEC = 60
# --- cutover source throttle ----------------------------------------------
# A round converges to overhead / (1 - W/T): with the application writing at
# W and the delta transferring at T, no number of rounds gets under the
Expand Down Expand Up @@ -896,6 +931,14 @@ def get_config_var(name, default=None):
# leader within about a minute of its primary going down (crashed or shut
# down); a wait beyond this means no member could be proven safe to lead.
REPL_TARGET_LEADERLESS_ALERT_SEC = 180
# A transfer that has waited this long for a target lvstore whose members are
# ALL online asks the control plane's guarded leaderless recovery
# (storage_node_ops.restore_healthy_lvs_leadership) to give it a leader, then
# at most every REPL_TARGET_LEADERLESS_RECOVER_EVERY_SEC. A primary SPDK that
# dropped the leadership itself takes it back only on IO, and a target gets
# none while replication waits (bf32 2026-11-21: LVS_7/LVS_10, 76 min).
REPL_TARGET_LEADERLESS_RECOVER_SEC = 60
REPL_TARGET_LEADERLESS_RECOVER_EVERY_SEC = 120
# Pass interval of the snapshot replication runner while any transfer or
# merge is in flight; TASK_EXEC_INTERVAL_SEC when idle. Not sub-second: each
# pass reads the task table (see test_transfer_completion_latency).
Expand All @@ -911,6 +954,13 @@ def get_config_var(name, default=None):
REPL_RUNNER_WORKERS = int(os.getenv("REPL_RUNNER_WORKERS", "8"))
# Pause before a task that returned a failure is dispatched again.
REPL_RUNNER_RETRY_PAUSE_SEC = 3.0
# An in_creation landing volume (REP_*) whose create is not running in this
# runner and that no other live task of its snapshot may be creating is taken
# for a dead attempt's leftover and deleted only after this long. Landing
# creates take up to ~50 s on a loaded target (bed bf13); bed bf32 (2026-11-21)
# deleted one 2 s into its create, which left a stale registration on the
# secondaries.
REPL_LANDING_ABANDON_SEC = int(os.getenv("REPL_LANDING_ABANDON_SEC", "600"))
# Requests a replication transfer keeps in flight. A full transfer sends one
# whole cluster per request (16 x 2 MiB = 32 MiB in flight); a delta
# (allow_partial) sends at most 64 KiB per request, so it needs a deeper window
Expand Down
8 changes: 5 additions & 3 deletions simplyblock_core/controllers/lvol_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -1606,9 +1606,11 @@ def _create_bdev_stack(lvol, snode, is_primary=True):
if not ret:
raise
else:
ret = rpc_client.bdev_lvol_register(
lvol.lvol_bdev, lvol.lvs_name, lvol.lvol_uuid, lvol.blobid,
qos_controller.wire_priority_class(snode.cluster_id, lvol.lvol_priority_class))
from simplyblock_core.controllers.lvol_register import register_lvol
ret = register_lvol(
rpc_client, lvol.lvol_bdev, lvol.lvs_name, lvol.lvol_uuid, lvol.blobid,
qos_controller.wire_priority_class(snode.cluster_id, lvol.lvol_priority_class),
cluster_id=snode.cluster_id, node_label=snode.get_id())

elif type == "bdev_lvol_clone":
if is_primary:
Expand Down
23 changes: 23 additions & 0 deletions simplyblock_core/controllers/lvol_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,26 @@ def replication_target_leaderless(lvol, lvs_name, waited_s, why, caused_by=ec.CA
f"{lvs_name} has had no leader for {int(waited_s)}s ({why})"),
node_id=lvol.get_id(),
event_level=EventObj.LEVEL_ERROR)


def migration_space_low(lvol, reason, caused_by=ec.CAUSED_BY_MONITOR):
"""A migration snapshot of *lvol* waits for free space on its source
cluster (simplyblock_core/migration_space.py). Warning level: client IO
is not affected, only the migration's own snapshots wait. Raised once per
wait, when it starts."""
from simplyblock_core.models.events import EventObj
try:
cluster_id = DBController().get_pool_by_id(lvol.pool_uuid).cluster_id
except Exception as e:
logger.error(f"No cluster could be resolved for lvol {lvol.get_id()}; event not logged: {e}")
return
ec.log_event_cluster(
cluster_id=cluster_id,
domain=ec.DOMAIN_CLUSTER,
event=ec.EVENT_REPLICATION_STALLED,
db_object=lvol,
caused_by=caused_by,
message=(f"Migration of LVol {lvol.get_id()} is waiting for free space on its "
f"source cluster: {reason}"),
node_id=lvol.get_id(),
event_level=EventObj.LEVEL_WARN)
123 changes: 123 additions & 0 deletions simplyblock_core/controllers/lvol_register.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""Registering a leader's lvol on a secondary (``bdev_lvol_register``).

The secondary opens the blob the leader created and exposes it as an lvol
bdev. SPDK (spdk #98) refuses that with -EEXIST when another lvol of the
lvstore is already registered on the same blob id: a stale lvol the leader
deleted but this node never removed, whose blob id the leader then reused.
Before that check the new lvol silently shared the stale lvol's open blob
handle, and deleting either one freed the handle under the other (bed bf32,
2026-11-21: two secondaries crashed with SIGSEGV in vbdev_lvol_resv_refresh).

A refused register used to fail like any other, and the stale lvol stayed:
every later reuse of that blob id failed on this node again. Here the stale
lvol is removed and the register retried once, but only when the control plane
has no live record of it. An lvol the control plane still knows is never
deleted on a guess; the register fails as before and says why.
"""

import errno
import logging

from simplyblock_core.db_controller import DBController
from simplyblock_core.models.lvol_model import LVol
from simplyblock_core.rpc_client import RPCRemoteError

logger = logging.getLogger(__name__)

# A record in one of these states is the control plane's own deletion in
# progress: its lvol on a secondary is what the deletion would remove anyway.
_GOING = (LVol.STATUS_IN_DELETION, LVol.STATUS_DELETED)


def _holder_on_blob(rpc_client, lvs_name, blobid):
"""The lvol of ``lvs_name`` registered on ``blobid`` on this node, or None."""
for lv in rpc_client.bdev_lvol_get_lvols(lvs_name) or []:
try:
if int(lv.get("blobid", -1)) == int(blobid):
return lv
except (TypeError, ValueError):
continue
return None


def _live_record(cluster_id, lvs_name, name, uuid, db=None):
"""A control-plane volume record that still owns the lvol ``name``/``uuid``."""
db = db or DBController()
for rec in db.get_lvols(cluster_id):
if rec.lvs_name != lvs_name:
continue
if rec.lvol_bdev != name and rec.lvol_uuid != uuid:
continue
if rec.status in _GOING:
continue
return rec
return None


def stale_lvol_to_remove(rpc_client, lvs_name, lvol_name, lvol_uuid, blobid, cluster_id, db=None):
"""Decide what a refused register (-EEXIST) found on ``blobid``.

Returns ``(holder, reason, is_self)``. ``holder`` is the stale lvol (as
reported by ``bdev_lvol_get_lvols``) that may be removed, or None with
``reason`` saying why nothing will be removed. ``is_self``: the lvol on
the blob is the one being registered (a repeated register).
"""
holder = _holder_on_blob(rpc_client, lvs_name, blobid)
if holder is None:
return None, f"no lvol of {lvs_name} is registered on blob {blobid} here", False
name, uuid = holder.get("name", ""), holder.get("uuid", "")
if name == lvol_name or (lvol_uuid and uuid == lvol_uuid):
return None, f"{lvs_name}/{name} is this lvol, already registered", True
if holder.get("is_snapshot"):
# Removing a snapshot re-parents or drops its clones: never on a guess.
return None, f"blob {blobid} is held by snapshot {lvs_name}/{name}", False
rec = _live_record(cluster_id, lvs_name, name, uuid, db=db)
if rec is not None:
return None, (f"blob {blobid} is held by {lvs_name}/{name}, which the control plane "
f"still knows as lvol {rec.get_id()} ({rec.status})"), False
return holder, "", False


def register_lvol(rpc_client, lvol_name, lvs_name, lvol_uuid, blobid, priority_class=0, *,
cluster_id, node_label="", db=None):
"""``bdev_lvol_register`` that clears a stale lvol on the same blob id.

Same result as ``rpc_client.bdev_lvol_register``. On -EEXIST the stale
lvol is removed (sync delete on this node, confirmed gone) and the
register is retried once; when it may not be removed, the original error
is raised.
"""
try:
return rpc_client.bdev_lvol_register(lvol_name, lvs_name, lvol_uuid, blobid, priority_class)
except RPCRemoteError as e:
if e.code != -errno.EEXIST:
raise
refused = e

where = f" on {node_label}" if node_label else ""
holder, reason, is_self = stale_lvol_to_remove(
rpc_client, lvs_name, lvol_name, lvol_uuid, blobid, cluster_id, db=db)
if holder is None:
if is_self:
logger.info(f"register {lvs_name}/{lvol_name}{where}: {reason}")
return rpc_client.bdev_get(f"{lvs_name}/{lvol_name}") or True
logger.error(f"register {lvs_name}/{lvol_name} (blob {blobid}){where} refused "
f"(EEXIST) and not cleared: {reason}")
raise refused

stale = f"{lvs_name}/{holder.get('name')}"
logger.warning(
f"register {lvs_name}/{lvol_name} (blob {blobid}){where} refused: stale lvol {stale} "
f"(uuid {holder.get('uuid')}) is still registered on that blob, the leader deleted "
f"it and reused the id. Removing it here and retrying")
try:
rpc_client.delete_lvol(stale, sync=True)
except RPCRemoteError as e:
if e.code != -errno.ENODEV:
logger.error(f"delete of stale lvol {stale}{where} failed: {e}")
raise refused from e
if rpc_client.bdev_get(stale) is not None:
logger.error(f"stale lvol {stale}{where} is still present after its delete; "
f"not registering {lvs_name}/{lvol_name} on blob {blobid}")
raise refused
return rpc_client.bdev_lvol_register(lvol_name, lvs_name, lvol_uuid, blobid, priority_class)
15 changes: 9 additions & 6 deletions simplyblock_core/controllers/migration_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
tasks_controller,
)
from simplyblock_core.controllers.host_auth import _reapply_allowed_hosts
from simplyblock_core.controllers.lvol_register import register_lvol
from simplyblock_core.controllers.migration_bdev_ops import (
delete_bdev_blocking as _delete_bdev_blocking,
)
Expand Down Expand Up @@ -1394,10 +1395,11 @@ def _create_migration_impl(lvol_id, target_node_id, ctrl_loss_tmo, host_nqn,
f"create_migration: {composite} already on secondary "
f"{_pre_sec_node.get_id()} — skipping bdev_lvol_register")
elif _tgt_blobid is not None and _tgt_uuid is not None:
ret_sec = _sec_rpc_reg.bdev_lvol_register(
bdev_short, tgt_node.lvstore, _tgt_uuid, _tgt_blobid,
ret_sec = register_lvol(
_sec_rpc_reg, bdev_short, tgt_node.lvstore, _tgt_uuid, _tgt_blobid,
qos_controller.wire_priority_class(
tgt_node.cluster_id, lvol.lvol_priority_class))
tgt_node.cluster_id, lvol.lvol_priority_class),
cluster_id=tgt_node.cluster_id, node_label=_pre_sec_node.get_id())
if ret_sec:
undo.replicas["secondary"] = (_sec_rpc_reg, _pre_sec_node)
_sec_rpc_reg.bdev_lvol_set_migration_flag(composite)
Expand Down Expand Up @@ -1426,10 +1428,11 @@ def _create_migration_impl(lvol_id, target_node_id, ctrl_loss_tmo, host_nqn,
f"create_migration: {composite} already on tertiary "
f"{_pre_ter_node.get_id()} — skipping bdev_lvol_register")
elif _tgt_blobid is not None and _tgt_uuid is not None:
ret_ter = _ter_rpc_reg.bdev_lvol_register(
bdev_short, tgt_node.lvstore, _tgt_uuid, _tgt_blobid,
ret_ter = register_lvol(
_ter_rpc_reg, bdev_short, tgt_node.lvstore, _tgt_uuid, _tgt_blobid,
qos_controller.wire_priority_class(
tgt_node.cluster_id, lvol.lvol_priority_class))
tgt_node.cluster_id, lvol.lvol_priority_class),
cluster_id=tgt_node.cluster_id, node_label=_pre_ter_node.get_id())
if ret_ter:
undo.replicas["tertiary"] = (_ter_rpc_reg, _pre_ter_node)
_ter_rpc_reg.bdev_lvol_set_migration_flag(composite)
Expand Down
23 changes: 20 additions & 3 deletions simplyblock_core/controllers/ns_host_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,22 @@ def connected_hosts(nqn: str, node_ids: Iterable[str], db=None) -> set | None:

def stranded_hosts(nqn: str, removing: Iterable[str], keeping: Iterable[str],
db=None) -> set | None:
"""Hosts connected to *nqn* on the *removing* nodes but on none of the
*keeping* nodes; None when that could not be established."""
"""Hosts connected to *nqn* on the *removing* nodes that have no controller
on the *keeping* nodes; None when that could not be established.

A host NQN does not identify a machine: one Kubernetes node connects with
the kernel default (``/etc/nvme/hostnqn``) on one path and with the
simplyblock form derived from its node UID on another (bed bf28,
2026-11-19: every client reached the source as
``nqn.2014-08.io.simplyblock:uuid:<node uid>`` and the early-prepared
target as ``nqn.2014-08.org.nvmexpress:uuid:<machine id>``, with different
host ids), and nothing records which forms belong together. So hosts are
matched by name where they can be, and every unmatched host on the keeping
side is taken to be one unmatched host of the removing side under its
other name. Hosts are stranded only when the removing side has more
unmatched hosts than the keeping side can account for; all of the removing
side's unmatched hosts are then reported, since which of them is the
stranded one cannot be told."""
gone = connected_hosts(nqn, removing, db=db)
if gone is None:
return None
Expand All @@ -72,7 +86,10 @@ def stranded_hosts(nqn: str, removing: Iterable[str], keeping: Iterable[str],
stay = connected_hosts(nqn, keeping, db=db)
if stay is None:
return None
return gone - stay
unmatched_gone, unmatched_stay = gone - stay, stay - gone
if len(unmatched_gone) <= len(unmatched_stay):
return set()
return unmatched_gone


def removal_blocked(nqn: str, removing: Iterable[str], keeping: Iterable[str],
Expand Down
10 changes: 10 additions & 0 deletions simplyblock_core/controllers/tasks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,16 @@ def _add_task(function_name, cluster_id, node_id, device_id,
task_obj.function_params = function_params
task_obj.max_retry = max_retry
task_obj.status = JobSchedule.STATUS_NEW
if function_name == JobSchedule.FN_SNAPSHOT_REPLICATION:
# The scan above is a check-then-write: two replication workers
# enqueueing the same chain ancestor 100 ms apart both passed it and
# wrote two tasks for one snapshot (bed bf32 2026-11-21). The write
# itself is the atomic claim.
active_id, created = db.ensure_snapshot_replication_task(task_obj)
if not created:
logger.info(f"Task found, skip adding new task: {active_id}")
return False
return task_obj.uuid
task_obj.write_to_db(db.kv_store)
if send_to_cluster_log:
tasks_events.task_create(task_obj)
Expand Down
Loading
Loading