diff --git a/simplyblock_core/controllers/migration_controller.py b/simplyblock_core/controllers/migration_controller.py index df86cdfd1e..4f9c74326f 100644 --- a/simplyblock_core/controllers/migration_controller.py +++ b/simplyblock_core/controllers/migration_controller.py @@ -713,7 +713,7 @@ def _get_snap_ancestry(snap_uuid): # Cleanup safety helpers # --------------------------------------------------------------------------- -def get_snaps_safe_to_delete_on_source(migration): +def get_snaps_safe_to_delete_on_source(migration, moving_lvol_ids=frozenset()): """ Return the set of snapshot UUIDs (from the migration plan) that are safe to delete from the *source* node after a successful migration. @@ -732,12 +732,19 @@ def get_snaps_safe_to_delete_on_source(migration): Intermediate snapshots created during migration always belong to the migrating volume, so they are always included as initial candidates. + + *moving_lvol_ids* are lvols treated as already gone from the source even + though their records still say otherwise -- a batch group's siblings, + which are leaving with this migration. A snapshot the result only + contains because of them must not be deleted yet: the siblings' source + bdevs still clone from it. See _handle_cleanup_source's deferral. """ candidates = set(migration.intermediate_snaps) # always owned by migrating lvol # Build the set of lvol UUIDs still on the source node so we can distinguish # "owner still on SRC" (must protect) from "owner already migrated" (safe to clean up). - source_lvols = db.get_lvols_by_node_id(migration.source_node_id) + source_lvols = [lv for lv in db.get_lvols_by_node_id(migration.source_node_id) + if lv.uuid not in moving_lvol_ids] source_lvol_ids = {lv.uuid for lv in source_lvols} for snap_uuid in migration.snap_migration_plan: @@ -767,6 +774,17 @@ def get_snaps_safe_to_delete_on_source(migration): return candidates +def source_lvols_cloning_from(snap_uuid, source_node_id): + """uuids of lvols on *source_node_id* whose clone ancestry includes *snap_uuid*. + + The same reference test get_snaps_safe_to_delete_on_source's Rule 2 + applies, for a single snapshot: non-empty means its source copy is still + some volume's backing data and must stay. + """ + return [lv.uuid for lv in db.get_lvols_by_node_id(source_node_id) + if lv.cloned_from_snap and snap_uuid in _collect_snap_ancestry(lv.cloned_from_snap)] + + def get_snaps_to_delete_on_target(migration): """ Return the list of snapshot UUIDs to remove from the *target* node when diff --git a/simplyblock_core/controllers/replica_chain.py b/simplyblock_core/controllers/replica_chain.py index 530f46a37b..ea294c07f0 100644 --- a/simplyblock_core/controllers/replica_chain.py +++ b/simplyblock_core/controllers/replica_chain.py @@ -118,8 +118,15 @@ def _lvol_info(info): def _is_snapshot(info): + """Converted. SPDK's ``snapshot`` flag means "has clones": a converted + lvol nothing is cloned from yet reports false, and only its write + support going away shows the convert (probed on a live SPDK).""" + if isinstance(info, list): + info = info[0] if info else None lv = _lvol_info(info) - return bool(lv.get("is_snapshot") or lv.get("snapshot")) + if lv.get("is_snapshot") or lv.get("snapshot"): + return True + return bool(lv) and ((info or {}).get("supported_io_types") or {}).get("write") is False def _names(info): diff --git a/simplyblock_core/models/lvol_migration_group.py b/simplyblock_core/models/lvol_migration_group.py index bbac9bddd6..c5fc289439 100644 --- a/simplyblock_core/models/lvol_migration_group.py +++ b/simplyblock_core/models/lvol_migration_group.py @@ -25,8 +25,9 @@ Main calls bdev_lvol_batch_final_step with all lvols ordered by ns_id. batch_result is set to True on success, False on failure. CLEANUP_SOURCE - Workers delete their own source bdevs/snaps. Main performs the ANA flip - and source subsystem teardown, then waits for cleanup_source_done. + Workers delete their own source bdevs/snaps. Main performs the ANA flip, + waits for cleanup_source_done, then deletes the snapshots workers deferred + (source_snaps_deferred) and tears down the source subsystem. CLEANUP_TARGET (failure / cancel path) Main signals batch_result=False; workers go to CLEANUP_TARGET and delete their target snaps. Main deletes the target subsystem. @@ -117,6 +118,15 @@ class LVolMigrationGroup(BaseModel): # migration_ids that have completed CLEANUP_SOURCE. cleanup_source_done: list[str] = default_factory(list) + # snap_uuid → source composite bdev name ("/") of each + # snapshot a worker could not delete from the source during its own + # CLEANUP_SOURCE only because group siblings still cloned from it there. + # The owning worker runs before those siblings have moved, so the + # orchestrator deletes these once, after the cleanup_source barrier. + # The name is recorded because by then _apply_migration_to_db has already + # repointed the snapshot record at the target. + source_snaps_deferred: dict = default_factory(dict) + # Written by the main orchestrator after bdev_lvol_batch_final_step. # None = call not yet made; True = success; False = failure. batch_result: bool | None = None diff --git a/simplyblock_core/rpc_client.py b/simplyblock_core/rpc_client.py index cdfa02aa69..467434496f 100644 --- a/simplyblock_core/rpc_client.py +++ b/simplyblock_core/rpc_client.py @@ -2,6 +2,7 @@ import hashlib import http.client import json +import os import threading from collections import OrderedDict from enum import IntEnum @@ -183,12 +184,32 @@ class RPCProtocolError(RPCException): """Response wasn't valid/well-formed JSON-RPC.""" +# strerror text -> errno, for SPDK handlers that answer with a generic +# JSON-RPC code and carry the errno only as spdk_strerror() in the message. +_ERRNO_BY_STRERROR = {os.strerror(n): n for n in errno.errorcode} + + class RPCRemoteError(RPCException): def __init__(self, message: str, code: int, data: Any = None): super().__init__(message) self.code = code self.data = data + @property + def posix_errno(self) -> int | None: + """The errno SPDK failed with, or None when it cannot be told. + + SPDK reports it two ways: as the code itself (``-errno``), or under a + generic JSON-RPC code with ``spdk_strerror(errno)`` as the message -- + a repeated ``bdev_lvol_add_clone`` answers + ``{"code": -32602, "message": "File exists"}``. Comparing ``code`` + against ``-errno.X`` alone misses the second form. ``-1`` is + ``RPCErrorCode.invalid_state``, not EPERM, so it is not read as one. + """ + if self.code < -1 and -self.code in errno.errorcode: + return -self.code + return _ERRNO_BY_STRERROR.get(str(self)) + def request_reached_remote(err: BaseException) -> bool: """True when a failed RPC provably reached SPDK: it answered with an diff --git a/simplyblock_core/services/tasks_runner_batch_migration.py b/simplyblock_core/services/tasks_runner_batch_migration.py index 5e7c8e725b..de77068e7a 100644 --- a/simplyblock_core/services/tasks_runner_batch_migration.py +++ b/simplyblock_core/services/tasks_runner_batch_migration.py @@ -29,7 +29,9 @@ PHASE_CLEANUP_SOURCE (orchestrator: wait + source teardown) Wait for all workers to signal cleanup_source_done. - Delete the source NVMe-oF subsystem (workers delete individual source bdevs). + Delete the source snapshots workers deferred (only group siblings still + cloned from them) and the source NVMe-oF subsystem (workers delete their + own individual source bdevs). Advance to PHASE_COMPLETED → mark task DONE. PHASE_CLEANUP_TARGET (orchestrator: wait + target teardown) @@ -38,6 +40,7 @@ NVMe-oF subsystem and marks group FAILED/CANCELLED. """ +import errno import time from simplyblock_core import constants, utils @@ -49,6 +52,7 @@ tasks_controller, tasks_events, ) +from simplyblock_core.controllers.migration_bdev_ops import delete_bdev_blocking from simplyblock_core.exceptions import MigrationConflictError, PreconditionError from simplyblock_core.models.cluster import Cluster from simplyblock_core.models.job_schedule import JobSchedule @@ -57,6 +61,8 @@ from simplyblock_core.rpc_client import RPCErrorCode, RPCException, RPCRemoteError from simplyblock_core.services.hub_controller_manager import HubControllerManager from simplyblock_core.services.tasks_runner_lvol_migration import ( + _bdev_is_immutable_snapshot, + _bdev_is_linked_under, _build_paths, _ensure_and_prune_target_paths, _get_source_tertiary_node, @@ -456,17 +462,24 @@ def _commit_intermediate_snapshot_chain(group, member_migrations, tgt_node, tgt_ # Same known SPDK behavior _reconstruct_snap_tree already guards # against: converting an already-immutable bdev is rejected, so a # retry that reaches an earlier round already committed here would - # otherwise fail every time. bdev_lvol_get_bdevs reports - # is_snapshot on the primary; treat that as "already done" and - # just advance the predecessor pointer. + # otherwise fail every time (re-linking it answers EEXIST). Treat + # an already-immutable bdev as "already done" and just advance the + # predecessor pointer. Read it through the shared helper: SPDK's + # snapshot flag stays false until something is cloned from the + # bdev, which for these is the cutover that just failed. _existing = tgt_rpc.bdev_get(tgt_composite) - if _existing and _existing.get('driver_specific', {}).get('lvol', {}).get('is_snapshot'): + if _bdev_is_immutable_snapshot(_existing): pred_composite = tgt_composite continue if pred_composite: - if not tgt_rpc.bdev_lvol_add_clone(tgt_composite, pred_composite): - return f"bdev_lvol_add_clone failed for intermediate snap {snap_uuid}" + # A retry can also land between add_clone and convert: the + # link exists but the bdev is still writable. Link only where + # it is missing -- repeating add_clone answers EEXIST. + # replica_chain already skips replicas that read through it. + if not _bdev_is_linked_under(_existing, pred_composite.split("/", 1)[1]): + if not tgt_rpc.bdev_lvol_add_clone(tgt_composite, pred_composite): + return f"bdev_lvol_add_clone failed for intermediate snap {snap_uuid}" _err = replica_chain.add_clone_on_replicas(tgt_node, tgt_composite, pred_composite, db=db) if _err: return f"add_clone on a replica failed for intermediate snap {snap_uuid}: {_err}" @@ -972,6 +985,55 @@ def _handle_cleanup_source_barrier(group): return expected.issubset(done_set) +def _delete_deferred_source_snaps(group, src_node, src_rpc, primary_src_node=None): + """ + Delete the source snapshots workers deferred to the group + (``group.source_snaps_deferred``): ones only group siblings still cloned + from when their owner cleaned up. Runs after the cleanup_source barrier, + when every sibling's source bdev is gone and its record is on the target. + + Each one is re-checked first: a sibling that failed instead of signalling + is still on the source and still needs its parent. Best-effort, like the + rest of source cleanup -- returns a list of notes for anything kept. + """ + primary_src_node = primary_src_node or src_node + notes: list = [] + replicas = [] + if primary_src_node.secondary_node_id and primary_src_node.secondary_node_id != src_node.get_id(): + try: + replicas.append(db.get_storage_node_by_id(primary_src_node.secondary_node_id)) + except KeyError as e: + logger.warning(f"Group {group.uuid[:8]}: secondary src node lookup (non-fatal): {e}") + tert_node = _get_source_tertiary_node(primary_src_node) + if tert_node and tert_node.get_id() != src_node.get_id(): + replicas.append(tert_node) + replica_rpcs = [_make_rpc(n) for n in replicas] + + for snap_uuid, bdev_name in group.source_snaps_deferred.items(): + holders = migration_controller.source_lvols_cloning_from(snap_uuid, group.source_node_id) + if holders: + logger.warning( + f"Group {group.uuid[:8]}: keeping source snapshot {bdev_name}: " + f"still cloned by {holders}") + notes.append(f"source snap {bdev_name} kept, still cloned by {holders}") + continue + try: + if not src_rpc.bdev_get(bdev_name): + logger.info(f"Group {group.uuid[:8]}: source snapshot {bdev_name} already gone") + continue + delete_bdev_blocking( + bdev_name, src_rpc, + secondary_rpc=replica_rpcs[0] if replica_rpcs else None, + tertiary_rpc=replica_rpcs[1] if len(replica_rpcs) > 1 else None, + all_nodes=[src_node, *replicas], + lvs_name=primary_src_node.lvstore) + logger.info(f"Group {group.uuid[:8]}: deleted deferred source snapshot {bdev_name}") + except (RuntimeError, RPCException) as e: + logger.warning(f"Group {group.uuid[:8]}: delete deferred source snapshot {bdev_name}: {e}") + notes.append(f"source snap {bdev_name} delete failed: {e}") + return notes + + def _delete_source_subsystem(group, src_node, src_rpc, tgt_node, tgt_rpc, primary_src_node=None): """ Delete the source NVMe-oF subsystem on all SRC replicas (active source, @@ -1067,6 +1129,31 @@ def _try_delete(rpc, node_id, label): # Retry-budget helper # --------------------------------------------------------------------------- +# SPDK error codes that are a definite answer about state a retry replays +# unchanged: the orchestrator re-runs the same step against the same bdevs, +# so it gets the same answer every time. Spending the retry budget on them +# only delays cleanup and buries the first error under the ceiling message. +_PERMANENT_RPC_ERRNOS = frozenset({errno.EEXIST, errno.EOPNOTSUPP, errno.ENOTSUP}) + + +def _batch_enter_cleanup_target(task, group, group_id, msg): + """Give up on the cutover: send the group to cleanup_target and suspend.""" + logger.error(msg) + group.phase = LVolMigrationGroup.PHASE_CLEANUP_TARGET + group.error_message = msg + task.function_result = msg + group.write_to_db(db.kv_store) + for rec in group.members: + try: + mig = db.get_migration_by_id(rec['migration_id']) + migration_events.migration_phase_changed(mig) + except Exception: + pass + task.status = JobSchedule.STATUS_SUSPENDED + task.write_to_db(db.kv_store) + return False + + def _batch_budget_suspend(task, group, group_id, error_msg): """Charge retry budget and suspend; redirect to cleanup_target when exhausted. @@ -1076,21 +1163,9 @@ def _batch_budget_suspend(task, group, group_id, error_msg): task.retry += 1 task.function_result = error_msg if task.retry >= constants.LVOL_MIG_MAX_RETRIES: - ceiling_msg = ( + return _batch_enter_cleanup_target(task, group, group_id, ( f"Group {group_id[:8]}: max retry ({constants.LVOL_MIG_MAX_RETRIES}) " - f"reached; entering cleanup_target: {error_msg}" - ) - logger.error(ceiling_msg) - group.phase = LVolMigrationGroup.PHASE_CLEANUP_TARGET - group.error_message = ceiling_msg - task.function_result = ceiling_msg - group.write_to_db(db.kv_store) - for rec in group.members: - try: - mig = db.get_migration_by_id(rec['migration_id']) - migration_events.migration_phase_changed(mig) - except Exception: - pass + f"reached; entering cleanup_target: {error_msg}")) task.status = JobSchedule.STATUS_SUSPENDED task.write_to_db(db.kv_store) return False @@ -1373,6 +1448,10 @@ def task_runner(task): task.status = JobSchedule.STATUS_SUSPENDED task.write_to_db(db.kv_store) return False + if isinstance(exc, RPCRemoteError) and exc.posix_errno in _PERMANENT_RPC_ERRNOS: + return _batch_enter_cleanup_target(task, group, group_id, ( + f"Group {group_id[:8]}: permanent RPC error in phase {phase} " + f"(code {exc.code}); entering cleanup_target without retrying: {exc}")) return _batch_budget_suspend(task, group, group_id, f"RPC error in phase {phase}: {exc}") # ── PHASE_CLEANUP_SOURCE: wait for workers, then delete source subsystem ─── @@ -1385,6 +1464,10 @@ def task_runner(task): task.write_to_db(db.kv_store) return False + _cleanup_notes = _delete_deferred_source_snaps( + group, src_node, src_rpc, primary_src_node=primary_src_node) + if _cleanup_notes: + group.error_message = "source cleanup partial: " + "; ".join(_cleanup_notes) _delete_source_subsystem(group, src_node, src_rpc, tgt_node, tgt_rpc, primary_src_node=primary_src_node) diff --git a/simplyblock_core/services/tasks_runner_lvol_migration.py b/simplyblock_core/services/tasks_runner_lvol_migration.py index 90a880c091..295e0c10d5 100644 --- a/simplyblock_core/services/tasks_runner_lvol_migration.py +++ b/simplyblock_core/services/tasks_runner_lvol_migration.py @@ -175,6 +175,35 @@ def _get_migration_nic(node): _MIGRATION_BDEV_SUFFIX_DONE = 'am' +def _group_sibling_lvol_ids(migration): + """uuids of every OTHER lvol migrating in the same batch group as + `migration` (empty set if `migration` isn't a batch-group member). + + Used by _apply_migration_to_db()'s owned-snapshot handling to tell a + clone sibling that's migrating to the SAME target as part of this same + group apart from one genuinely staying behind on a different node -- + only the latter still needs the snapshot's pre-migration location + preserved; a sibling moving with us needs nothing left behind. + """ + if not migration.migration_group_id: + return set() + try: + group = db.get_migration_group_by_id(migration.migration_group_id) + except KeyError: + return set() + uuids = set() + for member in group.members: + mig_id = member.get("migration_id") + if not mig_id: + continue + try: + sibling_mig = db.get_migration_by_id(mig_id) + except KeyError: + continue + uuids.add(sibling_mig.lvol_id) + return uuids + + def _apply_migration_to_db(migration, tgt_lvol_uuid=None, tgt_lvol_bdev=None): """ Update control-plane DB records after a successful lvol migration. @@ -330,31 +359,64 @@ def _apply_migration_to_db(migration, tgt_lvol_uuid=None, tgt_lvol_bdev=None): }) original_snap.write_to_db(db.kv_store) else: - referenced = False + # A living clone sibling only means "this snapshot's PRE-migration + # copy is still needed, so preserve the primary record and record + # our own copy as an extra instance instead" when that sibling is + # staying at its current node. When the sibling is itself a + # member of the SAME batch group (migration.migration_group_id) + # it is migrating to the exact same target right now too -- the + # whole branch (this snapshot and everything cloned from it) + # moves together, nothing is left behind that still needs the + # pre-migration location, and the primary record should simply + # move like the unreferenced case. + # + # Previously this didn't distinguish the two: ANY clone sibling + # (group member or not) was treated as "still referenced", which + # — correctly for a genuinely-external sibling, but WRONGLY for a + # group-moving one — skipped persisting the snapshot's own + # corrected snap_bdev/snap_uuid/blobid/lvol.* fields onto its + # primary record entirely (the write only ran in the + # "not referenced" branch, using a separately-fetched, still- + # stale `original_snap` otherwise). For a batch group migrating a + # snapshot together with everything cloned from it, that left the + # primary record pointing at the pre-migration source bdev/ + # lvstore forever, which then made the next migration attempt + # look for a bdev that no longer existed at that name + # (`No such device`). + group_sibling_ids = _group_sibling_lvol_ids(migration) + external_snap = None for mini in db.get_mini_lvols(): - if mini.uuid == migration.lvol_id: + if mini.uuid == migration.lvol_id or mini.uuid in group_sibling_ids: continue if mini.cloned_from_snap and mini.cloned_from_snap == snap_uuid: logger.debug( f"_apply_migration_to_db: snapshot {snap_uuid} " - f"is still referenced by lvol {mini.uuid}") - original_snap = db.get_snapshot_by_id(snap_uuid) - if not any(s.get('lvol', {}).get('node_id') == snap.lvol.node_id - for s in original_snap.instances): - original_snap.instances.append({ - "lvol": { - "node_id": snap.lvol.node_id, - "hostname": snap.lvol.hostname, - "lvol_bdev": snap.lvol.lvol_bdev, - "uuid": snap.lvol.uuid, - }, - "snap_bdev": snap.snap_bdev, - "uuid": snap.uuid, - }) - original_snap.write_to_db(db.kv_store) - referenced = True + f"is still referenced by lvol {mini.uuid} (not moving with us)") + external_snap = db.get_snapshot_by_id(snap_uuid) break - if not referenced: + + if external_snap is not None: + # Something outside this migration (and outside its batch + # group) still needs the pre-migration copy -- leave the + # primary record alone (do NOT persist `snap`'s in-memory + # target-side mutations above) and only record our own new + # copy as an extra instance on a fresh, unmutated fetch. + if not any(s.get('lvol', {}).get('node_id') == snap.lvol.node_id + for s in external_snap.instances): + external_snap.instances.append({ + "lvol": { + "node_id": snap.lvol.node_id, + "hostname": snap.lvol.hostname, + "lvol_bdev": snap.lvol.lvol_bdev, + "uuid": snap.lvol.uuid, + }, + "snap_bdev": snap.snap_bdev, + "uuid": snap.uuid, + }) + external_snap.write_to_db(db.kv_store) + else: + # No one is left behind needing the pre-migration copy -- + # safe to move the primary record itself. snap.write_to_db(db.kv_store) logger.debug( @@ -1170,6 +1232,14 @@ def _bdev_is_immutable_snapshot(bdev_info) -> bool: quietly answer False for every bdev -- "never converted" -- and send a retry straight back into the transfer SPDK fences a node for. A list is still read, by its first entry, for any caller that has one. + + SPDK's ``snapshot`` flag means "a snapshot that has clones", not + "converted": a just-converted lvol nothing has been linked under yet + reports ``snapshot: false``, ``clone: false`` -- exactly the state a retry + finds an intermediate snapshot in when the cutover that would have + attached the live lvol to it failed (61 cluster, 2026-10-29). What + convert does change unconditionally is the bdev turning read-only, so + ``supported_io_types.write == false`` is read as converted too. """ if isinstance(bdev_info, list): bdev_info = bdev_info[0] if bdev_info else None @@ -1177,7 +1247,19 @@ def _bdev_is_immutable_snapshot(bdev_info) -> bool: lvol = bdev_info["driver_specific"]["lvol"] except (KeyError, TypeError): return False - return bool(lvol.get("is_snapshot") or lvol.get("snapshot")) + if lvol.get("is_snapshot") or lvol.get("snapshot"): + return True + return (bdev_info.get("supported_io_types") or {}).get("write") is False + + +def _bdev_is_linked_under(bdev_info, parent_short) -> bool: + """True if a ``bdev_get`` answer shows the lvol already cloned from + *parent_short* (bare lvol name, no lvstore prefix) -- add_clone ran. + Repeating add_clone for that pair answers EEXIST.""" + try: + return bdev_info["driver_specific"]["lvol"].get("base_snapshot") == parent_short + except (KeyError, TypeError): + return False def _replica_bdev_state(rpc, composite): @@ -2815,11 +2897,25 @@ def _handle_cleanup_source(migration, src_node, src_rpc, tgt_node, tgt_rpc, prim # target before we touch the source. If the target is unreachable, skip # all source snap deletions to avoid accidental data loss. _snaps_to_delete_src: list = [] + _snaps_deferred_src: dict = {} try: to_delete_all = migration_controller.get_snaps_safe_to_delete_on_source(migration) + # A batch group's siblings are leaving the source too, but their + # records still place them there until their own cleanup runs, so + # the owner of a snapshot they clone from (always processed first) + # would otherwise keep it on the source for ever -- and no sibling + # ever reconsiders it: it is only in the owner's plan. Hand those + # to the orchestrator, which deletes them after the barrier. + # SFAM-2840: LVS_19/SNAP_84 left behind under CLN_85/CLN_86. + deferred_all: set = set() + if migration.migration_group_id: + deferred_all = (migration_controller.get_snaps_safe_to_delete_on_source( + migration, moving_lvol_ids=_group_sibling_lvol_ids(migration)) + - to_delete_all - set(migration.intermediate_snaps)) tgt_lvols = tgt_rpc.bdev_lvol_get_lvols(tgt_node.lvstore) or [] tgt_names = {e.get('name', '').split('/')[-1] for e in tgt_lvols} - for snap_uuid in to_delete_all: + src_lvs_name = (primary_src_node or src_node).lvstore + for snap_uuid in to_delete_all | deferred_all: try: snap = db.get_snapshot_by_id(snap_uuid) _snap_bdev = snap.snap_bdev or '' @@ -2827,13 +2923,25 @@ def _handle_cleanup_source(migration, src_node, src_rpc, tgt_node, tgt_rpc, prim _m_name = _snap_tgt_short_name(snap) _canonical = _snap_short_name(snap) _am_name = _canonical + _MIGRATION_BDEV_SUFFIX_DONE - if any(n in tgt_names for n in (_primary, _m_name, _canonical, _am_name)): - _snaps_to_delete_src.append(snap_uuid) - else: + if not any(n in tgt_names for n in (_primary, _m_name, _canonical, _am_name)): logger.warning( f"Target missing snapshot {_m_name} ({snap_uuid}); " "skipping source delete to protect data") _warnings.append(f"target missing snap {_m_name}; source copy kept") + elif snap_uuid in to_delete_all: + _snaps_to_delete_src.append(snap_uuid) + else: + _src_bdev = source_snap_bdevs_saved.get(snap_uuid) or _snap_bdev + if not _src_bdev.startswith(f"{src_lvs_name}/"): + logger.warning( + f"Snapshot {snap_uuid} no longer names a source bdev " + f"({_src_bdev}); cannot defer its source delete") + _warnings.append(f"snap {snap_uuid}: source name unknown; source copy kept") + else: + logger.info( + f"Source snapshot {_src_bdev} ({snap_uuid}) is still cloned by " + "group siblings; deferring its delete to the group orchestrator") + _snaps_deferred_src[snap_uuid] = _src_bdev except KeyError: pass # already gone from DB; safe to skip except Exception as _ve: @@ -2842,6 +2950,18 @@ def _handle_cleanup_source(migration, src_node, src_rpc, tgt_node, tgt_rpc, prim "skipping all source snap deletions") _warnings.append(f"snap target-verification failed: {_ve}") _snaps_to_delete_src = [] + _snaps_deferred_src = {} + + if _snaps_deferred_src: + try: + db.atomic_update( + db.get_migration_group_by_id(migration.migration_group_id), + lambda g: g.source_snaps_deferred.update(_snaps_deferred_src)) + except KeyError: + logger.warning( + f"Group {migration.migration_group_id} not found; deferred source " + f"snapshots {sorted(_snaps_deferred_src.values())} will not be deleted") + _warnings.append("group missing; deferred source snaps kept") ctx = { 'stage': 'cleanup_src', diff --git a/tests/integration/migration/test_unit_controller.py b/tests/integration/migration/test_unit_controller.py index e4d05c0f15..c8683cf018 100644 --- a/tests/integration/migration/test_unit_controller.py +++ b/tests/integration/migration/test_unit_controller.py @@ -539,6 +539,80 @@ def test_snapshot_node_id_updated(self): assert snap.lvol.node_id == "node-tgt" assert snap.snap_bdev == "lvs_tgt/s1m" # migration suffix 'm' is appended on target + def test_snapshot_moves_when_sibling_is_group_member(self): + """Regression for the bug where an owned snapshot's own snap_bdev/ + lvol.node_id update was silently dropped whenever ANY other lvol + still cloned from it, including a sibling that is ITSELF a member + of the same batch migration group (migrating to the exact same + target right now) -- nothing is left behind needing the + pre-migration copy in that case, so the primary record must still + move, exactly like the no-sibling case. A migrated-back snapshot + that never moved kept pointing at its pre-migration bdev/lvstore + forever, and the next migration then failed looking for a bdev + that no longer existed there ("No such device"). + """ + lvol = _lvol("lvol-1", "node-src") + snap = _snap("s1", "lvol-1", "node-src") + sibling_clone = _lvol("lvol-clone", "node-src", cloned_from_snap="s1") + + mig = _migration(lvol_id="lvol-1", source_node="node-src", + target_node="node-tgt", snaps_migrated=["s1"]) + mig.migration_group_id = "group-1" + + sibling_mig = _migration(lvol_id="lvol-clone", source_node="node-src", + target_node="node-tgt") + group = MagicMock() + group.members = [{"migration_id": "sibling-mig-uuid"}] + + mock_db = self._mock_db(lvol, snap) + mock_db.get_mini_lvols.return_value = [sibling_clone] + mock_db.get_migration_group_by_id.return_value = group + mock_db.get_migration_by_id.return_value = sibling_mig + with patch.object(runner, 'db', mock_db): + result = runner._apply_migration_to_db(mig) + + assert result is True + assert snap.lvol.node_id == "node-tgt" + assert snap.snap_bdev == "lvs_tgt/s1m" + assert snap.instances == [] # nothing left behind -- no instance needed + + def test_snapshot_primary_preserved_when_externally_referenced(self): + """When a migrating lvol's owned snapshot still has a clone sibling + that is NOT part of the same migration group (a genuinely separate + lvol staying at its current node), the snapshot's own primary + record (snap_bdev / lvol.node_id) must stay representing the + surviving copy that sibling still needs -- only an "instances" + entry records the migrating lvol's own new copy. Guards against the + group-sibling fix above going too far and moving snapshots that are + still needed elsewhere. + """ + lvol = _lvol("lvol-1", "node-src") + sibling_clone = _lvol("lvol-clone", "node-src", cloned_from_snap="s1") + + mig = _migration(lvol_id="lvol-1", source_node="node-src", + target_node="node-tgt", snaps_migrated=["s1"]) + + # get_snapshot_by_id for "s1" is called twice in the owned branch: + # once at the top of the per-snapshot loop (mutated in memory only, + # to compute what our own new instance entry should say) and once + # more to fetch the record that actually gets persisted -- a fresh + # copy each time, exactly like two separate reads of the same + # still-pre-migration underlying DB bytes. + fetches = [_snap("s1", "lvol-1", "node-src") for _ in range(2)] + fetch_iter = iter(fetches) + mock_db = self._mock_db(lvol) + mock_db.get_snapshot_by_id.side_effect = lambda sid: next(fetch_iter) + mock_db.get_mini_lvols.return_value = [sibling_clone] + with patch.object(runner, 'db', mock_db): + result = runner._apply_migration_to_db(mig) + + assert result is True + persisted = fetches[1] # the one write_to_db() was actually called on + assert persisted.lvol.node_id == "node-src" # primary left alone + assert persisted.snap_bdev == "lvs/s1" # primary left alone + assert len(persisted.instances) == 1 + assert persisted.instances[0]["lvol"]["node_id"] == "node-tgt" + def test_missing_lvol_returns_false(self): mig = _migration(lvol_id="lvol-gone") diff --git a/tests/unit/tasks/test_batch_migration_commit_chain_retry.py b/tests/unit/tasks/test_batch_migration_commit_chain_retry.py new file mode 100644 index 0000000000..56a78a623f --- /dev/null +++ b/tests/unit/tasks/test_batch_migration_commit_chain_retry.py @@ -0,0 +1,230 @@ +"""A retried batch cutover must not re-link intermediate snapshots the failed +attempt already committed, and a permanent RPC error must not burn the retry +budget. + +Live on 2026-10-29 (61 cluster, SFAM-2840 round trip, return hop): the first +bdev_lvol_batch_transfer_final_step failed inside SPDK. Every retry then +re-ran _commit_intermediate_snapshot_chain, whose "already committed" guard +never fired. Two reasons, found one after the other on the cluster: + +* it read driver_specific.lvol.is_snapshot; bdev_get_bdevs calls the flag + ``snapshot``; +* even ``snapshot`` stays false on a converted lvol until something is cloned + from it -- and for an intermediate snapshot that is the cutover that just + failed. Probed directly: create, convert, bdev_get_bdevs answers + snapshot=false, clone=false, supported_io_types.write=false. + +bdev_lvol_add_clone on the already-linked LVS_1/SNAP_20m answered "File +exists" on all five retries, and the group reached cleanup_target only after +the whole budget, with the SPDK failure that started it buried under the +ceiling message. + +The bdev fixtures below copy the shapes a live SPDK returned, not the shape +the code expected -- the previous mocks used is_snapshot=True for a converted +bdev and so agreed with the bug. + +Pure logic tests: DB, RPC clients and events are mocked. +""" +import errno +import unittest +from unittest.mock import MagicMock, patch + +import simplyblock_core.services.tasks_runner_batch_migration as runner +from simplyblock_core import constants +from simplyblock_core.models.cluster import Cluster +from simplyblock_core.models.job_schedule import JobSchedule +from simplyblock_core.models.lvol_migration_group import LVolMigrationGroup +from simplyblock_core.models.storage_node import StorageNode +from simplyblock_core.rpc_client import RPCErrorCode, RPCRemoteError + +TGT_LVS = "LVS_1" + + +def _bdev(*, converted, base_snapshot=None): + """bdev_get_bdevs entry as a live SPDK returns it (only the keys read here). + + A converted lvol nothing is cloned from yet still reports snapshot=false; + only its write support goes away.""" + lvol = {"lvol_store_uuid": "c522c36d", "snapshot": False, + "clone": base_snapshot is not None, + "lvol_leadership": True, "lvs_leadership": True} + if base_snapshot: + lvol["base_snapshot"] = base_snapshot + return {"name": "u", "supported_io_types": {"read": True, "write": not converted}, + "driver_specific": {"lvol": lvol}} + + +def _snap(uuid, short): + s = MagicMock() + s.uuid = uuid + s.short = short + return s + + +class TestCommitChainSkipsCommittedSnapshots(unittest.TestCase): + + def setUp(self): + self.snaps = { + "pred": _snap("pred", "SNAP_14m"), + "i0": _snap("i0", "SNAP_20m"), + "i1": _snap("i1", "SNAP_23m"), + } + self.db = MagicMock() + self.db.get_snapshot_by_id.side_effect = lambda u: self.snaps[u] + self.tgt_node = MagicMock() + self.tgt_node.lvstore = TGT_LVS + self.tgt_rpc = MagicMock() + self.member = MagicMock() + self.member.uuid = "mig-1" + self.member.intermediate_snaps = ["i0", "i1"] + self.member.snaps_transferred_group = ["pred"] + self.member.snaps_preexisting_on_target = [] + self.group = MagicMock() + self.group.uuid = "group-1" + for p in ( + patch.object(runner, "db", self.db), + patch.object(runner, "_snap_tgt_short_name", side_effect=lambda s: s.short), + # Replicas go through replica_chain, which reads its own idempotency + # off each member; the primary-side guard is what is under test. + patch.object(runner.replica_chain, "add_clone_on_replicas", return_value=None), + patch.object(runner.replica_chain, "convert_on_replicas", return_value=None), + patch("simplyblock_core.controllers.lvol_controller.is_node_leader", return_value=True), + ): + p.start() + self.addCleanup(p.stop) + + def _commit(self): + return runner._commit_intermediate_snapshot_chain( + self.group, [self.member], self.tgt_node, self.tgt_rpc) + + def test_retry_after_full_commit_touches_nothing(self): + self.tgt_rpc.bdev_get.return_value = _bdev(converted=True, base_snapshot="SNAP_14m") + self.assertIsNone(self._commit()) + self.tgt_rpc.bdev_lvol_add_clone.assert_not_called() + self.tgt_rpc.bdev_lvol_convert.assert_not_called() + + def test_retry_resumes_after_the_last_committed_snapshot(self): + # A new intermediate round appended SNAP_23m after SNAP_20m was committed. + self.tgt_rpc.bdev_get.side_effect = lambda name: ( + _bdev(converted=True, base_snapshot="SNAP_14m") if name.endswith("SNAP_20m") + else _bdev(converted=False)) + self.assertIsNone(self._commit()) + self.tgt_rpc.bdev_lvol_add_clone.assert_called_once_with( + f"{TGT_LVS}/SNAP_23m", f"{TGT_LVS}/SNAP_20m") + self.tgt_rpc.bdev_lvol_convert.assert_called_once_with(f"{TGT_LVS}/SNAP_23m") + + def test_retry_between_link_and_convert_only_converts(self): + self.member.intermediate_snaps = ["i0"] + self.tgt_rpc.bdev_get.return_value = _bdev(converted=False, base_snapshot="SNAP_14m") + self.assertIsNone(self._commit()) + self.tgt_rpc.bdev_lvol_add_clone.assert_not_called() + self.tgt_rpc.bdev_lvol_convert.assert_called_once_with(f"{TGT_LVS}/SNAP_20m") + + def test_converted_bdev_with_no_clones_reads_as_immutable(self): + self.assertTrue(runner._bdev_is_immutable_snapshot(_bdev(converted=True))) + self.assertFalse(runner._bdev_is_immutable_snapshot(_bdev(converted=False))) + + def test_first_attempt_links_the_whole_chain(self): + self.tgt_rpc.bdev_get.return_value = _bdev(converted=False) + self.assertIsNone(self._commit()) + self.assertEqual( + [c.args for c in self.tgt_rpc.bdev_lvol_add_clone.call_args_list], + [(f"{TGT_LVS}/SNAP_20m", f"{TGT_LVS}/SNAP_14m"), + (f"{TGT_LVS}/SNAP_23m", f"{TGT_LVS}/SNAP_20m")]) + + +class TestPermanentRpcErrorSkipsRetryBudget(unittest.TestCase): + + def setUp(self): + self.task = MagicMock() + self.task.uuid = "task-1" + self.task.cluster_id = "cl-1" + self.task.retry = 0 + self.task.status = JobSchedule.STATUS_RUNNING + self.task.function_params = {"group_id": "grp-1"} + + self.group = LVolMigrationGroup() + self.group.uuid = "grp-1" + self.group.cluster_id = "cl-1" + self.group.source_node_id = "src-1" + self.group.target_node_id = "tgt-1" + self.group.phase = LVolMigrationGroup.PHASE_INTERMEDIATE + self.group.members = [{"ns_id": 1, "migration_id": "mig-1"}] + self.group.write_to_db = MagicMock() + + node = MagicMock() + node.status = StorageNode.STATUS_ONLINE + node.get_id.return_value = "src-1" + cluster = MagicMock() + cluster.status = Cluster.STATUS_ACTIVE + worker = MagicMock() + worker.has_deadline_passed.return_value = False + + self.db = MagicMock() + self.db.get_task_by_id.return_value = self.task + self.db.get_migration_group_by_id.return_value = self.group + self.db.get_storage_node_by_id.return_value = node + self.db.get_cluster_by_id.return_value = cluster + self.db.get_migration_by_id.return_value = worker + for p in ( + patch.object(runner, "db", self.db), + patch.object(runner, "_group_source_nodes", return_value=(node, node)), + patch.object(runner, "_make_rpc", return_value=MagicMock()), + patch.object(runner, "tasks_controller"), + patch.object(runner, "migration_events"), + ): + p.start() + self.addCleanup(p.stop) + runner.tasks_controller.get_active_cluster_expand_task.return_value = None + + def _run_with(self, exc): + with patch.object(runner, "_handle_intermediate_barrier", side_effect=exc): + return runner.task_runner(self.task) + + def test_eexist_goes_straight_to_cleanup_target(self): + # The answer a repeated bdev_lvol_add_clone gave on the cluster: the + # errno only in the message, under JSON-RPC's generic invalid-params code. + self._run_with(RPCRemoteError("File exists", RPCErrorCode.invalid_params)) + self.assertEqual(self.group.phase, LVolMigrationGroup.PHASE_CLEANUP_TARGET) + self.assertEqual(self.task.retry, 0) + self.assertIn("permanent RPC error", self.group.error_message) + self.assertIn("File exists", self.group.error_message) + self.assertEqual(self.task.status, JobSchedule.STATUS_SUSPENDED) + + def test_transient_error_still_charges_the_budget(self): + self._run_with(RPCRemoteError("Device or resource busy", -errno.EBUSY)) + self.assertEqual(self.group.phase, LVolMigrationGroup.PHASE_INTERMEDIATE) + self.assertEqual(self.task.retry, 1) + self.assertEqual(self.task.status, JobSchedule.STATUS_SUSPENDED) + + def test_eexist_as_a_negative_errno_code_is_permanent_too(self): + self._run_with(RPCRemoteError("File exists", -errno.EEXIST)) + self.assertEqual(self.group.phase, LVolMigrationGroup.PHASE_CLEANUP_TARGET) + self.assertEqual(self.task.retry, 0) + + def test_transient_error_reaches_cleanup_at_the_ceiling(self): + self.task.retry = constants.LVOL_MIG_MAX_RETRIES - 1 + self._run_with(RPCRemoteError("Device or resource busy", -errno.EBUSY)) + self.assertEqual(self.group.phase, LVolMigrationGroup.PHASE_CLEANUP_TARGET) + self.assertIn("max retry", self.group.error_message) + + +class TestRemoteErrorErrno(unittest.TestCase): + + def test_errno_from_a_negative_errno_code(self): + self.assertEqual(RPCRemoteError("No such device", -errno.ENODEV).posix_errno, errno.ENODEV) + + def test_errno_from_the_message_under_a_generic_code(self): + self.assertEqual( + RPCRemoteError("File exists", RPCErrorCode.invalid_params).posix_errno, errno.EEXIST) + + def test_no_errno_for_free_text(self): + self.assertIsNone( + RPCRemoteError("lvol is busy migrating", RPCErrorCode.internal_error).posix_errno) + + def test_invalid_state_code_is_not_read_as_eperm(self): + self.assertIsNone(RPCRemoteError("bad state", RPCErrorCode.invalid_state).posix_errno) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/tasks/test_batch_migration_shared_snapshot_cleanup.py b/tests/unit/tasks/test_batch_migration_shared_snapshot_cleanup.py new file mode 100644 index 0000000000..19f05a9c2f --- /dev/null +++ b/tests/unit/tasks/test_batch_migration_shared_snapshot_cleanup.py @@ -0,0 +1,226 @@ +"""A batch group deletes a source snapshot its own members clone from (SFAM-2840). + +MIG-T-008 moved LVOL_83 with its snapshot SNAP_84 and the two clones of it, +CLN_85 and CLN_86, as one batch. Only the owner's worker has SNAP_84 in its +plan, and it cleans up first, while the clones' records still place them on +the source -- so it kept the snapshot, no other worker ever reconsidered it, +and LVS_19/SNAP_84 outlived the batch. The next hop back to that node then +collided with it. + +Pure logic tests: one in-memory DB stands in for FDB for both the controller +and the runners; RPC clients and bdev deletes are mocked. +""" +import unittest +from unittest.mock import MagicMock, patch + +import simplyblock_core.controllers.migration_controller as ctl +import simplyblock_core.services.tasks_runner_batch_migration as batch_runner +import simplyblock_core.services.tasks_runner_lvol_migration as runner +from simplyblock_core.models.lvol_migration import LVolMigration +from simplyblock_core.models.lvol_migration_group import LVolMigrationGroup +from simplyblock_core.models.lvol_model import LVol +from simplyblock_core.models.snapshot import SnapShot + +SRC, TGT = "node-src", "node-tgt" +SRC_LVS, TGT_LVS = "LVS_19", "LVS_7" + + +class _FakeDB: + + kv_store = None # write_to_db is patched out; only passed through + + def __init__(self): + self.lvols, self.snaps, self.migrations, self.groups = {}, {}, {}, {} + + def get_lvols_by_node_id(self, node_id): + return [lv for lv in self.lvols.values() if lv.node_id == node_id] + + def _get(self, table, key): + if key not in table: + raise KeyError(key) + return table[key] + + def get_lvol_by_id(self, uuid): + return self._get(self.lvols, uuid) + + def get_snapshot_by_id(self, uuid): + return self._get(self.snaps, uuid) + + def get_migration_by_id(self, uuid): + return self._get(self.migrations, uuid) + + def get_migration_group_by_id(self, uuid): + return self._get(self.groups, uuid) + + def atomic_update(self, obj, mutate): + mutate(obj) + return obj + + +def _lvol(uuid, bdev, cloned_from_snap=""): + lv = LVol() + lv.uuid = uuid + lv.node_id = SRC + lv.lvol_bdev = bdev + lv.cloned_from_snap = cloned_from_snap + return lv + + +def _node(node_id, lvstore): + n = MagicMock() + n.get_id.return_value = node_id + n.lvstore = lvstore + n.secondary_node_id = "" + n.tertiary_node_id = "" + return n + + +def _tree(): + """LVOL_83 -> SNAP_84 -> {CLN_85, CLN_86}, all on the source, one batch group.""" + db = _FakeDB() + db.lvols = { + "lvol-83": _lvol("lvol-83", "LVOL_83"), + "cln-85": _lvol("cln-85", "CLN_85", cloned_from_snap="snap-84"), + "cln-86": _lvol("cln-86", "CLN_86", cloned_from_snap="snap-84"), + } + snap = SnapShot() + snap.uuid = "snap-84" + snap.snap_bdev = f"{SRC_LVS}/SNAP_84" + snap.lvol = db.lvols["lvol-83"] + db.snaps = {"snap-84": snap} + + group = LVolMigrationGroup() + group.uuid = "grp" + group.source_node_id = SRC + group.target_node_id = TGT + group.snap_owners = {"snap-84": "mig-83"} + for ns_id, lvol_id in enumerate(("lvol-83", "cln-85", "cln-86"), start=1): + m = LVolMigration() + m.uuid = "mig-" + lvol_id.split("-")[1] + m.lvol_id = lvol_id + m.source_node_id = SRC + m.target_node_id = TGT + m.migration_group_id = "grp" + # start_batch_migration: a shared snapshot is in its owner's plan only. + owned = ["snap-84"] if lvol_id == "lvol-83" else [] + m.snap_migration_plan = list(owned) + m.snaps_migrated = list(owned) + m.transfer_context = {"source_lvol_bdev": db.lvols[lvol_id].lvol_bdev} + db.migrations[m.uuid] = m + group.members.append({"ns_id": ns_id, "migration_id": m.uuid}) + db.groups = {"grp": group} + return db + + +def _apply_moves_record(db): + """_apply_migration_to_db stand-in: the lvol and its owned snaps go to the target.""" + def _apply(migration, **_): + db.lvols[migration.lvol_id].node_id = TGT + for snap_uuid in migration.snaps_migrated: + snap = db.snaps[snap_uuid] + snap.snap_bdev = f"{TGT_LVS}/{snap.snap_bdev.split('/', 1)[1]}m" + return True + return _apply + + +class TestSharedSnapshotOfAGroup(unittest.TestCase): + + def setUp(self): + self.db = _tree() + self.src_node, self.tgt_node = _node(SRC, SRC_LVS), _node(TGT, TGT_LVS) + self.src_rpc, self.tgt_rpc = MagicMock(), MagicMock() + self.tgt_rpc.bdev_lvol_get_lvols.return_value = [{"name": f"{TGT_LVS}/SNAP_84m"}] + self.worker_deletes = MagicMock() + patches = [ + patch.object(ctl, "db", self.db), + patch.object(runner, "db", self.db), + patch.object(batch_runner, "db", self.db), + patch.object(runner, "_delete_bdev_blocking", self.worker_deletes), + patch.object(runner, "_apply_migration_to_db", _apply_moves_record(self.db)), + patch.object(runner, "_get_source_secondary_node", return_value=None), + patch.object(runner, "_get_source_tertiary_node", return_value=None), + patch.object(runner, "_get_target_secondary_node", return_value=(None, None)), + patch.object(runner, "_get_target_tertiary_node", return_value=(None, None)), + patch.object(runner, "_rename_migrated_bdevs"), + patch.object(batch_runner, "_get_source_tertiary_node", return_value=None), + patch.object(LVolMigration, "write_to_db"), + patch.object(LVolMigrationGroup, "write_to_db"), + ] + for p in patches: + p.start() + self.addCleanup(p.stop) + + def _run_worker_cleanups(self): + # The order the run logged: owner first (lowest ns_id), then the clones. + for mig_id in ("mig-83", "mig-85", "mig-86"): + runner._handle_cleanup_source( + self.db.migrations[mig_id], self.src_node, self.src_rpc, + self.tgt_node, self.tgt_rpc) + + def _worker_deleted(self): + return [c.args[0] for c in self.worker_deletes.call_args_list] + + def test_owner_defers_the_snapshot_instead_of_keeping_it(self): + self._run_worker_cleanups() + self.assertNotIn(f"{SRC_LVS}/SNAP_84", self._worker_deleted()) # clones still on it + self.assertEqual(self.db.groups["grp"].source_snaps_deferred, + {"snap-84": f"{SRC_LVS}/SNAP_84"}) + + def test_orchestrator_deletes_the_snapshot_after_the_barrier(self): + self._run_worker_cleanups() + with patch.object(batch_runner, "delete_bdev_blocking") as deletes: + notes = batch_runner._delete_deferred_source_snaps( + self.db.groups["grp"], self.src_node, self.src_rpc) + deletes.assert_called_once() + self.assertEqual(deletes.call_args.args[0], f"{SRC_LVS}/SNAP_84") + self.assertEqual(deletes.call_args.kwargs["lvs_name"], SRC_LVS) + self.assertEqual(notes, []) + + def test_a_sibling_left_on_the_source_still_protects_it(self): + # CLN_86's worker failed instead of signalling: it is still on the source. + for mig_id in ("mig-83", "mig-85"): + runner._handle_cleanup_source( + self.db.migrations[mig_id], self.src_node, self.src_rpc, + self.tgt_node, self.tgt_rpc) + with patch.object(batch_runner, "delete_bdev_blocking") as deletes: + notes = batch_runner._delete_deferred_source_snaps( + self.db.groups["grp"], self.src_node, self.src_rpc) + deletes.assert_not_called() + self.assertEqual(len(notes), 1) + self.assertIn("cln-86", notes[0]) + + def test_an_already_deleted_snapshot_is_skipped(self): + # Orchestrator re-entry after a crash between delete and COMPLETED. + self._run_worker_cleanups() + self.src_rpc.bdev_get.return_value = [] + with patch.object(batch_runner, "delete_bdev_blocking") as deletes: + notes = batch_runner._delete_deferred_source_snaps( + self.db.groups["grp"], self.src_node, self.src_rpc) + deletes.assert_not_called() + self.assertEqual(notes, []) + + +class TestMovingLvolIds(unittest.TestCase): + + def test_moving_clones_no_longer_protect_their_parent(self): + db = _tree() + mig = db.migrations["mig-83"] + with patch.object(ctl, "db", db): + self.assertEqual(ctl.get_snaps_safe_to_delete_on_source(mig), set()) + self.assertEqual( + ctl.get_snaps_safe_to_delete_on_source( + mig, moving_lvol_ids={"lvol-83", "cln-85", "cln-86"}), + {"snap-84"}) + + def test_a_clone_outside_the_group_still_protects_it(self): + db = _tree() + mig = db.migrations["mig-83"] + with patch.object(ctl, "db", db): + self.assertEqual( + ctl.get_snaps_safe_to_delete_on_source( + mig, moving_lvol_ids={"lvol-83", "cln-85"}), + set()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_replica_chain.py b/tests/unit/test_replica_chain.py index 59a10eadc4..cd1e6dfa7a 100644 --- a/tests/unit/test_replica_chain.py +++ b/tests/unit/test_replica_chain.py @@ -120,6 +120,25 @@ def test_retries_are_idempotent(self): self.assertEqual(rc.convert_on(converted, "secondary", "LVS/C"), (rc.DONE, None)) converted.rpc_client.return_value.bdev_lvol_convert.assert_not_called() + def test_a_converted_lvol_with_no_clones_is_not_converted_again(self): + """What a live SPDK answers right after bdev_lvol_convert, before + anything is cloned from it (61 cluster, 2026-10-29): snapshot=false, + clone=false, only write support gone. A batch cutover that fails + leaves its intermediate snapshots in exactly this state, and SPDK + rejects converting them again.""" + converted = _node("sec", bdev={ + "supported_io_types": {"read": True, "write": False}, + "driver_specific": {"lvol": {"snapshot": False, "clone": False}}}) + self.assertEqual(rc.convert_on(converted, "secondary", "LVS/C"), (rc.DONE, None)) + converted.rpc_client.return_value.bdev_lvol_convert.assert_not_called() + + def test_a_writable_lvol_is_still_converted(self): + writable = _node("sec", bdev={ + "supported_io_types": {"read": True, "write": True}, + "driver_specific": {"lvol": {"snapshot": False, "clone": True}}}) + self.assertEqual(rc.convert_on(writable, "secondary", "LVS/C"), (rc.DONE, None)) + writable.rpc_client.return_value.bdev_lvol_convert.assert_called_once_with("LVS/C") + # --------------------------------------------------------------------------- # Owed changes: recorded when a member is skipped, replayed when it answers