Skip to content
Merged
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
22 changes: 20 additions & 2 deletions simplyblock_core/controllers/migration_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion simplyblock_core/controllers/replica_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
14 changes: 12 additions & 2 deletions simplyblock_core/models/lvol_migration_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 ("<lvstore>/<bdev>") 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
Expand Down
21 changes: 21 additions & 0 deletions simplyblock_core/rpc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import hashlib
import http.client
import json
import os
import threading
from collections import OrderedDict
from enum import IntEnum
Expand Down Expand Up @@ -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
Expand Down
125 changes: 104 additions & 21 deletions simplyblock_core/services/tasks_runner_batch_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -38,6 +40,7 @@
NVMe-oF subsystem and marks group FAILED/CANCELLED.
"""

import errno
import time

from simplyblock_core import constants, utils
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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}"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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 ───
Expand All @@ -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)

Expand Down
Loading
Loading