From fbdee62043c1e4fe0b1b0c453f1c6f759d15a4df Mon Sep 17 00:00:00 2001 From: wmousa Date: Mon, 23 Nov 2026 17:13:13 +0100 Subject: [PATCH 1/5] feat(jm): rebuild the journal raid when a node's devices change The journal raid of a node is built over the journal partitions of its devices and kept that member list for life: a device migrated out after a failure left the raid degraded for good, and a device with a journal partition the raid did not use never joined it. A raid0 leg cannot take a member in or give one up, and the raid has no superblock, so the raid is now built anew, empty, over the members the node's devices call for, and the journal coordinator of the LVS leader resynchronises it from the node's other journal copies. A jm_raid_reshape task does it on the restart runner: queued when a device reaches failed_and_migrated or is added, started only on an active cluster with every node online, no migration or restart open and every journal in sync, one node at a time, and finished once jc_get_jm_status reports the journals in sync on three consecutive polls. A device that is only missing keeps its member, as before. Raid legs are capped at four devices: two legs up to eight devices, three from nine to twelve, and so on. A JM that holds a journal is rebuilt from the legs recorded for it and never from the planner, so a node of more than eight devices built as two halves keeps reading its journal. On block-device nodes every device now gives a journal partition of --jm-percent of the node's smallest device, where it was sized from the node's total capacity and the number of devices. The size no longer depends on the device count, so a device that joins later is split to the same size. The journal partition of a device that left the raid is not offered as a new data device by a restart. The planner helpers that assumed exactly two legs and had no caller are removed. Co-Authored-By: Claude Fable 5.2 --- simplyblock_cli/cli-reference.yaml | 4 +- simplyblock_cli/cli.py | 4 +- .../controllers/device_controller.py | 214 +++++ .../controllers/tasks_controller.py | 37 + simplyblock_core/jm_raid.py | 155 ++-- simplyblock_core/models/job_schedule.py | 10 + simplyblock_core/rpc_client.py | 7 +- .../services/tasks_runner_restart.py | 103 ++- simplyblock_core/storage_node_ops.py | 29 +- simplyblock_core/utils/__init__.py | 35 +- simplyblock_web/api/v2/_dtos.py | 1 + tests/unit/test_jm_raid.py | 115 +-- tests/unit/test_jm_raid_layout.py | 2 +- tests/unit/test_jm_raid_reshape.py | 865 ++++++++++++++++++ tests/unit/test_lblk_journal_disk_split.py | 16 +- tests/unit/test_lblk_journal_raid.py | 58 +- 16 files changed, 1434 insertions(+), 221 deletions(-) create mode 100644 tests/unit/test_jm_raid_reshape.py diff --git a/simplyblock_cli/cli-reference.yaml b/simplyblock_cli/cli-reference.yaml index 483a70cd5a..f48c142368 100644 --- a/simplyblock_cli/cli-reference.yaml +++ b/simplyblock_cli/cli-reference.yaml @@ -93,7 +93,7 @@ commands: type: str default: "" - name: "--lblk" - help: "Configure the node with Linux block devices (lblk cluster mode) instead of NVMe PCIe devices: eligible whole disks or partitions (unmounted, unheld; disks additionally unpartitioned) are wrapped in SPDK AIO bdevs. Select devices with --blk-names, --blk-names-exclude or --blk-serials; without a selector, every eligible whole disk is used (partitions must be selected explicitly). Each storage node gets its journal from its own devices: every selected partition is split in two, and every whole disk is partitioned, into a journal partition and a data partition. The journal partitions of a node are all the same size and are mirrored (RAID 0+1), so the journal survives the loss of a device; --jm-percent of the node's capacity is the journal the node can use. A node of a single device carries one journal partition. A device that carries simplyblock data is never partitioned; a node on such disks keeps the journal layout it has. Use --lblk-journal-device for a dedicated journal device on whole disks. Minimum 2 partitions or SSDs per node, or a single whole disk." + help: "Configure the node with Linux block devices (lblk cluster mode) instead of NVMe PCIe devices: eligible whole disks or partitions (unmounted, unheld; disks additionally unpartitioned) are wrapped in SPDK AIO bdevs. Select devices with --blk-names, --blk-names-exclude or --blk-serials; without a selector, every eligible whole disk is used (partitions must be selected explicitly). Each storage node gets its journal from its own devices: every selected partition is split in two, and every whole disk is partitioned, into a journal partition and a data partition. The journal partitions of a node are all the same size, --jm-percent of the smallest device, and are mirrored (RAID 0+1), so the journal survives the loss of a device. A node of a single device carries one journal partition. A device that carries simplyblock data is never partitioned; a node on such disks keeps the journal layout it has. Use --lblk-journal-device for a dedicated journal device on whole disks. Minimum 2 partitions or SSDs per node, or a single whole disk." dest: lblk type: bool action: store_true @@ -121,7 +121,7 @@ commands: type: bool action: store_true - name: "--jm-percent" - help: "Usable journal size in percent of the node's total selected capacity when the journal is carved from the selected partitions or disks (requires --lblk, not with --lblk-journal-device). On a node of several devices the journal is mirrored, so the space taken is larger: each device gives a journal partition of that size divided by half the number of devices, rounded down. Default: `3`." + help: "Size of the journal partition each device gives, in percent of the node's smallest selected device, when the journal is carved from the selected partitions or disks (requires --lblk, not with --lblk-journal-device). On a node of several devices the journal is mirrored, so the journal the node can use is about half of what its devices give. Default: `3`." dest: jm_percent required: false type: int diff --git a/simplyblock_cli/cli.py b/simplyblock_cli/cli.py index fdbf52f33d..8d98896dee 100755 --- a/simplyblock_cli/cli.py +++ b/simplyblock_cli/cli.py @@ -109,12 +109,12 @@ def init_storage_node__configure(self, subparser): subcommand.add_argument('--device-model', help='NVMe SSD model string, example: --model PM1628. Can be used alone to filter by model, or combined with --size-range to further filter by size.', type=str, default='', dest='device_model', required=False) subcommand.add_argument('--size-range', help='NVMe SSD device size range separated by -, can be X(m,g,t) or bytes as integer, example: --size-range 50G-1T or --size-range 1232345-67823987. Can be used alone to filter by size, or combined with --device-model to further filter by model.', type=str, default='', dest='size_range', required=False) subcommand.add_argument('--nvme-names', help='Comma separated list of nvme namespace names like nvme0n1,nvme1n1.', type=str, default='', dest='nvme_names', required=False) - subcommand.add_argument('--lblk', help='Configure the node with Linux block devices (lblk cluster mode) instead of NVMe PCIe devices: eligible whole disks or partitions (unmounted, unheld; disks additionally unpartitioned) are wrapped in SPDK AIO bdevs. Select devices with --blk-names, --blk-names-exclude or --blk-serials; without a selector, every eligible whole disk is used (partitions must be selected explicitly). Each storage node gets its journal from its own devices: every selected partition is split in two, and every whole disk is partitioned, into a journal partition and a data partition. The journal partitions of a node are all the same size and are mirrored (RAID 0+1), so the journal survives the loss of a device; --jm-percent of the node\'s capacity is the journal the node can use. A node of a single device carries one journal partition. A device that carries simplyblock data is never partitioned; a node on such disks keeps the journal layout it has. Use --lblk-journal-device for a dedicated journal device on whole disks. Minimum 2 partitions or SSDs per node, or a single whole disk.', dest='lblk', action='store_true') + subcommand.add_argument('--lblk', help='Configure the node with Linux block devices (lblk cluster mode) instead of NVMe PCIe devices: eligible whole disks or partitions (unmounted, unheld; disks additionally unpartitioned) are wrapped in SPDK AIO bdevs. Select devices with --blk-names, --blk-names-exclude or --blk-serials; without a selector, every eligible whole disk is used (partitions must be selected explicitly). Each storage node gets its journal from its own devices: every selected partition is split in two, and every whole disk is partitioned, into a journal partition and a data partition. The journal partitions of a node are all the same size, --jm-percent of the smallest device, and are mirrored (RAID 0+1), so the journal survives the loss of a device. A node of a single device carries one journal partition. A device that carries simplyblock data is never partitioned; a node on such disks keeps the journal layout it has. Use --lblk-journal-device for a dedicated journal device on whole disks. Minimum 2 partitions or SSDs per node, or a single whole disk.', dest='lblk', action='store_true') subcommand.add_argument('--blk-names', help='Comma separated list of block devices to use (requires --lblk). Each entry is a persistent /dev/disk name, such as /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_drive-scsi0 or /dev/disk/by-partuuid/28427de0-1916-4c05-895f-0829cd8790ba. A kernel name (sdb) or kernel path (/dev/sdb) is refused: it states a position in this boot\'s enumeration order, and it would name another disk after a reboot that probes the controllers in another order. The path is taken as given: the node records it, and add-node and every restart open the device by that path alone, never by serial or kernel name. A path that no longer exists is a missing device. Use --blk-serials for a device udev published no persistent name for. Requested devices must be eligible; a busy device is an error.', type=str, default='', dest='blk_names', required=False) subcommand.add_argument('--blk-names-exclude', help='Comma separated list of block devices to exclude (requires --lblk), spelled the way --blk-names takes them. All other eligible disks are used.', type=str, default='', dest='blk_names_exclude', required=False) subcommand.add_argument('--blk-serials', help='Comma separated list of block device serial numbers (or WWNs) to use (requires --lblk).', type=str, default='', dest='blk_serials', required=False) subcommand.add_argument('--lblk-journal-device', help='With --lblk and whole disks: dedicate each node\'s smallest disk to the journal instead of partitioning every disk into a journal partition and a data partition (the default). Needs at least two disks per node. Partition selections always carry their journal in split partitions.', dest='lblk_journal_device', action='store_true') - subcommand.add_argument('--jm-percent', help='Usable journal size in percent of the node\'s total selected capacity when the journal is carved from the selected partitions or disks (requires --lblk, not with --lblk-journal-device). On a node of several devices the journal is mirrored, so the space taken is larger: each device gives a journal partition of that size divided by half the number of devices, rounded down. Default: `3`.', type=int, default=3, dest='jm_percent', required=False) + subcommand.add_argument('--jm-percent', help='Size of the journal partition each device gives, in percent of the node\'s smallest selected device, when the journal is carved from the selected partitions or disks (requires --lblk, not with --lblk-journal-device). On a node of several devices the journal is mirrored, so the journal the node can use is about half of what its devices give. Default: `3`.', type=int, default=3, dest='jm_percent', required=False) subcommand.add_argument('--force', help='Force format detected or passed nvme pci address to 4K and clean partitions. With --lblk: mark partitioned disks eligible; the partition wipe happens at add-node with --force-format.', dest='force', action='store_true') subcommand.add_argument('--enable-inline-checksum', help='When formatting (with --force), prefer an LBAF that supports >=8 bytes of NVMe metadata per block, so alceml can run inline checksum validation in md-on-device mode. Drives with no md-capable LBAF still format to plain 4K and will use the fallback layout.', dest='inline_checksum', action='store_true') subcommand.add_argument('--calculate-hp-only', help='Calculate the minimum required huge pages, it depends on the following params: --sockets-to-use, --nodes-per-socket, --number-of-devices. Subsystem count and the vCPU budget are cluster-level settings.', dest='calculate_hp_only', action='store_true') diff --git a/simplyblock_core/controllers/device_controller.py b/simplyblock_core/controllers/device_controller.py index 62b43b7382..0cdd025196 100644 --- a/simplyblock_core/controllers/device_controller.py +++ b/simplyblock_core/controllers/device_controller.py @@ -1399,6 +1399,216 @@ def clear_rebuilt_jm_legs(snode: StorageNode, rpc_client: RPCClient) -> None: _set_jm_leg_stale(db_controller, snode.get_id(), leg, False) +class JMReshapeNotReady(Exception): + """The JM raid of a node cannot be rebuilt over its current devices now. + Nothing was changed; a later attempt may find the node ready.""" + + +class JMReshapeError(Exception): + """Rebuilding the JM raid of a node failed after its old JM stack was + taken down. The node has no journal of its own until a retry succeeds.""" + + +def _devices_of_jm_member(snode: StorageNode, member: str) -> list[NVMeDevice]: + """The data devices that share their physical device with the JM raid + member ``member``: the inverse of _jm_raid_member_of_device. + + On an lblk node that is the data partition recorded next to the journal + partition (StorageNode.lblk_devices); on an NVMe drive every data + partition of the member's controller.""" + for entry in snode.lblk_devices or []: + if (entry.get("journal_raid") and entry.get("serial") + and utils.aio_bdev_name_for_serial(entry["serial"]) == member): + return [d for d in snode.nvme_devices if d.serial_number == entry.get("data_serial")] + return [d for d in snode.nvme_devices + if d.bdev_type != "aio" and _on_controller(member, d.nvme_controller)] + + +def _jm_members_in_service(snode: StorageNode) -> list[str]: + """The journal partition of every device of the node that serves data + (ONLINE), in the order of the node's device records. + + An lblk device carries one when the configure split it + (utils.split_lblk_journal_raid) and the node record knows the pair. An + NVMe drive carries one as its first partition when the node cuts its + drives into a journal and data partitions.""" + members: list[str] = [] + online = {d.serial_number for d in snode.nvme_devices if d.status == NVMeDevice.STATUS_ONLINE} + for entry in snode.lblk_devices or []: + if entry.get("journal_raid") and entry.get("serial") and entry.get("data_serial") in online: + members.append(utils.aio_bdev_name_for_serial(entry["serial"])) + if snode.num_partitions_per_dev and snode.jm_percent: + for dev in snode.nvme_devices: + if dev.status != NVMeDevice.STATUS_ONLINE or dev.bdev_type == "aio" or not dev.is_partition: + continue + base, sep, number = dev.nvme_bdev.rpartition("p") + if not sep or not number.isdigit() or number == "1": + continue + member = f"{base}p1" + if member not in members: + members.append(member) + return members + + +def jm_raid_target_members(snode: StorageNode) -> list[str]: + """The members the JM raid of ``snode`` consists of once it follows the + node's devices; empty for a node whose journal is not a raid over its + devices, or that has no device left to build one on. + + A member leaves when every device on its physical device was migrated + out after a failure (FAILED_AND_MIGRATED): that device is gone for good. + A member joins when a device that serves data carries a journal partition + the raid does not use. A device that is only missing -- removed, + unavailable, not found by a restart -- keeps its member: the raid runs + without it and rebuilds it when it returns + (storage_node_ops._create_jm_stack_on_raid).""" + jm = snode.jm_device + if not jm or not jm.jm_nvme_bdev_list: + return [] + current = list(jm.jm_nvme_bdev_list) + gone = [] + for member in current: + devices = _devices_of_jm_member(snode, member) + if devices and all(d.status == NVMeDevice.STATUS_FAILED_AND_MIGRATED for d in devices): + gone.append(member) + return jm_raid.reshaped_members(current, gone, _jm_members_in_service(snode)) + + +def jm_raid_reshape_needed(snode: StorageNode) -> bool: + """Whether the JM raid of ``snode`` is built over other members than the + node's devices call for (jm_raid_target_members).""" + target = jm_raid_target_members(snode) + return bool(target) and target != list(snode.jm_device.jm_nvme_bdev_list) + + +def queue_jm_raid_reshape(node_id: str) -> None: + """Queue the rebuild of the node's JM raid when a device change left it + built over the wrong members. The task runs when the cluster is quiet and + takes one node at a time (tasks_runner_restart.task_runner_jm_reshape).""" + db_controller = DBController() + try: + snode = db_controller.get_storage_node_by_id(node_id) + except KeyError: + return + if jm_raid_reshape_needed(snode): + logger.info("JM raid of node %s no longer matches its devices: queueing a rebuild over %s", + node_id, jm_raid_target_members(snode)) + tasks_controller.add_jm_raid_reshape_task(snode.cluster_id, node_id) + + +def _delete_jm_stack(snode: StorageNode, rpc_client: RPCClient) -> None: + """Take down the node's whole JM stack, from the nvmf subsystem to the + raid0 legs, deleting what is there and skipping what is not, so that a + second call after a failure half way finishes the job. + + The legs are deleted with the top raid: bdev_raid_create answers with the + bdev that already has the name, so a leg left behind would be reused with + its old members by the build that follows.""" + jm = snode.jm_device + if snode.enable_ha_jm and jm.nvmf_nqn and rpc_client.subsystem_get(jm.nvmf_nqn): + rpc_client.subsystem_delete(jm.nvmf_nqn) + if jm.pt_bdev and rpc_client.bdev_get(jm.pt_bdev): + rpc_client.bdev_PT_NoExcl_delete(jm.pt_bdev) + if jm.jm_bdev and rpc_client.bdev_get(jm.jm_bdev): + rpc_client.bdev_jm_delete(jm.jm_bdev, safe_removal=snode.enable_ha_jm) + if jm.alceml_bdev and rpc_client.bdev_get(jm.alceml_bdev): + rpc_client.bdev_alceml_delete(jm.alceml_bdev) + raids = [r.get("name", "") for r in rpc_client.bdev_raid_get_bdevs(category="all") or []] + # Shortest name first: the top raid1 goes before the legs it sits on. + for name in sorted((n for n in raids if jm_raid.is_jm_raid_bdev(n, snode.get_id())), key=len): + rpc_client.bdev_raid_delete(name) + + +def reshape_jm_raid(node_id: str) -> list[str]: + """Rebuild the JM raid of a node over the devices it has now, empty, and + return the new member list. + + The raid cannot grow or lose a member in place: a raid0 leg has no way to + take one in or give one up, and the raid carries no superblock. So the + journal of the node is stopped, the raid is created anew over the members + jm_raid_target_members names, the journal storage is formatted on it and + the JM started again. The journal coordinator of the LVS leader then + brings the empty JM up to date from the node's other journal copies by + itself (jm_resync_pending tells when it is done). Until then the node + relies on those copies, so the caller rebuilds one node at a time and only + on a cluster whose journals are all in sync. + + Raises JMReshapeNotReady, before anything is touched, when the node is not + online, has no JM raid over its devices or a member it needs is not + there. Raises JMReshapeError or an RPCException once the old stack is + down; calling again finishes the rebuild.""" + db_controller = DBController() + snode = db_controller.get_storage_node_by_id(node_id) + if snode.status != StorageNode.STATUS_ONLINE: + raise JMReshapeNotReady(f"node {node_id} is {snode.status}") + target = jm_raid_target_members(snode) + if not target: + raise JMReshapeNotReady(f"node {node_id} has no JM raid over its devices to rebuild") + jm = snode.jm_device + rpc_client = snode.rpc_client() + absent = [m for m in target if not rpc_client.bdev_get(m)] + if absent: + raise JMReshapeNotReady( + f"JM raid member(s) {absent} of node {node_id} are not present; the raid is " + f"rebuilt once they are back or their devices are migrated out") + + layout = jm_raid.layout_of_record(jm.jm_nvme_bdev_list, jm.raid_bdev, jm.jm_leg_bdevs) + logger.info("Rebuilding the JM raid of node %s: members %s -> %s (%s)", + node_id, jm.jm_nvme_bdev_list, target, layout) + set_jm_device_state(jm.get_id(), JMDevice.STATUS_UNAVAILABLE) + _delete_jm_stack(snode, rpc_client) + new_jm = storage_node_ops._create_jm_stack_on_raid( + rpc_client, target, snode, after_restart=False, layout=layout) + if not new_jm: + raise JMReshapeError(f"failed to build the JM stack of node {node_id} over {target}") + db_controller.atomic_update( + db_controller.get_storage_node_by_id(node_id), + lambda n, jm_new=new_jm: setattr(n, "jm_device", jm_new)) + # Makes every online node connect to the JM under its new subsystem. + set_jm_device_state(new_jm.get_id(), JMDevice.STATUS_ONLINE) + return target + + +def jm_resync_pending(snode: StorageNode) -> list[str]: + """The journals the JM of ``snode`` is a copy of that are not known to be + in sync, each with the reason; empty when all of them are. + + The JM of a node holds the journal of the node's own LVS and of every LVS + whose owner picked it as a remote copy (StorageNode.jm_ids). The journal + coordinator of an LVS runs its synchronisation on the node that leads the + LVS, so that node is the one asked (jc_get_jm_status: False for a JM that + is not ready or has replication running). A journal whose leader cannot + be found or asked counts as pending: an unknown answer is not "in sync".""" + from simplyblock_core.controllers import lvol_controller + + db_controller = DBController() + nodes = db_controller.get_storage_nodes_by_cluster_id(snode.cluster_id) + by_id = {n.get_id(): n for n in nodes} + jm_id = snode.jm_device.get_id() if snode.jm_device else "" + pending = [] + for owner in nodes: + if not owner.lvstore or owner.status == StorageNode.STATUS_REMOVED: + continue + if owner.get_id() != snode.get_id() and jm_id not in owner.jm_ids: + continue + hosts = [owner] + [by_id[i] for i in (owner.secondary_node_id, owner.tertiary_node_id) + if i in by_id] + leader = next((h for h in hosts if h.status == StorageNode.STATUS_ONLINE + and lvol_controller.is_node_leader(h, owner.lvstore)), None) + if leader is None: + pending.append(f"{owner.lvstore}: no leader found") + continue + try: + status = leader.rpc_client(timeout=10, retry=1).jc_get_jm_status(owner.jm_vuid) + except RPCException as e: + pending.append(f"{owner.lvstore}: {e}") + continue + busy = sorted(name for name, ready in (status or {}).items() if ready is False) + if busy or not status: + pending.append(f"{owner.lvstore}: {busy or 'no JM reported'}") + return pending + + def remove_from_jm_device(device_id, jm_bdev): db_controller = DBController() @@ -1711,6 +1921,8 @@ def _apply_online(d, o=dev_order, p=placement): distr_controller.send_cluster_map_add_device(device_obj, node) if add_migration_task: tasks_controller.add_new_device_mig_task(device_id) + # A device that brings a journal partition extends the node's JM raid. + queue_jm_raid_reshape(snode.get_id()) return device_id @@ -1725,6 +1937,8 @@ def device_set_failed_and_migrated(device_id): if node.status == StorageNode.STATUS_ONLINE: rpc_client = node.rpc_client() rpc_client.distr_replace_id_in_map_prob(dev.cluster_device_order, -1) + # The device is gone for good, and its journal partition with it. + queue_jm_raid_reshape(dev.node_id) return True diff --git a/simplyblock_core/controllers/tasks_controller.py b/simplyblock_core/controllers/tasks_controller.py index e9c7dad063..da60755cab 100644 --- a/simplyblock_core/controllers/tasks_controller.py +++ b/simplyblock_core/controllers/tasks_controller.py @@ -410,6 +410,14 @@ def _add_task(function_name, cluster_id, node_id, device_id, logger.info(f"Task found, skip adding new task: {task_id}") return False + elif function_name == JobSchedule.FN_JM_RAID_RESHAPE: + # The task rebuilds over whatever the node's devices call for when it + # runs, so one open task covers every change queued behind it. + open_tasks = [t for t in get_active_jm_raid_reshape_tasks(cluster_id) if t.node_id == node_id] + if open_tasks: + logger.info(f"Task found, skip adding new task: {open_tasks[0].uuid}") + return False + task_obj = JobSchedule() task_obj.uuid = str(uuid.uuid4()) task_obj.cluster_id = cluster_id @@ -1365,6 +1373,35 @@ def get_port_allow_tasks(cluster_id, node_id, port_number): return False +def add_jm_raid_reshape_task(cluster_id, node_id): + return _add_task(JobSchedule.FN_JM_RAID_RESHAPE, cluster_id, node_id, "") + + +def get_active_jm_raid_reshape_tasks(cluster_id): + """The open JM raid rebuilds of the cluster.""" + return [task for task in db.get_job_tasks(cluster_id) + if task.function_name == JobSchedule.FN_JM_RAID_RESHAPE + and task.status != JobSchedule.STATUS_DONE and task.canceled is False] + + +#: Work that moves data or takes a node's journal away. A JM raid rebuild +#: leaves a node without a journal copy of its own until the resync is done, +#: so it waits for all of it, cluster-wide. +_JM_RAID_RESHAPE_WAITS_FOR = ( + JobSchedule.FN_DEV_MIG, JobSchedule.FN_FAILED_DEV_MIG, JobSchedule.FN_NEW_DEV_MIG, + JobSchedule.FN_NODE_RESTART, JobSchedule.FN_DEV_RESTART, JobSchedule.FN_NODE_ADD, + JobSchedule.FN_NODE_REMOVAL, JobSchedule.FN_CLUSTER_EXPAND, + JobSchedule.FN_LVOL_MIG, JobSchedule.FN_LVOL_BATCH_MIG, +) + + +def get_jm_raid_reshape_blocking_tasks(cluster_id): + """The open tasks of the cluster a JM raid rebuild waits for.""" + return [task for task in db.get_job_tasks(cluster_id) + if task.function_name in _JM_RAID_RESHAPE_WAITS_FOR + and task.status != JobSchedule.STATUS_DONE and task.canceled is False] + + def add_jc_comp_resume_task(cluster_id, node_id, jm_vuid): return _add_task(JobSchedule.FN_JC_COMP_RESUME, cluster_id, node_id, "", function_params={"jm_vuid": jm_vuid}, max_retry=10) diff --git a/simplyblock_core/jm_raid.py b/simplyblock_core/jm_raid.py index 22a932c918..b52fe81e30 100644 --- a/simplyblock_core/jm_raid.py +++ b/simplyblock_core/jm_raid.py @@ -6,17 +6,23 @@ physical writes per node — and at FTT=2 the journal is replicated to 4 JMs, so a 10-drive node meant ~40 device writes per record. -To cap that at 2× per node (independent of drive count) without hitting SPDK's -``raid5f`` full-stripe-write limitation, the JM uses a **RAID 0+1** layout: - - 1 device -> no raid (single-device / test-only node) - 2 devices -> raid1 over two single-device legs (a 2-way mirror) - > 2 devices-> split drives into two ±1 balanced groups, - raid0 over each group, raid1 over the two raid0 legs - -The top RAID1 is always exactly 2-wide, so every drive lifecycle event reduces -to "rebuild the affected leg's raid0 and let RAID1 resync"; only when *both* -legs are lost does the journal (JC) layer resync the records from peer JMs. +To cap that without hitting SPDK's ``raid5f`` full-stripe-write limitation (the +JM's storage writes single blocks, raid5f takes whole stripes only), the JM +uses a **RAID 0+1** layout over groups of at most GROUP_MAX_DEVICES devices: + + 1 device -> no raid (single-device / test-only node) + 2 devices -> raid1 over two single-device legs (a 2-way mirror) + 3-8 devices -> two ±1 balanced groups, raid0 over each, + raid1 over the two raid0 legs + 9-12 devices -> three such groups, raid1 over three raid0 legs + and so on: one more leg for every GROUP_MAX_DEVICES devices. + +One journal record costs one device write per leg. A device that is only +missing costs the leg it sits in, and the JM runs on the others; the leg is +rebuilt from them when the device is back. A device that leaves for good, or +a new one, changes the member list: the raid is then built anew, empty, over +the new list, and the journal (JC) layer resyncs the records from the node's +other journal copies (device_controller.reshape_jm_raid). This module is pure logic (no RPC, no DB) so the decisions are unit-testable. The orchestration that issues the bdev_raid RPCs lives in storage_node_ops. @@ -47,17 +53,31 @@ LAYOUT_RAID01 = "raid01" # journals built by the RAID 0+1 planner -def split_two_groups(items: list) -> tuple[list, list]: - """Split ``items`` into two groups whose sizes differ by at most one. +#: Most devices one raid0 leg stripes over. A node with more devices gets more +#: legs, not wider ones: a leg is lost with any one of its devices. +GROUP_MAX_DEVICES = 4 + - The first group gets the extra element when the count is odd, so e.g. - 3->(2,1), 4->(2,2), 5->(3,2), 6->(3,3). +def split_groups(items: list) -> list[list]: + """Split ``items`` into the fewest groups of at most GROUP_MAX_DEVICES, + but at least two, whose sizes differ by at most one. + + The first groups get the extra elements, so e.g. 3->(2,1), 4->(2,2), + 5->(3,2), 8->(4,4), 9->(3,3,3), 10->(4,3,3), 12->(4,4,4), 13->(4,3,3,3). + Up to eight items this is the split into two halves every RAID 0+1 JM was + built with before the groups were capped. """ - half = (len(items) + 1) // 2 - return list(items[:half]), list(items[half:]) + count = max(2, -(-len(items) // GROUP_MAX_DEVICES)) + base, extra = divmod(len(items), count) + groups, start = [], 0 + for index in range(count): + size = base + (1 if index < extra else 0) + groups.append(list(items[start:start + size])) + start += size + return groups -def plan_topology(members: list[str], layout: str = LAYOUT_RAID01) -> dict: +def plan_topology(members: list[str], layout: str = LAYOUT_RAID01, legs=None) -> dict: """Decide the JM RAID topology for the given base bdevs. ``layout`` selects the geometry and MUST match the one the JM's storage was @@ -69,10 +89,17 @@ def plan_topology(members: list[str], layout: str = LAYOUT_RAID01) -> dict: pre-RAID0+1 layout that clusters upgraded from an older release were built with). + ``legs`` are the leg member lists the JM was built with, when a record + of them exists. A JM that holds a journal is rebuilt with exactly those: + the split of a member list is a rule that can change (it did, when the + groups were capped at GROUP_MAX_DEVICES), the bytes on the drives cannot. + They are used when they cover ``members`` exactly, and ignored otherwise + (a record of another member list says nothing about this one). + Returns: {'level': RAID_NONE, 'base': , 'legs': []} 1 member {'level': RAID_1_NWAY, 'base': None, 'members': [all]} legacy, >=2 - {'level': RAID_0PLUS1, 'base': None, 'legs': [groupA, groupB]} raid01, >=2 + {'level': RAID_0PLUS1, 'base': None, 'legs': [group, group, ...]} raid01, >=2 Raises ValueError if there are no members. """ @@ -83,73 +110,51 @@ def plan_topology(members: list[str], layout: str = LAYOUT_RAID01) -> dict: return {"level": RAID_NONE, "base": members[0], "legs": []} if layout == LAYOUT_LEGACY: return {"level": RAID_1_NWAY, "base": None, "members": list(members)} - a, b = split_two_groups(members) - return {"level": RAID_0PLUS1, "base": None, "legs": [a, b]} + recorded = [list(leg) for leg in legs or [] if leg] + if len(recorded) >= 2 and [m for leg in recorded for m in leg] == list(members): + return {"level": RAID_0PLUS1, "base": None, "legs": recorded} + return {"level": RAID_0PLUS1, "base": None, "legs": split_groups(members)} -def member_size_for_usable(usable_bytes: int, member_count: int) -> int: - """Size every member must have for a RAID 0+1 JM of ``usable_bytes``. +def layout_of_record(members: list[str], raid_bdev: str, leg_bdevs: list[str]) -> str: + """The layout a JM record was built under, read from its shape. - The members are all of one size (a raid uses each member only up to the - size of its smallest one). The top raid1 is as large as its smaller leg, - and that leg stripes ``member_count // 2`` members, so the usable size is - ``member_size * (member_count // 2)``: 2 members of S give S, 3 give S (the - third one's S is unused), 4 give 2S, 5 give 2S. A single member is the - journal itself. + Recorded legs mean RAID 0+1. A raid over two or more members without + recorded legs is the legacy N-way mirror, whose build path never recorded + any. A single member is no raid at all and belongs to neither: it is read + as RAID 0+1, the layout it grows into when the node gets a second device. """ - if member_count < 1: - raise ValueError("cannot size a JM RAID over zero devices") - width = max(1, member_count // 2) - return -(-int(usable_bytes) // width) + if leg_bdevs or len(members) < 2 or not raid_bdev: + return LAYOUT_RAID01 + return LAYOUT_LEGACY -def is_balanced(legs: list[list]) -> bool: - """True if the two legs' member counts differ by at most one.""" - return abs(len(legs[0]) - len(legs[1])) <= 1 +def reshaped_members(current: list[str], gone, added) -> list[str]: + """The member list of a JM raid after its node lost the devices of + ``gone`` for good and gained those of ``added``. - -def smaller_leg_index(legs: list[list]) -> int: - """Index of the leg a new device should join (the smaller one; ties -> 0).""" - return 0 if len(legs[0]) <= len(legs[1]) else 1 + The members that stay keep their order and the new ones follow, so the + list does not depend on the order the changes were noticed in. The raid + over the result is built empty (device_controller.reshape_jm_raid), so no + member has to keep the position it was written in. + """ + gone = set(gone) + kept = [m for m in current if m not in gone] + return kept + [m for m in dict.fromkeys(added) if m not in kept and m not in gone] -def plan_reconfigure(legs: list[list], *, failed=None, added=None) -> dict: - """Plan the leg rebuild(s) for a drive lifecycle event. +def is_jm_raid_bdev(name: str, node_id: str) -> bool: + """Whether the raid bdev ``name`` is part of the JM raid of ``node_id``: + the top raid1 or one of its raid0 legs (_create_jm_stack_on_raid names + them raid_jm_ and raid_jm__l).""" + top = f"raid_jm_{node_id}" + return name == top or name.startswith(f"{top}_l") - Args: - legs: current two legs, each a list of member bdev names. - failed: a member (or list of members) permanently removed/failed. Each - is dropped from whichever leg holds it, and that leg is rebuilt. - added: a new (or re-inserted) member bdev. It joins the smaller leg, - which is then rebuilt. A re-inserted drive that's no longer in any - leg is handled here too — it's simply "added". - Returns: - {'rebuild': [sorted leg indices to destroy+recreate], - 'legs': [new leg membership lists]} - - RAID0 cannot grow or drop a member in place, so any membership change means - destroying and recreating that leg's raid0 (then RAID1 resyncs it from the - surviving leg). A leg that loses its last member becomes empty — the caller - runs the array degraded on the surviving leg until a drive is available. - """ - new = [list(legs[0]), list(legs[1])] - rebuild = set() - - if failed is not None: - failed_list = failed if isinstance(failed, (list, tuple, set)) else [failed] - for dev in failed_list: - for i in (0, 1): - if dev in new[i]: - new[i].remove(dev) - rebuild.add(i) - - if added is not None: - i = smaller_leg_index(new) - new[i].append(added) - rebuild.add(i) - - return {"rebuild": sorted(rebuild), "legs": new} +def usable_members(legs: list[list]) -> int: + """How many members' worth of space a RAID 0+1 JM over ``legs`` can use: + the top raid1 is as large as its smallest leg.""" + return min(len(leg) for leg in legs) if legs else 1 def leg_of(member: str, leg_bdevs: list[str], leg_members: list[list[str]]) -> str: diff --git a/simplyblock_core/models/job_schedule.py b/simplyblock_core/models/job_schedule.py index 31d729421d..87fa2f1f94 100644 --- a/simplyblock_core/models/job_schedule.py +++ b/simplyblock_core/models/job_schedule.py @@ -110,6 +110,16 @@ class JobSchedule(BaseModel): # from the fence) and, once the steps are done, ``fenced`` (True). One # active task per site (tasks_controller.add_sync_site_fence_task). FN_SYNC_SITE_FENCE = "sync_site_fence" + # Rebuilds the JM raid of ``node_id`` over the devices the node has now, + # after a device was migrated out for good or one was added + # (device_controller.reshape_jm_raid). Runs on the restart runner, which + # keeps it apart from a restart of the same node. function_params carries + # ``phase`` once the rebuild has started: "rebuild" while the JM stack is + # down or being built, "resync" while the empty JM is brought up to date, + # then with ``ready_polls`` (consecutive polls that found every journal in + # sync) and ``members`` (the new member list). One open task per node + # (tasks_controller.add_jm_raid_reshape_task). + FN_JM_RAID_RESHAPE = "jm_raid_reshape" canceled: bool = False cluster_id: str = "" diff --git a/simplyblock_core/rpc_client.py b/simplyblock_core/rpc_client.py index cdfa02aa69..8ab7c4cd15 100644 --- a/simplyblock_core/rpc_client.py +++ b/simplyblock_core/rpc_client.py @@ -2242,8 +2242,11 @@ def nvmf_get_blocked_ports(self) -> set[int]: entries = blocked.get("blocked_ports", []) if isinstance(blocked, dict) else [] return {int(e.get("port", -1)) for e in entries} - def bdev_raid_get_bdevs(self): - return self._request("bdev_raid_get_bdevs", category="online") + def bdev_raid_get_bdevs(self, category="online"): + """The raid bdevs of ``category``: "online" (the default), "configuring", + "offline" or "all". A raid that lost a member it cannot run without is + not online, and is still there to be deleted.""" + return self._request("bdev_raid_get_bdevs", category=category) def rpc_get_methods(self): """Names of every RPC method the node's running SPDK app exposes diff --git a/simplyblock_core/services/tasks_runner_restart.py b/simplyblock_core/services/tasks_runner_restart.py index 6e7eebd109..cef6ef09c5 100644 --- a/simplyblock_core/services/tasks_runner_restart.py +++ b/simplyblock_core/services/tasks_runner_restart.py @@ -10,10 +10,12 @@ from simplyblock_core.models.job_schedule import JobSchedule from simplyblock_core.models.nvme_device import NVMeDevice from simplyblock_core.models.storage_node import StorageNode +from simplyblock_core.rpc_client import RPCException from simplyblock_core.services.task_runner_base import ( RunnerSpec, TaskAbort, TaskDefer, + TaskProgress, TaskRetry, checkpoint, serve, @@ -245,6 +247,99 @@ def task_runner(task): return task_runner_device(task) if task.function_name == JobSchedule.FN_NODE_RESTART: return task_runner_node(task) + if task.function_name == JobSchedule.FN_JM_RAID_RESHAPE: + return task_runner_jm_reshape(task) + + +# Consecutive polls, one runner cycle apart, that must find every journal in +# sync before a rebuilt JM raid counts as resynchronised: the journal +# coordinator starts its replication a few seconds after the new JM connects, +# and a poll that lands before that reads "in sync" too. +JM_RESHAPE_READY_POLLS = 3 + + +def _jm_reshape_blocker(task, node) -> str: + """Why the JM raid rebuild of ``node`` must not start now, or "". + + The rebuild leaves the node without a journal copy of its own until the + resync is done, so it starts only when nothing else is in the way: every + node online, the cluster active, no data movement or restart queued, no + other node being rebuilt, and every journal this JM belongs to in sync.""" + cluster = db.get_cluster_by_id(task.cluster_id) + if cluster.status != Cluster.STATUS_ACTIVE: + return f"cluster is {cluster.status}" + for peer in db.get_storage_nodes_by_cluster_id(task.cluster_id): + if peer.status not in (StorageNode.STATUS_ONLINE, StorageNode.STATUS_REMOVED): + return f"node {peer.get_id()} is {peer.status}" + blocking = tasks_controller.get_jm_raid_reshape_blocking_tasks(task.cluster_id) + if blocking: + return f"task {blocking[0].function_name} {blocking[0].uuid} is open" + for other in tasks_controller.get_active_jm_raid_reshape_tasks(task.cluster_id): + if other.uuid != task.uuid and other.function_params.get("phase"): + return f"the JM raid of node {other.node_id} is being rebuilt" + pending = device_controller.jm_resync_pending(node) + if pending: + return f"journal not in sync: {'; '.join(pending)}" + return "" + + +def task_runner_jm_reshape(task): + """Rebuild the JM raid of the task's node over its current devices and + wait for the journal resync (device_controller.reshape_jm_raid). + + Three stages, recorded in function_params["phase"] so that a runner that + dies in between carries on where it was: not started (every precondition + is checked, nothing was touched), "rebuild" (the old JM stack is being or + was taken down; the build is repeated until it succeeds), "resync" (the + new JM is up; polled until every journal it belongs to is in sync).""" + try: + node = db.get_storage_node_by_id(task.node_id) + except KeyError: + raise TaskAbort("node not found") + if node.status == StorageNode.STATUS_REMOVED: + raise TaskAbort("node is removed") + if node.status != StorageNode.STATUS_ONLINE: + raise TaskDefer(f"node is {node.status}") + + phase = task.function_params.get("phase") + if not phase: + if not device_controller.jm_raid_reshape_needed(node): + set_result(task, "JM raid already matches the node's devices") + return + blocker = _jm_reshape_blocker(task, node) + if blocker: + raise TaskDefer(f"JM raid rebuild waits: {blocker}") + task = checkpoint(task, phase="rebuild") + if task is None: + raise TaskAbort("canceled before the JM raid rebuild started") + phase = "rebuild" + + if phase == "rebuild": + try: + members = device_controller.reshape_jm_raid(node.get_id()) + except device_controller.JMReshapeNotReady as e: + raise TaskRetry(f"JM raid rebuild not possible yet: {e}") + except (device_controller.JMReshapeError, RPCException) as e: + raise TaskRetry(f"JM raid rebuild failed: {e}") + task = checkpoint(task, phase="resync", members=members, ready_polls=0) + if task is None: + # The JM is rebuilt and online either way; only the wait is dropped. + raise TaskAbort("canceled after the JM raid was rebuilt") + # The journal coordinator needs a few seconds to see the new JM and + # start replicating to it; a poll before that reads "in sync". + time.sleep(5) + + node = db.get_storage_node_by_id(task.node_id) + pending = device_controller.jm_resync_pending(node) + if pending: + if task.function_params.get("ready_polls"): + checkpoint(task, ready_polls=0) + raise TaskProgress(f"journal resync running: {'; '.join(pending)}") + polls = int(task.function_params.get("ready_polls", 0)) + 1 + if polls < JM_RESHAPE_READY_POLLS: + checkpoint(task, ready_polls=polls) + raise TaskProgress(f"journals in sync ({polls}/{JM_RESHAPE_READY_POLLS} polls)") + set_result(task, f"JM raid rebuilt over {task.function_params.get('members')}; journals in sync") def task_runner_device(task): @@ -309,6 +404,11 @@ def _abandon_task(task): """ ceiling_reached = 0 <= task.max_retry <= task.retry + if task.function_name == JobSchedule.FN_JM_RAID_RESHAPE: + # Nothing to give up on: the node keeps the JM it has, or none until + # its next restart builds one. + return + if task.function_name == JobSchedule.FN_NODE_RESTART: if ceiling_reached and not task.canceled: _give_up_on_node(task) @@ -728,7 +828,8 @@ def _watchdog_orphaned_transitional_nodes(cluster_id): SPEC = RunnerSpec( name="tasks-runner-restart", - function_names=[JobSchedule.FN_DEV_RESTART, JobSchedule.FN_NODE_RESTART], + function_names=[JobSchedule.FN_DEV_RESTART, JobSchedule.FN_NODE_RESTART, + JobSchedule.FN_JM_RAID_RESHAPE], handler=task_runner, on_finish=_abandon_task, on_cycle=lambda cluster: _watchdog_orphaned_transitional_nodes(cluster.get_id()), diff --git a/simplyblock_core/storage_node_ops.py b/simplyblock_core/storage_node_ops.py index a42c244df3..c27e90d2f2 100644 --- a/simplyblock_core/storage_node_ops.py +++ b/simplyblock_core/storage_node_ops.py @@ -1712,7 +1712,12 @@ class JMRaidNoCurrentLeg(Exception): def _create_jm_stack_on_raid(rpc_client, jm_nvme_bdevs, snode: StorageNode, after_restart, - missing=()): + missing=(), layout=""): + # ``layout`` names the geometry for a caller that builds the raid over a + # member list other than the recorded one (device_controller. + # reshape_jm_raid), where the shape of the record no longer tells it. A + # layout pinned on the cluster still wins. + # # ``jm_nvme_bdevs`` is always the JM's full member list, in the order it # was first built in. ``missing`` names the members that are not there # (a node restart with a drive gone): the geometry is still planned over @@ -1723,10 +1728,11 @@ def _create_jm_stack_on_raid(rpc_client, jm_nvme_bdevs, snode: StorageNode, afte # RAID 0+1 journal layout (see simplyblock_core/jm_raid.py): # 1 device -> no raid (bare device) # 2 devices -> raid1 over two single-device legs (a 2-way mirror) - # > 2 devices-> two ±1 balanced raid0 legs, mirrored by a top raid1 + # > 2 devices-> ±1 balanced raid0 legs of at most four devices each, two + # of them up to eight devices, mirrored by a top raid1 # The top raid bdev keeps the name raid_jm_ so the alceml/jm stack - # above is unchanged; the two raid0 legs are raid_jm__l{0,1}. This - # caps journal write amplification at 2x/node instead of N-way mirroring. + # above is unchanged; the raid0 legs are raid_jm__l. A journal + # write costs one device write per leg instead of one per device. node = snode.get_id() # Resolve the JM RAID geometry to build. It is NOT recorded on disk (raid @@ -1745,7 +1751,7 @@ def _create_jm_stack_on_raid(rpc_client, jm_nvme_bdevs, snode: StorageNode, afte db_controller = DBController() cluster = db_controller.get_cluster_by_id(snode.cluster_id) jm_dev = snode.jm_device - layout = (getattr(cluster, "jm_raid_layout", "") or "").strip() + layout = (getattr(cluster, "jm_raid_layout", "") or "").strip() or layout if not layout: prior_legs = list(getattr(jm_dev, "jm_leg_bdevs", None) or []) if jm_dev else [] prior_raid = getattr(jm_dev, "raid_bdev", "") if jm_dev else "" @@ -1756,7 +1762,10 @@ def _create_jm_stack_on_raid(rpc_client, jm_nvme_bdevs, snode: StorageNode, afte logger.info("JM RAID geometry for %s: %s (%d member(s))", node[:8], layout, len(jm_nvme_bdevs)) - plan = jm_raid.plan_topology(jm_nvme_bdevs, layout=layout) + # A JM that holds a journal keeps the legs it was built with; one that is + # formatted is planned anew (jm_raid.plan_topology). + recorded_legs = list(jm_dev.jm_leg_members or []) if after_restart and jm_dev else None + plan = jm_raid.plan_topology(jm_nvme_bdevs, layout=layout, legs=recorded_legs) missing = set(missing) leg_bdevs = [] leg_members = [] @@ -9239,8 +9248,14 @@ def _reconcile_discovered_devices(snode, nvme_devs): # The members of an lblk journal raid are block devices of their own. The # JM record keeps them by bdev name, which for an AIO device is derived # from its serial (utils.aio_bdev_name_for_serial); they are journal, and - # never a new data device. + # never a new data device. That holds for every journal partition the node + # record knows, in the raid or not: the one of a device that was migrated + # out leaves the raid (device_controller.reshape_jm_raid) and may still be + # on the host, and one that has not joined yet is not in the list either. jm_raid_members = set(snode.jm_device.jm_nvme_bdev_list) if snode.jm_device else set() + jm_raid_members.update( + utils.aio_bdev_name_for_serial(e["serial"]) for e in snode.lblk_devices or [] + if e.get("journal_raid") and e.get("serial")) for dev in nvme_devs: if dev.serial_number == jm_dev_sn: diff --git a/simplyblock_core/utils/__init__.py b/simplyblock_core/utils/__init__.py index e6a56dd350..82f7755240 100644 --- a/simplyblock_core/utils/__init__.py +++ b/simplyblock_core/utils/__init__.py @@ -2439,25 +2439,25 @@ def lblk_journal_raid_member_size(unit_sizes, jm_percent=3) -> int: """Size of each journal raid member of a node whose devices have ``unit_sizes``, in bytes, a whole number of MiB. - The journal the node can use is ``jm_percent`` of its total selected - capacity, floored at LBLK_JM_MIN_SIZE. Every device contributes a member - of the same size (jm_raid.member_size_for_usable gives it), and none - more than LBLK_JM_SPLIT_MAX_FRACTION of itself. Pure.""" - from simplyblock_core import jm_raid - + Every device gives a journal partition of the same size: ``jm_percent`` + of the smallest device, floored at LBLK_JM_MIN_SIZE, and never more than + LBLK_JM_SPLIT_MAX_FRACTION of that device. The size depends on no other + device and not on their number, so a device that joins the node later is + split to the same size and none of the existing partitions has to change. + The journal the node can use is that size times the devices of the + smallest raid0 leg (jm_raid.usable_members): mirrored, about half of what + the devices give. Pure.""" sizes = [int(s) for s in unit_sizes] - total_size = sum(sizes) - usable = max(total_size * int(jm_percent) // 100, constants.LBLK_JM_MIN_SIZE) - member = jm_raid.member_size_for_usable(usable, len(sizes)) + smallest = min(sizes) + member = max(smallest * int(jm_percent) // 100, constants.LBLK_JM_MIN_SIZE) member = -(-member // _MIB) * _MIB - max_member = int(min(sizes) * constants.LBLK_JM_SPLIT_MAX_FRACTION) + max_member = int(smallest * constants.LBLK_JM_SPLIT_MAX_FRACTION) if member > max_member: raise ValueError( - f"journal needs {usable} bytes ({jm_percent}% of {total_size}, " - f"min {constants.LBLK_JM_MIN_SIZE}), which takes {member} bytes of each of " - f"the node's {len(sizes)} devices, but the smallest one ({min(sizes)} bytes) " - f"may contribute at most {max_member}; provide larger devices or lower " - f"--jm-percent") + f"each device gives a journal partition of {member} bytes ({jm_percent}% of " + f"the smallest of the node's {len(sizes)} devices, min " + f"{constants.LBLK_JM_MIN_SIZE}), but that device ({smallest} bytes) may " + f"contribute at most {max_member}; provide larger devices") return member @@ -2534,9 +2534,8 @@ def lblk_node_journal_layout(lblk_entries, jm_percent=3, journal_device=False, - A node of two or more devices, partitions and whole disks alike, carves it from all of them: every device gets a journal partition of the same size, and the journal is the RAID 0+1 over those members - (split_lblk_journal_raid). ``jm_percent`` of the node's capacity is the - journal the node can use, not the space taken: see - lblk_journal_raid_member_size. + (split_lblk_journal_raid). Each one is ``jm_percent`` of the smallest + device: see lblk_journal_raid_member_size. - A node whose devices already carry such members (an earlier split, reused by detect_lblk_devices) keeps them. A device of it without one -- a split that failed half way, a device added to the selection -- is diff --git a/simplyblock_web/api/v2/_dtos.py b/simplyblock_web/api/v2/_dtos.py index c946c655bf..397450ee05 100644 --- a/simplyblock_web/api/v2/_dtos.py +++ b/simplyblock_web/api/v2/_dtos.py @@ -158,6 +158,7 @@ "sync_promote", "sync_resync", "sync_site_fence", + "jm_raid_reshape", ] diff --git a/tests/unit/test_jm_raid.py b/tests/unit/test_jm_raid.py index 373457aeb3..71404ebf83 100644 --- a/tests/unit/test_jm_raid.py +++ b/tests/unit/test_jm_raid.py @@ -1,6 +1,6 @@ """ Unit tests for simplyblock_core/jm_raid.py — the Journal-Manager RAID topology -and reconfiguration planner. +planner. Background: the per-node JM device used to be an N-way RAID1 mirror across the JM partition (`p1`) of every drive, which costs N physical writes per journal @@ -8,13 +8,14 @@ - 1 device -> no raid (test-only single-device node) - 2 devices -> raid1 over two single-device legs == a 2-way mirror - - >2 devices-> split drives into two ±1 balanced groups, raid0 each group, - raid1 over the two raid0 legs + - >2 devices-> split drives into ±1 balanced groups of at most four (two + groups up to eight drives), raid0 each group, raid1 over + the raid0 legs -That caps amplification at 2× per node regardless of drive count, and avoids +That costs one device write per leg instead of one per drive, and avoids SPDK's raid5f full-stripe-write constraint. These tests pin the pure planning -logic that decides the topology and the per-leg rebuild actions for the drive -lifecycle (fail / add / re-insert / both-legs-lost). +logic that decides the topology. What happens when a node's drives change is +in test_jm_raid_reshape.py. """ import importlib.util @@ -34,25 +35,39 @@ def _load(): JM = _load() -class TestSplitTwoGroups(unittest.TestCase): - def test_sizes_balanced_within_one(self): - # (input length) -> expected (len groupA, len groupB) +class TestSplitGroups(unittest.TestCase): + def test_group_sizes(self): + # (input length) -> expected group sizes: at most four devices per + # group, at least two groups, sizes within one of each other. expected = {2: (1, 1), 3: (2, 1), 4: (2, 2), 5: (3, 2), - 6: (3, 3), 7: (4, 3), 8: (4, 4), 10: (5, 5)} - for n, (la, lb) in expected.items(): - a, b = JM.split_two_groups(list(range(n))) - self.assertEqual((len(a), len(b)), (la, lb), f"n={n}") - self.assertLessEqual(abs(len(a) - len(b)), 1, f"n={n}") - - def test_partition_is_complete_and_disjoint(self): - items = [f"d{i}" for i in range(7)] - a, b = JM.split_two_groups(items) - self.assertEqual(sorted(a + b), sorted(items)) - self.assertFalse(set(a) & set(b)) - - def test_larger_group_first(self): - a, b = JM.split_two_groups([1, 2, 3, 4, 5]) # 5 -> (3,2) - self.assertGreaterEqual(len(a), len(b)) + 6: (3, 3), 7: (4, 3), 8: (4, 4), + 9: (3, 3, 3), 10: (4, 3, 3), 11: (4, 4, 3), 12: (4, 4, 4), + 13: (4, 3, 3, 3), 16: (4, 4, 4, 4), 17: (4, 4, 3, 3, 3)} + for n, sizes in expected.items(): + groups = JM.split_groups(list(range(n))) + self.assertEqual(tuple(len(g) for g in groups), sizes, f"n={n}") + + def test_no_group_wider_than_the_cap_and_never_fewer_than_two(self): + for n in range(2, 40): + groups = JM.split_groups(list(range(n))) + self.assertGreaterEqual(len(groups), 2, f"n={n}") + self.assertLessEqual(max(len(g) for g in groups), JM.GROUP_MAX_DEVICES, f"n={n}") + self.assertLessEqual(max(map(len, groups)) - min(map(len, groups)), 1, f"n={n}") + + def test_up_to_eight_devices_it_is_the_split_into_two_halves(self): + """Every RAID 0+1 JM built before the groups were capped was split + into two halves, the first one taking the odd device. The capped + split must give the same two legs for the same member list, or a + restart would read those journals back scrambled.""" + for n in range(2, 9): + items = [f"d{i}" for i in range(n)] + half = (n + 1) // 2 + self.assertEqual(JM.split_groups(items), [items[:half], items[half:]], f"n={n}") + + def test_partition_is_complete_in_order_and_disjoint(self): + items = [f"d{i}" for i in range(11)] + groups = JM.split_groups(items) + self.assertEqual([m for g in groups for m in g], items) class TestPlanTopology(unittest.TestCase): @@ -82,57 +97,5 @@ def test_six_devices_3_3(self): self.assertEqual(sorted(p["legs"][0] + p["legs"][1]), list("abcdef")) -class TestLegHelpers(unittest.TestCase): - def test_is_balanced(self): - self.assertTrue(JM.is_balanced([["a", "b"], ["c"]])) # 2,1 - self.assertTrue(JM.is_balanced([["a"], ["b"]])) # 1,1 - self.assertFalse(JM.is_balanced([["a", "b", "c"], ["d"]])) # 3,1 - - def test_smaller_leg_index(self): - self.assertEqual(JM.smaller_leg_index([["a", "b"], ["c"]]), 1) - self.assertEqual(JM.smaller_leg_index([["a"], ["b", "c"]]), 0) - # tie -> leg 0 - self.assertEqual(JM.smaller_leg_index([["a"], ["b"]]), 0) - - -class TestPlanReconfigure(unittest.TestCase): - def test_failed_device_rebuilds_only_its_leg(self): - legs = [["a", "b"], ["c", "d"]] - r = JM.plan_reconfigure(legs, failed="b") - self.assertEqual(r["rebuild"], [0]) - self.assertEqual(r["legs"], [["a"], ["c", "d"]]) - - def test_added_device_goes_to_smaller_leg(self): - legs = [["a", "b"], ["c"]] # leg 1 is smaller - r = JM.plan_reconfigure(legs, added="x") - self.assertEqual(r["rebuild"], [1]) - self.assertEqual(r["legs"], [["a", "b"], ["c", "x"]]) - - def test_failure_on_both_legs_rebuilds_both(self): - legs = [["a", "b"], ["c", "d"]] - r = JM.plan_reconfigure(legs, failed=["b", "d"]) - self.assertEqual(r["rebuild"], [0, 1]) - self.assertEqual(r["legs"], [["a"], ["c"]]) - - def test_reinserted_device_is_added_to_smaller_leg(self): - # a device that is no longer part of any leg's raid0 is re-incorporated - legs = [["a", "b", "c"], ["d", "e"]] - r = JM.plan_reconfigure(legs, added="f") - self.assertEqual(r["rebuild"], [1]) - self.assertEqual(r["legs"], [["a", "b", "c"], ["d", "e", "f"]]) - - def test_no_event_no_rebuild(self): - legs = [["a", "b"], ["c", "d"]] - r = JM.plan_reconfigure(legs) - self.assertEqual(r["rebuild"], []) - self.assertEqual(r["legs"], legs) - - def test_failed_device_not_present_is_noop(self): - legs = [["a", "b"], ["c", "d"]] - r = JM.plan_reconfigure(legs, failed="zzz") - self.assertEqual(r["rebuild"], []) - self.assertEqual(r["legs"], legs) - - if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_jm_raid_layout.py b/tests/unit/test_jm_raid_layout.py index 2a34cef7dd..1052b4562f 100644 --- a/tests/unit/test_jm_raid_layout.py +++ b/tests/unit/test_jm_raid_layout.py @@ -99,7 +99,7 @@ def test_a_recorded_raid_without_legs_is_treated_as_legacy(self): def test_it_plans_with_the_resolved_layout_not_the_default(self): src = self._src() - assert "plan_topology(jm_nvme_bdevs, layout=layout)" in src + assert "plan_topology(jm_nvme_bdevs, layout=layout, legs=recorded_legs)" in src def test_legacy_level_builds_one_raid1_over_all_members(self): src = self._src() diff --git a/tests/unit/test_jm_raid_reshape.py b/tests/unit/test_jm_raid_reshape.py new file mode 100644 index 0000000000..63b36ddfee --- /dev/null +++ b/tests/unit/test_jm_raid_reshape.py @@ -0,0 +1,865 @@ +"""The JM raid follows the devices of its node. + +A node's journal raid is built over the journal partitions of its devices. A +device that fails and is migrated out takes its partition with it for good, +and a device that is added brings one. The raid cannot take a member in or +give one up in place (raid0 legs, no superblock), so it is built anew, empty, +over the members the node's devices call for, and the journal coordinator of +the LVS leader resynchronises it from the node's other journal copies. + + - jm_raid: the member list after a change, the layout a record was built + under, and the legs: at most four devices each, and for a JM that holds a + journal always the ones it was built with. + - device_controller: which members the node's devices call for, the + teardown that leaves no raid behind, the rebuild, and whether the resync + is done. + - tasks_runner_restart: the task that does it, one node at a time and only + on a quiet cluster. +""" +import unittest +from unittest.mock import MagicMock, patch + +import pytest + +import simplyblock_core.services.task_runner_base as trb +from simplyblock_core import jm_raid, storage_node_ops, utils +from simplyblock_core.controllers import device_controller, tasks_controller +from simplyblock_core.models.cluster import Cluster +from simplyblock_core.models.job_schedule import JobSchedule +from simplyblock_core.models.nvme_device import JMDevice, NVMeDevice +from simplyblock_core.models.storage_node import StorageNode +from simplyblock_core.rpc_client import RPCException +from simplyblock_core.services.task_runner_base import ( + TaskAbort, + TaskDefer, + TaskProgress, + TaskRetry, +) + +ONLINE = NVMeDevice.STATUS_ONLINE +MIGRATED = NVMeDevice.STATUS_FAILED_AND_MIGRATED + + +def _lblk_node(statuses, members=None, node_id="n1"): + """An lblk node of len(statuses) devices, each a journal partition and a + data partition. ``members`` is the JM raid's recorded member list; all of + the node's journal partitions by default.""" + snode = StorageNode() + snode.uuid = node_id + snode.cluster_id = "c1" + snode.status = StorageNode.STATUS_ONLINE + snode.lblk_devices = [] + snode.nvme_devices = [] + names = [] + for index, status in enumerate(statuses): + snode.lblk_devices.append({"name": f"sd{index}1", "serial": f"J{index}", "journal": True, + "journal_raid": True, "data_serial": f"D{index}"}) + snode.lblk_devices.append({"name": f"sd{index}2", "serial": f"D{index}"}) + dev = NVMeDevice() + dev.uuid = f"dev{index}" + dev.serial_number = f"D{index}" + dev.bdev_type = "aio" + dev.nvme_bdev = utils.aio_bdev_name_for_serial(f"D{index}") + dev.status = status + snode.nvme_devices.append(dev) + names.append(utils.aio_bdev_name_for_serial(f"J{index}")) + jm = JMDevice() + jm.uuid = "jm1" + jm.status = JMDevice.STATUS_ONLINE + jm.jm_nvme_bdev_list = list(names if members is None else members) + jm.jm_bdev = f"jm_{node_id}" + jm.alceml_bdev = f"alceml_jm_{node_id}" + jm.raid_bdev = f"raid_jm_{node_id}" if len(jm.jm_nvme_bdev_list) > 1 else jm.jm_nvme_bdev_list[0] + legs = jm_raid.split_groups(jm.jm_nvme_bdev_list) if len(jm.jm_nvme_bdev_list) > 1 else [] + jm.jm_leg_members = legs + jm.jm_leg_bdevs = [leg[0] if len(leg) == 1 else f"raid_jm_{node_id}_l{i}" + for i, leg in enumerate(legs)] + snode.jm_device = jm + return snode, names + + +def _nvme_node(statuses, members): + """An NVMe node whose drives are cut into a journal partition (p1) and one + data partition (p2).""" + snode = StorageNode() + snode.uuid = "n1" + snode.num_partitions_per_dev = 1 + snode.jm_percent = 3 + snode.nvme_devices = [] + for index, status in enumerate(statuses): + dev = NVMeDevice() + dev.uuid = f"dev{index}" + dev.nvme_controller = f"nvme_{index}" + dev.nvme_bdev = f"nvme_{index}n1p2" + dev.is_partition = True + dev.status = status + snode.nvme_devices.append(dev) + jm = JMDevice() + jm.uuid = "jm1" + jm.jm_nvme_bdev_list = list(members) + snode.jm_device = jm + return snode + + +class TestReshapedMembers(unittest.TestCase): + + def test_gone_members_leave_and_the_rest_keep_their_order(self): + self.assertEqual(jm_raid.reshaped_members(list("abcd"), ["b"], []), list("acd")) + + def test_added_members_follow_the_ones_that_stay(self): + self.assertEqual(jm_raid.reshaped_members(list("ab"), [], ["c", "d"]), list("abcd")) + + def test_a_member_already_there_is_not_added_twice(self): + self.assertEqual(jm_raid.reshaped_members(list("ab"), [], ["b", "c", "c"]), list("abc")) + + def test_a_gone_member_is_not_added_back(self): + self.assertEqual(jm_raid.reshaped_members(list("ab"), ["b"], ["b", "c"]), list("ac")) + + def test_nothing_changed(self): + self.assertEqual(jm_raid.reshaped_members(list("abc"), [], list("abc")), list("abc")) + + +class TestLayoutOfRecord(unittest.TestCase): + + def test_recorded_legs_are_raid01(self): + self.assertEqual(jm_raid.layout_of_record(list("abcd"), "raid_jm_n", ["l0", "l1"]), + jm_raid.LAYOUT_RAID01) + + def test_a_raid_without_legs_is_the_legacy_mirror(self): + self.assertEqual(jm_raid.layout_of_record(list("abcd"), "raid_jm_n", []), + jm_raid.LAYOUT_LEGACY) + + def test_a_single_device_grows_into_raid01_not_into_the_legacy_mirror(self): + """A single-device JM records its partition as raid_bdev and no legs, + the shape of a legacy record. Read as legacy, a node growing from one + device to three would get a three-way mirror.""" + self.assertEqual(jm_raid.layout_of_record(["a"], "a", []), jm_raid.LAYOUT_RAID01) + + +class TestRecordedLegs(unittest.TestCase): + + def test_new_jm_of_twelve_devices_gets_three_legs(self): + members = [f"m{i}" for i in range(12)] + legs = jm_raid.plan_topology(members)["legs"] + self.assertEqual([len(leg) for leg in legs], [4, 4, 4]) + + def test_a_jm_built_in_two_halves_keeps_them(self): + """Twelve devices built before the groups were capped are two legs of + six. Re-planned into three legs of four, every stripe would be read + from the wrong drives.""" + members = [f"m{i}" for i in range(12)] + built = [members[:6], members[6:]] + self.assertEqual(jm_raid.plan_topology(members, legs=built)["legs"], built) + + def test_a_record_of_other_members_is_ignored(self): + members = list("abcdef") + legs = jm_raid.plan_topology(members, legs=[list("ab"), list("cd")])["legs"] + self.assertEqual(legs, [list("abc"), list("def")]) + + def test_no_record_plans_anew(self): + self.assertEqual(jm_raid.plan_topology(list("abcd"), legs=None)["legs"], + [list("ab"), list("cd")]) + self.assertEqual(jm_raid.plan_topology(list("abcd"), legs=[])["legs"], + [list("ab"), list("cd")]) + + def test_is_jm_raid_bdev(self): + self.assertTrue(jm_raid.is_jm_raid_bdev("raid_jm_n1", "n1")) + self.assertTrue(jm_raid.is_jm_raid_bdev("raid_jm_n1_l2", "n1")) + self.assertFalse(jm_raid.is_jm_raid_bdev("raid_jm_n10", "n1")) + self.assertFalse(jm_raid.is_jm_raid_bdev("raid_jm_n2_l0", "n1")) + + +class TestStackKeepsRecordedLegs(unittest.TestCase): + """storage_node_ops._create_jm_stack_on_raid, RPCs mocked.""" + + def _run(self, members, recorded_legs=None, after_restart=False, layout="", pinned=""): + rpc = MagicMock() + rpc.bdev_raid_create.return_value = True + rpc.bdev_jm_create.return_value = True + rpc.bdev_get.return_value = {"block_size": 512, "num_blocks": 1000} + snode = MagicMock() + snode.get_id.return_value = "n1" + snode.enable_ha_jm = False + snode.data_nics = [] + snode.create_alceml.return_value = True + snode.jm_device = None + if recorded_legs is not None: + jm = JMDevice() + jm.raid_bdev = "raid_jm_n1" + jm.jm_leg_members = recorded_legs + jm.jm_leg_bdevs = [f"raid_jm_n1_l{i}" for i in range(len(recorded_legs))] + snode.jm_device = jm + cluster = MagicMock() + cluster.jm_raid_layout = pinned + with patch.object(storage_node_ops, "DBController") as db_cls: + db_cls.return_value.get_cluster_by_id.return_value = cluster + jm = storage_node_ops._create_jm_stack_on_raid( + rpc, list(members), snode, after_restart=after_restart, layout=layout) + calls = [(c.args[0], list(c.args[1]), c.args[2]) for c in rpc.bdev_raid_create.call_args_list] + return jm, calls, snode + + def test_restart_of_a_twelve_device_jm_built_in_two_halves(self): + members = [f"m{i}" for i in range(12)] + jm, calls, _ = self._run(members, recorded_legs=[members[:6], members[6:]], + after_restart=True) + self.assertEqual(calls, [ + ("raid_jm_n1_l0", members[:6], "0"), + ("raid_jm_n1_l1", members[6:], "0"), + ("raid_jm_n1", ["raid_jm_n1_l0", "raid_jm_n1_l1"], "1"), + ]) + self.assertEqual(jm.jm_leg_members, [members[:6], members[6:]]) + + def test_new_twelve_device_jm_is_three_legs_under_one_raid1(self): + members = [f"m{i}" for i in range(12)] + jm, calls, _ = self._run(members) + self.assertEqual(calls, [ + ("raid_jm_n1_l0", members[:4], "0"), + ("raid_jm_n1_l1", members[4:8], "0"), + ("raid_jm_n1_l2", members[8:], "0"), + ("raid_jm_n1", ["raid_jm_n1_l0", "raid_jm_n1_l1", "raid_jm_n1_l2"], "1"), + ]) + + def test_a_formatted_jm_is_planned_anew_whatever_the_record_says(self): + members = [f"m{i}" for i in range(12)] + jm, calls, snode = self._run(members, recorded_legs=[members[:6], members[6:]], + after_restart=False) + self.assertEqual([len(leg) for leg in jm.jm_leg_members], [4, 4, 4]) + self.assertEqual(snode.create_alceml.call_args.kwargs["pba_init_mode"], 3) + + def test_the_layout_given_decides_when_the_record_cannot(self): + # The record of a single-device JM looks legacy (a raid_bdev, no legs). + rpc_jm = JMDevice() + rpc_jm.raid_bdev = "a" + with patch.object(storage_node_ops, "DBController") as db_cls: + cluster = MagicMock() + cluster.jm_raid_layout = "" + db_cls.return_value.get_cluster_by_id.return_value = cluster + rpc = MagicMock() + rpc.bdev_get.return_value = {"block_size": 512, "num_blocks": 1000} + snode = MagicMock() + snode.get_id.return_value = "n1" + snode.enable_ha_jm = False + snode.data_nics = [] + snode.jm_device = rpc_jm + jm = storage_node_ops._create_jm_stack_on_raid( + rpc, list("abc"), snode, after_restart=False, layout=jm_raid.LAYOUT_RAID01) + self.assertEqual(jm.jm_leg_members, [["a", "b"], ["c"]]) + + def test_a_layout_pinned_on_the_cluster_wins_over_the_one_given(self): + jm, calls, _ = self._run(list("abc"), layout=jm_raid.LAYOUT_RAID01, + pinned=jm_raid.LAYOUT_LEGACY) + self.assertEqual(calls, [("raid_jm_n1", list("abc"), "1")]) + self.assertEqual(jm.jm_leg_bdevs, []) + + +class TestTargetMembers(unittest.TestCase): + + def test_all_devices_online_changes_nothing(self): + snode, names = _lblk_node([ONLINE] * 4) + self.assertEqual(device_controller.jm_raid_target_members(snode), names) + self.assertFalse(device_controller.jm_raid_reshape_needed(snode)) + + def test_a_migrated_out_device_takes_its_member_with_it(self): + snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE, ONLINE]) + self.assertEqual(device_controller.jm_raid_target_members(snode), + [names[0], names[2], names[3]]) + self.assertTrue(device_controller.jm_raid_reshape_needed(snode)) + + def test_a_device_that_is_only_missing_keeps_its_member(self): + for status in (NVMeDevice.STATUS_REMOVED, NVMeDevice.STATUS_UNAVAILABLE, + NVMeDevice.STATUS_FAILED, NVMeDevice.STATUS_READONLY): + snode, names = _lblk_node([ONLINE, status, ONLINE]) + self.assertEqual(device_controller.jm_raid_target_members(snode), names, status) + self.assertFalse(device_controller.jm_raid_reshape_needed(snode), status) + + def test_an_online_device_whose_partition_is_not_in_the_raid_joins(self): + snode, names = _lblk_node([ONLINE] * 3) + snode.jm_device.jm_nvme_bdev_list = names[:2] + self.assertEqual(device_controller.jm_raid_target_members(snode), names) + self.assertTrue(device_controller.jm_raid_reshape_needed(snode)) + + def test_a_new_device_joins_only_once_it_serves_data(self): + snode, names = _lblk_node([ONLINE, ONLINE, NVMeDevice.STATUS_NEW], members=None) + snode.jm_device.jm_nvme_bdev_list = names[:2] + self.assertEqual(device_controller.jm_raid_target_members(snode), names[:2]) + + def test_shrink_from_three_to_two_and_to_one(self): + snode, names = _lblk_node([ONLINE, ONLINE, MIGRATED]) + self.assertEqual(device_controller.jm_raid_target_members(snode), names[:2]) + snode, names = _lblk_node([ONLINE, MIGRATED]) + self.assertEqual(device_controller.jm_raid_target_members(snode), names[:1]) + + def test_no_device_left_is_nothing_to_build(self): + snode, _ = _lblk_node([MIGRATED, MIGRATED]) + self.assertEqual(device_controller.jm_raid_target_members(snode), []) + self.assertFalse(device_controller.jm_raid_reshape_needed(snode)) + + def test_a_journal_on_a_dedicated_device_is_not_a_raid_over_the_devices(self): + snode, _ = _lblk_node([ONLINE, ONLINE]) + snode.jm_device.jm_nvme_bdev_list = [] + self.assertEqual(device_controller.jm_raid_target_members(snode), []) + snode.jm_device = None + self.assertEqual(device_controller.jm_raid_target_members(snode), []) + self.assertFalse(device_controller.jm_raid_reshape_needed(snode)) + + def test_nvme_member_leaves_when_every_partition_of_its_drive_is_migrated(self): + snode = _nvme_node([ONLINE, MIGRATED, ONLINE], ["nvme_0n1p1", "nvme_1n1p1", "nvme_2n1p1"]) + self.assertEqual(device_controller.jm_raid_target_members(snode), + ["nvme_0n1p1", "nvme_2n1p1"]) + + def test_nvme_member_stays_while_one_partition_of_its_drive_is_in_use(self): + snode = _nvme_node([ONLINE, MIGRATED], ["nvme_0n1p1", "nvme_1n1p1"]) + other = NVMeDevice() + other.nvme_controller = "nvme_1" + other.nvme_bdev = "nvme_1n1p3" + other.is_partition = True + other.status = ONLINE + snode.nvme_devices.append(other) + self.assertEqual(device_controller.jm_raid_target_members(snode), + ["nvme_0n1p1", "nvme_1n1p1"]) + + def test_nvme_controller_names_are_not_matched_by_prefix(self): + # nvme_1 and nvme_11 are two drives. + snode = _nvme_node([MIGRATED], ["nvme_11n1p1"]) + snode.nvme_devices[0].nvme_controller = "nvme_1" + self.assertEqual(device_controller.jm_raid_target_members(snode), ["nvme_11n1p1"]) + + def test_nvme_drive_with_a_journal_partition_the_raid_does_not_use_joins(self): + snode = _nvme_node([ONLINE, ONLINE, ONLINE], ["nvme_0n1p1", "nvme_1n1p1"]) + self.assertEqual(device_controller.jm_raid_target_members(snode), + ["nvme_0n1p1", "nvme_1n1p1", "nvme_2n1p1"]) + + def test_an_unpartitioned_nvme_drive_brings_no_journal_partition(self): + snode = _nvme_node([ONLINE, ONLINE], ["nvme_0n1p1"]) + snode.nvme_devices[1].nvme_bdev = "nvme_1n1" + snode.nvme_devices[1].is_partition = False + self.assertEqual(device_controller.jm_raid_target_members(snode), ["nvme_0n1p1"]) + + +class TestQueueReshape(unittest.TestCase): + + def _queue(self, snode): + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(device_controller.tasks_controller, "add_jm_raid_reshape_task") as add: + db_cls.return_value.get_storage_node_by_id.return_value = snode + device_controller.queue_jm_raid_reshape(snode.get_id()) + return add + + def test_queued_when_the_raid_no_longer_matches(self): + snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) + self._queue(snode).assert_called_once_with("c1", "n1") + + def test_not_queued_when_it_matches(self): + snode, _ = _lblk_node([ONLINE, ONLINE, ONLINE]) + self._queue(snode).assert_not_called() + + def test_a_node_that_is_gone_is_ignored(self): + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(device_controller.tasks_controller, "add_jm_raid_reshape_task") as add: + db_cls.return_value.get_storage_node_by_id.side_effect = KeyError("n1") + device_controller.queue_jm_raid_reshape("n1") + add.assert_not_called() + + def test_a_device_migrated_out_queues_the_rebuild_of_its_node(self): + dev = MagicMock() + dev.node_id = "n1" + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(device_controller, "device_set_state"), \ + patch.object(device_controller, "queue_jm_raid_reshape") as queue: + db_cls.return_value.get_storage_device_by_id.return_value = dev + db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = [] + device_controller.device_set_failed_and_migrated("dev1") + queue.assert_called_once_with("n1") + + +class TestOneOpenTaskPerNode(unittest.TestCase): + + def _open(self, node_id, status=JobSchedule.STATUS_RUNNING, canceled=False): + task = JobSchedule() + task.uuid = f"t-{node_id}" + task.node_id = node_id + task.function_name = JobSchedule.FN_JM_RAID_RESHAPE + task.status = status + task.canceled = canceled + return task + + def _add(self, existing): + with patch.object(tasks_controller, "db") as db, \ + patch.object(tasks_controller, "tasks_events"): + db.get_job_tasks.return_value = existing + return tasks_controller.add_jm_raid_reshape_task("c1", "n1"), db + + def test_added_when_the_node_has_none(self): + task_id, _ = self._add([self._open("n2")]) + self.assertTrue(task_id) + + def test_not_added_twice_for_one_node(self): + task_id, _ = self._add([self._open("n1")]) + self.assertFalse(task_id) + + def test_a_done_or_canceled_task_does_not_count(self): + task_id, _ = self._add([self._open("n1", status=JobSchedule.STATUS_DONE), + self._open("n1", canceled=True)]) + self.assertTrue(task_id) + + def test_blocking_tasks_are_the_ones_that_move_data_or_restart(self): + mig = self._open("n2") + mig.function_name = JobSchedule.FN_NEW_DEV_MIG + comp = self._open("n2") + comp.function_name = JobSchedule.FN_JC_COMP_RESUME + done = self._open("n2", status=JobSchedule.STATUS_DONE) + done.function_name = JobSchedule.FN_NODE_RESTART + with patch.object(tasks_controller, "db") as db: + db.get_job_tasks.return_value = [mig, comp, done, self._open("n3")] + self.assertEqual(tasks_controller.get_jm_raid_reshape_blocking_tasks("c1"), [mig]) + + +class TestDeleteJmStack(unittest.TestCase): + + def _rpc(self, raids, present=None): + rpc = MagicMock() + rpc.bdev_raid_get_bdevs.return_value = [{"name": n} for n in raids] + rpc.bdev_get.side_effect = lambda name: {"name": name} if present is None or name in present else None + rpc.subsystem_get.return_value = {"nqn": "x"} + return rpc + + def test_every_layer_and_every_raid_of_the_node_is_deleted(self): + snode, _ = _lblk_node([ONLINE] * 12) + snode.enable_ha_jm = True + snode.jm_device.nvmf_nqn = "nqn:jm" + snode.jm_device.pt_bdev = "jm_n1_PT" + rpc = self._rpc(["raid_jm_n1_l0", "raid_jm_n1_l1", "raid_jm_n1_l2", "raid_jm_n1", + "raid_jm_n2", "raid_jm_n10_l0", "other"]) + device_controller._delete_jm_stack(snode, rpc) + rpc.subsystem_delete.assert_called_once_with("nqn:jm") + rpc.bdev_PT_NoExcl_delete.assert_called_once_with("jm_n1_PT") + rpc.bdev_jm_delete.assert_called_once_with("jm_n1", safe_removal=True) + rpc.bdev_alceml_delete.assert_called_once_with("alceml_jm_n1") + # The top raid first, then its legs; no raid of another node. + self.assertEqual([c.args[0] for c in rpc.bdev_raid_delete.call_args_list], + ["raid_jm_n1", "raid_jm_n1_l0", "raid_jm_n1_l1", "raid_jm_n1_l2"]) + # A raid that is not online is still found. + rpc.bdev_raid_get_bdevs.assert_called_once_with(category="all") + + def test_a_second_call_after_a_failure_half_way_skips_what_is_gone(self): + snode, _ = _lblk_node([ONLINE] * 4) + snode.enable_ha_jm = True + snode.jm_device.nvmf_nqn = "nqn:jm" + snode.jm_device.pt_bdev = "jm_n1_PT" + rpc = self._rpc(["raid_jm_n1_l1"], present=set()) + rpc.subsystem_get.return_value = None + device_controller._delete_jm_stack(snode, rpc) + rpc.subsystem_delete.assert_not_called() + rpc.bdev_PT_NoExcl_delete.assert_not_called() + rpc.bdev_jm_delete.assert_not_called() + rpc.bdev_alceml_delete.assert_not_called() + rpc.bdev_raid_delete.assert_called_once_with("raid_jm_n1_l1") + + def test_a_single_device_jm_has_no_raid_to_delete(self): + snode, names = _lblk_node([ONLINE]) + rpc = self._rpc([]) + device_controller._delete_jm_stack(snode, rpc) + rpc.bdev_raid_delete.assert_not_called() + + +class TestReshapeJmRaid(unittest.TestCase): + + def _reshape(self, snode, absent=(), new_jm=None, create_error=None): + rpc = MagicMock() + rpc.bdev_get.side_effect = lambda name: None if name in absent else {"name": name} + rpc.bdev_raid_get_bdevs.return_value = [] + self.rpc = rpc + self.order = [] + if new_jm is None: + new_jm = JMDevice() + new_jm.uuid = "jm1" + + def create(*args, **kwargs): + self.order.append("create") + if create_error: + raise create_error + return new_jm + + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(StorageNode, "rpc_client", return_value=rpc), \ + patch.object(device_controller, "set_jm_device_state", + side_effect=lambda _id, state: self.order.append(state)) as set_state, \ + patch.object(device_controller, "_delete_jm_stack", + side_effect=lambda *a: self.order.append("delete")) as delete, \ + patch.object(storage_node_ops, "_create_jm_stack_on_raid", side_effect=create) as build: + db = db_cls.return_value + db.get_storage_node_by_id.return_value = snode + db.atomic_update.side_effect = lambda obj, fn: (fn(obj), self.order.append("record"), obj)[2] + self.db, self.set_state, self.delete, self.build = db, set_state, delete, build + return device_controller.reshape_jm_raid(snode.get_id()) + + def test_rebuilds_over_the_remaining_devices_empty(self): + snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE, ONLINE]) + target = [names[0], names[2], names[3]] + self.assertEqual(self._reshape(snode), target) + args, kwargs = self.build.call_args + self.assertEqual(args[1], target) + self.assertIs(kwargs["after_restart"], False) # formatted, not read back + self.assertEqual(kwargs["layout"], jm_raid.LAYOUT_RAID01) + # Down, torn down, built, recorded, and only then online for the peers. + self.assertEqual(self.order, [JMDevice.STATUS_UNAVAILABLE, "delete", "create", "record", + JMDevice.STATUS_ONLINE]) + + def test_a_legacy_mirror_stays_a_legacy_mirror(self): + snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) + snode.jm_device.jm_leg_bdevs = [] + snode.jm_device.jm_leg_members = [] + self._reshape(snode) + self.assertEqual(self.build.call_args.kwargs["layout"], jm_raid.LAYOUT_LEGACY) + + def test_a_single_device_jm_grows_into_raid01(self): + snode, names = _lblk_node([ONLINE, ONLINE], members=None) + snode.jm_device.jm_nvme_bdev_list = names[:1] + snode.jm_device.raid_bdev = names[0] + snode.jm_device.jm_leg_bdevs = [] + self.assertEqual(self._reshape(snode), names) + self.assertEqual(self.build.call_args.kwargs["layout"], jm_raid.LAYOUT_RAID01) + + def test_nothing_is_touched_while_a_member_is_absent(self): + snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) + with self.assertRaises(device_controller.JMReshapeNotReady) as ctx: + self._reshape(snode, absent={names[2]}) + self.assertIn(names[2], str(ctx.exception)) + self.assertEqual(self.order, []) + + def test_nothing_is_touched_on_a_node_that_is_not_online(self): + snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) + snode.status = StorageNode.STATUS_RESTARTING + with self.assertRaises(device_controller.JMReshapeNotReady): + self._reshape(snode) + self.assertEqual(self.order, []) + + def test_a_node_without_a_raid_over_its_devices_is_refused(self): + snode, _ = _lblk_node([ONLINE, ONLINE]) + snode.jm_device.jm_nvme_bdev_list = [] + with self.assertRaises(device_controller.JMReshapeNotReady): + self._reshape(snode) + self.assertEqual(self.order, []) + + def test_a_failed_build_leaves_the_old_record_for_the_retry(self): + snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) + with self.assertRaises(device_controller.JMReshapeError): + self._reshape(snode, new_jm=False) + self.assertEqual(self.order, [JMDevice.STATUS_UNAVAILABLE, "delete", "create"]) + # The record still names the old members, so the retry still sees + # that the raid does not match the devices. + self.assertEqual(snode.jm_device.jm_nvme_bdev_list, names) + self.assertTrue(device_controller.jm_raid_reshape_needed(snode)) + + def test_an_rpc_failure_during_the_build_is_passed_on(self): + snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) + with self.assertRaises(RPCException): + self._reshape(snode, create_error=RPCException("boom")) + self.assertNotIn("record", self.order) + self.assertNotIn(JMDevice.STATUS_ONLINE, self.order) + + +class TestResyncPending(unittest.TestCase): + + def _node(self, node_id, lvstore, jm_vuid, jm_ids=(), sec="", status=StorageNode.STATUS_ONLINE): + node = StorageNode() + node.uuid = node_id + node.cluster_id = "c1" + node.status = status + node.lvstore = lvstore + node.jm_vuid = jm_vuid + node.jm_ids = list(jm_ids) + node.secondary_node_id = sec + jm = JMDevice() + jm.uuid = f"jm-{node_id}" + node.jm_device = jm + return node + + def _pending(self, nodes, leaders, statuses): + """``leaders``: lvstore -> id of the node that leads it. ``statuses``: + (node id, jm_vuid) -> jc_get_jm_status answer, or an exception.""" + asked = [] + + def rpc_for(node): + rpc = MagicMock() + + def status(jm_vuid): + asked.append((node.get_id(), jm_vuid)) + answer = statuses[(node.get_id(), jm_vuid)] + if isinstance(answer, Exception): + raise answer + return answer + rpc.jc_get_jm_status.side_effect = status + return rpc + + from simplyblock_core.controllers import lvol_controller + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(StorageNode, "rpc_client", autospec=True, + side_effect=lambda self, **kw: rpc_for(self)), \ + patch.object(lvol_controller, "is_node_leader", + side_effect=lambda node, lvs: leaders.get(lvs) == node.get_id()): + db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = nodes + pending = device_controller.jm_resync_pending(nodes[0]) + return pending, asked + + def test_in_sync_when_every_leader_reports_every_jm_ready(self): + n1 = self._node("n1", "LVS_1", 1, jm_ids=["jm-n2"], sec="n2") + n2 = self._node("n2", "LVS_2", 2, jm_ids=["jm-n1"], sec="n1") + pending, asked = self._pending( + [n1, n2], {"LVS_1": "n1", "LVS_2": "n2"}, + {("n1", 1): {"jm_n1": True, "remote_jm_n2n1": True}, + ("n2", 2): {"jm_n2": True, "remote_jm_n1n1": True}}) + self.assertEqual(pending, []) + # Its own journal, and the one it is a remote copy of. + self.assertEqual(sorted(asked), [("n1", 1), ("n2", 2)]) + + def test_a_journal_it_is_no_copy_of_is_not_asked_about(self): + n1 = self._node("n1", "LVS_1", 1) + n3 = self._node("n3", "LVS_3", 3, jm_ids=["jm-n2"]) + pending, asked = self._pending([n1, n3], {"LVS_1": "n1", "LVS_3": "n3"}, + {("n1", 1): {"jm_n1": True}}) + self.assertEqual((pending, asked), ([], [("n1", 1)])) + + def test_replication_running_is_pending(self): + n1 = self._node("n1", "LVS_1", 1) + pending, _ = self._pending([n1], {"LVS_1": "n1"}, + {("n1", 1): {"jm_n1": False, "remote_jm_n2n1": True}}) + self.assertEqual(len(pending), 1) + self.assertIn("LVS_1", pending[0]) + self.assertIn("jm_n1", pending[0]) + + def test_the_leader_is_asked_not_the_owner(self): + n1 = self._node("n1", "LVS_1", 1, sec="n2") + n2 = self._node("n2", "", 0) + pending, asked = self._pending([n1, n2], {"LVS_1": "n2"}, {("n2", 1): {"jm_n1": True}}) + self.assertEqual((pending, asked), ([], [("n2", 1)])) + + def test_no_leader_is_pending(self): + n1 = self._node("n1", "LVS_1", 1) + pending, asked = self._pending([n1], {}, {}) + self.assertEqual(asked, []) + self.assertIn("no leader", pending[0]) + + def test_a_leader_that_cannot_be_asked_is_pending(self): + n1 = self._node("n1", "LVS_1", 1) + pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): RPCException("down")}) + self.assertIn("down", pending[0]) + + def test_an_empty_answer_is_pending(self): + n1 = self._node("n1", "LVS_1", 1) + pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {}}) + self.assertEqual(len(pending), 1) + + +# -- the task --------------------------------------------------------------- + +@pytest.fixture +def runner(monkeypatch): + import simplyblock_core.services.tasks_runner_restart as module + + # checkpoint / set_result commit onto the stored row, not onto the frozen + # view the handler carries on with: the rows the tests hold are the store. + _ROWS.clear() + + def atomic_update(obj, mutate): + row = _ROWS[obj.uuid] + mutate(row) + return row + + monkeypatch.setattr(trb.db, "atomic_update", atomic_update) + monkeypatch.setattr(module.time, "sleep", lambda s: None) + + node = StorageNode() + node.uuid = "n1" + node.cluster_id = "c1" + node.status = StorageNode.STATUS_ONLINE + peer = StorageNode() + peer.uuid = "n2" + peer.status = StorageNode.STATUS_ONLINE + cluster = MagicMock() + cluster.status = Cluster.STATUS_ACTIVE + + db = MagicMock() + db.get_storage_node_by_id.return_value = node + db.get_storage_nodes_by_cluster_id.return_value = [node, peer] + db.get_cluster_by_id.return_value = cluster + monkeypatch.setattr(module, "db", db) + + dc = MagicMock() + dc.JMReshapeNotReady = device_controller.JMReshapeNotReady + dc.JMReshapeError = device_controller.JMReshapeError + dc.jm_raid_reshape_needed.return_value = True + dc.jm_resync_pending.return_value = [] + dc.reshape_jm_raid.return_value = ["a", "b"] + monkeypatch.setattr(module, "device_controller", dc) + + tc = MagicMock() + tc.get_jm_raid_reshape_blocking_tasks.return_value = [] + tc.get_active_jm_raid_reshape_tasks.return_value = [] + monkeypatch.setattr(module, "tasks_controller", tc) + + module.node, module.peer, module.cluster = node, peer, cluster + module.dc, module.tc = dc, tc + yield module + for name in ("node", "peer", "cluster", "dc", "tc"): + delattr(module, name) + + +_ROWS: dict = {} + + +def _task(uuid="t1", node_id="n1", **params): + task = JobSchedule() + task.uuid = uuid + task.cluster_id = "c1" + task.node_id = node_id + task.function_name = JobSchedule.FN_JM_RAID_RESHAPE + task.function_params = params + _ROWS[uuid] = task + return task + + +def test_the_restart_runner_serves_the_task(runner): + assert JobSchedule.FN_JM_RAID_RESHAPE in runner.SPEC.function_names + task = _task() + runner.dc.jm_raid_reshape_needed.return_value = False + runner.SPEC.handler(task) + assert "already matches" in task.function_result + + +def test_nothing_to_do_when_the_raid_matches(runner): + runner.dc.jm_raid_reshape_needed.return_value = False + task = _task() + runner.task_runner_jm_reshape(task) + runner.dc.reshape_jm_raid.assert_not_called() + assert "phase" not in task.function_params + + +@pytest.mark.parametrize("block, reason", [ + (lambda r: setattr(r.cluster, "status", Cluster.STATUS_DEGRADED), "cluster is"), + (lambda r: setattr(r.peer, "status", StorageNode.STATUS_OFFLINE), "node n2 is"), + (lambda r: setattr(r.tc.get_jm_raid_reshape_blocking_tasks, "return_value", + [MagicMock(function_name="new_device_migration", uuid="m1")]), "is open"), + (lambda r: setattr(r.dc.jm_resync_pending, "return_value", ["LVS_1: ['jm_n2']"]), + "journal not in sync"), +]) +def test_it_waits_and_touches_nothing_while_the_cluster_is_not_quiet(runner, block, reason): + block(runner) + task = _task() + with pytest.raises(TaskDefer) as exc: + runner.task_runner_jm_reshape(task) + assert reason in str(exc.value) + runner.dc.reshape_jm_raid.assert_not_called() + assert "phase" not in task.function_params + + +def test_one_node_at_a_time(runner): + other = _task("t2", "n2", phase="resync") + queued = _task("t3", "n3") + runner.tc.get_active_jm_raid_reshape_tasks.return_value = [queued, other] + task = _task() + with pytest.raises(TaskDefer) as exc: + runner.task_runner_jm_reshape(task) + assert "node n2 is being rebuilt" in str(exc.value) + runner.dc.reshape_jm_raid.assert_not_called() + + +def test_a_task_that_only_waits_does_not_hold_up_another(runner): + queued = _task("t3", "n3") + runner.tc.get_active_jm_raid_reshape_tasks.return_value = [queued] + task = _task() + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + runner.dc.reshape_jm_raid.assert_called_once_with("n1") + + +def test_a_removed_node_between_the_others_does_not_block(runner): + runner.peer.status = StorageNode.STATUS_REMOVED + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(_task()) + runner.dc.reshape_jm_raid.assert_called_once() + + +def test_the_phase_is_recorded_before_the_stack_is_taken_down(runner): + task = _task() + seen = {} + runner.dc.reshape_jm_raid.side_effect = lambda node_id: ( + seen.update(phase=task.function_params.get("phase")), ["a", "b"])[1] + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + assert seen["phase"] == "rebuild" + assert task.function_params["phase"] == "resync" + assert task.function_params["members"] == ["a", "b"] + + +def test_resync_is_polled_until_the_journals_stay_in_sync(runner): + task = _task() + runner.dc.jm_resync_pending.side_effect = [[], ["LVS_1: ['jm_n1']"]] # precondition, then poll + with pytest.raises(TaskProgress) as exc: + runner.task_runner_jm_reshape(task) + assert "resync running" in str(exc.value) + + runner.dc.jm_resync_pending.side_effect = None + runner.dc.jm_resync_pending.return_value = [] + for polls in range(1, runner.JM_RESHAPE_READY_POLLS): + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + assert task.function_params["ready_polls"] == polls + runner.task_runner_jm_reshape(task) + assert "journals in sync" in task.function_result + # Built once; every later cycle only polled. + runner.dc.reshape_jm_raid.assert_called_once() + + +def test_a_poll_that_finds_replication_again_starts_the_count_over(runner): + task = _task(phase="resync", members=["a", "b"], ready_polls=2) + runner.dc.jm_resync_pending.return_value = ["LVS_1: ['jm_n1']"] + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + assert task.function_params["ready_polls"] == 0 + runner.dc.reshape_jm_raid.assert_not_called() + + +@pytest.mark.parametrize("error", [ + device_controller.JMReshapeNotReady("member gone"), + device_controller.JMReshapeError("build failed"), + RPCException("boom"), +]) +def test_a_failed_rebuild_is_retried_without_asking_the_preconditions_again(runner, error): + task = _task() + runner.dc.reshape_jm_raid.side_effect = error + with pytest.raises(TaskRetry): + runner.task_runner_jm_reshape(task) + assert task.function_params["phase"] == "rebuild" + + # The stack is down now: the next attempt builds whatever the cluster + # looks like, and even when the record already matches the devices. + runner.cluster.status = Cluster.STATUS_DEGRADED + runner.dc.jm_raid_reshape_needed.return_value = False + runner.dc.reshape_jm_raid.side_effect = None + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + assert runner.dc.reshape_jm_raid.call_count == 2 + assert task.function_params["phase"] == "resync" + + +def test_node_states(runner): + runner.node.status = StorageNode.STATUS_OFFLINE + with pytest.raises(TaskDefer): + runner.task_runner_jm_reshape(_task()) + runner.node.status = StorageNode.STATUS_REMOVED + with pytest.raises(TaskAbort): + runner.task_runner_jm_reshape(_task()) + runner.db.get_storage_node_by_id.side_effect = KeyError("n1") + with pytest.raises(TaskAbort): + runner.task_runner_jm_reshape(_task()) + runner.dc.reshape_jm_raid.assert_not_called() + + +def test_giving_up_does_not_touch_a_device_or_the_node(runner): + task = _task() + task.max_retry = 3 + task.retry = 3 + runner._abandon_task(task) + runner.dc.device_set_unavailable.assert_not_called() + runner.dc.device_set_retries_exhausted.assert_not_called() diff --git a/tests/unit/test_lblk_journal_disk_split.py b/tests/unit/test_lblk_journal_disk_split.py index 789145d557..b82210f401 100644 --- a/tests/unit/test_lblk_journal_disk_split.py +++ b/tests/unit/test_lblk_journal_disk_split.py @@ -106,8 +106,8 @@ def test_several_whole_disks_each_get_a_journal_raid_member(self): result, disk_calls, _ = self._layout(entries) self.assertEqual(result, {"split-raid": True}) self.assertEqual(disk_calls, []) - # 3% of 300G usable, on a two-member mirror: 9G on each disk. - self.assertEqual(self.raid_calls, [(["sdb", "sdc"], 9 * GIB)]) + # 3% of the smaller disk, on each disk. + self.assertEqual(self.raid_calls, [(["sdb", "sdc"], 3 * GIB)]) def test_single_partition_is_split(self): _, disk_calls, part_calls = self._layout({"sdb1": _entry("sdb1", GIB, type="part")}) @@ -118,7 +118,7 @@ def test_partitions_and_disks_of_one_node_all_get_a_member(self): entries = {"sdb1": _entry("sdb1", 100 * GIB, type="part"), "sdc": _entry("sdc", 100 * GIB)} self._layout(entries) - self.assertEqual(self.raid_calls, [(["sdb1", "sdc"], 6 * GIB)]) + self.assertEqual(self.raid_calls, [(["sdb1", "sdc"], 3 * GIB)]) # A node whose devices already carry journal raid members. @@ -187,7 +187,7 @@ def test_partitions_are_split_even_with_opt_out(self): entries = {"sdb1": _entry("sdb1", 100 * GIB, type="part"), "sdb2": _entry("sdb2", 100 * GIB, type="part")} _, disk_calls, part_calls = self._layout(entries, journal_device=True) - self.assertEqual(self.raid_calls, [(["sdb1", "sdb2"], 6 * GIB)]) + self.assertEqual(self.raid_calls, [(["sdb1", "sdb2"], 3 * GIB)]) self.assertEqual((disk_calls, part_calls), ([], [])) def test_empty(self): @@ -322,8 +322,8 @@ def test_several_disks_one_node_each_carry_a_journal_raid_member(self): for jm, data in (("sdb1", "sdb2"), ("sdc1", "sdc2")): self.assertTrue(devices[jm]["journal"] and devices[jm]["journal_raid"]) self.assertEqual(devices[jm]["data_serial"], devices[data]["serial"]) - # 3% of 150G usable on a two-member mirror: the same on both disks. - self.assertEqual(devices[jm]["size"], 150 * GIB * 3 // 100) + # The floor (3% of the 50G disk is less): the same on both disks. + self.assertEqual(devices[jm]["size"], constants.LBLK_JM_MIN_SIZE) self.assertFalse(devices[data].get("journal")) # The members are one journal device, not an alceml each. self.assertEqual(config["nodes"][0]["number_of_alcemls"], 3) @@ -335,11 +335,11 @@ def test_two_nodes_per_host_each_mirror_over_their_own_disks(self): self.assertEqual(sorted(calls), ["sdb", "sdc", "sdd", "sde"]) self.assertEqual(self._names(config), [["sdb1", "sdb2", "sdd1", "sdd2"], ["sdc1", "sdc2", "sde1", "sde2"]]) - for node, total in zip(config["nodes"], (400, 600)): + for node, smallest in zip(config["nodes"], (100, 200)): members = [e for e in node["lblk_devices"] if e.get("journal")] self.assertEqual(len(members), 2) self.assertTrue(all(e.get("journal_raid") for e in members)) - self.assertEqual({e["size"] for e in members}, {total * GIB * 3 // 100}) + self.assertEqual({e["size"] for e in members}, {smallest * GIB * 3 // 100}) def test_journal_device_opt_out(self): config, calls = self._run({"sdb": _entry("sdb", 100 * GIB), diff --git a/tests/unit/test_lblk_journal_raid.py b/tests/unit/test_lblk_journal_raid.py index 5b69b660fb..c28cae6ae0 100644 --- a/tests/unit/test_lblk_journal_raid.py +++ b/tests/unit/test_lblk_journal_raid.py @@ -45,27 +45,12 @@ def _inv(name, size, dtype="part"): class TestMemberSize(unittest.TestCase): - def test_member_size_follows_the_raid_geometry(self): - self.assertEqual(jm_raid.member_size_for_usable(9 * GIB, 1), 9 * GIB) - self.assertEqual(jm_raid.member_size_for_usable(9 * GIB, 2), 9 * GIB) - self.assertEqual(jm_raid.member_size_for_usable(9 * GIB, 3), 9 * GIB) - self.assertEqual(jm_raid.member_size_for_usable(9 * GIB, 4), 9 * GIB // 2) - self.assertEqual(jm_raid.member_size_for_usable(9 * GIB, 5), 9 * GIB // 2) - self.assertEqual(jm_raid.member_size_for_usable(10, 6), 4) # rounded up - - def test_no_members_refused(self): - with self.assertRaises(ValueError): - jm_raid.member_size_for_usable(GIB, 0) - - def test_planned_raid_is_at_least_as_large_as_asked(self): - # The raid1 is as large as its smaller raid0 leg. - usable = 7 * GIB + 13 - for count in range(2, 12): - member = jm_raid.member_size_for_usable(usable, count) + def test_usable_members_is_the_smallest_leg(self): + # The raid1 is as large as its smallest raid0 leg. + for count, usable in {2: 1, 3: 1, 4: 2, 5: 2, 8: 4, 9: 3, 10: 3, 12: 4, 13: 3}.items(): legs = jm_raid.plan_topology([f"m{i}" for i in range(count)])["legs"] - smaller_leg = min(len(leg) for leg in legs) * member - self.assertGreaterEqual(smaller_leg, usable, count) - self.assertLess(smaller_leg - usable, min(len(leg) for leg in legs), count) + self.assertEqual(jm_raid.usable_members(legs), usable, count) + self.assertEqual(jm_raid.usable_members([]), 1) # a single device, no raid def test_legs_left_when_a_member_is_missing(self): self.assertEqual(jm_raid.mountable_top_legs(["l0", "l1"], [], ["l1"]), ["l0", "l1"]) @@ -81,14 +66,17 @@ def test_jm_on_a_single_leg(self): self.assertFalse(jm_raid.runs_on_single_leg("raid_jm_n", ["a", "b"], ["a", "b"])) self.assertFalse(jm_raid.runs_on_single_leg("a", ["a"], [])) # single-drive JM - def test_three_devices_of_150_200_100_at_two_percent(self): - # 2% of 450G is a 9G journal; the mirror's smaller leg is one member. + def test_member_is_a_share_of_the_smallest_device(self): + # 3% of the 100G device, whatever the others hold. sizes = [150 * GIB, 200 * GIB, 100 * GIB] - self.assertEqual(utils.lblk_journal_raid_member_size(sizes, jm_percent=2), 9 * GIB) + self.assertEqual(utils.lblk_journal_raid_member_size(sizes), 3 * GIB) + self.assertEqual(utils.lblk_journal_raid_member_size(sizes, jm_percent=5), 5 * GIB) - def test_four_devices_halve_the_member(self): - self.assertEqual( - utils.lblk_journal_raid_member_size([100 * GIB] * 4, jm_percent=3), 6 * GIB) + def test_member_does_not_depend_on_the_number_of_devices(self): + """A device that joins the node later is split to the size the others + have, so the size must not change with the count.""" + sizes = {utils.lblk_journal_raid_member_size([100 * GIB] * count) for count in range(2, 14)} + self.assertEqual(sizes, {3 * GIB}) def test_journal_floor(self): self.assertEqual(utils.lblk_journal_raid_member_size([10 * GIB, 10 * GIB]), @@ -97,11 +85,12 @@ def test_journal_floor(self): def test_member_is_a_whole_number_of_mib(self): member = utils.lblk_journal_raid_member_size([100 * GIB + 7, 100 * GIB + 5, 300 * GIB]) self.assertEqual(member % MIB, 0) - self.assertGreaterEqual(member, (500 * GIB + 12) * 3 // 100) + self.assertGreaterEqual(member, (100 * GIB + 5) * 3 // 100) + self.assertLess(member - (100 * GIB + 5) * 3 // 100, MIB) - def test_member_larger_than_half_the_smallest_device_refused(self): + def test_floor_larger_than_half_the_smallest_device_refused(self): with self.assertRaises(ValueError) as ctx: - utils.lblk_journal_raid_member_size([10 * GIB, 1000 * GIB, 1000 * GIB]) + utils.lblk_journal_raid_member_size([3 * GIB, 1000 * GIB, 1000 * GIB]) self.assertIn("smallest", str(ctx.exception)) @@ -296,6 +285,17 @@ def test_restart_does_not_take_members_for_new_data_devices(self): self.assertEqual([d.serial_number for d in new_devices], ["NEW"]) self.assertEqual(sorted(d.serial_number for d in node.nvme_devices), ["D0", "D1", "NEW"]) + def test_restart_does_not_take_a_partition_that_left_the_raid_for_a_new_device(self): + """The journal partition of a device that was migrated out leaves the + raid (device_controller.reshape_jm_raid) and can still be on the host. + It is journal space of the node, not a device to offer for data.""" + node = _raid_node(3) + node.jm_device.jm_nvme_bdev_list = node.jm_device.jm_nvme_bdev_list[:2] + discovered = [_aio(s) for s in ("J0", "D0", "J1", "D1", "J2", "D2")] + new_devices = storage_node_ops._reconcile_discovered_devices(node, discovered) + self.assertEqual(new_devices, []) + self.assertEqual(sorted(d.serial_number for d in node.nvme_devices), ["D0", "D1", "D2"]) + class TestRestartWithMissingMember(unittest.TestCase): """_prepare_cluster_devices_on_restart hands the builder the JM's full From 1689f2e90ba601c98ab0b1f90be694e00f7ec12d Mon Sep 17 00:00:00 2001 From: wmousa Date: Mon, 23 Nov 2026 17:53:39 +0100 Subject: [PATCH 2/5] fix(jm): synchronise the journal a rebuilt JM does not hold The jm_raid_reshape task trusted jc_get_jm_status to tell when the rebuilt, empty JM was back in sync. On the lab the LVS leader reported every JM of its journal ready while the leader's own rebuilt JM did not hold that journal at all: the journal coordinator re-levels a JM it reaches over the network when it reconnects, and does not for its local one. The task reported "journals in sync" on a node whose JM held two of three journals. The JM itself is now asked whether it holds each journal it is a copy of (bdev_jm_get_status), and a journal it lacks that nobody replicates is started with jc_explicit_synchronization on the confirmed LVS leader, never on a follower. A journal that still does not arrive after ten synchronisations costs the task retries instead of an endless wait. Co-Authored-By: Claude Fable 5.2 --- .../controllers/device_controller.py | 107 +++++++++++--- simplyblock_core/models/job_schedule.py | 3 +- .../services/tasks_runner_restart.py | 23 ++- tests/unit/test_jm_raid_reshape.py | 132 +++++++++++++++++- 4 files changed, 237 insertions(+), 28 deletions(-) diff --git a/simplyblock_core/controllers/device_controller.py b/simplyblock_core/controllers/device_controller.py index 0cdd025196..86e1286315 100644 --- a/simplyblock_core/controllers/device_controller.py +++ b/simplyblock_core/controllers/device_controller.py @@ -1528,8 +1528,9 @@ def reshape_jm_raid(node_id: str) -> list[str]: journal of the node is stopped, the raid is created anew over the members jm_raid_target_members names, the journal storage is formatted on it and the JM started again. The journal coordinator of the LVS leader then - brings the empty JM up to date from the node's other journal copies by - itself (jm_resync_pending tells when it is done). Until then the node + brings the empty JM up to date from the node's other journal copies, by + itself where it reaches the JM over the network and when told to for its + own local JM (start_jm_resync; jm_resync_pending tells when it is done). Until then the node relies on those copies, so the caller rebuilds one node at a time and only on a cluster whose journals are all in sync. @@ -1569,46 +1570,116 @@ def reshape_jm_raid(node_id: str) -> list[str]: return target -def jm_resync_pending(snode: StorageNode) -> list[str]: - """The journals the JM of ``snode`` is a copy of that are not known to be - in sync, each with the reason; empty when all of them are. +def _jm_journals(snode: StorageNode) -> list[dict]: + """The journals the JM of ``snode`` is a copy of, each with what is known + about its synchronisation. The JM of a node holds the journal of the node's own LVS and of every LVS whose owner picked it as a remote copy (StorageNode.jm_ids). The journal coordinator of an LVS runs its synchronisation on the node that leads the - LVS, so that node is the one asked (jc_get_jm_status: False for a JM that - is not ready or has replication running). A journal whose leader cannot - be found or asked counts as pending: an unknown answer is not "in sync".""" + LVS, so that node is the one asked. Per journal: + + lvs, jm_vuid the LVS and its journal group + leader the node leading the LVS, or None when none is found + busy the JMs the leader reports as not ready or replicating + (jc_get_jm_status), None when the leader cannot be asked + or names no JM at all + held whether the JM of ``snode`` holds the journal + (bdev_jm_get_status on its node), None when it cannot be + asked + error why leader, busy or held is unknown, or "" + """ from simplyblock_core.controllers import lvol_controller db_controller = DBController() nodes = db_controller.get_storage_nodes_by_cluster_id(snode.cluster_id) by_id = {n.get_id(): n for n in nodes} jm_id = snode.jm_device.get_id() if snode.jm_device else "" - pending = [] + journals = [] for owner in nodes: if not owner.lvstore or owner.status == StorageNode.STATUS_REMOVED: continue if owner.get_id() != snode.get_id() and jm_id not in owner.jm_ids: continue + journal: dict = {"lvs": owner.lvstore, "jm_vuid": owner.jm_vuid, "leader": None, + "busy": None, "held": None, "error": ""} + journals.append(journal) hosts = [owner] + [by_id[i] for i in (owner.secondary_node_id, owner.tertiary_node_id) if i in by_id] - leader = next((h for h in hosts if h.status == StorageNode.STATUS_ONLINE - and lvol_controller.is_node_leader(h, owner.lvstore)), None) - if leader is None: - pending.append(f"{owner.lvstore}: no leader found") + journal["leader"] = next((h for h in hosts if h.status == StorageNode.STATUS_ONLINE + and lvol_controller.is_node_leader(h, owner.lvstore)), None) + if journal["leader"] is None: + journal["error"] = "no leader found" continue try: - status = leader.rpc_client(timeout=10, retry=1).jc_get_jm_status(owner.jm_vuid) + status = journal["leader"].rpc_client(timeout=10, retry=1).jc_get_jm_status(owner.jm_vuid) + held = snode.rpc_client(timeout=10, retry=1).bdev_jm_get_status(owner.jm_vuid) except RPCException as e: - pending.append(f"{owner.lvstore}: {e}") + journal["error"] = str(e) + continue + if not status: + journal["error"] = "no JM reported" continue - busy = sorted(name for name, ready in (status or {}).items() if ready is False) - if busy or not status: - pending.append(f"{owner.lvstore}: {busy or 'no JM reported'}") + journal["busy"] = sorted(name for name, ready in status.items() if ready is False) + journal["held"] = bool(held) and held.get("res", 0) > 0 + return journals + + +def jm_resync_pending(snode: StorageNode, require_held: bool = True) -> list[str]: + """The journals the JM of ``snode`` is a copy of that are not known to be + in sync, each with the reason; empty when all of them are. + + In sync means the LVS leader reports every JM of the journal ready and no + replication running, and, unless ``require_held`` is off, that the JM of + ``snode`` holds the journal. The second is asked of the JM itself because + the first does not tell: after a JM was rebuilt empty the leader reported + it ready while it did not hold the journal of the node's own LVS at all + (lab, 2026-11-23). A journal whose state cannot be established counts as + pending: an unknown answer is not "in sync".""" + pending = [] + for journal in _jm_journals(snode): + if journal["error"]: + pending.append(f"{journal['lvs']}: {journal['error']}") + elif journal["busy"]: + pending.append(f"{journal['lvs']}: {journal['busy']}") + elif require_held and not journal["held"]: + pending.append(f"{journal['lvs']}: not on the JM of node {snode.get_id()}") return pending +def start_jm_resync(snode: StorageNode) -> list[str]: + """Start the synchronisation of every journal the JM of ``snode`` should + hold and does not, and return the LVS names it was started for. + + The journal coordinator brings a JM it reaches over the network up to + date by itself when the JM reconnects. It does not do so for the leader's + own local JM: rebuilt empty under it, that JM stayed without the journal + until jc_explicit_synchronization was called on the leader, which then + replicated it within seconds (lab, 2026-11-23). + + Only ever on the confirmed leader of the LVS: explicit synchronisation + makes the calling node's journal coordinator the journal writer, and on a + follower that takes the leadership away from the real leader + (storage_node_ops.resync_solo_lvs_on_leaders). A journal with replication + already running, or whose state is unknown, is left alone.""" + started = [] + for journal in _jm_journals(snode): + if journal["error"] or journal["busy"] or journal["held"]: + continue + leader = journal["leader"] + logger.info("Journal of %s (jm_vuid %s) is not on the JM of node %s: starting its " + "synchronisation on the LVS leader %s", + journal["lvs"], journal["jm_vuid"], snode.get_id(), leader.get_id()) + try: + leader.rpc_client(timeout=10, retry=0).jc_explicit_synchronization(journal["jm_vuid"]) + except RPCException as e: + logger.warning("jc_explicit_synchronization %s on leader %s failed: %s", + journal["jm_vuid"], leader.get_id(), e) + continue + started.append(journal["lvs"]) + return started + + def remove_from_jm_device(device_id, jm_bdev): db_controller = DBController() diff --git a/simplyblock_core/models/job_schedule.py b/simplyblock_core/models/job_schedule.py index 87fa2f1f94..fcc98b46f7 100644 --- a/simplyblock_core/models/job_schedule.py +++ b/simplyblock_core/models/job_schedule.py @@ -117,7 +117,8 @@ class JobSchedule(BaseModel): # ``phase`` once the rebuild has started: "rebuild" while the JM stack is # down or being built, "resync" while the empty JM is brought up to date, # then with ``ready_polls`` (consecutive polls that found every journal in - # sync) and ``members`` (the new member list). One open task per node + # sync), ``sync_calls`` (synchronisations started for a journal the new JM + # did not hold) and ``members`` (the new member list). One open task per node # (tasks_controller.add_jm_raid_reshape_task). FN_JM_RAID_RESHAPE = "jm_raid_reshape" diff --git a/simplyblock_core/services/tasks_runner_restart.py b/simplyblock_core/services/tasks_runner_restart.py index cef6ef09c5..18cc3b87cb 100644 --- a/simplyblock_core/services/tasks_runner_restart.py +++ b/simplyblock_core/services/tasks_runner_restart.py @@ -256,6 +256,9 @@ def task_runner(task): # coordinator starts its replication a few seconds after the new JM connects, # and a poll that lands before that reads "in sync" too. JM_RESHAPE_READY_POLLS = 3 +# Synchronisations started for a journal that is not on the rebuilt JM before +# the task counts further ones as failures (a retry each, up to its ceiling). +JM_RESHAPE_MAX_SYNC_CALLS = 10 def _jm_reshape_blocker(task, node) -> str: @@ -277,7 +280,9 @@ def _jm_reshape_blocker(task, node) -> str: for other in tasks_controller.get_active_jm_raid_reshape_tasks(task.cluster_id): if other.uuid != task.uuid and other.function_params.get("phase"): return f"the JM raid of node {other.node_id} is being rebuilt" - pending = device_controller.jm_resync_pending(node) + # Whether the JM holds every journal is not asked here: one that does not + # is the very thing the rebuild repairs. + pending = device_controller.jm_resync_pending(node, require_held=False) if pending: return f"journal not in sync: {'; '.join(pending)}" return "" @@ -291,7 +296,9 @@ def task_runner_jm_reshape(task): dies in between carries on where it was: not started (every precondition is checked, nothing was touched), "rebuild" (the old JM stack is being or was taken down; the build is repeated until it succeeds), "resync" (the - new JM is up; polled until every journal it belongs to is in sync).""" + new JM is up; polled until it holds every journal it belongs to and all + of them are in sync, starting the synchronisation where it did not start + by itself).""" try: node = db.get_storage_node_by_id(task.node_id) except KeyError: @@ -332,8 +339,16 @@ def task_runner_jm_reshape(task): node = db.get_storage_node_by_id(task.node_id) pending = device_controller.jm_resync_pending(node) if pending: - if task.function_params.get("ready_polls"): - checkpoint(task, ready_polls=0) + # A journal the JM does not hold and nobody replicates is started on + # its LVS leader; the journal coordinator does not do that by itself + # for the leader's own JM. + started = device_controller.start_jm_resync(node) + sync_calls = int(task.function_params.get("sync_calls", 0)) + (1 if started else 0) + if started or task.function_params.get("ready_polls"): + checkpoint(task, ready_polls=0, sync_calls=sync_calls) + if started and sync_calls > JM_RESHAPE_MAX_SYNC_CALLS: + raise TaskRetry(f"journal of {started} still not on the rebuilt JM after " + f"{sync_calls - 1} synchronisations") raise TaskProgress(f"journal resync running: {'; '.join(pending)}") polls = int(task.function_params.get("ready_polls", 0)) + 1 if polls < JM_RESHAPE_READY_POLLS: diff --git a/tests/unit/test_jm_raid_reshape.py b/tests/unit/test_jm_raid_reshape.py index 63b36ddfee..311d1346b3 100644 --- a/tests/unit/test_jm_raid_reshape.py +++ b/tests/unit/test_jm_raid_reshape.py @@ -575,10 +575,13 @@ def _node(self, node_id, lvstore, jm_vuid, jm_ids=(), sec="", status=StorageNode node.jm_device = jm return node - def _pending(self, nodes, leaders, statuses): - """``leaders``: lvstore -> id of the node that leads it. ``statuses``: - (node id, jm_vuid) -> jc_get_jm_status answer, or an exception.""" - asked = [] + def _call(self, func, nodes, leaders, statuses, not_held=(), **kwargs): + """Run ``func`` for nodes[0]. ``leaders``: lvstore -> id of the node + that leads it. ``statuses``: (node id, jm_vuid) -> jc_get_jm_status + answer, or an exception. ``not_held``: the jm_vuids whose journal the + JM of nodes[0] does not hold. Returns (result, the jc_get_jm_status + calls, the jc_explicit_synchronization calls).""" + asked, synced = [], [] def rpc_for(node): rpc = MagicMock() @@ -589,7 +592,17 @@ def status(jm_vuid): if isinstance(answer, Exception): raise answer return answer + + def held(jm_vuid): + assert node.get_id() == nodes[0].get_id(), "asked of the JM's own node" + if jm_vuid in not_held: + return {"res": -1, "njournals": 2} + return {"res": 1, "njournals": 3, "jm_vuid": jm_vuid, "total_records": 14} + rpc.jc_get_jm_status.side_effect = status + rpc.bdev_jm_get_status.side_effect = held + rpc.jc_explicit_synchronization.side_effect = \ + lambda jm_vuid: synced.append((node.get_id(), jm_vuid)) return rpc from simplyblock_core.controllers import lvol_controller @@ -599,9 +612,75 @@ def status(jm_vuid): patch.object(lvol_controller, "is_node_leader", side_effect=lambda node, lvs: leaders.get(lvs) == node.get_id()): db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = nodes - pending = device_controller.jm_resync_pending(nodes[0]) + result = func(nodes[0], **kwargs) + return result, asked, synced + + def _pending(self, nodes, leaders, statuses, **kwargs): + pending, asked, _ = self._call(device_controller.jm_resync_pending, nodes, leaders, + statuses, **kwargs) return pending, asked + def test_ready_everywhere_but_not_on_the_jm_is_pending(self): + """The lab case: the JM was rebuilt empty, the leader reported every + JM of the journal ready, and the JM did not hold the journal.""" + n1 = self._node("n1", "LVS_1", 1) + pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {"jm_n1": True}}, + not_held={1}) + self.assertEqual(len(pending), 1) + self.assertIn("not on the JM", pending[0]) + + def test_before_the_rebuild_a_journal_the_jm_lacks_does_not_hold_it_up(self): + n1 = self._node("n1", "LVS_1", 1) + pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {"jm_n1": True}}, + not_held={1}, require_held=False) + self.assertEqual(pending, []) + + def test_the_sync_is_started_on_the_leader_for_a_journal_the_jm_lacks(self): + n1 = self._node("n1", "LVS_1", 1, jm_ids=["jm-n2"], sec="n2") + n2 = self._node("n2", "LVS_2", 2, jm_ids=["jm-n1"], sec="n1") + started, _, synced = self._call( + device_controller.start_jm_resync, [n1, n2], {"LVS_1": "n1", "LVS_2": "n2"}, + {("n1", 1): {"jm_n1": True}, ("n2", 2): {"jm_n2": True}}, not_held={1}) + self.assertEqual(started, ["LVS_1"]) + self.assertEqual(synced, [("n1", 1)]) # the journal it holds is left alone + + def test_the_sync_goes_to_the_leader_even_when_that_is_another_node(self): + n1 = self._node("n1", "LVS_1", 1, sec="n2") + n2 = self._node("n2", "", 0) + started, _, synced = self._call( + device_controller.start_jm_resync, [n1, n2], {"LVS_1": "n2"}, + {("n2", 1): {"jm_n1": True}}, not_held={1}) + self.assertEqual((started, synced), (["LVS_1"], [("n2", 1)])) + + def test_no_sync_is_started_without_a_confirmed_leader(self): + """On a follower an explicit synchronisation takes the leadership + away from the real leader.""" + n1 = self._node("n1", "LVS_1", 1, sec="n2") + n2 = self._node("n2", "", 0) + started, _, synced = self._call(device_controller.start_jm_resync, [n1, n2], {}, {}, + not_held={1}) + self.assertEqual((started, synced), ([], [])) + + def test_no_sync_is_started_while_replication_runs_or_the_state_is_unknown(self): + n1 = self._node("n1", "LVS_1", 1) + for answer in ({"jm_n1": False}, {}, RPCException("down")): + started, _, synced = self._call(device_controller.start_jm_resync, [n1], + {"LVS_1": "n1"}, {("n1", 1): answer}, not_held={1}) + self.assertEqual((started, synced), ([], []), answer) + + def test_a_failed_sync_call_is_not_reported_as_started(self): + n1 = self._node("n1", "LVS_1", 1) + from simplyblock_core.controllers import lvol_controller + rpc = MagicMock() + rpc.jc_get_jm_status.return_value = {"jm_n1": True} + rpc.bdev_jm_get_status.return_value = {"res": -1} + rpc.jc_explicit_synchronization.side_effect = RPCException("refused") + with patch.object(device_controller, "DBController") as db_cls, \ + patch.object(StorageNode, "rpc_client", return_value=rpc), \ + patch.object(lvol_controller, "is_node_leader", return_value=True): + db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = [n1] + self.assertEqual(device_controller.start_jm_resync(n1), []) + def test_in_sync_when_every_leader_reports_every_jm_ready(self): n1 = self._node("n1", "LVS_1", 1, jm_ids=["jm-n2"], sec="n2") n2 = self._node("n2", "LVS_2", 2, jm_ids=["jm-n1"], sec="n1") @@ -690,6 +769,7 @@ def atomic_update(obj, mutate): dc.JMReshapeError = device_controller.JMReshapeError dc.jm_raid_reshape_needed.return_value = True dc.jm_resync_pending.return_value = [] + dc.start_jm_resync.return_value = [] dc.reshape_jm_raid.return_value = ["a", "b"] monkeypatch.setattr(module, "device_controller", dc) @@ -811,6 +891,48 @@ def test_resync_is_polled_until_the_journals_stay_in_sync(runner): runner.dc.reshape_jm_raid.assert_called_once() +def test_the_precondition_does_not_ask_whether_the_jm_holds_its_journals(runner): + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(_task()) + assert runner.dc.jm_resync_pending.call_args_list[0].kwargs == {"require_held": False} + assert runner.dc.jm_resync_pending.call_args_list[1].kwargs == {} + + +def test_a_journal_the_rebuilt_jm_lacks_is_synchronised_on_its_leader(runner): + """The lab case: nothing replicates and the journal is not on the JM.""" + task = _task(phase="resync", members=["a", "b"], ready_polls=0) + runner.dc.jm_resync_pending.return_value = ["LVS_1: not on the JM of node n1"] + runner.dc.start_jm_resync.return_value = ["LVS_1"] + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + runner.dc.start_jm_resync.assert_called_once() + assert task.function_params["sync_calls"] == 1 + + # Replication runs now: nothing more is started, and nothing is counted. + runner.dc.jm_resync_pending.return_value = ["LVS_1: ['jm_n1']"] + runner.dc.start_jm_resync.return_value = [] + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + assert task.function_params["sync_calls"] == 1 + + runner.dc.jm_resync_pending.return_value = [] + for _ in range(runner.JM_RESHAPE_READY_POLLS - 1): + with pytest.raises(TaskProgress): + runner.task_runner_jm_reshape(task) + runner.task_runner_jm_reshape(task) + assert "journals in sync" in task.function_result + runner.dc.reshape_jm_raid.assert_not_called() + + +def test_a_journal_that_never_arrives_costs_retries_not_an_endless_wait(runner): + task = _task(phase="resync", members=["a", "b"], sync_calls=runner.JM_RESHAPE_MAX_SYNC_CALLS) + runner.dc.jm_resync_pending.return_value = ["LVS_1: not on the JM of node n1"] + runner.dc.start_jm_resync.return_value = ["LVS_1"] + with pytest.raises(TaskRetry) as exc: + runner.task_runner_jm_reshape(task) + assert "still not on the rebuilt JM" in str(exc.value) + + def test_a_poll_that_finds_replication_again_starts_the_count_over(runner): task = _task(phase="resync", members=["a", "b"], ready_polls=2) runner.dc.jm_resync_pending.return_value = ["LVS_1: ['jm_n1']"] From 614d1193849b8947e71720c6551f091e6978f750 Mon Sep 17 00:00:00 2001 From: wmousa Date: Mon, 23 Nov 2026 20:26:32 +0100 Subject: [PATCH 3/5] test(jm): cover the journal raid rebuild against the real database The rebuild, its task and the journal resync read and write node and task records, so their tests belong to the integration tier: 36 cases drive the restart runner's spec over seeded clusters in FoundationDB, with only the SPDK RPC client, the leadership probe and the device-status fan-out replaced. The unit file keeps what is pure logic. Writing them showed the task marking itself as rebuilding before it knew the rebuild could start: a member that was absent then cost a retry and, worse, let every later attempt skip the quiet-cluster checks although nothing had been taken down. Whether the raid can be rebuilt is now asked with the other preconditions, before the phase is recorded. Co-Authored-By: Claude Fable 5.2 --- .../controllers/device_controller.py | 33 +- .../services/tasks_runner_restart.py | 5 +- tests/integration/test_jm_raid_reshape.py | 714 +++++++++++++++++ tests/unit/test_jm_raid_reshape.py | 717 +----------------- 4 files changed, 766 insertions(+), 703 deletions(-) create mode 100644 tests/integration/test_jm_raid_reshape.py diff --git a/simplyblock_core/controllers/device_controller.py b/simplyblock_core/controllers/device_controller.py index 86e1286315..a70d3ddc2a 100644 --- a/simplyblock_core/controllers/device_controller.py +++ b/simplyblock_core/controllers/device_controller.py @@ -1519,6 +1519,27 @@ def _delete_jm_stack(snode: StorageNode, rpc_client: RPCClient) -> None: rpc_client.bdev_raid_delete(name) +def jm_raid_reshape_not_ready(snode: StorageNode) -> str: + """Why the JM raid of ``snode`` cannot be rebuilt over its current devices + now, or "" when it can. Touches nothing. + + The node must be online and have a JM raid over its devices, and every + member the new raid consists of must be there: a device that is only + missing keeps its member (jm_raid_target_members), and a raid is not built + over a list with a hole in it.""" + if snode.status != StorageNode.STATUS_ONLINE: + return f"node {snode.get_id()} is {snode.status}" + target = jm_raid_target_members(snode) + if not target: + return f"node {snode.get_id()} has no JM raid over its devices to rebuild" + rpc_client = snode.rpc_client() + absent = [m for m in target if not rpc_client.bdev_get(m)] + if absent: + return (f"JM raid member(s) {absent} of node {snode.get_id()} are not present; the " + f"raid is rebuilt once they are back or their devices are migrated out") + return "" + + def reshape_jm_raid(node_id: str) -> list[str]: """Rebuild the JM raid of a node over the devices it has now, empty, and return the new member list. @@ -1540,18 +1561,12 @@ def reshape_jm_raid(node_id: str) -> list[str]: down; calling again finishes the rebuild.""" db_controller = DBController() snode = db_controller.get_storage_node_by_id(node_id) - if snode.status != StorageNode.STATUS_ONLINE: - raise JMReshapeNotReady(f"node {node_id} is {snode.status}") + reason = jm_raid_reshape_not_ready(snode) + if reason: + raise JMReshapeNotReady(reason) target = jm_raid_target_members(snode) - if not target: - raise JMReshapeNotReady(f"node {node_id} has no JM raid over its devices to rebuild") jm = snode.jm_device rpc_client = snode.rpc_client() - absent = [m for m in target if not rpc_client.bdev_get(m)] - if absent: - raise JMReshapeNotReady( - f"JM raid member(s) {absent} of node {node_id} are not present; the raid is " - f"rebuilt once they are back or their devices are migrated out") layout = jm_raid.layout_of_record(jm.jm_nvme_bdev_list, jm.raid_bdev, jm.jm_leg_bdevs) logger.info("Rebuilding the JM raid of node %s: members %s -> %s (%s)", diff --git a/simplyblock_core/services/tasks_runner_restart.py b/simplyblock_core/services/tasks_runner_restart.py index 18cc3b87cb..3671f2be0c 100644 --- a/simplyblock_core/services/tasks_runner_restart.py +++ b/simplyblock_core/services/tasks_runner_restart.py @@ -267,7 +267,8 @@ def _jm_reshape_blocker(task, node) -> str: The rebuild leaves the node without a journal copy of its own until the resync is done, so it starts only when nothing else is in the way: every node online, the cluster active, no data movement or restart queued, no - other node being rebuilt, and every journal this JM belongs to in sync.""" + other node being rebuilt, every journal this JM belongs to in sync, and + every member of the new raid present.""" cluster = db.get_cluster_by_id(task.cluster_id) if cluster.status != Cluster.STATUS_ACTIVE: return f"cluster is {cluster.status}" @@ -285,7 +286,7 @@ def _jm_reshape_blocker(task, node) -> str: pending = device_controller.jm_resync_pending(node, require_held=False) if pending: return f"journal not in sync: {'; '.join(pending)}" - return "" + return device_controller.jm_raid_reshape_not_ready(node) def task_runner_jm_reshape(task): diff --git a/tests/integration/test_jm_raid_reshape.py b/tests/integration/test_jm_raid_reshape.py new file mode 100644 index 0000000000..c6f5842b7e --- /dev/null +++ b/tests/integration/test_jm_raid_reshape.py @@ -0,0 +1,714 @@ +"""The JM raid of a node is rebuilt when the node's devices change. + +A device that fails and is migrated out takes its journal partition with it +for good. The raid over the node's journal partitions cannot give a member up +in place, so a ``jm_raid_reshape`` task builds it anew, empty, over the +members the node's devices call for, and waits until the new JM holds every +journal it is a copy of again. + +These tests run the flow against the real FoundationDB: the device change +queues the task, the restart runner's spec drives it, and the node record is +read back from the database. Only what sits above the database is replaced: +the SPDK RPC client of each node, the leadership probe and the device-status +fan-out to the cluster's distribs. +""" +from unittest.mock import MagicMock, patch + +import pytest + +from simplyblock_core import jm_raid, storage_node_ops +from simplyblock_core.controllers import ( + device_controller, + lvol_controller, + tasks_controller, +) +from simplyblock_core.db_controller import DBController +from simplyblock_core.models.cluster import Cluster +from simplyblock_core.models.job_schedule import JobSchedule +from simplyblock_core.models.nvme_device import JMDevice, NVMeDevice +from simplyblock_core.models.storage_node import StorageNode +from simplyblock_core.rpc_client import RPCException +from simplyblock_core.services import tasks_runner_restart +from tests.integration.task_driver import drive + +CLUSTER = "7d2c1a4e-0000-4000-8000-000000000001" +NODES = [f"7d2c1a4e-0000-4000-8000-00000000010{i}" for i in (1, 2, 3)] +ONLINE = NVMeDevice.STATUS_ONLINE +MIGRATED = NVMeDevice.STATUS_FAILED_AND_MIGRATED + + +def _device_id(node_index, device_index): + return f"7d2c1a4e-0000-4000-8000-00000000{node_index}0{device_index:02d}" + + +def _members(count): + return [f"nvme_{i}n1p1" for i in range(count)] + + +class Rpc: + """The SPDK side of one node: what the control plane asked of it, and the + answers a healthy node gives. ``journals_missing`` are the jm_vuids its JM + does not hold; an explicit synchronisation of one, called on any node, + puts it there when ``sync_works``.""" + + def __init__(self, env, node_id): + self.env, self.node_id = env, node_id + self.mock = MagicMock() + self.mock.bdev_get.side_effect = lambda name: ( + None if name in env.absent else {"name": name, "block_size": 4096, "num_blocks": 1000}) + self.mock.bdev_raid_create.side_effect = self._raid_create + self.mock.bdev_raid_get_bdevs.side_effect = lambda category="online": [ + {"name": name} for name in env.raids[node_id]] + self.mock.bdev_raid_delete.side_effect = lambda name: env.raids[node_id].remove(name) + self.mock.bdev_jm_create.return_value = True + self.mock.subsystem_get.return_value = None + self.mock.jc_get_jm_status.side_effect = self._jc_status + self.mock.bdev_jm_get_status.side_effect = self._jm_status + self.mock.jc_explicit_synchronization.side_effect = self._explicit_sync + + def _raid_create(self, name, members, level, *args, **kwargs): + if name in self.env.failing_raids: + return False + self.env.raids[self.node_id].append(name) + self.env.created.append((self.node_id, name, list(members), level)) + return True + + def _jc_status(self, jm_vuid): + if jm_vuid in self.env.unreachable: + raise RPCException("leader does not answer") + return {"jm_local": jm_vuid not in self.env.replicating, "remote_jm_n1": True} + + def _jm_status(self, jm_vuid): + if jm_vuid in self.env.journals_missing[self.node_id]: + return {"res": -1, "njournals": 2} + return {"res": 1, "njournals": 3, "jm_vuid": jm_vuid, "total_records": 14} + + def _explicit_sync(self, jm_vuid): + self.env.synced.append((self.node_id, jm_vuid)) + if self.env.sync_works: + for missing in self.env.journals_missing.values(): + missing.discard(jm_vuid) + return {"res": 1} + + +class Env: + def __init__(self, db): + self.db = db + self.absent: set = set() + self.failing_raids: set = set() + self.replicating: set = set() + self.unreachable: set = set() + self.sync_works = True + self.created: list = [] + self.synced: list = [] + self.raids = {node_id: [] for node_id in NODES} + self.journals_missing = {node_id: set() for node_id in NODES} + self.leaders: dict = {} + self.rpcs = {node_id: Rpc(self, node_id) for node_id in NODES} + + def node(self, index=0) -> StorageNode: + return self.db.get_storage_node_by_id(NODES[index]) + + def task(self, task_id) -> JobSchedule: + return self.db.get_task_by_id(task_id) + + def reshape_tasks(self, node_index=None): + return [t for t in self.db.get_job_tasks(CLUSTER) + if t.function_name == JobSchedule.FN_JM_RAID_RESHAPE + and (node_index is None or t.node_id == NODES[node_index])] + + def set_device(self, node_index, device_index, status): + def _mut(node): + node.nvme_devices[device_index].status = status + self.db.atomic_update(self.node(node_index), _mut) + + def set_node(self, node_index, **fields): + def _mut(node): + for name, value in fields.items(): + setattr(node, name, value) + self.db.atomic_update(self.node(node_index), _mut) + + def set_cluster(self, **fields): + def _mut(cluster): + for name, value in fields.items(): + setattr(cluster, name, value) + self.db.atomic_update(self.db.get_cluster_by_id(CLUSTER), _mut) + + def queue(self, node_index=0) -> str: + task_id = tasks_controller.add_jm_raid_reshape_task(CLUSTER, NODES[node_index]) + assert task_id + return task_id + + def drive(self, task_id) -> JobSchedule: + return drive(tasks_runner_restart.SPEC, self.task(task_id)) + + +def _seed_node(db, index, devices=4, legacy=False): + """A node whose drives are each cut into a journal partition (p1) and a + data partition (p2), with the JM raid over all the journal partitions. Its + JM is also a copy of the next node's journal, as in a three-node cluster + where every node keeps two remote journal copies.""" + node = StorageNode() + node.uuid = NODES[index] + node.cluster_id = CLUSTER + node.status = StorageNode.STATUS_ONLINE + node.hostname = f"worker-{index + 1}" + node.lvstore = f"LVS_{index + 1}" + node.jm_vuid = index + 1 + node.enable_ha_jm = False + node.num_partitions_per_dev = 1 + node.jm_percent = 3 + node.secondary_node_id = NODES[(index + 1) % len(NODES)] + node.jm_ids = [n for n in NODES if n != NODES[index]] + node.nvme_devices = [] + for i in range(devices): + dev = NVMeDevice() + dev.uuid = _device_id(index + 1, i) + dev.cluster_id = CLUSTER + dev.node_id = node.uuid + dev.nvme_controller = f"nvme_{i}" + dev.nvme_bdev = f"nvme_{i}n1p2" + dev.is_partition = True + dev.status = ONLINE + dev.cluster_device_order = index * 16 + i + node.nvme_devices.append(dev) + members = _members(devices) + legs = [] if legacy or devices < 2 else jm_raid.split_groups(members) + jm = JMDevice() + jm.uuid = node.uuid + jm.node_id = node.uuid + jm.status = JMDevice.STATUS_ONLINE + jm.jm_nvme_bdev_list = members + jm.jm_bdev = f"jm_{node.uuid}" + jm.alceml_bdev = f"alceml_jm_{node.uuid}" + jm.raid_bdev = f"raid_jm_{node.uuid}" if devices > 1 else members[0] + jm.jm_leg_members = legs + jm.jm_leg_bdevs = [leg[0] if len(leg) == 1 else f"raid_jm_{node.uuid}_l{i}" + for i, leg in enumerate(legs)] + node.jm_device = jm + node.write_to_db(db.kv_store) + return node + + +@pytest.fixture() +def env(): + db = DBController() + if db.kv_store is None: + pytest.skip("FoundationDB is not available") + cluster = Cluster() + cluster.uuid = CLUSTER + cluster.status = Cluster.STATUS_ACTIVE + cluster.write_to_db(db.kv_store) + for index in range(len(NODES)): + _seed_node(db, index) + environment = Env(db) + for index, node_id in enumerate(NODES): + environment.raids[node_id] = [f"raid_jm_{node_id}_l0", f"raid_jm_{node_id}_l1", + f"raid_jm_{node_id}"] + environment.leaders[f"LVS_{index + 1}"] = node_id + with patch.object(StorageNode, "rpc_client", autospec=True, + side_effect=lambda self, **kw: environment.rpcs[self.get_id()].mock), \ + patch.object(lvol_controller, "is_node_leader", + side_effect=lambda node, lvs: environment.leaders.get(lvs) == node.get_id()), \ + patch("simplyblock_core.distr_controller.send_dev_status_event"), \ + patch.object(tasks_runner_restart.time, "sleep"): + yield environment + + +def _raids_built(env, node_index=0): + return [(name, members, level) for node_id, name, members, level in env.created + if node_id == NODES[node_index]] + + +# -- the device change queues the task --------------------------------------- + +def test_a_device_migrated_out_queues_the_rebuild_of_its_node(env): + env.set_device(0, 1, NVMeDevice.STATUS_FAILED) + + assert device_controller.device_set_failed_and_migrated(_device_id(1, 1)) + + assert env.node().nvme_devices[1].status == MIGRATED + tasks = env.reshape_tasks() + assert [t.node_id for t in tasks] == [NODES[0]] + assert tasks[0].status == JobSchedule.STATUS_NEW + + +def test_a_second_device_of_the_node_does_not_queue_a_second_task(env): + env.set_device(0, 1, NVMeDevice.STATUS_FAILED) + env.set_device(0, 2, NVMeDevice.STATUS_FAILED) + + device_controller.device_set_failed_and_migrated(_device_id(1, 1)) + device_controller.device_set_failed_and_migrated(_device_id(1, 2)) + + assert len(env.reshape_tasks()) == 1 + + +def test_each_node_gets_its_own_task(env): + env.set_device(0, 1, NVMeDevice.STATUS_FAILED) + env.set_device(1, 0, NVMeDevice.STATUS_FAILED) + + device_controller.device_set_failed_and_migrated(_device_id(1, 1)) + device_controller.device_set_failed_and_migrated(_device_id(2, 0)) + + assert sorted(t.node_id for t in env.reshape_tasks()) == sorted(NODES[:2]) + + +def test_nothing_is_queued_for_a_journal_on_a_dedicated_device(env): + def _mut(node): + node.jm_device.jm_nvme_bdev_list = [] + env.db.atomic_update(env.node(), _mut) + env.set_device(0, 1, NVMeDevice.STATUS_FAILED) + + device_controller.device_set_failed_and_migrated(_device_id(1, 1)) + + assert env.reshape_tasks() == [] + + +def test_a_finished_task_does_not_stand_in_for_the_next_change(env): + env.set_device(0, 1, MIGRATED) + first = env.queue() + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): + env.drive(first) + assert env.task(first).status == JobSchedule.STATUS_DONE + + env.set_device(0, 2, NVMeDevice.STATUS_FAILED) + device_controller.device_set_failed_and_migrated(_device_id(1, 2)) + + assert len([t for t in env.reshape_tasks() if t.status != JobSchedule.STATUS_DONE]) == 1 + + +# -- the rebuild ------------------------------------------------------------- + +def test_the_raid_is_rebuilt_over_the_remaining_devices_and_the_task_ends_in_sync(env): + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + + task = env.drive(task_id) + + node = env.node() + remaining = ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] + assert node.jm_device.jm_nvme_bdev_list == remaining + assert node.jm_device.jm_leg_members == [remaining[:2], remaining[2:]] + assert node.jm_device.status == JMDevice.STATUS_ONLINE + assert node.jm_device.stale_jm_legs == [] + # The old raid1 and both of its legs are gone before the new ones are made. + assert _raids_built(env) == [ + (f"raid_jm_{NODES[0]}_l0", remaining[:2], "0"), + (f"raid_jm_{NODES[0]}", [f"raid_jm_{NODES[0]}_l0", "nvme_3n1p1"], "1"), + ] + assert sorted(env.raids[NODES[0]]) == sorted([f"raid_jm_{NODES[0]}_l0", f"raid_jm_{NODES[0]}"]) + # Formatted, not read back. + assert env.rpcs[NODES[0]].mock.bdev_alceml_create.call_args.kwargs["pba_init_mode"] == 3 + assert task.status == JobSchedule.STATUS_RUNNING + assert task.function_params["phase"] == "resync" + assert task.function_params["members"] == remaining + + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS - 1): + task = env.drive(task_id) + assert task.status == JobSchedule.STATUS_DONE + assert "journals in sync" in task.function_result + assert env.synced == [] + assert len(_raids_built(env)) == 2 # built once + + +def test_nothing_to_do_ends_the_task_without_touching_the_node(env): + task = env.drive(env.queue()) + + assert task.status == JobSchedule.STATUS_DONE + assert "already matches" in task.function_result + assert env.created == [] + assert env.node().jm_device.jm_nvme_bdev_list == _members(4) + + +def test_shrinking_to_two_devices_is_a_plain_mirror_and_to_one_no_raid(env): + env.set_device(0, 0, MIGRATED) + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): + env.drive(task_id) + node = env.node() + assert node.jm_device.jm_nvme_bdev_list == ["nvme_2n1p1", "nvme_3n1p1"] + assert node.jm_device.jm_leg_bdevs == ["nvme_2n1p1", "nvme_3n1p1"] + assert _raids_built(env) == [(f"raid_jm_{NODES[0]}", ["nvme_2n1p1", "nvme_3n1p1"], "1")] + + env.created.clear() + env.set_device(0, 2, MIGRATED) + task_id = env.queue() + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): + task = env.drive(task_id) + node = env.node() + assert task.status == JobSchedule.STATUS_DONE + assert node.jm_device.jm_nvme_bdev_list == ["nvme_3n1p1"] + assert node.jm_device.raid_bdev == "nvme_3n1p1" + assert node.jm_device.jm_leg_bdevs == [] + assert env.created == [] + assert env.raids[NODES[0]] == [] # no raid left behind + + +def test_a_single_device_jm_grows_into_a_mirror_not_into_the_legacy_layout(env): + """A device that brings a journal partition joins the raid. Its record of + one member looks like a legacy mirror (a raid_bdev and no legs).""" + def _mut(node): + jm = node.jm_device + jm.jm_nvme_bdev_list = ["nvme_0n1p1"] + jm.raid_bdev = "nvme_0n1p1" + jm.jm_leg_bdevs = [] + jm.jm_leg_members = [] + env.db.atomic_update(env.node(), _mut) + env.raids[NODES[0]] = [] + for index in (2, 3): + env.set_device(0, index, NVMeDevice.STATUS_NEW) + + env.drive(env.queue()) + + node = env.node() + assert node.jm_device.jm_nvme_bdev_list == ["nvme_0n1p1", "nvme_1n1p1"] + assert node.jm_device.jm_leg_bdevs == ["nvme_0n1p1", "nvme_1n1p1"] + assert _raids_built(env) == [(f"raid_jm_{NODES[0]}", ["nvme_0n1p1", "nvme_1n1p1"], "1")] + + +def test_a_legacy_mirror_is_rebuilt_as_a_legacy_mirror(env): + """A cluster pinned to the mirror over all members keeps that layout.""" + env.set_cluster(jm_raid_layout=jm_raid.LAYOUT_LEGACY) + + def _mut(node): + node.jm_device.jm_leg_bdevs = [] + node.jm_device.jm_leg_members = [] + env.db.atomic_update(env.node(), _mut) + env.raids[NODES[0]] = [f"raid_jm_{NODES[0]}"] + env.set_device(0, 1, MIGRATED) + + env.drive(env.queue()) + + node = env.node() + remaining = ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] + assert _raids_built(env) == [(f"raid_jm_{NODES[0]}", remaining, "1")] + assert node.jm_device.jm_nvme_bdev_list == remaining + assert node.jm_device.jm_leg_bdevs == [] + + +# -- the resync -------------------------------------------------------------- + +def test_a_journal_the_new_jm_does_not_hold_is_synchronised_on_its_leader(env): + """Lab, 2026-11-23: the leader reported every JM of its journal ready + while its own rebuilt JM did not hold that journal.""" + env.set_device(0, 1, MIGRATED) + env.journals_missing[NODES[0]] = {1} + task_id = env.queue() + + task = env.drive(task_id) + + assert env.synced == [(NODES[0], 1)] + assert task.status == JobSchedule.STATUS_RUNNING + assert task.function_params["sync_calls"] == 1 + assert task.function_params["ready_polls"] == 0 + + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): + task = env.drive(task_id) + assert task.status == JobSchedule.STATUS_DONE + assert env.synced == [(NODES[0], 1)] # once was enough + + +def test_the_sync_goes_to_the_node_that_leads_the_lvs(env): + env.set_device(0, 1, MIGRATED) + env.journals_missing[NODES[0]] = {1} + env.leaders["LVS_1"] = NODES[1] # failed over to its secondary + + env.drive(env.queue()) + + assert env.synced == [(NODES[1], 1)] + + +def test_no_sync_without_a_confirmed_leader(env): + """On a follower an explicit synchronisation takes the leadership away.""" + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + env.drive(task_id) + env.journals_missing[NODES[0]] = {1} + del env.leaders["LVS_1"] + + task = env.drive(task_id) + + assert env.synced == [] + assert task.status == JobSchedule.STATUS_RUNNING + assert "no leader found" in task.function_result + + +def test_replication_that_runs_is_waited_for_not_started_again(env): + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + env.drive(task_id) + env.journals_missing[NODES[0]] = {1} + env.replicating.add(1) + + task = env.drive(task_id) + + assert env.synced == [] + assert task.status == JobSchedule.STATUS_RUNNING + assert task.function_params["ready_polls"] == 0 + + +def test_a_journal_that_never_arrives_costs_retries(env): + env.set_device(0, 1, MIGRATED) + env.journals_missing[NODES[0]] = {1} + env.sync_works = False + task_id = env.queue() + + for _ in range(tasks_runner_restart.JM_RESHAPE_MAX_SYNC_CALLS): + task = env.drive(task_id) + assert task.retry == 0 + task = env.drive(task_id) + + assert task.retry == 1 + assert task.status == JobSchedule.STATUS_SUSPENDED + assert "still not on the rebuilt JM" in task.function_result + assert len(_raids_built(env)) == 2 # the raid itself is not rebuilt again + + +# -- when the rebuild must not start ----------------------------------------- + +def _assert_untouched(env, task, reason): + assert task.status == JobSchedule.STATUS_SUSPENDED + assert task.retry == 0 + assert reason in task.function_result + assert "phase" not in task.function_params + assert env.created == [] + assert env.node().jm_device.jm_nvme_bdev_list == _members(4) + assert env.node().jm_device.status == JMDevice.STATUS_ONLINE + + +def test_it_waits_for_an_active_cluster(env): + env.set_device(0, 1, MIGRATED) + env.set_cluster(status=Cluster.STATUS_DEGRADED) + _assert_untouched(env, env.drive(env.queue()), "cluster is degraded") + + +def test_it_waits_while_another_node_is_not_online(env): + env.set_device(0, 1, MIGRATED) + env.set_node(2, status=StorageNode.STATUS_OFFLINE) + _assert_untouched(env, env.drive(env.queue()), f"node {NODES[2]} is offline") + + +def test_a_removed_node_does_not_hold_it_up(env): + env.set_device(0, 1, MIGRATED) + env.set_node(2, status=StorageNode.STATUS_REMOVED) + + task = env.drive(env.queue()) + + assert task.function_params["phase"] == "resync" + + +def test_it_waits_for_data_movement_to_end(env): + env.set_device(0, 1, MIGRATED) + migration = JobSchedule() + migration.uuid = "7d2c1a4e-0000-4000-8000-000000000a01" + migration.cluster_id = CLUSTER + migration.node_id = NODES[1] + migration.function_name = JobSchedule.FN_NEW_DEV_MIG + migration.status = JobSchedule.STATUS_RUNNING + migration.write_to_db(env.db.kv_store) + + _assert_untouched(env, env.drive(env.queue()), "new_device_migration") + + +def test_it_waits_while_a_journal_is_being_replicated(env): + env.set_device(0, 1, MIGRATED) + env.replicating.add(2) # a journal this JM is a remote copy of + _assert_untouched(env, env.drive(env.queue()), "journal not in sync") + + +def test_it_waits_while_a_leader_cannot_be_asked(env): + env.set_device(0, 1, MIGRATED) + env.unreachable.add(1) + _assert_untouched(env, env.drive(env.queue()), "leader does not answer") + + +def test_a_journal_the_old_jm_lacks_does_not_hold_the_rebuild_up(env): + env.set_device(0, 1, MIGRATED) + env.journals_missing[NODES[0]] = {1} + + task = env.drive(env.queue()) + + assert task.function_params["phase"] == "resync" + + +def test_it_waits_while_a_member_it_needs_is_absent(env): + """A device that is only missing keeps its member; the raid is not built + over a list with a hole in it.""" + env.set_device(0, 1, MIGRATED) + env.set_device(0, 3, NVMeDevice.STATUS_REMOVED) + env.absent.add("nvme_3n1p1") + task_id = env.queue() + + task = env.drive(task_id) + + assert task.status == JobSchedule.STATUS_SUSPENDED + assert task.retry == 0 + assert "phase" not in task.function_params + assert "nvme_3n1p1" in task.function_result + assert env.created == [] + node = env.node() + assert node.jm_device.jm_nvme_bdev_list == _members(4) + assert node.jm_device.status == JMDevice.STATUS_ONLINE # the old stack was not taken down + assert sorted(env.raids[NODES[0]]) == sorted( + [f"raid_jm_{NODES[0]}_l0", f"raid_jm_{NODES[0]}_l1", f"raid_jm_{NODES[0]}"]) + + env.absent.clear() + env.set_device(0, 3, ONLINE) + task = env.drive(task_id) + assert task.function_params["phase"] == "resync" + assert env.node().jm_device.jm_nvme_bdev_list == ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] + + +def test_one_node_at_a_time(env): + env.set_device(0, 1, MIGRATED) + env.set_device(1, 1, MIGRATED) + first, second = env.queue(0), env.queue(1) + + assert env.drive(first).function_params["phase"] == "resync" + waiting = env.drive(second) + + assert waiting.status == JobSchedule.STATUS_SUSPENDED + assert f"node {NODES[0]} is being rebuilt" in waiting.function_result + assert env.node(1).jm_device.jm_nvme_bdev_list == _members(4) + assert _raids_built(env, 1) == [] + + for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS - 1): + env.drive(first) + assert env.task(first).status == JobSchedule.STATUS_DONE + + assert env.drive(second).function_params["phase"] == "resync" + assert env.node(1).jm_device.jm_nvme_bdev_list == ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] + + +def test_a_queued_task_that_has_not_started_does_not_hold_up_another(env): + env.set_device(0, 1, MIGRATED) + env.set_device(1, 1, MIGRATED) + env.queue(0) + second = env.queue(1) + + assert env.drive(second).function_params["phase"] == "resync" + + +# -- failures ---------------------------------------------------------------- + +def test_a_failed_build_is_retried_until_the_node_has_a_jm_again(env): + env.set_device(0, 1, MIGRATED) + env.failing_raids.add(f"raid_jm_{NODES[0]}") + task_id = env.queue() + + task = env.drive(task_id) + + assert task.status == JobSchedule.STATUS_SUSPENDED + assert task.retry == 1 + assert task.function_params["phase"] == "rebuild" + node = env.node() + # The record still names the old members: the raid still does not match. + assert node.jm_device.jm_nvme_bdev_list == _members(4) + assert node.jm_device.status == JMDevice.STATUS_UNAVAILABLE + + # The stack is down: the retry builds whatever the cluster looks like now. + env.failing_raids.clear() + env.set_cluster(status=Cluster.STATUS_DEGRADED) + task = env.drive(task_id) + + node = env.node() + assert task.function_params["phase"] == "resync" + assert node.jm_device.jm_nvme_bdev_list == ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] + assert node.jm_device.status == JMDevice.STATUS_ONLINE + # The leg the failed attempt left behind was deleted, not reused. + assert [name for name, _, _ in _raids_built(env)].count(f"raid_jm_{NODES[0]}_l0") == 2 + + +def test_a_canceled_task_does_not_start_the_rebuild(env): + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + + def _cancel(task): + task.canceled = True + env.db.atomic_update(env.task(task_id), _cancel) + + task = env.drive(task_id) + + assert task.status == JobSchedule.STATUS_DONE + assert env.created == [] + assert env.node().jm_device.jm_nvme_bdev_list == _members(4) + + +def test_a_node_that_is_not_online_waits_and_a_removed_one_ends_the_task(env): + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + env.set_node(0, status=StorageNode.STATUS_OFFLINE) + + task = env.drive(task_id) + assert task.status == JobSchedule.STATUS_SUSPENDED + assert task.retry == 0 + + env.set_node(0, status=StorageNode.STATUS_REMOVED) + task = env.drive(task_id) + assert task.status == JobSchedule.STATUS_DONE + assert env.created == [] + + +# -- a JM that holds a journal keeps its legs -------------------------------- + +def _twelve_member_node(db, legs): + node = _seed_node(db, 0, devices=12) + + def _mut(fresh): + fresh.jm_device.jm_leg_members = legs + fresh.jm_device.jm_leg_bdevs = [f"raid_jm_{NODES[0]}_l{i}" for i in range(len(legs))] + db.atomic_update(node, _mut) + return db.get_storage_node_by_id(NODES[0]) + + +def test_a_restart_rebuilds_a_twelve_device_jm_from_the_two_halves_it_was_built_in(env): + """Built before the legs were capped at four devices. Re-planned into + three legs, every stripe would be read from the wrong drives.""" + members = _members(12) + node = _twelve_member_node(env.db, [members[:6], members[6:]]) + env.raids[NODES[0]] = [] + + jm = storage_node_ops._create_jm_stack_on_raid( + env.rpcs[NODES[0]].mock, members, node, after_restart=True) + + assert _raids_built(env) == [ + (f"raid_jm_{NODES[0]}_l0", members[:6], "0"), + (f"raid_jm_{NODES[0]}_l1", members[6:], "0"), + (f"raid_jm_{NODES[0]}", [f"raid_jm_{NODES[0]}_l0", f"raid_jm_{NODES[0]}_l1"], "1"), + ] + assert jm.jm_leg_members == [members[:6], members[6:]] + assert env.rpcs[NODES[0]].mock.bdev_alceml_create.call_args.kwargs["pba_init_mode"] == 1 + + +def test_a_new_twelve_device_jm_is_three_legs_of_four(env): + members = _members(12) + node = _twelve_member_node(env.db, [members[:6], members[6:]]) + env.raids[NODES[0]] = [] + + jm = storage_node_ops._create_jm_stack_on_raid( + env.rpcs[NODES[0]].mock, members, node, after_restart=False) + + assert [(name, level) for name, _, level in _raids_built(env)] == [ + (f"raid_jm_{NODES[0]}_l0", "0"), (f"raid_jm_{NODES[0]}_l1", "0"), + (f"raid_jm_{NODES[0]}_l2", "0"), (f"raid_jm_{NODES[0]}", "1")] + assert jm.jm_leg_members == [members[:4], members[4:8], members[8:]] + + +def test_a_restart_with_a_member_of_one_of_three_legs_missing_runs_on_the_other_two(env): + members = _members(12) + legs = [members[:4], members[4:8], members[8:]] + node = _twelve_member_node(env.db, legs) + env.raids[NODES[0]] = [] + + jm = storage_node_ops._create_jm_stack_on_raid( + env.rpcs[NODES[0]].mock, members, node, after_restart=True, missing=[members[5]]) + + assert _raids_built(env) == [ + (f"raid_jm_{NODES[0]}_l0", legs[0], "0"), + (f"raid_jm_{NODES[0]}_l2", legs[2], "0"), + (f"raid_jm_{NODES[0]}", [f"raid_jm_{NODES[0]}_l0", f"raid_jm_{NODES[0]}_l2"], "1"), + ] + assert jm.raid_bdev == f"raid_jm_{NODES[0]}" + assert jm.jm_leg_members == legs # the full geometry stays on record + assert jm.stale_jm_legs == [f"raid_jm_{NODES[0]}_l1"] diff --git a/tests/unit/test_jm_raid_reshape.py b/tests/unit/test_jm_raid_reshape.py index 311d1346b3..ebc7f1a9e8 100644 --- a/tests/unit/test_jm_raid_reshape.py +++ b/tests/unit/test_jm_raid_reshape.py @@ -10,31 +10,19 @@ - jm_raid: the member list after a change, the layout a record was built under, and the legs: at most four devices each, and for a JM that holds a journal always the ones it was built with. - - device_controller: which members the node's devices call for, the - teardown that leaves no raid behind, the rebuild, and whether the resync - is done. - - tasks_runner_restart: the task that does it, one node at a time and only - on a quiet cluster. + - device_controller: which members the node's devices call for, whether the + raid can be rebuilt now, and the teardown that leaves no raid behind. + +The rebuild itself, the task that runs it and the journal resync read and +write node and task records: tests/integration/test_jm_raid_reshape.py. """ import unittest from unittest.mock import MagicMock, patch -import pytest - -import simplyblock_core.services.task_runner_base as trb -from simplyblock_core import jm_raid, storage_node_ops, utils -from simplyblock_core.controllers import device_controller, tasks_controller -from simplyblock_core.models.cluster import Cluster -from simplyblock_core.models.job_schedule import JobSchedule +from simplyblock_core import jm_raid, utils +from simplyblock_core.controllers import device_controller from simplyblock_core.models.nvme_device import JMDevice, NVMeDevice from simplyblock_core.models.storage_node import StorageNode -from simplyblock_core.rpc_client import RPCException -from simplyblock_core.services.task_runner_base import ( - TaskAbort, - TaskDefer, - TaskProgress, - TaskRetry, -) ONLINE = NVMeDevice.STATUS_ONLINE MIGRATED = NVMeDevice.STATUS_FAILED_AND_MIGRATED @@ -169,89 +157,6 @@ def test_is_jm_raid_bdev(self): self.assertFalse(jm_raid.is_jm_raid_bdev("raid_jm_n2_l0", "n1")) -class TestStackKeepsRecordedLegs(unittest.TestCase): - """storage_node_ops._create_jm_stack_on_raid, RPCs mocked.""" - - def _run(self, members, recorded_legs=None, after_restart=False, layout="", pinned=""): - rpc = MagicMock() - rpc.bdev_raid_create.return_value = True - rpc.bdev_jm_create.return_value = True - rpc.bdev_get.return_value = {"block_size": 512, "num_blocks": 1000} - snode = MagicMock() - snode.get_id.return_value = "n1" - snode.enable_ha_jm = False - snode.data_nics = [] - snode.create_alceml.return_value = True - snode.jm_device = None - if recorded_legs is not None: - jm = JMDevice() - jm.raid_bdev = "raid_jm_n1" - jm.jm_leg_members = recorded_legs - jm.jm_leg_bdevs = [f"raid_jm_n1_l{i}" for i in range(len(recorded_legs))] - snode.jm_device = jm - cluster = MagicMock() - cluster.jm_raid_layout = pinned - with patch.object(storage_node_ops, "DBController") as db_cls: - db_cls.return_value.get_cluster_by_id.return_value = cluster - jm = storage_node_ops._create_jm_stack_on_raid( - rpc, list(members), snode, after_restart=after_restart, layout=layout) - calls = [(c.args[0], list(c.args[1]), c.args[2]) for c in rpc.bdev_raid_create.call_args_list] - return jm, calls, snode - - def test_restart_of_a_twelve_device_jm_built_in_two_halves(self): - members = [f"m{i}" for i in range(12)] - jm, calls, _ = self._run(members, recorded_legs=[members[:6], members[6:]], - after_restart=True) - self.assertEqual(calls, [ - ("raid_jm_n1_l0", members[:6], "0"), - ("raid_jm_n1_l1", members[6:], "0"), - ("raid_jm_n1", ["raid_jm_n1_l0", "raid_jm_n1_l1"], "1"), - ]) - self.assertEqual(jm.jm_leg_members, [members[:6], members[6:]]) - - def test_new_twelve_device_jm_is_three_legs_under_one_raid1(self): - members = [f"m{i}" for i in range(12)] - jm, calls, _ = self._run(members) - self.assertEqual(calls, [ - ("raid_jm_n1_l0", members[:4], "0"), - ("raid_jm_n1_l1", members[4:8], "0"), - ("raid_jm_n1_l2", members[8:], "0"), - ("raid_jm_n1", ["raid_jm_n1_l0", "raid_jm_n1_l1", "raid_jm_n1_l2"], "1"), - ]) - - def test_a_formatted_jm_is_planned_anew_whatever_the_record_says(self): - members = [f"m{i}" for i in range(12)] - jm, calls, snode = self._run(members, recorded_legs=[members[:6], members[6:]], - after_restart=False) - self.assertEqual([len(leg) for leg in jm.jm_leg_members], [4, 4, 4]) - self.assertEqual(snode.create_alceml.call_args.kwargs["pba_init_mode"], 3) - - def test_the_layout_given_decides_when_the_record_cannot(self): - # The record of a single-device JM looks legacy (a raid_bdev, no legs). - rpc_jm = JMDevice() - rpc_jm.raid_bdev = "a" - with patch.object(storage_node_ops, "DBController") as db_cls: - cluster = MagicMock() - cluster.jm_raid_layout = "" - db_cls.return_value.get_cluster_by_id.return_value = cluster - rpc = MagicMock() - rpc.bdev_get.return_value = {"block_size": 512, "num_blocks": 1000} - snode = MagicMock() - snode.get_id.return_value = "n1" - snode.enable_ha_jm = False - snode.data_nics = [] - snode.jm_device = rpc_jm - jm = storage_node_ops._create_jm_stack_on_raid( - rpc, list("abc"), snode, after_restart=False, layout=jm_raid.LAYOUT_RAID01) - self.assertEqual(jm.jm_leg_members, [["a", "b"], ["c"]]) - - def test_a_layout_pinned_on_the_cluster_wins_over_the_one_given(self): - jm, calls, _ = self._run(list("abc"), layout=jm_raid.LAYOUT_RAID01, - pinned=jm_raid.LAYOUT_LEGACY) - self.assertEqual(calls, [("raid_jm_n1", list("abc"), "1")]) - self.assertEqual(jm.jm_leg_bdevs, []) - - class TestTargetMembers(unittest.TestCase): def test_all_devices_online_changes_nothing(self): @@ -336,84 +241,6 @@ def test_an_unpartitioned_nvme_drive_brings_no_journal_partition(self): self.assertEqual(device_controller.jm_raid_target_members(snode), ["nvme_0n1p1"]) -class TestQueueReshape(unittest.TestCase): - - def _queue(self, snode): - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(device_controller.tasks_controller, "add_jm_raid_reshape_task") as add: - db_cls.return_value.get_storage_node_by_id.return_value = snode - device_controller.queue_jm_raid_reshape(snode.get_id()) - return add - - def test_queued_when_the_raid_no_longer_matches(self): - snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) - self._queue(snode).assert_called_once_with("c1", "n1") - - def test_not_queued_when_it_matches(self): - snode, _ = _lblk_node([ONLINE, ONLINE, ONLINE]) - self._queue(snode).assert_not_called() - - def test_a_node_that_is_gone_is_ignored(self): - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(device_controller.tasks_controller, "add_jm_raid_reshape_task") as add: - db_cls.return_value.get_storage_node_by_id.side_effect = KeyError("n1") - device_controller.queue_jm_raid_reshape("n1") - add.assert_not_called() - - def test_a_device_migrated_out_queues_the_rebuild_of_its_node(self): - dev = MagicMock() - dev.node_id = "n1" - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(device_controller, "device_set_state"), \ - patch.object(device_controller, "queue_jm_raid_reshape") as queue: - db_cls.return_value.get_storage_device_by_id.return_value = dev - db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = [] - device_controller.device_set_failed_and_migrated("dev1") - queue.assert_called_once_with("n1") - - -class TestOneOpenTaskPerNode(unittest.TestCase): - - def _open(self, node_id, status=JobSchedule.STATUS_RUNNING, canceled=False): - task = JobSchedule() - task.uuid = f"t-{node_id}" - task.node_id = node_id - task.function_name = JobSchedule.FN_JM_RAID_RESHAPE - task.status = status - task.canceled = canceled - return task - - def _add(self, existing): - with patch.object(tasks_controller, "db") as db, \ - patch.object(tasks_controller, "tasks_events"): - db.get_job_tasks.return_value = existing - return tasks_controller.add_jm_raid_reshape_task("c1", "n1"), db - - def test_added_when_the_node_has_none(self): - task_id, _ = self._add([self._open("n2")]) - self.assertTrue(task_id) - - def test_not_added_twice_for_one_node(self): - task_id, _ = self._add([self._open("n1")]) - self.assertFalse(task_id) - - def test_a_done_or_canceled_task_does_not_count(self): - task_id, _ = self._add([self._open("n1", status=JobSchedule.STATUS_DONE), - self._open("n1", canceled=True)]) - self.assertTrue(task_id) - - def test_blocking_tasks_are_the_ones_that_move_data_or_restart(self): - mig = self._open("n2") - mig.function_name = JobSchedule.FN_NEW_DEV_MIG - comp = self._open("n2") - comp.function_name = JobSchedule.FN_JC_COMP_RESUME - done = self._open("n2", status=JobSchedule.STATUS_DONE) - done.function_name = JobSchedule.FN_NODE_RESTART - with patch.object(tasks_controller, "db") as db: - db.get_job_tasks.return_value = [mig, comp, done, self._open("n3")] - self.assertEqual(tasks_controller.get_jm_raid_reshape_blocking_tasks("c1"), [mig]) - - class TestDeleteJmStack(unittest.TestCase): def _rpc(self, raids, present=None): @@ -462,526 +289,32 @@ def test_a_single_device_jm_has_no_raid_to_delete(self): rpc.bdev_raid_delete.assert_not_called() -class TestReshapeJmRaid(unittest.TestCase): +class TestNotReady(unittest.TestCase): - def _reshape(self, snode, absent=(), new_jm=None, create_error=None): + def _reason(self, snode, absent=()): rpc = MagicMock() rpc.bdev_get.side_effect = lambda name: None if name in absent else {"name": name} - rpc.bdev_raid_get_bdevs.return_value = [] - self.rpc = rpc - self.order = [] - if new_jm is None: - new_jm = JMDevice() - new_jm.uuid = "jm1" - - def create(*args, **kwargs): - self.order.append("create") - if create_error: - raise create_error - return new_jm - - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(StorageNode, "rpc_client", return_value=rpc), \ - patch.object(device_controller, "set_jm_device_state", - side_effect=lambda _id, state: self.order.append(state)) as set_state, \ - patch.object(device_controller, "_delete_jm_stack", - side_effect=lambda *a: self.order.append("delete")) as delete, \ - patch.object(storage_node_ops, "_create_jm_stack_on_raid", side_effect=create) as build: - db = db_cls.return_value - db.get_storage_node_by_id.return_value = snode - db.atomic_update.side_effect = lambda obj, fn: (fn(obj), self.order.append("record"), obj)[2] - self.db, self.set_state, self.delete, self.build = db, set_state, delete, build - return device_controller.reshape_jm_raid(snode.get_id()) - - def test_rebuilds_over_the_remaining_devices_empty(self): - snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE, ONLINE]) - target = [names[0], names[2], names[3]] - self.assertEqual(self._reshape(snode), target) - args, kwargs = self.build.call_args - self.assertEqual(args[1], target) - self.assertIs(kwargs["after_restart"], False) # formatted, not read back - self.assertEqual(kwargs["layout"], jm_raid.LAYOUT_RAID01) - # Down, torn down, built, recorded, and only then online for the peers. - self.assertEqual(self.order, [JMDevice.STATUS_UNAVAILABLE, "delete", "create", "record", - JMDevice.STATUS_ONLINE]) - - def test_a_legacy_mirror_stays_a_legacy_mirror(self): + with patch.object(StorageNode, "rpc_client", return_value=rpc): + return device_controller.jm_raid_reshape_not_ready(snode) + + def test_ready_when_every_member_of_the_new_raid_is_there(self): + snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE, ONLINE]) + self.assertEqual(self._reason(snode), "") + + def test_the_member_of_the_device_that_left_is_not_needed(self): snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) - snode.jm_device.jm_leg_bdevs = [] - snode.jm_device.jm_leg_members = [] - self._reshape(snode) - self.assertEqual(self.build.call_args.kwargs["layout"], jm_raid.LAYOUT_LEGACY) - - def test_a_single_device_jm_grows_into_raid01(self): - snode, names = _lblk_node([ONLINE, ONLINE], members=None) - snode.jm_device.jm_nvme_bdev_list = names[:1] - snode.jm_device.raid_bdev = names[0] - snode.jm_device.jm_leg_bdevs = [] - self.assertEqual(self._reshape(snode), names) - self.assertEqual(self.build.call_args.kwargs["layout"], jm_raid.LAYOUT_RAID01) - - def test_nothing_is_touched_while_a_member_is_absent(self): + self.assertEqual(self._reason(snode, absent={names[1]}), "") + + def test_a_member_the_new_raid_needs_is_absent(self): snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) - with self.assertRaises(device_controller.JMReshapeNotReady) as ctx: - self._reshape(snode, absent={names[2]}) - self.assertIn(names[2], str(ctx.exception)) - self.assertEqual(self.order, []) + self.assertIn(names[2], self._reason(snode, absent={names[2]})) - def test_nothing_is_touched_on_a_node_that_is_not_online(self): + def test_a_node_that_is_not_online(self): snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) snode.status = StorageNode.STATUS_RESTARTING - with self.assertRaises(device_controller.JMReshapeNotReady): - self._reshape(snode) - self.assertEqual(self.order, []) + self.assertIn(StorageNode.STATUS_RESTARTING, self._reason(snode)) - def test_a_node_without_a_raid_over_its_devices_is_refused(self): + def test_a_node_without_a_raid_over_its_devices(self): snode, _ = _lblk_node([ONLINE, ONLINE]) snode.jm_device.jm_nvme_bdev_list = [] - with self.assertRaises(device_controller.JMReshapeNotReady): - self._reshape(snode) - self.assertEqual(self.order, []) - - def test_a_failed_build_leaves_the_old_record_for_the_retry(self): - snode, names = _lblk_node([ONLINE, MIGRATED, ONLINE]) - with self.assertRaises(device_controller.JMReshapeError): - self._reshape(snode, new_jm=False) - self.assertEqual(self.order, [JMDevice.STATUS_UNAVAILABLE, "delete", "create"]) - # The record still names the old members, so the retry still sees - # that the raid does not match the devices. - self.assertEqual(snode.jm_device.jm_nvme_bdev_list, names) - self.assertTrue(device_controller.jm_raid_reshape_needed(snode)) - - def test_an_rpc_failure_during_the_build_is_passed_on(self): - snode, _ = _lblk_node([ONLINE, MIGRATED, ONLINE]) - with self.assertRaises(RPCException): - self._reshape(snode, create_error=RPCException("boom")) - self.assertNotIn("record", self.order) - self.assertNotIn(JMDevice.STATUS_ONLINE, self.order) - - -class TestResyncPending(unittest.TestCase): - - def _node(self, node_id, lvstore, jm_vuid, jm_ids=(), sec="", status=StorageNode.STATUS_ONLINE): - node = StorageNode() - node.uuid = node_id - node.cluster_id = "c1" - node.status = status - node.lvstore = lvstore - node.jm_vuid = jm_vuid - node.jm_ids = list(jm_ids) - node.secondary_node_id = sec - jm = JMDevice() - jm.uuid = f"jm-{node_id}" - node.jm_device = jm - return node - - def _call(self, func, nodes, leaders, statuses, not_held=(), **kwargs): - """Run ``func`` for nodes[0]. ``leaders``: lvstore -> id of the node - that leads it. ``statuses``: (node id, jm_vuid) -> jc_get_jm_status - answer, or an exception. ``not_held``: the jm_vuids whose journal the - JM of nodes[0] does not hold. Returns (result, the jc_get_jm_status - calls, the jc_explicit_synchronization calls).""" - asked, synced = [], [] - - def rpc_for(node): - rpc = MagicMock() - - def status(jm_vuid): - asked.append((node.get_id(), jm_vuid)) - answer = statuses[(node.get_id(), jm_vuid)] - if isinstance(answer, Exception): - raise answer - return answer - - def held(jm_vuid): - assert node.get_id() == nodes[0].get_id(), "asked of the JM's own node" - if jm_vuid in not_held: - return {"res": -1, "njournals": 2} - return {"res": 1, "njournals": 3, "jm_vuid": jm_vuid, "total_records": 14} - - rpc.jc_get_jm_status.side_effect = status - rpc.bdev_jm_get_status.side_effect = held - rpc.jc_explicit_synchronization.side_effect = \ - lambda jm_vuid: synced.append((node.get_id(), jm_vuid)) - return rpc - - from simplyblock_core.controllers import lvol_controller - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(StorageNode, "rpc_client", autospec=True, - side_effect=lambda self, **kw: rpc_for(self)), \ - patch.object(lvol_controller, "is_node_leader", - side_effect=lambda node, lvs: leaders.get(lvs) == node.get_id()): - db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = nodes - result = func(nodes[0], **kwargs) - return result, asked, synced - - def _pending(self, nodes, leaders, statuses, **kwargs): - pending, asked, _ = self._call(device_controller.jm_resync_pending, nodes, leaders, - statuses, **kwargs) - return pending, asked - - def test_ready_everywhere_but_not_on_the_jm_is_pending(self): - """The lab case: the JM was rebuilt empty, the leader reported every - JM of the journal ready, and the JM did not hold the journal.""" - n1 = self._node("n1", "LVS_1", 1) - pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {"jm_n1": True}}, - not_held={1}) - self.assertEqual(len(pending), 1) - self.assertIn("not on the JM", pending[0]) - - def test_before_the_rebuild_a_journal_the_jm_lacks_does_not_hold_it_up(self): - n1 = self._node("n1", "LVS_1", 1) - pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {"jm_n1": True}}, - not_held={1}, require_held=False) - self.assertEqual(pending, []) - - def test_the_sync_is_started_on_the_leader_for_a_journal_the_jm_lacks(self): - n1 = self._node("n1", "LVS_1", 1, jm_ids=["jm-n2"], sec="n2") - n2 = self._node("n2", "LVS_2", 2, jm_ids=["jm-n1"], sec="n1") - started, _, synced = self._call( - device_controller.start_jm_resync, [n1, n2], {"LVS_1": "n1", "LVS_2": "n2"}, - {("n1", 1): {"jm_n1": True}, ("n2", 2): {"jm_n2": True}}, not_held={1}) - self.assertEqual(started, ["LVS_1"]) - self.assertEqual(synced, [("n1", 1)]) # the journal it holds is left alone - - def test_the_sync_goes_to_the_leader_even_when_that_is_another_node(self): - n1 = self._node("n1", "LVS_1", 1, sec="n2") - n2 = self._node("n2", "", 0) - started, _, synced = self._call( - device_controller.start_jm_resync, [n1, n2], {"LVS_1": "n2"}, - {("n2", 1): {"jm_n1": True}}, not_held={1}) - self.assertEqual((started, synced), (["LVS_1"], [("n2", 1)])) - - def test_no_sync_is_started_without_a_confirmed_leader(self): - """On a follower an explicit synchronisation takes the leadership - away from the real leader.""" - n1 = self._node("n1", "LVS_1", 1, sec="n2") - n2 = self._node("n2", "", 0) - started, _, synced = self._call(device_controller.start_jm_resync, [n1, n2], {}, {}, - not_held={1}) - self.assertEqual((started, synced), ([], [])) - - def test_no_sync_is_started_while_replication_runs_or_the_state_is_unknown(self): - n1 = self._node("n1", "LVS_1", 1) - for answer in ({"jm_n1": False}, {}, RPCException("down")): - started, _, synced = self._call(device_controller.start_jm_resync, [n1], - {"LVS_1": "n1"}, {("n1", 1): answer}, not_held={1}) - self.assertEqual((started, synced), ([], []), answer) - - def test_a_failed_sync_call_is_not_reported_as_started(self): - n1 = self._node("n1", "LVS_1", 1) - from simplyblock_core.controllers import lvol_controller - rpc = MagicMock() - rpc.jc_get_jm_status.return_value = {"jm_n1": True} - rpc.bdev_jm_get_status.return_value = {"res": -1} - rpc.jc_explicit_synchronization.side_effect = RPCException("refused") - with patch.object(device_controller, "DBController") as db_cls, \ - patch.object(StorageNode, "rpc_client", return_value=rpc), \ - patch.object(lvol_controller, "is_node_leader", return_value=True): - db_cls.return_value.get_storage_nodes_by_cluster_id.return_value = [n1] - self.assertEqual(device_controller.start_jm_resync(n1), []) - - def test_in_sync_when_every_leader_reports_every_jm_ready(self): - n1 = self._node("n1", "LVS_1", 1, jm_ids=["jm-n2"], sec="n2") - n2 = self._node("n2", "LVS_2", 2, jm_ids=["jm-n1"], sec="n1") - pending, asked = self._pending( - [n1, n2], {"LVS_1": "n1", "LVS_2": "n2"}, - {("n1", 1): {"jm_n1": True, "remote_jm_n2n1": True}, - ("n2", 2): {"jm_n2": True, "remote_jm_n1n1": True}}) - self.assertEqual(pending, []) - # Its own journal, and the one it is a remote copy of. - self.assertEqual(sorted(asked), [("n1", 1), ("n2", 2)]) - - def test_a_journal_it_is_no_copy_of_is_not_asked_about(self): - n1 = self._node("n1", "LVS_1", 1) - n3 = self._node("n3", "LVS_3", 3, jm_ids=["jm-n2"]) - pending, asked = self._pending([n1, n3], {"LVS_1": "n1", "LVS_3": "n3"}, - {("n1", 1): {"jm_n1": True}}) - self.assertEqual((pending, asked), ([], [("n1", 1)])) - - def test_replication_running_is_pending(self): - n1 = self._node("n1", "LVS_1", 1) - pending, _ = self._pending([n1], {"LVS_1": "n1"}, - {("n1", 1): {"jm_n1": False, "remote_jm_n2n1": True}}) - self.assertEqual(len(pending), 1) - self.assertIn("LVS_1", pending[0]) - self.assertIn("jm_n1", pending[0]) - - def test_the_leader_is_asked_not_the_owner(self): - n1 = self._node("n1", "LVS_1", 1, sec="n2") - n2 = self._node("n2", "", 0) - pending, asked = self._pending([n1, n2], {"LVS_1": "n2"}, {("n2", 1): {"jm_n1": True}}) - self.assertEqual((pending, asked), ([], [("n2", 1)])) - - def test_no_leader_is_pending(self): - n1 = self._node("n1", "LVS_1", 1) - pending, asked = self._pending([n1], {}, {}) - self.assertEqual(asked, []) - self.assertIn("no leader", pending[0]) - - def test_a_leader_that_cannot_be_asked_is_pending(self): - n1 = self._node("n1", "LVS_1", 1) - pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): RPCException("down")}) - self.assertIn("down", pending[0]) - - def test_an_empty_answer_is_pending(self): - n1 = self._node("n1", "LVS_1", 1) - pending, _ = self._pending([n1], {"LVS_1": "n1"}, {("n1", 1): {}}) - self.assertEqual(len(pending), 1) - - -# -- the task --------------------------------------------------------------- - -@pytest.fixture -def runner(monkeypatch): - import simplyblock_core.services.tasks_runner_restart as module - - # checkpoint / set_result commit onto the stored row, not onto the frozen - # view the handler carries on with: the rows the tests hold are the store. - _ROWS.clear() - - def atomic_update(obj, mutate): - row = _ROWS[obj.uuid] - mutate(row) - return row - - monkeypatch.setattr(trb.db, "atomic_update", atomic_update) - monkeypatch.setattr(module.time, "sleep", lambda s: None) - - node = StorageNode() - node.uuid = "n1" - node.cluster_id = "c1" - node.status = StorageNode.STATUS_ONLINE - peer = StorageNode() - peer.uuid = "n2" - peer.status = StorageNode.STATUS_ONLINE - cluster = MagicMock() - cluster.status = Cluster.STATUS_ACTIVE - - db = MagicMock() - db.get_storage_node_by_id.return_value = node - db.get_storage_nodes_by_cluster_id.return_value = [node, peer] - db.get_cluster_by_id.return_value = cluster - monkeypatch.setattr(module, "db", db) - - dc = MagicMock() - dc.JMReshapeNotReady = device_controller.JMReshapeNotReady - dc.JMReshapeError = device_controller.JMReshapeError - dc.jm_raid_reshape_needed.return_value = True - dc.jm_resync_pending.return_value = [] - dc.start_jm_resync.return_value = [] - dc.reshape_jm_raid.return_value = ["a", "b"] - monkeypatch.setattr(module, "device_controller", dc) - - tc = MagicMock() - tc.get_jm_raid_reshape_blocking_tasks.return_value = [] - tc.get_active_jm_raid_reshape_tasks.return_value = [] - monkeypatch.setattr(module, "tasks_controller", tc) - - module.node, module.peer, module.cluster = node, peer, cluster - module.dc, module.tc = dc, tc - yield module - for name in ("node", "peer", "cluster", "dc", "tc"): - delattr(module, name) - - -_ROWS: dict = {} - - -def _task(uuid="t1", node_id="n1", **params): - task = JobSchedule() - task.uuid = uuid - task.cluster_id = "c1" - task.node_id = node_id - task.function_name = JobSchedule.FN_JM_RAID_RESHAPE - task.function_params = params - _ROWS[uuid] = task - return task - - -def test_the_restart_runner_serves_the_task(runner): - assert JobSchedule.FN_JM_RAID_RESHAPE in runner.SPEC.function_names - task = _task() - runner.dc.jm_raid_reshape_needed.return_value = False - runner.SPEC.handler(task) - assert "already matches" in task.function_result - - -def test_nothing_to_do_when_the_raid_matches(runner): - runner.dc.jm_raid_reshape_needed.return_value = False - task = _task() - runner.task_runner_jm_reshape(task) - runner.dc.reshape_jm_raid.assert_not_called() - assert "phase" not in task.function_params - - -@pytest.mark.parametrize("block, reason", [ - (lambda r: setattr(r.cluster, "status", Cluster.STATUS_DEGRADED), "cluster is"), - (lambda r: setattr(r.peer, "status", StorageNode.STATUS_OFFLINE), "node n2 is"), - (lambda r: setattr(r.tc.get_jm_raid_reshape_blocking_tasks, "return_value", - [MagicMock(function_name="new_device_migration", uuid="m1")]), "is open"), - (lambda r: setattr(r.dc.jm_resync_pending, "return_value", ["LVS_1: ['jm_n2']"]), - "journal not in sync"), -]) -def test_it_waits_and_touches_nothing_while_the_cluster_is_not_quiet(runner, block, reason): - block(runner) - task = _task() - with pytest.raises(TaskDefer) as exc: - runner.task_runner_jm_reshape(task) - assert reason in str(exc.value) - runner.dc.reshape_jm_raid.assert_not_called() - assert "phase" not in task.function_params - - -def test_one_node_at_a_time(runner): - other = _task("t2", "n2", phase="resync") - queued = _task("t3", "n3") - runner.tc.get_active_jm_raid_reshape_tasks.return_value = [queued, other] - task = _task() - with pytest.raises(TaskDefer) as exc: - runner.task_runner_jm_reshape(task) - assert "node n2 is being rebuilt" in str(exc.value) - runner.dc.reshape_jm_raid.assert_not_called() - - -def test_a_task_that_only_waits_does_not_hold_up_another(runner): - queued = _task("t3", "n3") - runner.tc.get_active_jm_raid_reshape_tasks.return_value = [queued] - task = _task() - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - runner.dc.reshape_jm_raid.assert_called_once_with("n1") - - -def test_a_removed_node_between_the_others_does_not_block(runner): - runner.peer.status = StorageNode.STATUS_REMOVED - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(_task()) - runner.dc.reshape_jm_raid.assert_called_once() - - -def test_the_phase_is_recorded_before_the_stack_is_taken_down(runner): - task = _task() - seen = {} - runner.dc.reshape_jm_raid.side_effect = lambda node_id: ( - seen.update(phase=task.function_params.get("phase")), ["a", "b"])[1] - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - assert seen["phase"] == "rebuild" - assert task.function_params["phase"] == "resync" - assert task.function_params["members"] == ["a", "b"] - - -def test_resync_is_polled_until_the_journals_stay_in_sync(runner): - task = _task() - runner.dc.jm_resync_pending.side_effect = [[], ["LVS_1: ['jm_n1']"]] # precondition, then poll - with pytest.raises(TaskProgress) as exc: - runner.task_runner_jm_reshape(task) - assert "resync running" in str(exc.value) - - runner.dc.jm_resync_pending.side_effect = None - runner.dc.jm_resync_pending.return_value = [] - for polls in range(1, runner.JM_RESHAPE_READY_POLLS): - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - assert task.function_params["ready_polls"] == polls - runner.task_runner_jm_reshape(task) - assert "journals in sync" in task.function_result - # Built once; every later cycle only polled. - runner.dc.reshape_jm_raid.assert_called_once() - - -def test_the_precondition_does_not_ask_whether_the_jm_holds_its_journals(runner): - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(_task()) - assert runner.dc.jm_resync_pending.call_args_list[0].kwargs == {"require_held": False} - assert runner.dc.jm_resync_pending.call_args_list[1].kwargs == {} - - -def test_a_journal_the_rebuilt_jm_lacks_is_synchronised_on_its_leader(runner): - """The lab case: nothing replicates and the journal is not on the JM.""" - task = _task(phase="resync", members=["a", "b"], ready_polls=0) - runner.dc.jm_resync_pending.return_value = ["LVS_1: not on the JM of node n1"] - runner.dc.start_jm_resync.return_value = ["LVS_1"] - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - runner.dc.start_jm_resync.assert_called_once() - assert task.function_params["sync_calls"] == 1 - - # Replication runs now: nothing more is started, and nothing is counted. - runner.dc.jm_resync_pending.return_value = ["LVS_1: ['jm_n1']"] - runner.dc.start_jm_resync.return_value = [] - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - assert task.function_params["sync_calls"] == 1 - - runner.dc.jm_resync_pending.return_value = [] - for _ in range(runner.JM_RESHAPE_READY_POLLS - 1): - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - runner.task_runner_jm_reshape(task) - assert "journals in sync" in task.function_result - runner.dc.reshape_jm_raid.assert_not_called() - - -def test_a_journal_that_never_arrives_costs_retries_not_an_endless_wait(runner): - task = _task(phase="resync", members=["a", "b"], sync_calls=runner.JM_RESHAPE_MAX_SYNC_CALLS) - runner.dc.jm_resync_pending.return_value = ["LVS_1: not on the JM of node n1"] - runner.dc.start_jm_resync.return_value = ["LVS_1"] - with pytest.raises(TaskRetry) as exc: - runner.task_runner_jm_reshape(task) - assert "still not on the rebuilt JM" in str(exc.value) - - -def test_a_poll_that_finds_replication_again_starts_the_count_over(runner): - task = _task(phase="resync", members=["a", "b"], ready_polls=2) - runner.dc.jm_resync_pending.return_value = ["LVS_1: ['jm_n1']"] - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - assert task.function_params["ready_polls"] == 0 - runner.dc.reshape_jm_raid.assert_not_called() - - -@pytest.mark.parametrize("error", [ - device_controller.JMReshapeNotReady("member gone"), - device_controller.JMReshapeError("build failed"), - RPCException("boom"), -]) -def test_a_failed_rebuild_is_retried_without_asking_the_preconditions_again(runner, error): - task = _task() - runner.dc.reshape_jm_raid.side_effect = error - with pytest.raises(TaskRetry): - runner.task_runner_jm_reshape(task) - assert task.function_params["phase"] == "rebuild" - - # The stack is down now: the next attempt builds whatever the cluster - # looks like, and even when the record already matches the devices. - runner.cluster.status = Cluster.STATUS_DEGRADED - runner.dc.jm_raid_reshape_needed.return_value = False - runner.dc.reshape_jm_raid.side_effect = None - with pytest.raises(TaskProgress): - runner.task_runner_jm_reshape(task) - assert runner.dc.reshape_jm_raid.call_count == 2 - assert task.function_params["phase"] == "resync" - - -def test_node_states(runner): - runner.node.status = StorageNode.STATUS_OFFLINE - with pytest.raises(TaskDefer): - runner.task_runner_jm_reshape(_task()) - runner.node.status = StorageNode.STATUS_REMOVED - with pytest.raises(TaskAbort): - runner.task_runner_jm_reshape(_task()) - runner.db.get_storage_node_by_id.side_effect = KeyError("n1") - with pytest.raises(TaskAbort): - runner.task_runner_jm_reshape(_task()) - runner.dc.reshape_jm_raid.assert_not_called() - - -def test_giving_up_does_not_touch_a_device_or_the_node(runner): - task = _task() - task.max_retry = 3 - task.retry = 3 - runner._abandon_task(task) - runner.dc.device_set_unavailable.assert_not_called() - runner.dc.device_set_retries_exhausted.assert_not_called() + self.assertIn("no JM raid", self._reason(snode)) From 84c6ae27c5ee9ec92ae8f99b93b44707678756d2 Mon Sep 17 00:00:00 2001 From: wmousa Date: Mon, 23 Nov 2026 21:16:25 +0100 Subject: [PATCH 4/5] fix(jm): synchronise every journal once after the JM raid is rebuilt The task synchronised a journal to the rebuilt JM only when the JM reported that it did not hold it. On the lab that report was wrong more often than right: after a rebuild the leader's own JM answered bdev_jm_get_status with the journal as held while nothing had been replicated to it, and a restart of the node then found that journal not on its disks and had it replicated from the peers. The journals that were replicated (SPDK logs the start and the end of the replication) did read back after an immediate restart. Neither status RPC proves a rebuilt JM was brought up to date, so every journal the JM is a copy of is now synchronised explicitly on its LVS leader once after the rebuild, and again while the JM reports it missing. A journal whose replication is already running is synchronised when that is over, not on top of it. Co-Authored-By: Claude Fable 5.2 --- .../controllers/device_controller.py | 42 ++++--- simplyblock_core/models/job_schedule.py | 5 +- .../services/tasks_runner_restart.py | 26 +++-- tests/integration/test_jm_raid_reshape.py | 106 ++++++++++++------ 4 files changed, 116 insertions(+), 63 deletions(-) diff --git a/simplyblock_core/controllers/device_controller.py b/simplyblock_core/controllers/device_controller.py index a70d3ddc2a..4f3c205d9a 100644 --- a/simplyblock_core/controllers/device_controller.py +++ b/simplyblock_core/controllers/device_controller.py @@ -1646,10 +1646,9 @@ def jm_resync_pending(snode: StorageNode, require_held: bool = True) -> list[str In sync means the LVS leader reports every JM of the journal ready and no replication running, and, unless ``require_held`` is off, that the JM of - ``snode`` holds the journal. The second is asked of the JM itself because - the first does not tell: after a JM was rebuilt empty the leader reported - it ready while it did not hold the journal of the node's own LVS at all - (lab, 2026-11-23). A journal whose state cannot be established counts as + ``snode`` reports the journal as held. Both are necessary and neither is + proof that a rebuilt JM was brought up to date: see start_jm_resync, which + is what makes it so. A journal whose state cannot be established counts as pending: an unknown answer is not "in sync".""" pending = [] for journal in _jm_journals(snode): @@ -1662,29 +1661,38 @@ def jm_resync_pending(snode: StorageNode, require_held: bool = True) -> list[str return pending -def start_jm_resync(snode: StorageNode) -> list[str]: - """Start the synchronisation of every journal the JM of ``snode`` should - hold and does not, and return the LVS names it was started for. +def start_jm_resync(snode: StorageNode, synced=()) -> list[str]: + """Start the synchronisation of the journals the rebuilt JM of ``snode`` + is a copy of, on their LVS leaders, and return the LVS names it was + started for. - The journal coordinator brings a JM it reaches over the network up to - date by itself when the JM reconnects. It does not do so for the leader's - own local JM: rebuilt empty under it, that JM stayed without the journal - until jc_explicit_synchronization was called on the leader, which then - replicated it within seconds (lab, 2026-11-23). + Every journal is synchronised explicitly once after a rebuild (``synced`` + names the ones already done), and again whenever the JM reports that it + does not hold it. The journal coordinator brings a JM it reaches over the + network up to date by itself when the JM reconnects; it does not do so + for the leader's own local JM, and neither status RPC tells: after a + rebuild the leader reported that JM ready (jc_get_jm_status) and the JM + reported the journal as held (bdev_jm_get_status) while nothing had been + replicated to it, and a restart of the node then found the journal not on + its disks (lab, 2026-11-23). jc_explicit_synchronization on the leader + replicates it within seconds, and that copy reads back after a restart. Only ever on the confirmed leader of the LVS: explicit synchronisation makes the calling node's journal coordinator the journal writer, and on a follower that takes the leadership away from the real leader (storage_node_ops.resync_solo_lvs_on_leaders). A journal with replication - already running, or whose state is unknown, is left alone.""" + already running, or whose state is unknown, is left for a later call.""" + synced = set(synced) started = [] for journal in _jm_journals(snode): - if journal["error"] or journal["busy"] or journal["held"]: + if journal["error"] or journal["busy"]: + continue + if journal["held"] and journal["lvs"] in synced: continue leader = journal["leader"] - logger.info("Journal of %s (jm_vuid %s) is not on the JM of node %s: starting its " - "synchronisation on the LVS leader %s", - journal["lvs"], journal["jm_vuid"], snode.get_id(), leader.get_id()) + logger.info("Synchronising the journal of %s (jm_vuid %s) to the JM of node %s on the " + "LVS leader %s (held by the JM: %s)", journal["lvs"], journal["jm_vuid"], + snode.get_id(), leader.get_id(), journal["held"]) try: leader.rpc_client(timeout=10, retry=0).jc_explicit_synchronization(journal["jm_vuid"]) except RPCException as e: diff --git a/simplyblock_core/models/job_schedule.py b/simplyblock_core/models/job_schedule.py index fcc98b46f7..c05777f393 100644 --- a/simplyblock_core/models/job_schedule.py +++ b/simplyblock_core/models/job_schedule.py @@ -117,8 +117,9 @@ class JobSchedule(BaseModel): # ``phase`` once the rebuild has started: "rebuild" while the JM stack is # down or being built, "resync" while the empty JM is brought up to date, # then with ``ready_polls`` (consecutive polls that found every journal in - # sync), ``sync_calls`` (synchronisations started for a journal the new JM - # did not hold) and ``members`` (the new member list). One open task per node + # sync), ``sync_calls`` (cycles that started a journal synchronisation), + # ``synced`` (the LVS whose journal was synchronised to the new JM at least + # once) and ``members`` (the new member list). One open task per node # (tasks_controller.add_jm_raid_reshape_task). FN_JM_RAID_RESHAPE = "jm_raid_reshape" diff --git a/simplyblock_core/services/tasks_runner_restart.py b/simplyblock_core/services/tasks_runner_restart.py index 3671f2be0c..55dcb53ff7 100644 --- a/simplyblock_core/services/tasks_runner_restart.py +++ b/simplyblock_core/services/tasks_runner_restart.py @@ -338,18 +338,24 @@ def task_runner_jm_reshape(task): time.sleep(5) node = db.get_storage_node_by_id(task.node_id) - pending = device_controller.jm_resync_pending(node) - if pending: - # A journal the JM does not hold and nobody replicates is started on - # its LVS leader; the journal coordinator does not do that by itself - # for the leader's own JM. - started = device_controller.start_jm_resync(node) - sync_calls = int(task.function_params.get("sync_calls", 0)) + (1 if started else 0) - if started or task.function_params.get("ready_polls"): - checkpoint(task, ready_polls=0, sync_calls=sync_calls) - if started and sync_calls > JM_RESHAPE_MAX_SYNC_CALLS: + # Every journal the new JM is a copy of is synchronised on its LVS leader + # once, and again while the JM does not hold it: the journal coordinator + # does not bring the leader's own JM up to date by itself, and no status + # says so (device_controller.start_jm_resync). + synced = list(task.function_params.get("synced", [])) + started = device_controller.start_jm_resync(node, synced) + if started: + sync_calls = int(task.function_params.get("sync_calls", 0)) + 1 + checkpoint(task, ready_polls=0, sync_calls=sync_calls, + synced=sorted(set(synced) | set(started))) + if sync_calls > JM_RESHAPE_MAX_SYNC_CALLS: raise TaskRetry(f"journal of {started} still not on the rebuilt JM after " f"{sync_calls - 1} synchronisations") + raise TaskProgress(f"journal synchronisation started for {started}") + pending = device_controller.jm_resync_pending(node) + if pending: + if task.function_params.get("ready_polls"): + checkpoint(task, ready_polls=0) raise TaskProgress(f"journal resync running: {'; '.join(pending)}") polls = int(task.function_params.get("ready_polls", 0)) + 1 if polls < JM_RESHAPE_READY_POLLS: diff --git a/tests/integration/test_jm_raid_reshape.py b/tests/integration/test_jm_raid_reshape.py index c6f5842b7e..a852e7c56d 100644 --- a/tests/integration/test_jm_raid_reshape.py +++ b/tests/integration/test_jm_raid_reshape.py @@ -33,6 +33,8 @@ CLUSTER = "7d2c1a4e-0000-4000-8000-000000000001" NODES = [f"7d2c1a4e-0000-4000-8000-00000000010{i}" for i in (1, 2, 3)] +# Every node leads its own LVS, whose journal group is its index + 1. +ALL_SYNCED = sorted((node_id, index + 1) for index, node_id in enumerate(NODES)) ONLINE = NVMeDevice.STATUS_ONLINE MIGRATED = NVMeDevice.STATUS_FAILED_AND_MIGRATED @@ -142,6 +144,15 @@ def queue(self, node_index=0) -> str: def drive(self, task_id) -> JobSchedule: return drive(tasks_runner_restart.SPEC, self.task(task_id)) + def run_to_done(self, task_id, cycles=12) -> JobSchedule: + """Drive the task until it is done; fails when it is not after ``cycles``.""" + for _ in range(cycles): + task = self.drive(task_id) + if task.status == JobSchedule.STATUS_DONE: + return task + raise AssertionError(f"task not done after {cycles} cycles: {task.status} " + f"{task.function_params} {task.function_result}") + def _seed_node(db, index, devices=4, legacy=False): """A node whose drives are each cut into a journal partition (p1) and a @@ -267,9 +278,7 @@ def _mut(node): def test_a_finished_task_does_not_stand_in_for_the_next_change(env): env.set_device(0, 1, MIGRATED) first = env.queue() - for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): - env.drive(first) - assert env.task(first).status == JobSchedule.STATUS_DONE + env.run_to_done(first) env.set_device(0, 2, NVMeDevice.STATUS_FAILED) device_controller.device_set_failed_and_migrated(_device_id(1, 2)) @@ -302,12 +311,17 @@ def test_the_raid_is_rebuilt_over_the_remaining_devices_and_the_task_ends_in_syn assert task.status == JobSchedule.STATUS_RUNNING assert task.function_params["phase"] == "resync" assert task.function_params["members"] == remaining + # Every journal the new JM is a copy of was synchronised on its leader, + # although every status said it was there already. + assert sorted(env.synced) == ALL_SYNCED + assert task.function_params["synced"] == ["LVS_1", "LVS_2", "LVS_3"] for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS - 1): - task = env.drive(task_id) + assert env.drive(task_id).status == JobSchedule.STATUS_RUNNING + task = env.drive(task_id) assert task.status == JobSchedule.STATUS_DONE assert "journals in sync" in task.function_result - assert env.synced == [] + assert sorted(env.synced) == ALL_SYNCED # each once assert len(_raids_built(env)) == 2 # built once @@ -324,8 +338,7 @@ def test_shrinking_to_two_devices_is_a_plain_mirror_and_to_one_no_raid(env): env.set_device(0, 0, MIGRATED) env.set_device(0, 1, MIGRATED) task_id = env.queue() - for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): - env.drive(task_id) + env.run_to_done(task_id) node = env.node() assert node.jm_device.jm_nvme_bdev_list == ["nvme_2n1p1", "nvme_3n1p1"] assert node.jm_device.jm_leg_bdevs == ["nvme_2n1p1", "nvme_3n1p1"] @@ -334,8 +347,7 @@ def test_shrinking_to_two_devices_is_a_plain_mirror_and_to_one_no_raid(env): env.created.clear() env.set_device(0, 2, MIGRATED) task_id = env.queue() - for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): - task = env.drive(task_id) + task = env.run_to_done(task_id) node = env.node() assert task.status == JobSchedule.STATUS_DONE assert node.jm_device.jm_nvme_bdev_list == ["nvme_3n1p1"] @@ -389,34 +401,49 @@ def _mut(node): # -- the resync -------------------------------------------------------------- -def test_a_journal_the_new_jm_does_not_hold_is_synchronised_on_its_leader(env): - """Lab, 2026-11-23: the leader reported every JM of its journal ready - while its own rebuilt JM did not hold that journal.""" +def test_every_journal_is_synchronised_even_when_the_jm_says_it_holds_it(env): + """Lab, 2026-11-23: after a rebuild the leader reported its own JM ready + and the JM reported the journal as held, nothing had been replicated to + it, and a restart of the node found the journal not on its disks.""" env.set_device(0, 1, MIGRATED) - env.journals_missing[NODES[0]] = {1} - task_id = env.queue() - task = env.drive(task_id) + task = env.run_to_done(env.queue()) - assert env.synced == [(NODES[0], 1)] - assert task.status == JobSchedule.STATUS_RUNNING + assert sorted(env.synced) == ALL_SYNCED assert task.function_params["sync_calls"] == 1 + + +def test_a_journal_the_jm_does_not_hold_is_synchronised_again(env): + """Lab, 2026-11-23, first run: the leader reported every JM of its journal + ready while its own rebuilt JM did not hold that journal.""" + env.set_device(0, 1, MIGRATED) + task_id = env.queue() + env.sync_works = False + env.journals_missing[NODES[0]] = {1} + + task = env.drive(task_id) # every journal once + assert sorted(env.synced) == ALL_SYNCED + task = env.drive(task_id) # the missing one again + assert env.synced.count((NODES[0], 1)) == 2 + assert len(env.synced) == 4 + assert task.status == JobSchedule.STATUS_RUNNING + assert task.function_params["sync_calls"] == 2 assert task.function_params["ready_polls"] == 0 - for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS): - task = env.drive(task_id) - assert task.status == JobSchedule.STATUS_DONE - assert env.synced == [(NODES[0], 1)] # once was enough + env.sync_works = True + task = env.run_to_done(task_id) + assert env.synced.count((NODES[0], 1)) == 3 + assert len(env.synced) == 5 # the others were not repeated def test_the_sync_goes_to_the_node_that_leads_the_lvs(env): env.set_device(0, 1, MIGRATED) - env.journals_missing[NODES[0]] = {1} env.leaders["LVS_1"] = NODES[1] # failed over to its secondary env.drive(env.queue()) - assert env.synced == [(NODES[1], 1)] + assert (NODES[1], 1) in env.synced + assert (NODES[0], 1) not in env.synced def test_no_sync_without_a_confirmed_leader(env): @@ -424,28 +451,41 @@ def test_no_sync_without_a_confirmed_leader(env): env.set_device(0, 1, MIGRATED) task_id = env.queue() env.drive(task_id) + assert sorted(env.synced) == ALL_SYNCED env.journals_missing[NODES[0]] = {1} del env.leaders["LVS_1"] task = env.drive(task_id) - assert env.synced == [] + assert sorted(env.synced) == ALL_SYNCED # nothing more was started assert task.status == JobSchedule.STATUS_RUNNING assert "no leader found" in task.function_result -def test_replication_that_runs_is_waited_for_not_started_again(env): +def test_a_journal_being_replicated_is_synchronised_once_that_is_over(env): + """A JM reached over the network is brought up to date by the journal + coordinator when it reconnects; a second writer is not started on top.""" env.set_device(0, 1, MIGRATED) task_id = env.queue() - env.drive(task_id) - env.journals_missing[NODES[0]] = {1} - env.replicating.add(1) + original = device_controller.reshape_jm_raid - task = env.drive(task_id) + def _reshape_then_replicate(node_id): + members = original(node_id) + env.replicating.add(2) # starts as the new JM connects + return members + + with patch.object(device_controller, "reshape_jm_raid", side_effect=_reshape_then_replicate): + task = env.drive(task_id) - assert env.synced == [] + assert sorted(env.synced) == [(NODES[0], 1), (NODES[2], 3)] + task = env.drive(task_id) + assert sorted(env.synced) == [(NODES[0], 1), (NODES[2], 3)] assert task.status == JobSchedule.STATUS_RUNNING - assert task.function_params["ready_polls"] == 0 + assert "LVS_2" in task.function_result + + env.replicating.clear() + task = env.run_to_done(task_id) + assert sorted(env.synced) == ALL_SYNCED def test_a_journal_that_never_arrives_costs_retries(env): @@ -573,9 +613,7 @@ def test_one_node_at_a_time(env): assert env.node(1).jm_device.jm_nvme_bdev_list == _members(4) assert _raids_built(env, 1) == [] - for _ in range(tasks_runner_restart.JM_RESHAPE_READY_POLLS - 1): - env.drive(first) - assert env.task(first).status == JobSchedule.STATUS_DONE + env.run_to_done(first) assert env.drive(second).function_params["phase"] == "resync" assert env.node(1).jm_device.jm_nvme_bdev_list == ["nvme_0n1p1", "nvme_2n1p1", "nvme_3n1p1"] From a95e12dc3aba3985cd0f936ba7d1f4047869e200 Mon Sep 17 00:00:00 2001 From: wmousa Date: Mon, 23 Nov 2026 21:53:55 +0100 Subject: [PATCH 5/5] fix(device): a failed_and_migrated device is never brought back failed_and_migrated says a device's data was moved elsewhere and its place in the cluster given up; a replacement enters as a new record (new_device_from_failed). Nothing enforced that. device_set_state treated only "failed" as a state with restricted exits, and the node monitor's re-admit of a recovered node's devices skipped the online, removed and failed ones and set every other device ONLINE. On the lab a node was marked unreachable for a moment while a peer restarted, and was cleared back to ONLINE. The monitor set the three devices of that node that had been migrated out ONLINE again. SPDK could open none of them, each was walked through unavailable to removed, and with the peer still restarting the cluster was suspended and client IO failed. device_set_state now refuses every transition out of failed_and_migrated, whatever the cause, and the re-admit names the states it leaves alone, failed_and_migrated and new (a device that is not part of the cluster yet) among them. Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 40a572ff60e7a56167385284cedffd5df48c445d) --- .../controllers/device_controller.py | 15 ++ .../services/storage_node_monitor.py | 23 ++- .../test_failed_and_migrated_is_final.py | 141 ++++++++++++++++++ 3 files changed, 174 insertions(+), 5 deletions(-) create mode 100644 tests/integration/test_failed_and_migrated_is_final.py diff --git a/simplyblock_core/controllers/device_controller.py b/simplyblock_core/controllers/device_controller.py index 4f3c205d9a..362e1fb909 100644 --- a/simplyblock_core/controllers/device_controller.py +++ b/simplyblock_core/controllers/device_controller.py @@ -245,6 +245,21 @@ def device_set_state(device_id, state, cause=CAUSE_OTHER, connect_peers=True): f"node bring-up owns device re-online") return False + # Failed-and-migrated is final: the device's data was moved elsewhere and + # its place in the cluster was given up. Nothing brings that record back -- + # a replacement enters the cluster as a new device (new_device_from_failed + # adds a new record and leaves this one as it is). Every other writer is + # refused here, whatever its cause: the node monitor re-admitting a + # recovered node's devices set three migrated-out devices ONLINE, SPDK + # could open none of them, and with one more node restarting the cluster + # was suspended (lab, 2026-11-23). + if (device.status == NVMeDevice.STATUS_FAILED_AND_MIGRATED + and state != NVMeDevice.STATUS_FAILED_AND_MIGRATED): + logger.error( + f"Device {device_id} is failed_and_migrated; rejecting transition " + f"to {state} (cause={cause})") + return False + # Failed is a terminal state. The only allowed exits are: # STATUS_FAILED → STATUS_FAILED_AND_MIGRATED (failure data migration) # STATUS_FAILED → STATUS_ONLINE (explicit device restart) diff --git a/simplyblock_core/services/storage_node_monitor.py b/simplyblock_core/services/storage_node_monitor.py index 0d73802d63..0b2d631125 100644 --- a/simplyblock_core/services/storage_node_monitor.py +++ b/simplyblock_core/services/storage_node_monitor.py @@ -3043,6 +3043,21 @@ def check_node(snode): readmit_devices_after_node_online(snode.get_id()) +#: Device states a node's return to ONLINE does not touch. ONLINE needs +#: nothing. REMOVED, FAILED and FAILED_AND_MIGRATED were decided by an operator +#: or by the failure handling, not by the outage the node came back from, and +#: have paths of their own back into the cluster (device restart, failure +#: migration, new-device-from-failed). NEW is not part of the cluster yet: it +#: has no place in the cluster map to be re-admitted to. +_NOT_READMITTED = ( + NVMeDevice.STATUS_ONLINE, + NVMeDevice.STATUS_REMOVED, + NVMeDevice.STATUS_FAILED, + NVMeDevice.STATUS_FAILED_AND_MIGRATED, + NVMeDevice.STATUS_NEW, +) + + def readmit_devices_after_node_online(node_id): """Re-admit a recovered node's devices right after it was set ONLINE. @@ -3057,16 +3072,14 @@ def readmit_devices_after_node_online(node_id): device left unavailable here counts toward affected_nodes forever, and a later unrelated dual outage then suspends the whole cluster (incidents 2026-07-02, x3). So: now that the node IS online (guard passes), re-admit - its devices. REMOVED is terminal; FAILED transitions are owned by the - explicit device-restart / failure-migration paths. + its devices -- those the outage made unavailable, not the ones in a state + somebody decided on (_NOT_READMITTED). """ try: fresh = db.get_storage_node_by_id(node_id) readmitted = 0 for dev in fresh.nvme_devices: - if dev.status in (NVMeDevice.STATUS_ONLINE, - NVMeDevice.STATUS_REMOVED, - NVMeDevice.STATUS_FAILED): + if dev.status in _NOT_READMITTED: continue logger.info( f"Re-admitting device {dev.get_id()} (was {dev.status}) " diff --git a/tests/integration/test_failed_and_migrated_is_final.py b/tests/integration/test_failed_and_migrated_is_final.py new file mode 100644 index 0000000000..4b7c06e305 --- /dev/null +++ b/tests/integration/test_failed_and_migrated_is_final.py @@ -0,0 +1,141 @@ +"""A device that was failed and migrated out stays out. + +``failed_and_migrated`` says the device's data was moved elsewhere and its +place in the cluster given up. A replacement enters as a new device record +(``new_device_from_failed``); the old record is never brought back. + +Lab, 2026-11-23: a node was marked unreachable for a moment while a peer +restarted and then cleared back to ONLINE. The node monitor re-admits a +recovered node's devices, skipped the online, removed and failed ones, and set +the three devices of that node that had been migrated out ONLINE again. SPDK +could open none of them, and with the peer still restarting the cluster was +suspended and client IO failed. + +Run against the real FoundationDB: the monitor and the device controller read +the node back from the database, so the state is what they stored. Replaced +are the SPDK RPC client and the fan-out of device events to the distribs. +""" +from unittest.mock import MagicMock, patch + +import pytest + +from simplyblock_core import distr_controller +from simplyblock_core.controllers import device_controller +from simplyblock_core.db_controller import DBController +from simplyblock_core.models.cluster import Cluster +from simplyblock_core.models.nvme_device import NVMeDevice +from simplyblock_core.models.storage_node import StorageNode +from simplyblock_core.services import storage_node_monitor + +CLUSTER = "3b1f0c5a-0000-4000-8000-000000000001" +NODE = "3b1f0c5a-0000-4000-8000-000000000101" +STATUSES = ( + NVMeDevice.STATUS_ONLINE, + NVMeDevice.STATUS_UNAVAILABLE, + NVMeDevice.STATUS_FAILED_AND_MIGRATED, + NVMeDevice.STATUS_FAILED, + NVMeDevice.STATUS_REMOVED, + NVMeDevice.STATUS_NEW, +) + + +def _device_id(status): + return f"3b1f0c5a-0000-4000-8000-0000000002{STATUSES.index(status):02d}" + + +@pytest.fixture() +def db(): + controller = DBController() + if controller.kv_store is None: + pytest.skip("FoundationDB is not available") + cluster = Cluster() + cluster.uuid = CLUSTER + cluster.status = Cluster.STATUS_ACTIVE + cluster.write_to_db(controller.kv_store) + node = StorageNode() + node.uuid = NODE + node.cluster_id = CLUSTER + node.status = StorageNode.STATUS_ONLINE + node.hostname = "worker-1" + node.nvme_devices = [] + for index, status in enumerate(STATUSES): + dev = NVMeDevice() + dev.uuid = _device_id(status) + dev.cluster_id = CLUSTER + dev.node_id = NODE + dev.status = status + dev.cluster_device_order = -1 if status == NVMeDevice.STATUS_NEW else index + node.nvme_devices.append(dev) + node.write_to_db(controller.kv_store) + with patch.object(StorageNode, "rpc_client", return_value=MagicMock()), \ + patch.object(distr_controller, "send_dev_status_event"), \ + patch.object(distr_controller, "disconnect_device"), \ + patch.object(device_controller, "connect_peers_to_node_devices"), \ + patch.object(device_controller.tasks_controller, "add_device_mig_task_for_node"): + yield controller + + +def _statuses(db): + return {dev.get_id(): dev.status for dev in db.get_storage_node_by_id(NODE).nvme_devices} + + +def test_a_node_coming_back_online_readmits_only_what_the_outage_took(db): + storage_node_monitor.readmit_devices_after_node_online(NODE) + + after = _statuses(db) + assert after[_device_id(NVMeDevice.STATUS_UNAVAILABLE)] == NVMeDevice.STATUS_ONLINE + for status in STATUSES: + if status != NVMeDevice.STATUS_UNAVAILABLE: + assert after[_device_id(status)] == status, status + + +@pytest.mark.parametrize("state", [ + NVMeDevice.STATUS_ONLINE, + NVMeDevice.STATUS_UNAVAILABLE, + NVMeDevice.STATUS_REMOVED, + NVMeDevice.STATUS_READONLY, + NVMeDevice.STATUS_FAILED, +]) +@pytest.mark.parametrize("cause", [ + device_controller.CAUSE_OTHER, + device_controller.CAUSE_DEVICE_RESTART, + device_controller.CAUSE_NODE_RECOVERY, + device_controller.CAUSE_LOCAL_FAILURE, + device_controller.CAUSE_FAILURE_MIGRATION, +]) +def test_no_writer_takes_a_device_out_of_failed_and_migrated(db, state, cause): + device_id = _device_id(NVMeDevice.STATUS_FAILED_AND_MIGRATED) + + assert device_controller.device_set_state(device_id, state, cause=cause) is False + + assert _statuses(db)[device_id] == NVMeDevice.STATUS_FAILED_AND_MIGRATED + + +def test_setting_it_to_the_state_it_is_in_is_not_refused(db): + device_id = _device_id(NVMeDevice.STATUS_FAILED_AND_MIGRATED) + + assert device_controller.device_set_state( + device_id, NVMeDevice.STATUS_FAILED_AND_MIGRATED, + cause=device_controller.CAUSE_FAILURE_MIGRATION) + + assert _statuses(db)[device_id] == NVMeDevice.STATUS_FAILED_AND_MIGRATED + + +def test_a_failed_device_still_reaches_failed_and_migrated(db): + device_id = _device_id(NVMeDevice.STATUS_FAILED) + + assert device_controller.device_set_failed_and_migrated(device_id) + + assert _statuses(db)[device_id] == NVMeDevice.STATUS_FAILED_AND_MIGRATED + + +def test_a_removal_event_for_it_leaves_it_as_it_is(db): + """SPDK reports the removal of a drive that is long migrated out (it is + pulled, or its stale stack is torn down): the forced remove that follows + used to walk the record through unavailable to removed.""" + device_id = _device_id(NVMeDevice.STATUS_FAILED_AND_MIGRATED) + + device_controller.device_remove(device_id, force=True, + cause=device_controller.CAUSE_LOCAL_FAILURE) + + assert _statuses(db)[device_id] == NVMeDevice.STATUS_FAILED_AND_MIGRATED