diff --git a/seaweed-block/.gitignore b/seaweed-block/.gitignore index e294f80e58..9aea5270bd 100644 --- a/seaweed-block/.gitignore +++ b/seaweed-block/.gitignore @@ -22,3 +22,8 @@ coverage.out /blockmaster.exe /blockvolume /blockvolume.exe + +# Local test runner outputs and ad-hoc Windows builds. Formal QA evidence lives +# under internal/docs/qa-assignments or external shared artifacts, not here. +/results/ +/sw-testops.exe diff --git a/seaweed-block/README.md b/seaweed-block/README.md index e91a5a763f..78c125e9c1 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -1,35 +1,65 @@ -# seaweed-block +# Seaweed Block -`seaweed-block` is an experimental block storage service for Kubernetes. +

+ Seaweed Block alpha architecture: Kubernetes PVC to CSI, blockmaster, blockvolume, iSCSI, and WAL-backed recovery +

-It provides a CSI-based block volume path backed by SeaweedFS components. The -current implementation focuses on a small, understandable storage stack for -testing block volume creation, attach, mount, write/read, and cleanup flows. +Seaweed Block is an experimental Kubernetes block storage service built around +normal Kubernetes PVCs, a CSI driver, and SeaweedFS block components. + +The current alpha is focused on one user-visible loop: + +```text +install on Kubernetes +-> create a PVC-backed block volume +-> mount it in an app pod +-> write/read data +-> inspect status and support evidence +-> clean up +``` + +Start with the Kubernetes tutorial: + +- [First volume on Kubernetes](docs/quickstart-kubernetes.md) +- [Release notes](docs/releases/README.md) ## Status -Alpha. +Alpha / early beta shape. Not production-ready. -The current code passes a single-node Kubernetes smoke test: +What has been validated in the current alpha: -```text -dynamic PVC create -→ CSI attach -→ iSCSI mount -→ pod write/read checksum -→ cleanup -``` +- Day-1 install-to-first-volume path: activate stack, create PVC, writer pod + verifies data, reader pod verifies persisted data, status report generated, + cleanup clean. +- dynamic PVC provisioning through CSI. +- product-owned generated `blockvolume` lifecycle. +- multiple PVCs / volumes visible in inventory. +- durable local volume restart/reattach coverage. +- RF=3 `sync-quorum` recovery through CSI/pod recreate. +- RF=3 Kubernetes node-loss recovery through CSI/pod recreate on a surviving + node. +- RF=3 iSCSI ALUA + Linux dm-multipath transparent mounted failover on the + proven alpha path. +- read-only operations evidence through `sw-block ops inventory`, + `sw-block ops cluster --master-api ... -o json`, support bundles, and + product-owned event timelines. -This is not production-ready. +These are narrow alpha claims tied to documented gates and support artifacts. +Do not treat them as broad production HA or compatibility claims. Known missing pieces: -- multi-node failover -- failover while a volume is mounted -- durable production packaging (the alpha manifest still uses `emptyDir`) -- broader recovery testing -- RF=2/RF=3 replication on the Kubernetes path -- a real operator (a manifest launcher does the work today) +- production-grade installer/operator lifecycle or Helm chart, +- hosted dashboard/UI (only a local static read-only report exists), +- backup, snapshot, and restore workflow, +- returned-replica rebuild, reintegration, and failback, +- transparent node-loss failover without pod recreate, +- NVMe ANA parity for the transparent failover path, +- broad distro/kernel/initiator compatibility matrix, +- upgrade/rollback safety, +- performance, RTO, or SLO claims, +- security/RBAC/audit hardening for mutating admin actions. ## Why this exists @@ -67,16 +97,94 @@ Recovery is split into base transfer and live WAL feeding so normal writes keep flowing while a peer catches up. Only one peer is the source of truth for a recovery stream at any given time. -## Quick start +## Quick Start -Start here: +Use [First volume on Kubernetes](docs/quickstart-kubernetes.md). It runs +preflight, builds/imports local images, installs the stack, creates one PVC, +writes and reads data through an app pod replacement, and shows cleanup and +support-bundle evidence to inspect if anything fails. -- [First volume on Kubernetes](docs/quickstart-kubernetes.md) +Minimal lab path: -That guide is the single supported alpha entry point for a new user. It uses a -single-node Kubernetes/k3s path, runs preflight, builds/imports local images, -creates one PVC, writes and reads data through an app pod replacement, and -shows the cleanup and support-bundle evidence to inspect if anything fails. +```bash +bash scripts/activate-k8s-alpha.sh "$PWD" +bash scripts/run-basic-app-example.sh "$PWD" +cat "$(ls -td /tmp/sw-block-basic-app-* | head -1)/first-volume-summary.txt" +``` + +Expected summary fields: + +```text +first_volume_status=ok +writer_verified=true +reader_verified=true +inventory_status=ok +status_report=status/report/index.html +cleanup_status=ok +``` + +The activation script writes `/tmp/sw-block-activation-*/activation-summary.txt` +with the blockmaster, CSI controller, CSI node, StorageClass, protocol, ACK +profile, and next inspection commands. + +For QA/PM user-path testing against published images, use the same activation +entry point with image mode set to `published`: + +```bash +SW_BLOCK_ACTIVATION_IMAGE_MODE=published \ + bash scripts/activate-k8s-alpha.sh "$PWD" +``` + +That path uses `ghcr.io/seaweedfs/seaweed-block:alpha` and +`ghcr.io/seaweedfs/seaweed-block-csi:alpha` by default. Prefer immutable +release tags or `sha-` tags once a release candidate is cut. + +## Operations + +```bash +kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333 +sw-block ops cluster --master-api 127.0.0.1:9333 -o json \ + > /tmp/sw-block-cluster-evidence.json +sw-block ops report --master-api 127.0.0.1:9333 --out /tmp/sw-block-report +``` + +If `sw-block` is not in `PATH`, run the same commands from this repository as +`go run ./cmd/sw-block ops ...`. + +`sw-block ops report` writes a local static read-only status page plus +machine-readable artifacts. It is not a hosted dashboard and it has no mutating +admin actions. + +For replica-level support evidence: + +```bash +sw-block ops inventory \ + --namespace default \ + --master 127.0.0.1:9333 \ + --out /tmp/sw-block-inventory +``` + +## What Users Can Do Today + +- Install the alpha stack on a supported Kubernetes/k3s lab. +- Create PVC-backed block volumes through Kubernetes. +- Run app pods that mount the PVC and verify file data. +- Inspect cluster, volume, replica, primary, frontend, and event evidence. +- Generate a local read-only HTML status report from live master evidence or a + saved support bundle. +- Collect inventory and product evidence bundles for support. +- Exercise documented recovery gates in TestOps/lab environments. + +## What Users Should Not Expect Yet + +- A production-grade installer/operator or Helm chart. +- A hosted dashboard. +- Backup, snapshot, or restore workflows. +- Mutating admin actions such as promote, repair, rebuild, failback, or cleanup. +- Upgrade/rollback safety. +- Performance, RTO, or SLO guarantees. +- Broad distro/kernel/initiator compatibility. +- Transparent Kubernetes node-loss failover without pod recreate. ## Repository layout @@ -106,22 +214,12 @@ bash scripts/run-k8s-alpha.sh "$PWD" More detail: +- [docs/releases/README.md](docs/releases/README.md) - [docs/architecture.md](docs/architecture.md) - [docs/developer-architecture.md](docs/developer-architecture.md) - [docs/runtime-state-machines.md](docs/runtime-state-machines.md) - [docs/roadmap.md](docs/roadmap.md) -## Current limitations - -This project is still early. - -Do not use it for production workloads. The current alpha is for local -development, design validation, and Kubernetes smoke testing. - -Before production use, the project needs stronger recovery behavior, multi-node -support, durable packaging, observability, failure testing, and operational -documentation. - ## License Apache-2.0 diff --git a/seaweed-block/cmd/blockcsi/g15b_manifest_test.go b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go index 95b1eef789..2b1dba6f5a 100644 --- a/seaweed-block/cmd/blockcsi/g15b_manifest_test.go +++ b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go @@ -214,7 +214,7 @@ func TestG15b_ImageBuildInputs_ContainExpectedBinariesAndNodeTools(t *testing.T) } csi := g15bReadDeployFile(t, "Dockerfile.blockcsi") - for _, want := range []string{"./cmd/blockcsi", "open-iscsi", "nvme-cli", "e2fsprogs", "kmod", "util-linux", "/usr/local/bin/blockcsi"} { + for _, want := range []string{"./cmd/blockcsi", "open-iscsi", "multipath-tools", "sg3-utils", "nvme-cli", "e2fsprogs", "kmod", "util-linux", "/usr/local/bin/blockcsi"} { if !strings.Contains(csi, want) { t.Fatalf("Dockerfile.blockcsi missing %q", want) } @@ -228,7 +228,7 @@ func TestG15b_ImageBuildInputs_ContainExpectedBinariesAndNodeTools(t *testing.T) } for _, want := range []string{ "SW_BLOCK_IMPORT_K3S", - "sudo -n k3s ctr images import -", + "sudo -n k3s ctr -n k8s.io images import -", "docker image inspect", "alpha-images.env", "blockmaster.version.txt", diff --git a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go index 9df65b3d52..d68cff3583 100644 --- a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go +++ b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go @@ -124,13 +124,276 @@ func TestG15d_K8sRunner_NVMeProtocolWrapper(t *testing.T) { func TestAlphaCSINode_LoadsBothFrontendKernelModules(t *testing.T) { body := g15dReadFile(t, "deploy", "k8s", "alpha", "csi-node.yaml") - for _, want := range []string{"modprobe iscsi_tcp", "modprobe nvme_tcp"} { + for _, want := range []string{"modprobe iscsi_tcp", "modprobe nvme_tcp", "modprobe dm_multipath", "modprobe scsi_dh_alua", "/run/udev"} { if !strings.Contains(body, want) { t.Fatalf("alpha csi-node missing %q", want) } } } +func TestAlphaCSIDriver_AppliesFilesystemGroupOwnership(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "csi-driver.yaml") + for _, want := range []string{ + "kind: CSIDriver", + "name: block.csi.seaweedfs.com", + "fsGroupPolicy: File", + } { + if !strings.Contains(body, want) { + t.Fatalf("alpha CSIDriver missing %q", want) + } + } +} + +func TestAlphaScripts_Stage2MultipathIsOptIn(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_STAGE2_MULTIPATH", + "--stage2-multipath", + "stage2_multipath=$STAGE2_MULTIPATH", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsCanRenderExplicitMultiNodeSpecs(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_ALPHA_NODE_SPECS", + "render_cluster_spec_node_specs", + "server_id|kubernetes_node|host_or_ip|pool_id", + "host_or_ip must be non-loopback", + "data_addr: ${host}:${data_port}", + "ctrl_addr: ${host}:${ctrl_port}", + "kubernetes.io/hostname: ${node_name}", + "expected_slots_per_volume=$EXPECTED_SLOTS_PER_VOLUME", + "node_specs=${NODE_SPECS:-}", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsExternalISCSIIsOptInWithCHAPSecret(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI", + "SW_BLOCK_ISCSI_CHAP_SECRET_NAME", + "--launcher-external-iscsi", + "--launcher-iscsi-chap-secret-name=", + "launcher_external_iscsi=$LAUNCHER_EXTERNAL_ISCSI", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsCanRejectLoopbackPublishTargets(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS", + "--reject-loopback-publish-targets", + "reject_loopback_publish_targets=$REJECT_LOOPBACK_PUBLISH_TARGETS", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsCanExposeExternalStatusForPromotionProbes(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS", + "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS requires SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1", + "--launcher-external-status", + "launcher_external_status=", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AppDemoDeliversCHAPSecretToCSI(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{ + "SW_BLOCK_ISCSI_CHAP_USERNAME", + "SW_BLOCK_ISCSI_CHAP_SECRET", + "inject_node_stage_secret_into_storageclass", + "csi.storage.k8s.io/node-stage-secret-name", + "csi.storage.k8s.io/node-stage-secret-namespace", + "apply iSCSI CHAP Secret", + "--from-literal=chapUsername", + "--from-literal=chapSecret", + "delete secret \"$CHAP_SECRET_NAME\"", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-alpha-app-demo.sh missing %q", want) + } + } +} + +func TestNodeLoss_InstallAppliesCHAPSecretForExternalISCSI(t *testing.T) { + body := g15dReadFile(t, "scripts", "install-k8s-alpha.sh") + for _, want := range []string{ + "SW_BLOCK_ISCSI_CHAP_USERNAME", + "SW_BLOCK_ISCSI_CHAP_SECRET", + "SW_BLOCK_APP_NAMESPACE", + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI requires SW_BLOCK_ISCSI_CHAP_USERNAME", + "apply iSCSI CHAP Secret", + "--from-literal=chapUsername", + "--from-literal=chapSecret", + "chap_enabled=$([[ -n \"$CHAP_SECRET\" ]] && echo 1 || echo 0)", + } { + if !strings.Contains(body, want) { + t.Fatalf("install-k8s-alpha.sh missing %q", want) + } + } +} + +func TestStage2ISCSIALUAMultipathScenarioPinsOptInAndClaimBoundary(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "stage2-iscsi-alua-multipath-baseline-chain.yaml") + for _, want := range []string{ + "name: stage2-iscsi-alua-multipath-baseline-chain", + "multipath-prereq.txt", + "module_dm_multipath=loaded", + "module_scsi_dh_alua=loaded", + "SW_BLOCK_STAGE2_MULTIPATH=1", + "SW_BLOCK_ALPHA_LOGICAL_SERVERS=3", + "SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3", + "SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum", + "demo-app-pvc-writer-hold.yaml", + "SW_BLOCK_DEMO_STOP_AFTER=writer-verified", + "--stage2-multipath", + "--replica-id=r1", + "--replica-id=r2", + "--replica-id=r3", + "unique-iscsi-iqns.txt", + "multipath=true", + "staged transport=iscsi .* portals=.*127.0.0.1:3260", + "staged transport=iscsi .* portals=.*127.0.0.1:3261", + "staged transport=iscsi .* portals=.*127.0.0.1:3262", + "controlled-stop-writer-verified.txt", + "phase=writer-verified", + "iscsi-sessions.writer-mounted.txt", + "multipath.writer-mounted.txt", + "sg-rtpg.writer-mounted.txt", + "asymmetric access state", + "transparent_failover_claimed=false", + "next_required_gate=mounted_writer_primary_failure_without_pod_recreate", + "bounded-waits.txt", + "multipath -f", + } { + if !strings.Contains(body, want) { + t.Fatalf("stage2 multipath scenario missing %q", want) + } + } +} + +func TestStage2ISCSIALUAMultipathFailoverScenarioUsesMountedWriter(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "stage2-iscsi-alua-multipath-failover-chain.yaml") + for _, want := range []string{ + "name: stage2-iscsi-alua-multipath-failover-chain", + "SW_BLOCK_STAGE2_MULTIPATH=1", + "SW_BLOCK_ALPHA_LOGICAL_SERVERS=3", + "SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum", + "SW_BLOCK_DEMO_STOP_AFTER=writer-verified", + "SW_BLOCK_DEMO_KEEP_ON_STOP=1", + "pod_recreate_used=false", + "before_primary_replica=", + "target_deployment=", + "scale-primary-zero.log", + "post_failure_primary_count=1", + "timeout 180s kubectl -n default exec sw-block-demo-writer", + "mounted_workload_checksum_passed", + "data_check_after_failover=mounted_workload_checksum_passed", + "multipath-before.txt", + "multipath-after.txt", + "sg-inq.txt", + "sg-vpd83.txt", + "sg-rtpg.before.txt", + "sg-rtpg.after.txt", + "old_primary_stale_io_success_count=0", + "bounded_waits=pass", + } { + if !strings.Contains(body, want) { + t.Fatalf("stage2 multipath failover scenario missing %q", want) + } + } + if strings.Contains(body, "apply-reader") || strings.Contains(body, "demo-app-reader") || strings.Contains(body, "data_check_after_failover=reader") { + t.Fatalf("stage2 mounted failover scenario must not use reader pod recreate") + } +} + +func TestAlphaAppDemo_WriterVerifiedStopCapturesMountedHostPathEvidence(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{ + `"$DEMO_STOP_AFTER" != "writer-verified"`, + `"$DEMO_STOP_AFTER" == "writer-verified"`, + `capture_stage2_host_path_evidence "writer-mounted"`, + "iscsi-sessions.${label}.txt", + "multipath.${label}.txt", + "sg-rtpg.${label}.txt", + "controlled-stop-writer-verified.txt", + "ops-inventory-writer-verified", + "phase=writer-verified-failed", + "writer_verified=false", + "resources-kept: true", + "trap - EXIT", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-alpha-app-demo.sh missing writer-verified host-path evidence hook %q", want) + } + } +} + +func TestFailureBundleScenarioAssertsProcessHygieneAfterCleanup(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "light-use-first-volume-failure-bundle-chain.yaml") + finalIdx := strings.Index(body, "- name: final_asserts") + cleanupIdx := strings.Index(body, "- name: collect_and_cleanup") + if finalIdx < 0 || cleanupIdx < 0 || finalIdx > cleanupIdx { + t.Fatalf("failure-bundle scenario must have final_asserts before collect_and_cleanup") + } + finalSection := body[finalIdx:cleanupIdx] + if strings.Contains(finalSection, "assert_no_processes") { + t.Fatalf("final_asserts must not assert process hygiene before cleanup; controlled stop leaves live pods:\n%s", finalSection) + } + cleanupSection := body[cleanupIdx:] + for _, want := range []string{ + "scripts/uninstall-k8s-alpha.sh", + "action: assert_no_processes", + "blockmaster,blockvolume,blockcsi,iscsi-target", + } { + if !strings.Contains(cleanupSection, want) { + t.Fatalf("cleanup section missing %q", want) + } + } +} + func TestAlphaScripts_OwnerRefModeInjectsBothLauncherAndCSILookupFlags(t *testing.T) { for _, script := range []string{"run-g15d-k8s-dynamic.sh", "run-alpha-app-demo.sh"} { t.Run(script, func(t *testing.T) { @@ -174,11 +437,171 @@ func TestInstallAlpha_DefaultsToPVCOwnerReferenceCleanup(t *testing.T) { } } +func TestPhase20ActivationScriptPinsInstallToOperateLoop(t *testing.T) { + body := g15dReadFile(t, "scripts", "activate-k8s-alpha.sh") + for _, want := range []string{ + "scripts/preflight-k8s-alpha.sh", + "scripts/build-alpha-images.sh", + "scripts/install-k8s-alpha.sh", + "SW_BLOCK_ACTIVATION_IMAGE_MODE", + "SW_BLOCK_ACTIVATION_IMAGE_MODE must be local or published", + "--local-k3s", + "--ghcr", + "ready_schedulable_node_count", + "first_ready_node_with_internal_ip", + "DAY1_NETWORK_MODE=\"external-iscsi\"", + "SW_BLOCK_ALPHA_NODE_SPECS=\"$ALPHA_NODE_SPECS\"", + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=\"$LAUNCHER_EXTERNAL_ISCSI\"", + "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=\"$LAUNCHER_EXTERNAL_STATUS\"", + "SW_BLOCK_ISCSI_CHAP_USERNAME=\"$CHAP_USERNAME\"", + "csi.storage.k8s.io/node-stage-secret-name", + "day1_network_mode=$DAY1_NETWORK_MODE", + "phase_skip=build reason=published-images", + "published-images.env", + "image_digest=", + "csi_image_digest=", + "collect_failure_diagnostics", + "diagnostics/failure-context.txt", + "sw-blockmaster.previous.log", + "activation_blocker=image_flag_mismatch", + "remediation=republish the image from this commit or use matching sha- image tags", + "ghcr.io/seaweedfs/seaweed-block:alpha", + "ghcr.io/seaweedfs/seaweed-block-csi:alpha", + "deploy/k8s/alpha/storageclass.yaml", + "storageclass.rendered.yaml", + "activation-summary.txt", + "activation_status=$status", + `write_summary "ok"`, + "failed_phase=", + "image_mode=$IMAGE_MODE", + "master_ready_replicas=", + "csi_controller_ready_replicas=", + "csi_node_ready=", + "storageclass_provider=", + "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml", + "next_status=kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333", + "non_claims=alpha_only,no_backup_restore,no_upgrade_safety,no_mutating_dashboard_actions,no_broad_performance_slo", + } { + if !strings.Contains(body, want) { + t.Fatalf("activation script missing %q", want) + } + } +} + +func TestPhase20ActivationScenarioPinsDay1InstallGate(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "activation-day1-install-chain.yaml") + for _, want := range []string{ + "name: activation-day1-install-chain", + "scripts/activate-k8s-alpha.sh", + "activation-summary.txt", + "^activation_status=ok$", + "^master_ready_replicas=1$", + "^csi_controller_ready_replicas=1$", + "^csi_node_ready=[1-9][0-9]*/[1-9][0-9]*$", + "^storageclass_provider=block.csi.seaweedfs.com$", + "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml", + "readiness.txt", + "scripts/uninstall-k8s-alpha.sh", + "delete-storageclass.log", + `pattern: "sw-block-dynamic"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("activation scenario missing %q", want) + } + } +} + +func TestPhase20FirstVolumeScriptPinsUserLoop(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-basic-app-example.sh") + for _, want := range []string{ + "examples/kubernetes/basic-app", + "sw-block-example-pvc", + "sw-block-example-writer", + "sw-block-example-reader", + "first-volume-summary.txt", + "writer_verified=$writer_ok", + "reader_verified=$reader_ok", + "status_evidence=status/cluster-evidence.json,status/inventory", + "cluster_evidence=status/cluster-evidence.json", + "inventory_bundle=status/inventory", + "cleanup_status=$CLEANUP_STATUS", + "failed_phase=$FAILED_PHASE", + "SW_BLOCK_BASIC_APP_CLEANUP", + "inject_node_stage_secret_into_storageclass", + "csi.storage.k8s.io/node-stage-secret-name", + "node_stage_secret=", + "SW_BLOCK_CLI", + "command -v sw-block", + "sw_block_cmd ops cluster --master-api", + "sw_block_cmd ops inventory --namespace", + "PASS: basic app PVC writer/reader loop complete", + } { + if !strings.Contains(body, want) { + t.Fatalf("basic app wrapper missing %q", want) + } + } +} + +func TestPhase20FirstVolumeScenarioPinsPublishedUserGate(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "activation-day1-first-volume-chain.yaml") + for _, want := range []string{ + "name: activation-day1-first-volume-chain", + "SW_BLOCK_ACTIVATION_IMAGE_MODE", + "published", + "ghcr.io/seaweedfs/seaweed-block:sha-", + "scripts/activate-k8s-alpha.sh", + "scripts/run-basic-app-example.sh", + "env.SW_BLOCK_BASIC_APP_CLEANUP", + "first-volume-summary.txt", + "^first_volume_status=ok$", + "^pvc=sw-block-example-pvc$", + "^writer_verified=true$", + "^reader_verified=true$", + "^cleanup_status=ok$", + "status/cluster-evidence.json", + "status/inventory/volume-inventory-summary.txt", + "kubectl -n default delete pvc sw-block-example-pvc", + "SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES", + } { + if !strings.Contains(body, want) { + t.Fatalf("first-volume scenario missing %q", want) + } + } +} + +func TestPhase20AlphaStorageClassManifestIsDynamicPVCDefault(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "storageclass.yaml") + for _, want := range []string{ + "kind: StorageClass", + "name: sw-block-dynamic", + "provisioner: block.csi.seaweedfs.com", + `replicationFactor: "1"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("alpha storageclass missing %q", want) + } + } + uninstall := g15dReadFile(t, "scripts", "uninstall-k8s-alpha.sh") + for _, want := range []string{ + `STORAGECLASS_NAME="${SW_BLOCK_STORAGECLASS_NAME:-sw-block-dynamic}"`, + "delete alpha StorageClass", + `kubectl delete storageclass "$STORAGECLASS_NAME"`, + `storageclasses.storage.k8s.io \"$STORAGECLASS_NAME\" not found`, + } { + if !strings.Contains(uninstall, want) { + t.Fatalf("uninstall missing storageclass cleanup contract %q", want) + } + } +} + func TestAlphaBlockStack_EnablesProductOwnedLauncherApply(t *testing.T) { body := g15dReadFile(t, "deploy", "k8s", "alpha", "block-stack.yaml") for _, want := range []string{ "serviceAccountName: sw-block-master", + "hostNetwork: true", + "dnsPolicy: ClusterFirstWithHostNet", "--launcher-kubernetes-apply", + "--launcher-status", } { if !strings.Contains(body, want) { t.Fatalf("alpha block stack missing %q", want) @@ -197,6 +620,46 @@ func TestAlphaBlockStack_EnablesProductOwnedLauncherApply(t *testing.T) { } } +func TestAlphaRBAC_MasterLauncherCanReconcilePVCOwnerNamespaces(t *testing.T) { + rbac := g15dReadFile(t, "deploy", "k8s", "alpha", "rbac.yaml") + for _, want := range []string{ + "kind: ClusterRole", + "kind: ClusterRoleBinding", + "name: sw-block-master-launcher", + `resources: ["deployments"]`, + `verbs: ["get", "list", "watch", "create", "delete", "update", "patch"]`, + "kind: ServiceAccount", + "name: sw-block-master", + "kind: ClusterRole", + "name: sw-block-master-launcher", + } { + if !strings.Contains(rbac, want) { + t.Fatalf("alpha rbac missing %q", want) + } + } + if strings.Contains(rbac, "kind: Role\nmetadata:\n name: sw-block-master-launcher") { + t.Fatalf("master launcher RBAC must not be namespace-local; PVC-owned blockvolumes are reconciled in app namespaces") + } +} + +func TestAlphaUninstall_DoesNotParseUnrenderedBlockStackTemplate(t *testing.T) { + body := g15dReadFile(t, "scripts", "uninstall-k8s-alpha.sh") + if strings.Contains(body, `kubectl delete -f "$ROOT/deploy/k8s/alpha/block-stack.yaml"`) { + t.Fatalf("uninstall must not parse unrendered block-stack.yaml template") + } + for _, want := range []string{ + "delete deploy/sw-blockmaster", + "delete svc/blockmaster", + "delete configmap/sw-block-cluster-spec", + "delete secret \"$CHAP_SECRET_NAME\"", + "delete-block-stack.log", + } { + if !strings.Contains(body, want) { + t.Fatalf("uninstall script missing %q", want) + } + } +} + func TestApplyAlphaBlockvolumes_WaitsForGeneratedManifestInsteadOfKubeSystem(t *testing.T) { body := g15dReadFile(t, "scripts", "apply-k8s-alpha-blockvolumes.sh") if !strings.Contains(body, `kubectl wait -f "$ARTIFACT_DIR/generated-blockvolume.yaml" --for=condition=available`) { diff --git a/seaweed-block/cmd/blockcsi/main.go b/seaweed-block/cmd/blockcsi/main.go index eb2a1d57b5..31c3a9030e 100644 --- a/seaweed-block/cmd/blockcsi/main.go +++ b/seaweed-block/cmd/blockcsi/main.go @@ -25,13 +25,15 @@ import ( ) type flags struct { - endpoint string - masterAddr string - nodeID string - iqnPrefix string - pvcUIDLookup bool - version bool - printReadyLine bool + endpoint string + masterAddr string + nodeID string + iqnPrefix string + pvcUIDLookup bool + stage2Multipath bool + rejectLoopbackPublishTargets bool + version bool + printReadyLine bool } func parseFlags(args []string) (flags, error) { @@ -42,6 +44,8 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.nodeID, "node-id", "", "CSI node ID; defaults to hostname") fs.StringVar(&f.iqnPrefix, "iqn-prefix", "iqn.2026-05.io.seaweedfs", "fallback IQN prefix for unstage after plugin restart") fs.BoolVar(&f.pvcUIDLookup, "kubernetes-pvc-uid-lookup", false, "opt-in: resolve PVC UID through the in-cluster Kubernetes API before CreateVolume is sent to blockmaster") + fs.BoolVar(&f.stage2Multipath, "stage2-multipath", false, "opt-in: consume multiple iSCSI frontend targets as one host multipath device") + fs.BoolVar(&f.rejectLoopbackPublishTargets, "reject-loopback-publish-targets", false, "opt-in: reject loopback publish targets for node-loss recovery gates") fs.BoolVar(&f.version, "version", false, "print build provenance and exit") fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON ready line after listener bind") fs.SetOutput(os.Stderr) @@ -54,6 +58,9 @@ func parseFlags(args []string) (flags, error) { if f.endpoint == "" { return flags{}, fmt.Errorf("--endpoint is required") } + if f.masterAddr == "" && (f.stage2Multipath || f.rejectLoopbackPublishTargets || f.pvcUIDLookup) { + return flags{}, fmt.Errorf("--stage2-multipath, --reject-loopback-publish-targets, and --kubernetes-pvc-uid-lookup require --master") + } if f.nodeID == "" { host, err := os.Hostname() if err != nil || host == "" { @@ -108,6 +115,7 @@ func run(f flags) int { var ( masterConn *grpc.ClientConn lookup blockcsi.PublishTargetLookup + reporter blockcsi.EventReporter provisioner blockcsi.VolumeProvisioner resolver blockcsi.KubernetesMetadataResolver ) @@ -118,7 +126,16 @@ func run(f flags) int { return 1 } defer masterConn.Close() - lookup = blockcsi.NewControlStatusLookup(control.NewEvidenceServiceClient(masterConn)) + evidence := control.NewEvidenceServiceClient(masterConn) + var opts []blockcsi.ControlStatusLookupOption + if f.stage2Multipath { + opts = append(opts, blockcsi.WithMultipathPublishTargets()) + } + if f.rejectLoopbackPublishTargets { + opts = append(opts, blockcsi.WithLoopbackPublishTargetsRejected()) + } + lookup = blockcsi.NewControlStatusLookupWithOptions(evidence, opts...) + reporter = blockcsi.NewControlEventReporter(control.NewObservationServiceClient(masterConn)) provisioner = blockcsi.NewControlLifecycleProvisioner(control.NewLifecycleServiceClient(masterConn)) } if f.pvcUIDLookup && provisioner != nil { @@ -132,7 +149,7 @@ func run(f flags) int { srv := grpc.NewServer() csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer()) csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerAndMetadataResolver(lookup, provisioner, resolver)) - csipb.RegisterNodeServer(srv, blockcsi.NewDefaultNodeServer(f.nodeID, f.iqnPrefix)) + csipb.RegisterNodeServer(srv, blockcsi.NewDefaultNodeServerWithLookupAndEventReporter(f.nodeID, f.iqnPrefix, lookup, reporter)) if f.printReadyLine { _ = json.NewEncoder(os.Stdout).Encode(readyLine{ diff --git a/seaweed-block/cmd/blockcsi/main_test.go b/seaweed-block/cmd/blockcsi/main_test.go index f86cefe93a..b47e7459eb 100644 --- a/seaweed-block/cmd/blockcsi/main_test.go +++ b/seaweed-block/cmd/blockcsi/main_test.go @@ -93,6 +93,32 @@ func TestParseFlags_VersionDoesNotRequireEndpoint(t *testing.T) { } } +func TestParseFlags_Stage2MultipathIsExplicitOptIn(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--stage2-multipath"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.stage2Multipath { + t.Fatal("stage2 multipath flag not set") + } +} + +func TestParseFlags_RejectLoopbackPublishTargetsIsExplicitOptIn(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--reject-loopback-publish-targets"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.rejectLoopbackPublishTargets { + t.Fatal("reject loopback publish targets flag not set") + } +} + +func TestParseFlags_MasterDependentFlagsRequireMaster(t *testing.T) { + if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--stage2-multipath"}); err == nil { + t.Fatal("expected --stage2-multipath without --master to fail") + } +} + func TestG15a_BlockCSIControllerPublishUsesMasterFrontendFact(t *testing.T) { if testing.Short() { t.Skip("L2 subprocess test; -short skip") diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 65f62be49d..efa7043010 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -37,11 +37,14 @@ type flags struct { launcherMasterAddr string launcherDurableRoot string launcherStateHostPath string + launcherReplicationAck string launcherISCSIPortBase int launcherNVMePortBase int launcherPVCOwnerRef bool launcherStatus bool launcherKubernetesApply bool + launcherExternalISCSI bool + launcherExternalStatus bool launcherCHAPSecretName string launcherCHAPUserKey string launcherCHAPSecretKey string @@ -73,11 +76,14 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.launcherMasterAddr, "launcher-master-addr", "", "G15d master address used in rendered blockvolume args; defaults to listener address after bind") fs.StringVar(&f.launcherDurableRoot, "launcher-durable-root", "/var/lib/sw-block", "G15d rendered blockvolume durable root base") fs.StringVar(&f.launcherStateHostPath, "launcher-state-hostpath", "", "optional hostPath base mounted at the blockvolume durable root; empty keeps generated blockvolume state on throwaway emptyDir") + fs.StringVar(&f.launcherReplicationAck, "launcher-replication-ack", "best-effort", "G15d rendered blockvolume replication ACK profile: best-effort, sync-quorum, or sync-all") fs.IntVar(&f.launcherISCSIPortBase, "launcher-iscsi-port-base", 3260, "G15d iSCSI port base for generated blockvolume workloads") fs.IntVar(&f.launcherNVMePortBase, "launcher-nvme-port-base", 4420, "G15d NVMe/TCP port base for generated blockvolume workloads") fs.BoolVar(&f.launcherPVCOwnerRef, "launcher-pvc-owner-ref", false, "render generated blockvolume Deployments in the source PVC namespace with a PVC ownerReference; disabled by default for alpha harness compatibility") fs.BoolVar(&f.launcherStatus, "launcher-status", false, "render loopback-only blockvolume status endpoints in generated workload manifests; intended for TestOps/diagnostics") fs.BoolVar(&f.launcherKubernetesApply, "launcher-kubernetes-apply", false, "apply/delete generated blockvolume Deployments through the in-cluster Kubernetes API; scoped to app=sw-blockvolume and generated volume/replica labels") + fs.BoolVar(&f.launcherExternalISCSI, "launcher-external-iscsi", false, "render generated iSCSI frontends on node addresses instead of loopback; requires --launcher-iscsi-chap-secret-name") + fs.BoolVar(&f.launcherExternalStatus, "launcher-external-status", false, "render blockvolume status endpoints on node addresses instead of loopback; intended for explicit Kubernetes node-loss gates") fs.StringVar(&f.launcherCHAPSecretName, "launcher-iscsi-chap-secret-name", "", "optional Kubernetes Secret name used by generated blockvolume Deployments for target-side iSCSI CHAP") fs.StringVar(&f.launcherCHAPUserKey, "launcher-iscsi-chap-username-key", "chapUsername", "Kubernetes Secret key for generated blockvolume iSCSI CHAP username") fs.StringVar(&f.launcherCHAPSecretKey, "launcher-iscsi-chap-secret-key", "chapSecret", "Kubernetes Secret key for generated blockvolume iSCSI CHAP secret") @@ -93,6 +99,9 @@ func parseFlags(args []string) (flags, error) { if f.authorityStore == "" { return flags{}, fmt.Errorf("--authority-store is required") } + if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" { + return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name") + } return f, nil } @@ -121,12 +130,14 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 2 } - if len(topo.Volumes) == 0 { + if len(topo.Volumes) == 0 && len(clusterImport.Nodes) == 0 { // Without a topology the observation host classifies every // volume UnknownReplicaClaim; controller can never mint. // That is a valid "empty cluster" startup state and not an // error, but operators should know — log a prominent line. fmt.Fprintln(os.Stderr, "blockmaster: WARNING: --topology not supplied or empty; controller will not mint assignments until topology is provided") + } else if len(topo.Volumes) == 0 { + fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents") } cfg := master.Config{ AuthorityStoreDir: f.authorityStore, @@ -297,6 +308,12 @@ func runLifecycleLauncherTick(h *master.Host, f flags) error { if err != nil { return err } + if f.launcherStatus { + h.SetPromotionEvidenceProvider(master.NewWorkloadPlanPromotionEvidenceProvider(result.Plans, master.WorkloadPlanPromotionProbeConfig{ + AckProfile: f.launcherReplicationAck, + ExternalStatus: f.launcherExternalStatus, + })) + } if f.launcherManifestDir == "" && !f.launcherKubernetesApply { return nil } @@ -312,8 +329,11 @@ func runLifecycleLauncherTick(h *master.Host, f flags) error { MasterAddr: masterAddr, DurableRootBase: f.launcherDurableRoot, StateHostPathBase: f.launcherStateHostPath, + ReplicationAck: f.launcherReplicationAck, OwnerReferenceToPVC: f.launcherPVCOwnerRef, EnableStatus: f.launcherStatus, + ExternalISCSI: f.launcherExternalISCSI, + ExternalStatus: f.launcherExternalStatus, ISCSICHAP: launcher.CHAPSecretRef{ Name: f.launcherCHAPSecretName, UsernameKey: f.launcherCHAPUserKey, diff --git a/seaweed-block/cmd/blockmaster/main_test.go b/seaweed-block/cmd/blockmaster/main_test.go index 1718f7133f..abdd8914fd 100644 --- a/seaweed-block/cmd/blockmaster/main_test.go +++ b/seaweed-block/cmd/blockmaster/main_test.go @@ -65,6 +65,41 @@ func TestParseFlags_ClusterSpecOptional(t *testing.T) { } } +func TestParseFlags_LauncherExternalStatusOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + "--launcher-status", + "--launcher-external-status", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.launcherStatus || !f.launcherExternalStatus { + t.Fatalf("launcher status flags = %v/%v want true/true", f.launcherStatus, f.launcherExternalStatus) + } +} + +func TestParseFlags_LauncherExternalISCSIRequiresCHAP(t *testing.T) { + if _, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-external-iscsi", + }); err == nil { + t.Fatal("expected --launcher-external-iscsi without CHAP secret to fail") + } + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-external-iscsi", + "--launcher-iscsi-chap-secret-name", "sw-block-iscsi-chap", + }) + if err != nil { + t.Fatalf("parseFlags with CHAP: %v", err) + } + if !f.launcherExternalISCSI || f.launcherCHAPSecretName != "sw-block-iscsi-chap" { + t.Fatalf("external iscsi flags = %v/%q", f.launcherExternalISCSI, f.launcherCHAPSecretName) + } +} + func TestBlockmasterBareTopologyRegistersVolumeControlServices(t *testing.T) { h, err := master.New(master.Config{ AuthorityStoreDir: t.TempDir(), diff --git a/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go b/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go index fcb686b544..16dfb7df25 100644 --- a/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go +++ b/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go @@ -62,6 +62,85 @@ func TestParseFlags_IscsiPortalAddrStillRejectsExternalBind(t *testing.T) { } } +func TestParseFlags_IscsiExternalBindRequiresExplicitOptIn(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want explicit external bind opt-in") + } + if !strings.Contains(err.Error(), "not loopback") { + t.Fatalf("error = %q, want loopback bind rejection", err) + } +} + +func TestParseFlags_IscsiExternalBindOptInRequiresCHAP(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want CHAP requirement") + } + if !strings.Contains(err.Error(), "requires CHAP") { + t.Fatalf("error = %q, want CHAP requirement", err) + } +} + +func TestParseFlags_IscsiExternalBindOptInWithCHAP(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !got.allowExternalISCSIBind { + t.Fatal("allowExternalISCSIBind=false") + } +} + +func TestParseFlags_IscsiExternalBindOptInRejectsLoopback(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want loopback external bind rejected") + } + if !strings.Contains(err.Error(), "non-loopback") { + t.Fatalf("error = %q, want non-loopback requirement", err) + } +} + +func TestParseFlags_ExternalStatusBindIsExplicitFlag(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--status-addr", "10.0.0.12:23260", + "--allow-external-status-bind", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !got.allowExternalStatusBind { + t.Fatal("allowExternalStatusBind=false") + } +} + func TestParseFlags_IscsiDataOutTimeoutRequiresListen(t *testing.T) { args := append(requiredBlockvolumeArgs(), "--iscsi-dataout-timeout", "5s", diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 5a42aebe44..315dfa2817 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -12,6 +12,7 @@ import ( "os" "os/signal" "strconv" + "strings" "syscall" "time" @@ -55,18 +56,22 @@ type flags struct { // Default off; production binaries do NOT enable. Used by hardware // orchestration scripts for catch-up verification (R/H polling). statusRecovery bool + // External status bind is off by default. Node-loss gates opt in so + // blockmaster can probe surviving replicas across Kubernetes nodes. + allowExternalStatusBind bool // iSCSI frontend flags. iscsiListen is the TCP address the iSCSI - // target binds on; empty disables the frontend. The bind is - // rejected at startup if it is not a loopback address — - // unauthenticated frontend on an external port would be unsafe. - iscsiListen string - iscsiIQN string - iscsiPortalAddr string - iscsiDataOutTTL time.Duration - iscsiLUN uint - iscsiCHAPUser string - iscsiCHAPSecret string + // target binds on; empty disables the frontend. The safe default + // rejects non-loopback binds. Node-loss gates must opt into + // external bind and provide CHAP. + iscsiListen string + iscsiIQN string + iscsiPortalAddr string + iscsiDataOutTTL time.Duration + iscsiLUN uint + iscsiCHAPUser string + iscsiCHAPSecret string + allowExternalISCSIBind bool // NVMe/TCP frontend flags. Symmetric with iSCSI flags: same // loopback-only safe-default rule, same auto-enable of @@ -132,6 +137,7 @@ func parseFlags(args []string) (flags, error) { fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy") fs.StringVar(&f.statusAddr, "status-addr", "", "address for the status HTTP endpoint (e.g. 127.0.0.1:0); empty disables") fs.BoolVar(&f.statusRecovery, "status-recovery", false, "expose /status/recovery?volume= with engine.ReplicaProjection (Mode/R/S/H/RecoveryDecision); off by default; loopback-only; intended for hardware test orchestration") + fs.BoolVar(&f.allowExternalStatusBind, "allow-external-status-bind", false, "allow the unauthenticated status endpoint to bind and serve non-loopback addresses; intended only for explicit Kubernetes node-loss gates") fs.StringVar(&f.iscsiListen, "iscsi-listen", "", "iSCSI target bind address (e.g. 127.0.0.1:0); empty disables. Loopback-only unless paired with an operator-managed proxy") fs.StringVar(&f.iscsiIQN, "iscsi-iqn", "", "iSCSI target IQN (required if --iscsi-listen is set)") fs.StringVar(&f.iscsiPortalAddr, "iscsi-portal-addr", "", "iSCSI TargetAddress advertised in SendTargets responses (e.g. 203.0.113.10:3260,1). Defaults to the bound listen address. Does not change the loopback-only bind policy") @@ -139,6 +145,7 @@ func parseFlags(args []string) (flags, error) { fs.UintVar(&f.iscsiLUN, "iscsi-lun", 0, "iSCSI LUN id (default 0)") fs.StringVar(&f.iscsiCHAPUser, "iscsi-chap-username", "", "iSCSI target-side CHAP username. Requires --iscsi-chap-secret and --iscsi-listen") fs.StringVar(&f.iscsiCHAPSecret, "iscsi-chap-secret", "", "iSCSI target-side CHAP secret. Requires --iscsi-chap-username and --iscsi-listen") + fs.BoolVar(&f.allowExternalISCSIBind, "allow-external-iscsi-bind", false, "allow iSCSI to bind a non-loopback address; requires CHAP and is intended for explicit Kubernetes node-loss gates") fs.StringVar(&f.nvmeListen, "nvme-listen", "", "NVMe/TCP target bind address (e.g. 127.0.0.1:0); empty disables. Loopback-only (no auth)") fs.StringVar(&f.nvmeSubsysNQN, "nvme-subsysnqn", "", "NVMe subsystem NQN (required if --nvme-listen is set)") fs.UintVar(&f.nvmeNS, "nvme-ns", 1, "NVMe namespace id (default 1)") @@ -213,7 +220,7 @@ func parseFlags(args []string) (flags, error) { if f.iscsiIQN == "" { return flags{}, fmt.Errorf("--iscsi-iqn is required when --iscsi-listen is set") } - if err := enforceFrontendLoopbackBind("iscsi", f.iscsiListen); err != nil { + if err := enforceISCSIBindPolicy(f); err != nil { return flags{}, err } // iSCSI needs a Healthy adapter projection to open a @@ -317,6 +324,34 @@ func enforceFrontendLoopbackBind(kind, addr string) error { return nil } +func enforceISCSIBindPolicy(f flags) error { + if !f.allowExternalISCSIBind { + return enforceFrontendLoopbackBind("iscsi", f.iscsiListen) + } + if f.iscsiCHAPUser == "" || f.iscsiCHAPSecret == "" { + return fmt.Errorf("--allow-external-iscsi-bind requires CHAP") + } + host, _, err := net.SplitHostPort(f.iscsiListen) + if err != nil { + return fmt.Errorf("--iscsi-listen %q not host:port: %w", f.iscsiListen, err) + } + if host == "" { + return fmt.Errorf("--iscsi-listen %q has empty host; external iSCSI bind requires an explicit node address", f.iscsiListen) + } + if isLocalhostOrLoopbackHost(host) { + return fmt.Errorf("--iscsi-listen %q is loopback; external iSCSI bind requires a non-loopback node address", f.iscsiListen) + } + return nil +} + +func isLocalhostOrLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + func main() { f, err := parseFlags(os.Args[1:]) if err != nil { @@ -385,6 +420,9 @@ func run(f flags) int { if f.statusRecovery { status.EnableRecoveryEndpoint() } + if f.allowExternalStatusBind { + status.AllowExternalAccess() + } bound, err := status.Start(f.statusAddr) if err != nil { fmt.Fprintln(os.Stderr, "blockvolume: status server:", err) diff --git a/seaweed-block/cmd/blockvolume/ready_latch.go b/seaweed-block/cmd/blockvolume/ready_latch.go index d430bd9273..4c8b37c0c5 100644 --- a/seaweed-block/cmd/blockvolume/ready_latch.go +++ b/seaweed-block/cmd/blockvolume/ready_latch.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "reflect" "time" "github.com/seaweedfs/seaweed-block/core/adapter" @@ -15,6 +16,10 @@ type primaryOpenProvider interface { Open(context.Context, string) (frontend.Backend, error) } +type durableIdentityLatchProvider interface { + LatchVolumeIdentity(string) (bool, error) +} + func startReadyAssignmentLoop(ch <-chan adapter.AssignmentInfo, f flags, prov primaryOpenProvider, stdout, stderr io.Writer) { go func() { for info := range ch { @@ -34,7 +39,23 @@ func handleReadyAssignment(info adapter.AssignmentInfo, f flags, prov primaryOpe EndpointVersion: info.EndpointVersion, }) } - if prov == nil || info.VolumeID != f.volumeID || info.ReplicaID != f.replicaID || info.Epoch == 0 { + if providerIsNil(prov) || info.VolumeID != f.volumeID || info.ReplicaID != f.replicaID || info.Epoch == 0 { + return + } + + if latcher, ok := prov.(durableIdentityLatchProvider); ok { + latched, err := latcher.LatchVolumeIdentity(info.VolumeID) + if err != nil { + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable lineage latch failed volume=%s replica=%s epoch=%d ev=%d: %v\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, err) + } + return + } + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable lineage latched volume=%s replica=%s epoch=%d ev=%d changed=%t\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, latched) + } return } @@ -52,3 +73,16 @@ func handleReadyAssignment(info adapter.AssignmentInfo, f flags, prov primaryOpe info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion) } } + +func providerIsNil(prov primaryOpenProvider) bool { + if prov == nil { + return true + } + v := reflect.ValueOf(prov) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return v.IsNil() + default: + return false + } +} diff --git a/seaweed-block/cmd/blockvolume/ready_latch_test.go b/seaweed-block/cmd/blockvolume/ready_latch_test.go index 0e0c34f5bc..748f915531 100644 --- a/seaweed-block/cmd/blockvolume/ready_latch_test.go +++ b/seaweed-block/cmd/blockvolume/ready_latch_test.go @@ -23,6 +23,20 @@ func (p *recordingPrimaryOpenProvider) Open(_ context.Context, volumeID string) return nil, p.err } +type recordingLatchProvider struct { + recordingPrimaryOpenProvider + latchVolumeID string + latchCalls int + latchChanged bool + latchErr error +} + +func (p *recordingLatchProvider) LatchVolumeIdentity(volumeID string) (bool, error) { + p.latchCalls++ + p.latchVolumeID = volumeID + return p.latchChanged, p.latchErr +} + func TestReadyAssignment_PrimaryEnsuresDurableLineageAndPrintsReadyLine(t *testing.T) { prov := &recordingPrimaryOpenProvider{} var stdout, stderr bytes.Buffer @@ -45,6 +59,27 @@ func TestReadyAssignment_PrimaryEnsuresDurableLineageAndPrintsReadyLine(t *testi } } +func TestReadyAssignment_UsesDurableIdentityLatchWhenAvailable(t *testing.T) { + prov := &recordingLatchProvider{latchChanged: true} + var stderr bytes.Buffer + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, &stderr) + + if prov.latchCalls != 1 || prov.latchVolumeID != "v1" { + t.Fatalf("LatchVolumeIdentity calls=%d volume=%q, want 1/v1", prov.latchCalls, prov.latchVolumeID) + } + if prov.calls != 0 { + t.Fatalf("Open must not be called when durable identity latch is available: %d", prov.calls) + } + if got := stderr.String(); !strings.Contains(got, "durable lineage latched volume=v1 replica=r2 epoch=2 ev=1 changed=true") { + t.Fatalf("latch log mismatch: %s", got) + } +} + func TestReadyAssignment_IgnoresOtherReplica(t *testing.T) { prov := &recordingPrimaryOpenProvider{} @@ -59,6 +94,16 @@ func TestReadyAssignment_IgnoresOtherReplica(t *testing.T) { } } +func TestReadyAssignment_IgnoresTypedNilProvider(t *testing.T) { + var prov *recordingPrimaryOpenProvider + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, nil) +} + func TestReadyAssignment_ReportsDurableEnsureFailure(t *testing.T) { prov := &recordingPrimaryOpenProvider{err: errors.New("boom")} var stderr bytes.Buffer diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 26b2404342..f0a5ea685d 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -6,10 +6,15 @@ import ( "fmt" "io" "os" + "strconv" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/ops" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/internal/buildinfo" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) func main() { @@ -36,7 +41,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -45,6 +50,18 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsStatus(args[2:], stdout, stderr) case "inventory", "list": return runOpsInventory(args[2:], stdout, stderr) + case "cluster": + return runOpsCluster(args[2:], stdout, stderr) + case "volumes": + return runOpsVolumes(args[2:], stdout, stderr) + case "describe": + return runOpsDescribe(args[2:], stdout, stderr) + case "timeline": + return runOpsTimeline(args[2:], stdout, stderr) + case "explain": + return runOpsExplain(args[2:], stdout, stderr) + case "report": + return runOpsReport(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -111,18 +128,22 @@ func runOpsInventory(args []string, stdout, stderr io.Writer) int { fs := flag.NewFlagSet("sw-block ops inventory", flag.ContinueOnError) fs.SetOutput(stderr) var ( - namespace string - masterAddr string - outDir string - productRevision string - runnerRevision string - timeout time.Duration + namespace string + masterAddr string + outDir string + productRevision string + runnerRevision string + claimProfile string + requiredFrontiers requiredFrontierFlags + timeout time.Duration ) fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace to inspect once live discovery is enabled") fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address; when set, collect per-replica ops status bundles for replicas with --status-addr") fs.StringVar(&outDir, "out", "", "directory for volume-inventory.json, volume-inventory-summary.txt, and ops-inventory-bundle.json") fs.StringVar(&productRevision, "product-revision", "", "product revision label to include in the inventory") fs.StringVar(&runnerRevision, "runner-revision", "", "runner revision label to include in the inventory") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile: beta-recovery (default), controlled-best-effort-demo, or stage2-iscsi-alua-multipath") + fs.Var(&requiredFrontiers, "required-frontier", "mounted-writer required frontier as volume_id=lsn; repeat for multiple volumes") fs.DurationVar(&timeout, "timeout", 5*time.Second, "collection timeout") if err := fs.Parse(args); err != nil { return ops.VolumeStatusExitInvalid @@ -134,16 +155,22 @@ func runOpsInventory(args []string, stdout, stderr io.Writer) int { if productRevision == "" { productRevision = buildinfo.Version("sw-block") } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "sw-block ops inventory: --claim-profile=%q invalid; want %q, %q, or %q\n", claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.VolumeStatusExitInvalid + } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ - Namespace: namespace, - MasterAddr: masterAddr, - StatusBundleRoot: outDir, - ProductRevision: productRevision, - RunnerRevision: runnerRevision, - RunCommand: opsInventoryRunCommand, + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + RunnerRevision: runnerRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontiers.values, + RunCommand: opsInventoryRunCommand, }) inventory, code, err := ops.WriteVolumeInventoryArtifacts(ctx, outDir, collector) if err != nil { @@ -156,9 +183,610 @@ func runOpsInventory(args []string, stdout, stderr io.Writer) int { return code } +func runOpsCluster(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationCluster("sw-block ops cluster", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if out == "json" { + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops cluster: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + return ops.VolumeStatusExitOK + } + fmt.Fprint(stdout, ops.RenderClusterEvidenceText(cluster)) + return ops.VolumeStatusExitOK +} + +func runOpsVolumes(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationCluster("sw-block ops volumes", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if out == "json" { + raw, err := ops.MarshalObservationJSON(cluster.Volumes) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops volumes: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + return ops.VolumeStatusExitOK + } + for _, volume := range cluster.Volumes { + fmt.Fprintf(stdout, "volume %s status=%s rf=%d primary=%s node=%s frontend=%s\n", + emptyCLI(volume.VolumeID), + emptyCLI(volume.Status), + volume.ReplicationFactor, + emptyCLI(volume.PrimaryReplica), + emptyCLI(volume.PrimaryNode), + emptyCLI(volume.PublishTarget)) + } + if len(cluster.Volumes) == 0 { + fmt.Fprintln(stdout, "volumes: none") + } + return ops.VolumeStatusExitOK +} + +func runOpsDescribe(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationVolume("sw-block ops describe", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + switch out { + case "json": + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops describe: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + default: + fmt.Fprint(stdout, ops.RenderClusterEvidenceText(cluster)) + } + return ops.VolumeStatusExitOK +} + +func loadObservationCluster(command string, args []string, stderr io.Writer) (ops.ClusterEvidence, string, int) { + fs := flag.NewFlagSet(command, flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + namespace string + masterAddr string + masterAPIAddr string + out string + outDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&out, "o", "text", "output format: text or json") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(args); err != nil { + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "%s: unexpected args %s\n", command, strings.Join(fs.Args(), " ")) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + var ( + cluster ops.ClusterEvidence + err error + ) + if fromBundle != "" { + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: fromBundle}) + } else if masterAPIAddr != "" { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr) + } else { + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "%s: --claim-profile=%q invalid; want %q, %q, or %q\n", command, claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, "", outDir) + } + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + return cluster, out, ops.VolumeStatusExitOK +} + +func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) { + conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return ops.ClusterEvidence{}, err + } + defer conn.Close() + resp, err := control.NewClusterEvidenceServiceClient(conn).GetClusterStatus(ctx, &control.GetClusterStatusRequest{}) + if err != nil { + return ops.ClusterEvidence{}, err + } + return clusterEvidenceFromWire(resp), nil +} + +func clusterEvidenceFromWire(resp *control.ClusterStatusResponse) ops.ClusterEvidence { + if resp == nil { + return ops.ClusterEvidence{} + } + out := ops.ClusterEvidence{ + SchemaVersion: resp.GetSchemaVersion(), + ProductRevision: resp.GetProductRevision(), + Status: resp.GetStatus(), + Conditions: conditionsFromWire(resp.GetConditions()), + NonClaims: append([]string(nil), resp.GetNonClaims()...), + } + if ts := resp.GetCapturedAt(); ts != nil && ts.IsValid() { + out.CapturedAt = ts.AsTime() + } + for _, node := range resp.GetNodes() { + out.Nodes = append(out.Nodes, nodeEvidenceFromWire(node)) + } + for _, volume := range resp.GetVolumes() { + out.Volumes = append(out.Volumes, volumeEvidenceFromWire(volume)) + } + for _, event := range resp.GetEvents() { + out.Events = append(out.Events, clusterEventFromWire(event)) + } + return out +} + +func nodeEvidenceFromWire(node *control.NodeEvidence) ops.NodeEvidence { + if node == nil { + return ops.NodeEvidence{} + } + out := ops.NodeEvidence{ + NodeName: node.GetNodeName(), + KubernetesNode: node.GetKubernetesNode(), + PhysicalHost: node.GetPhysicalHost(), + InternalIP: node.GetInternalIp(), + Schedulable: node.GetSchedulable(), + Ready: node.GetReady(), + ReplicaCount: int(node.GetReplicaCount()), + RequiredImages: append([]string(nil), node.GetRequiredImages()...), + MissingImages: append([]string(nil), node.GetMissingImages()...), + Conditions: conditionsFromWire(node.GetConditions()), + } + if ts := node.GetLastHeartbeatAt(); ts != nil && ts.IsValid() { + out.LastHeartbeatAt = ts.AsTime() + } + return out +} + +func volumeEvidenceFromWire(volume *control.VolumeEvidence) ops.VolumeEvidence { + if volume == nil { + return ops.VolumeEvidence{} + } + out := ops.VolumeEvidence{ + VolumeID: volume.GetVolumeId(), + Namespace: volume.GetNamespace(), + PVCName: volume.GetPvcName(), + PVName: volume.GetPvName(), + ReplicationFactor: int(volume.GetReplicationFactor()), + AckProfile: volume.GetAckProfile(), + ClaimProfile: volume.GetClaimProfile(), + DesiredReplicas: int(volume.GetDesiredReplicas()), + ObservedReplicas: int(volume.GetObservedReplicas()), + Status: volume.GetStatus(), + Reason: volume.GetReason(), + PrimaryReplica: volume.GetPrimaryReplica(), + PrimaryNode: volume.GetPrimaryNode(), + PublishTarget: volume.GetPublishTarget(), + Epoch: volume.GetEpoch(), + EndpointVersion: volume.GetEndpointVersion(), + Conditions: conditionsFromWire(volume.GetConditions()), + NextActions: append([]string(nil), volume.GetNextActions()...), + SupportBundleHint: volume.GetSupportBundleHint(), + } + for _, replica := range volume.GetReplicas() { + out.Replicas = append(out.Replicas, replicaEvidenceFromWire(replica)) + } + return out +} + +func replicaEvidenceFromWire(replica *control.ReplicaEvidence) ops.ReplicaEvidence { + if replica == nil { + return ops.ReplicaEvidence{} + } + return ops.ReplicaEvidence{ + ReplicaID: replica.GetReplicaId(), + ServerID: replica.GetServerId(), + KubernetesNode: replica.GetKubernetesNode(), + PhysicalHost: replica.GetPhysicalHost(), + Observed: replica.GetObserved(), + Role: replica.GetRole(), + ReplicationRole: replica.GetReplicationRole(), + DurableLatched: replica.GetDurableLatched(), + DurableFrontierKnown: replica.GetDurableFrontierKnown(), + DurableFrontierLSN: replica.GetDurableFrontierLsn(), + CandidateReady: replica.GetCandidateReady(), + CandidateReadyReason: replica.GetCandidateReadyReason(), + FrontendProtocol: replica.GetFrontendProtocol(), + FrontendAddr: replica.GetFrontendAddr(), + StatusAddr: replica.GetStatusAddr(), + StalePrimaryFenced: replica.GetStalePrimaryFenced(), + Conditions: conditionsFromWire(replica.GetConditions()), + SupportBundlePath: replica.GetSupportBundlePath(), + } +} + +func conditionsFromWire(in []*control.ObservationCondition) []ops.ObservationCondition { + out := make([]ops.ObservationCondition, 0, len(in)) + for _, condition := range in { + if condition == nil { + continue + } + out = append(out, ops.ObservationCondition{ + Type: condition.GetType(), + Status: condition.GetStatus(), + Reason: condition.GetReason(), + Severity: condition.GetSeverity(), + Message: condition.GetMessage(), + }) + } + return out +} + +func clusterEventFromWire(event *control.ClusterEvent) ops.ClusterEvent { + if event == nil { + return ops.ClusterEvent{} + } + out := ops.ClusterEvent{ + EventID: event.GetEventId(), + VolumeID: event.GetVolumeId(), + ReplicaID: event.GetReplicaId(), + NodeName: event.GetNodeName(), + Type: event.GetEventType(), + Severity: event.GetSeverity(), + Message: event.GetMessage(), + Reason: event.GetReasonCode(), + OldValue: event.GetOldValue(), + NewValue: event.GetNewValue(), + Epoch: event.GetEpoch(), + EndpointVersion: event.GetEndpointVersion(), + CorrelationID: event.GetCorrelationId(), + EvidenceRef: event.GetEvidenceRef(), + } + if ts := event.GetEventTime(); ts != nil && ts.IsValid() { + out.EventTime = ts.AsTime() + } + return out +} + +func runOpsTimeline(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationVolume("sw-block ops timeline", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + switch out { + case "jsonl": + jsonl, err := ops.RenderClusterEventsJSONL(cluster.Events) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops timeline: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprint(stdout, jsonl) + case "json": + raw, err := ops.MarshalObservationJSON(cluster.Events) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops timeline: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + default: + for _, event := range cluster.Events { + fmt.Fprintf(stdout, "%s severity=%s reason=%s volume=%s replica=%s %s\n", + event.Type, + emptyCLI(event.Severity), + emptyCLI(event.Reason), + emptyCLI(event.VolumeID), + emptyCLI(event.ReplicaID), + event.Message) + } + } + return ops.VolumeStatusExitOK +} + +func runOpsExplain(args []string, stdout, stderr io.Writer) int { + cluster, _, code := loadObservationVolume("sw-block ops explain", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + fmt.Fprint(stdout, ops.RenderObservationExplainText(cluster)) + return ops.VolumeStatusExitOK +} + +func runOpsReport(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops report", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + namespace string + masterAddr string + masterAPIAddr string + outDir string + evidenceOutDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to render") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&outDir, "out", "", "directory for index.html, cluster-evidence.json, timeline.jsonl, and summary.txt") + fs.StringVar(&evidenceOutDir, "evidence-out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops report: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if outDir == "" { + fmt.Fprintln(stderr, "sw-block ops report: --out is required") + return ops.VolumeStatusExitInvalid + } + + var ( + cluster ops.ClusterEvidence + err error + ) + switch { + case fromBundle != "": + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: fromBundle}) + case masterAPIAddr != "": + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr) + default: + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "sw-block ops report: --claim-profile=%q invalid; want %q, %q, or %q\n", claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: evidenceOutDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, "", evidenceOutDir) + } + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if err := ops.WriteObservationReportArtifacts(outDir, cluster); err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "report_status=ok\n") + fmt.Fprintf(stdout, "report_dir=%s\n", outDir) + fmt.Fprintf(stdout, "html=%s\n", ops.ObservationReportHTMLArtifact) + fmt.Fprintf(stdout, "cluster_evidence=%s\n", ops.ObservationReportJSONArtifact) + fmt.Fprintf(stdout, "timeline=%s\n", ops.ObservationReportJSONLArtifact) + fmt.Fprintf(stdout, "summary=%s\n", ops.ObservationReportTextArtifact) + fmt.Fprintf(stdout, "read_only=true\n") + return ops.VolumeStatusExitOK +} + +func loadObservationVolume(command string, args []string, stderr io.Writer) (ops.ClusterEvidence, string, int) { + if len(args) == 0 || args[0] != "volume" { + fmt.Fprintf(stderr, "%s: expected volume [--from-bundle |--namespace ] \n", command) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + fs := flag.NewFlagSet(command+" volume", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + namespace string + masterAddr string + out string + outDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&out, "o", "text", "output format: text, json, or jsonl where supported") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(normalizeObservationVolumeArgs(args[1:])); err != nil { + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + remaining := fs.Args() + if len(remaining) != 1 { + fmt.Fprintf(stderr, "%s: is required\n", command) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + volumeID := remaining[0] + var ( + cluster ops.ClusterEvidence + err error + ) + if fromBundle != "" { + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{ + Dir: fromBundle, + VolumeID: volumeID, + }) + } else { + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "%s: --claim-profile=%q invalid; want %q, %q, or %q\n", command, claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, volumeID, outDir) + } + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + return cluster, out, ops.VolumeStatusExitOK +} + +func normalizeObservationVolumeArgs(args []string) []string { + valueFlags := map[string]bool{ + "--from-bundle": true, + "--namespace": true, + "--master": true, + "--out": true, + "-o": true, + "--product-revision": true, + "--claim-profile": true, + "--required-frontier": true, + "--timeout": true, + } + var volumeID string + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + arg := args[i] + if valueFlags[arg] { + out = append(out, arg) + if i+1 < len(args) { + i++ + out = append(out, args[i]) + } + continue + } + if strings.HasPrefix(arg, "-") { + out = append(out, arg) + continue + } + if volumeID == "" { + volumeID = arg + continue + } + out = append(out, arg) + } + if volumeID != "" { + out = append(out, volumeID) + } + return out +} + func usage(w io.Writer) { fmt.Fprintln(w, "usage:") fmt.Fprintln(w, " sw-block --version") fmt.Fprintln(w, " sw-block ops status --volume --master --status-addr --out ") fmt.Fprintln(w, " sw-block ops inventory --namespace [--master ] --out ") + fmt.Fprintln(w, " sw-block ops cluster --namespace [--master |--master-api ] [-o json]") + fmt.Fprintln(w, " sw-block ops volumes --namespace [--master ] [-o json]") + fmt.Fprintln(w, " sw-block ops describe volume --from-bundle [-o json]") + fmt.Fprintln(w, " sw-block ops describe volume --namespace [--master ] [--out ]") + fmt.Fprintln(w, " sw-block ops timeline volume --from-bundle [-o jsonl]") + fmt.Fprintln(w, " sw-block ops explain volume --from-bundle ") + fmt.Fprintln(w, " sw-block ops explain volume --namespace [--master ] [--out ]") + fmt.Fprintln(w, " sw-block ops report --from-bundle --out ") + fmt.Fprintln(w, " sw-block ops report --master-api --out ") +} + +func emptyCLI(value string) string { + if strings.TrimSpace(value) == "" { + return "-" + } + return value +} + +type requiredFrontierFlags struct { + values map[string]uint64 +} + +func (f *requiredFrontierFlags) String() string { + if f == nil || len(f.values) == 0 { + return "" + } + parts := make([]string, 0, len(f.values)) + for volumeID, lsn := range f.values { + parts = append(parts, fmt.Sprintf("%s=%d", volumeID, lsn)) + } + return strings.Join(parts, ",") +} + +func (f *requiredFrontierFlags) Set(raw string) error { + volumeID, lsnText, ok := strings.Cut(raw, "=") + volumeID = strings.TrimSpace(volumeID) + lsnText = strings.TrimSpace(lsnText) + if !ok || volumeID == "" || lsnText == "" { + return fmt.Errorf("expected volume_id=lsn") + } + lsn, err := strconv.ParseUint(lsnText, 10, 64) + if err != nil { + return fmt.Errorf("parse required frontier lsn: %w", err) + } + if f.values == nil { + f.values = map[string]uint64{} + } + f.values[volumeID] = lsn + return nil } diff --git a/seaweed-block/cmd/sw-block/main_test.go b/seaweed-block/cmd/sw-block/main_test.go index bd28017269..0f4f110936 100644 --- a/seaweed-block/cmd/sw-block/main_test.go +++ b/seaweed-block/cmd/sw-block/main_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" @@ -21,6 +22,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" ) func TestOpsStatusWritesArtifactsAndReturnsClean(t *testing.T) { @@ -234,6 +236,256 @@ func TestOpsInventoryMissingOutReturnsInvalid(t *testing.T) { } } +func TestOpsInventoryRejectsBadRequiredFrontierFlag(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--required-frontier", "pvc-a=not-a-number"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "parse required frontier lsn") { + t.Fatalf("stderr=%s stdout=%s", stderr.String(), stdout.String()) + } +} + +func TestOpsInventoryRejectsBadClaimProfile(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--claim-profile", "wishful-ha"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "--claim-profile") { + t.Fatalf("stderr=%s stdout=%s", stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), ops.PromotionClaimStage2ISCSIALUAMultipath) { + t.Fatalf("stderr should list stage2 profile: %s", stderr.String()) + } +} + +func TestOpsInventoryAcceptsStage2ClaimProfile(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--claim-profile", ops.PromotionClaimStage2ISCSIALUAMultipath}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d want %d stderr=%s stdout=%s", code, ops.VolumeStatusExitOK, stderr.String(), stdout.String()) + } + if strings.Contains(stderr.String(), "--claim-profile") { + t.Fatalf("stage2 claim profile should pass validation: stderr=%s stdout=%s", stderr.String(), stdout.String()) + } +} + +func TestOpsDescribeVolumeFromBundle(t *testing.T) { + dir := writeCmdObservationBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "--from-bundle", dir, "pvc-observed"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=degraded volumes=1", + "volume pvc-observed status=ok rf=3 ack=sync-quorum", + "primary r2 on m02 frontend=192.168.1.184:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsDescribeVolumeFromBundlePrefersProductClusterEvidence(t *testing.T) { + dir := writeCmdProductClusterBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "--from-bundle", dir, "pvc-product"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=ok volumes=1 nodes=1", + "volume pvc-product status=ok rf=3 ack=sync-quorum", + "primary r2 on m02 frontend=192.168.1.184:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + if strings.Contains(stdout.String(), "pvc-observed") { + t.Fatalf("describe should prefer product cluster evidence over fallback inventory:\n%s", stdout.String()) + } +} + +func TestOpsReportFromBundleWritesStaticReadOnlyArtifacts(t *testing.T) { + dir := writeCmdProductClusterBundle(t) + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, name := range []string{ + ops.ObservationReportHTMLArtifact, + ops.ObservationReportJSONArtifact, + ops.ObservationReportJSONLArtifact, + ops.ObservationReportTextArtifact, + } { + if _, err := os.Stat(filepath.Join(outDir, name)); err != nil { + t.Fatalf("missing report artifact %s: %v", name, err) + } + } + html, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportHTMLArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "sw-block read-only status", + "pvc-product", + "192.168.1.184:3260", + "This report is observation-only", + } { + if !strings.Contains(string(html), want) { + t.Fatalf("html missing %q:\n%s", want, html) + } + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "read_only=true") || !strings.Contains(string(summary), "volume=pvc-product") { + t.Fatalf("summary missing report evidence:\n%s", summary) + } + if !strings.Contains(stdout.String(), "report_status=ok") || !strings.Contains(stdout.String(), "html=index.html") { + t.Fatalf("stdout missing report paths:\n%s", stdout.String()) + } +} + +func TestOpsReportFromBundleAllowsEmptyClusterEvidence(t *testing.T) { + dir := t.TempDir() + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 17, 21, 0, 0, 0, time.UTC)) + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "volumes=0") || !strings.Contains(string(summary), "read_only=true") { + t.Fatalf("summary missing empty-cluster evidence:\n%s", summary) + } +} + +func TestOpsTimelineVolumeFromBundleJSONL(t *testing.T) { + dir := writeCmdObservationBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "timeline", "volume", "--from-bundle", dir, "-o", "jsonl", "pvc-observed"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stdout.String(), `"event_type":"authority_published"`) || + !strings.Contains(stdout.String(), `"reason_code":"candidate_covers_required_frontier"`) { + t.Fatalf("stdout missing timeline jsonl:\n%s", stdout.String()) + } +} + +func TestOpsExplainVolumeFromBundleBlockedImagePull(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "demo"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.KubeSystemPodsDeploysArtifact), []byte(`NAME READY STATUS RESTARTS AGE IP NODE +pod/sw-block-csi-node-n948t 0/2 Init:ErrImagePull 0 2m3s 192.168.1.184 m02 +deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:local +`), 0o644); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "explain", "volume", "--from-bundle", dir, "pvc-blocked"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed", + "waiting=ImagePullBackOff on node m02 image sw-block-csi:local", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsDescribeVolumeLiveInventory(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "pvc-live", "--namespace", "default", "--product-revision", "product-rev"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=ok volumes=1 nodes=0", + "volume pvc-live status=ok rf=1 ack=best-effort", + "pvc default/app-live", + "primary r1 on m02 frontend=127.0.0.1:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsClusterAndVolumesLiveInventory(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var clusterOut, clusterErr bytes.Buffer + code := run([]string{"ops", "cluster", "--namespace", "default", "--product-revision", "product-rev"}, &clusterOut, &clusterErr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("cluster exit=%d stderr=%s stdout=%s", code, clusterErr.String(), clusterOut.String()) + } + if !strings.Contains(clusterOut.String(), "cluster status=ok volumes=1 nodes=0") || + !strings.Contains(clusterOut.String(), "volume pvc-live status=ok rf=1 ack=best-effort") { + t.Fatalf("cluster output missing evidence:\n%s", clusterOut.String()) + } + + var volumesOut, volumesErr bytes.Buffer + code = run([]string{"ops", "volumes", "--namespace", "default", "--product-revision", "product-rev"}, &volumesOut, &volumesErr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("volumes exit=%d stderr=%s stdout=%s", code, volumesErr.String(), volumesOut.String()) + } + if !strings.Contains(volumesOut.String(), "volume pvc-live status=ok rf=1 primary=r1 node=m02 frontend=127.0.0.1:3260") { + t.Fatalf("volumes output missing evidence:\n%s", volumesOut.String()) + } +} + func cleanCmdResidueCommand(_ context.Context, name string, args ...string) ([]byte, error) { switch name { case "iscsiadm": @@ -247,6 +499,176 @@ func cleanCmdResidueCommand(_ context.Context, name string, args ...string) ([]b } } +const cmdSinglePVCListJSON = `{ + "items": [ + {"metadata":{"name":"app-live","namespace":"default","uid":"uid-live"},"spec":{"volumeName":"pvc-live","storageClassName":"sw-block-dynamic"},"status":{"phase":"Bound"}} + ] +}` + +const cmdSinglePVListJSON = `{ + "items": [ + {"metadata":{"name":"pvc-live"},"spec":{"claimRef":{"namespace":"default","name":"app-live","uid":"uid-live"},"csi":{"driver":"block.csi.seaweedfs.com","volumeHandle":"pvc-live"}}} + ] +}` + +const cmdSingleDeploymentListJSON = `{ + "items": [ + { + "metadata":{ + "name":"sw-blockvolume-pvc-live-r1", + "namespace":"default", + "labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-live","sw-block.seaweedfs.com/replica":"r1"}, + "ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-live","uid":"uid-live"}] + }, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02","--volume-id=pvc-live","--replica-id=r1","--data-addr=127.0.0.1:19101","--ctrl-addr=127.0.0.1:19102","--status-addr=127.0.0.1:23260","--iscsi-listen=127.0.0.1:3260","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-live"]}]}}}, + "status":{"replicas":1,"readyReplicas":1} + } + ] +}` + +func writeCmdObservationBundle(t *testing.T) string { + t.Helper() + dir := t.TempDir() + inventoryDir := filepath.Join(dir, "demo", "ops-inventory-reader-verified") + if err := os.MkdirAll(inventoryDir, 0o755); err != nil { + t.Fatal(err) + } + inventory := ops.BuildVolumeInventory(ops.VolumeInventoryInput{ + ProductRevision: "product-rev", + Volumes: []ops.VolumeInventoryVolumeInput{{ + VolumeID: "pvc-observed", + Namespace: "default", + PVCName: "sw-block-demo-pvc", + PVName: "pvc-observed", + ReplicationFactor: 3, + Replicas: []ops.VolumeInventoryReplicaInput{ + { + ReplicaID: "r2", + ServerID: "node-loss-r2", + NodeName: "m02", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.184:3260", + AuthorityRole: "primary", + ReplicationRole: "none", + Healthy: true, + FrontendPrimaryReady: true, + Epoch: 2, + EndpointVersion: 1, + AckProfile: ops.PromotionAckProfileSyncQuorum, + ClaimProfile: ops.PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + { + ReplicaID: "r3", + ServerID: "node-loss-r3", + NodeName: "tp01", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.188:3260", + AuthorityRole: "unknown", + ReplicationRole: "replica_ready", + AckProfile: ops.PromotionAckProfileSyncQuorum, + ClaimProfile: ops.PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + }, + }}, + }) + raw, err := ops.MarshalObservationJSON(inventory) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inventoryDir, ops.VolumeInventoryArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.NodeLossRecoverySummaryArtifact), []byte(strings.Join([]string{ + "result=promoted", + "ack_profile=sync-quorum", + "promoted=r2@m02", + "before_frontend=192.168.1.181:3260", + "after_frontend=192.168.1.184:3260", + "reader_verified=true", + "pod_recreate_used=true", + "old_primary_stale_io_success_count=0", + }, "\n")), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.ControlPlaneTimelineArtifact), []byte("event=authority_published from=r1 to=r2 primary=r2 primary_count=1 volume=pvc-observed\n"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func writeCmdProductClusterBundle(t *testing.T) string { + t.Helper() + dir := writeCmdObservationBundle(t) + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 17, 20, 0, 0, 0, time.UTC)) + cluster.ProductRevision = "product-cluster-rev" + cluster.Status = ops.ObservationStatusOK + cluster.Nodes = []ops.NodeEvidence{{ + NodeName: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + ReplicaCount: 1, + MissingImages: nil, + }} + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-product", + Namespace: "default", + PVCName: "sw-block-example-pvc", + ReplicationFactor: 3, + AckProfile: ops.PromotionAckProfileSyncQuorum, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Replicas: []ops.ReplicaEvidence{{ + ReplicaID: "r2", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.184:3260", + }}, + }} + cluster.Events = []ops.ClusterEvent{{ + EventID: "master-1", + EventTime: time.Date(2026, 5, 17, 20, 1, 0, 0, time.UTC), + VolumeID: "pvc-product", + ReplicaID: "r2", + Type: ops.EventTypeCSIReattachObserved, + Severity: "info", + Reason: ops.EventTypeCSIReattachObserved, + Message: "CSI staged volume on node", + NewValue: "192.168.1.184:3260", + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + return dir +} + func fixtureCmdKubectl(outputs map[string]string) func(context.Context, string, ...string) ([]byte, error) { return func(_ context.Context, name string, args ...string) ([]byte, error) { key := strings.TrimSpace(name + " " + strings.Join(args, " ")) @@ -280,6 +702,38 @@ func TestOpsStatusRequiresMasterAndStatusAddr(t *testing.T) { } } +func TestOpsClusterReadsMasterAPIProductEvents(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "-o", "json"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + var cluster ops.ClusterEvidence + if err := json.Unmarshal(stdout.Bytes(), &cluster); err != nil { + t.Fatalf("json: %v\n%s", err, stdout.String()) + } + if len(cluster.Events) != 1 || cluster.Events[0].Type != ops.EventTypeCSIReattachObserved { + t.Fatalf("events=%+v", cluster.Events) + } + if len(cluster.Volumes) != 1 || cluster.Volumes[0].VolumeID != "v1" || cluster.Volumes[0].PrimaryReplica != "r2" { + t.Fatalf("volumes=%+v", cluster.Volumes) + } +} + +func TestOpsClusterMasterAPIRejectsUnexpectedArgs(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "extra"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String()) + } +} + type cmdFakeEvidenceServer struct { control.UnimplementedEvidenceServiceServer } @@ -297,6 +751,46 @@ func (cmdFakeEvidenceServer) QueryVolumeStatus(context.Context, *control.StatusR }, nil } +type cmdFakeClusterEvidenceServer struct { + control.UnimplementedClusterEvidenceServiceServer +} + +func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + return &control.ClusterStatusResponse{ + SchemaVersion: ops.ObservationSchemaVersion, + CapturedAt: timestamppb.Now(), + ProductRevision: "test-rev", + Status: ops.ObservationStatusOK, + Volumes: []*control.VolumeEvidence{{ + VolumeId: "v1", + ReplicationFactor: 3, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + }}, + Events: []*control.ClusterEvent{{ + EventId: "master-1", + EventTime: timestamppb.Now(), + VolumeId: "v1", + ReplicaId: "r2", + NodeName: "m02", + EventType: ops.EventTypeCSIReattachObserved, + Severity: "info", + Message: "CSI staged volume on node", + ReasonCode: ops.EventTypeCSIReattachObserved, + NewValue: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + EvidenceRef: "csi-node", + }}, + }, nil +} + func startCmdFakeMaster(t *testing.T) (string, func()) { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") @@ -305,6 +799,7 @@ func startCmdFakeMaster(t *testing.T) (string, func()) { } srv := grpc.NewServer() control.RegisterEvidenceServiceServer(srv, cmdFakeEvidenceServer{}) + control.RegisterClusterEvidenceServiceServer(srv, cmdFakeClusterEvidenceServer{}) go func() { _ = srv.Serve(ln) }() return ln.Addr().String(), func() { srv.Stop() diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index fbc9f8ca68..bc79ef4505 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -312,6 +312,15 @@ func (a *VolumeReplicaAdapter) Projection() engine.ReplicaProjection { return engine.DeriveProjection(&a.state) } +// PromotionReadyFact returns the control-facing promotion readiness fact from +// engine truth domains. Unlike Projection(), this is safe to feed to authority +// because it does not pass through the operator-facing ReplicaProjection shape. +func (a *VolumeReplicaAdapter) PromotionReadyFact() engine.PromotionReadyFact { + a.mu.Lock() + defer a.mu.Unlock() + return engine.BuildPromotionReadyFact(&a.state) +} + // Diagnostics is an adapter-local inspection snapshot. It may include runtime // observations that are NOT engine truth (for example flow-control verdicts). // Callers must not feed this back into the engine as control input. diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index d2998a0d68..d46f4255db 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -27,6 +27,19 @@ type assignmentState struct { present bool } +// PublishEvent is emitted only after Publisher successfully mints and commits +// an AssignmentInfo. It is an observation hook; consumers must not feed it back +// into authority decisions. +type PublishEvent struct { + Info adapter.AssignmentInfo + Ask AssignmentAsk +} + +// PublishObserver receives successful publication events. Implementations must +// be non-blocking or very fast: Publisher calls this after releasing its state +// lock but before returning from apply. +type PublishObserver func(PublishEvent) + // subscription is a live, per-caller subscription to the authority // stream. Each Subscribe returns exactly one subscription; cancel // is isolated — one subscription ending does NOT affect others on @@ -137,6 +150,8 @@ type Publisher struct { // records are simply absent from state and the volume // behaves as "never bound" until a new mint. loadErrs []error + + observer PublishObserver } // PublisherOption configures a Publisher at construction. @@ -158,6 +173,15 @@ func WithStore(store AuthorityStore) PublisherOption { } } +// WithPublishObserver registers a read-only callback for successful mints. +// The callback is not replayed during durable reload; reload is existing state, +// not a new authority publication event. +func WithPublishObserver(observer PublishObserver) PublisherOption { + return func(p *Publisher) { + p.observer = observer + } +} + // NewPublisher creates a Publisher that consumes from dir. // // When WithStore is supplied, the constructor performs a @@ -489,9 +513,19 @@ func (p *Publisher) apply(ask AssignmentAsk) error { for _, s := range subs { s.deliver(next) } + if p.observer != nil { + safeInvokePublishObserver(p.observer, PublishEvent{Info: next, Ask: ask}) + } return nil } +func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent) { + defer func() { + _ = recover() + }() + observer(event) +} + // maxPublishedEpochForVolume scans the publisher's authoring state // and returns the maximum Epoch currently published on any // (VolumeID, *) key for the given volume. Zero return means no diff --git a/seaweed-block/core/authority/authority_test.go b/seaweed-block/core/authority/authority_test.go index 3faae6e741..d645a976d4 100644 --- a/seaweed-block/core/authority/authority_test.go +++ b/seaweed-block/core/authority/authority_test.go @@ -62,6 +62,50 @@ func TestPublisher_Bind_RejectsDoubleBind(t *testing.T) { } } +func TestPublisher_PublishObserverFiresAfterSuccessfulMintOnly(t *testing.T) { + var events []PublishEvent + pub := NewPublisher(NewStaticDirective(nil), WithPublishObserver(func(event PublishEvent) { + events = append(events, event) + })) + ask := AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r1", + DataAddr: "d", CtrlAddr: "c", + Intent: IntentBind, + } + if err := pub.apply(ask); err != nil { + t.Fatalf("Bind: %v", err) + } + if len(events) != 1 { + t.Fatalf("events=%d want 1", len(events)) + } + if events[0].Info.VolumeID != "v1" || events[0].Info.ReplicaID != "r1" || events[0].Info.Epoch != 1 { + t.Fatalf("event=%+v", events[0]) + } + if err := pub.apply(ask); !errors.Is(err, ErrBindAlreadyBound) { + t.Fatalf("second Bind: want ErrBindAlreadyBound, got %v", err) + } + if len(events) != 1 { + t.Fatalf("observer fired for rejected ask: events=%+v", events) + } +} + +func TestPublisher_PublishObserverPanicDoesNotAbortMint(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil), WithPublishObserver(func(PublishEvent) { + panic("observer bug") + })) + if err := pub.apply(AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r1", + DataAddr: "d", CtrlAddr: "c", + Intent: IntentBind, + }); err != nil { + t.Fatalf("Bind with panicking observer: %v", err) + } + line, ok := pub.VolumeAuthorityLine("v1") + if !ok || line.ReplicaID != "r1" { + t.Fatalf("authority was not minted after observer panic: %+v", line) + } +} + func TestPublisher_RefreshEndpoint_BumpsOnlyEndpointVersion(t *testing.T) { pub := NewPublisher(NewStaticDirective(nil)) if err := pub.apply(AssignmentAsk{ @@ -577,7 +621,7 @@ func TestPublisher_Run_LogsAndContinuesOnRejectedAsk(t *testing.T) { // Run semantic. dir := NewStaticDirective([]AssignmentAsk{ {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentReassign}, // rejected - {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, // accepted + {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, // accepted }) pub := NewPublisher(dir) ch, cancelSub := pub.Subscribe("v1", "r1") @@ -672,9 +716,9 @@ func newClosureExecutor() *closureExecutor { return ce } -func (e *closureExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn } -func (e *closureExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn } -func (e *closureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenceComplete = fn } +func (e *closureExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { e.onStart = fn } +func (e *closureExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { e.onClose = fn } +func (e *closureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { e.onFenceComplete = fn } func (e *closureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { return adapter.ProbeResult{ @@ -793,12 +837,12 @@ var nonForgeabilityAllowedPackageSuffixes = []string{ // EVERY production .go file in the repo (not just core/) and fails // if any file outside the allowlist: // -// 1. constructs adapter.AssignmentInfo via composite literal with -// a non-zero Epoch or non-zero EndpointVersion, OR -// 2. declares a local variable of type adapter.AssignmentInfo, -// (*adapter.AssignmentInfo), or []adapter.AssignmentInfo. A -// local variable of this type is the classic bypass shape for -// deferred mutation: `var x AssignmentInfo; x.Epoch = input`. +// 1. constructs adapter.AssignmentInfo via composite literal with +// a non-zero Epoch or non-zero EndpointVersion, OR +// 2. declares a local variable of type adapter.AssignmentInfo, +// (*adapter.AssignmentInfo), or []adapter.AssignmentInfo. A +// local variable of this type is the classic bypass shape for +// deferred mutation: `var x AssignmentInfo; x.Epoch = input`. // // Using go/ast/parser rather than regex closes two prior weaknesses: // - the regex-based check only matched struct literals, so a @@ -1015,10 +1059,10 @@ func Forge(userInput uint64) { // of human-readable findings describing any disallowed use of // adapter.AssignmentInfo. It catches: // -// (a) composite literals of type AssignmentInfo / adapter.AssignmentInfo -// with Epoch or EndpointVersion fields set to non-zero values; -// (b) local variable declarations (var / :=) whose declared or -// inferred type is AssignmentInfo (value, pointer, or slice). +// (a) composite literals of type AssignmentInfo / adapter.AssignmentInfo +// with Epoch or EndpointVersion fields set to non-zero values; +// (b) local variable declarations (var / :=) whose declared or +// inferred type is AssignmentInfo (value, pointer, or slice). // // Function parameters, method receivers, return type declarations, // and struct field types are NOT flagged — consuming values flows @@ -1242,4 +1286,3 @@ func receiveOrFail(t *testing.T, ch <-chan adapter.AssignmentInfo, who string) a return adapter.AssignmentInfo{} } } - diff --git a/seaweed-block/core/authority/controller.go b/seaweed-block/core/authority/controller.go index c89767ebe1..3b2eb98d33 100644 --- a/seaweed-block/core/authority/controller.go +++ b/seaweed-block/core/authority/controller.go @@ -450,7 +450,7 @@ func (c *TopologyController) decideVolume( projectedLoad map[string]int, ) (AssignmentAsk, string, bool) { if !hasLine { - cands := acceptableCandidates(vol, serverIndex) + cands := placeableCandidates(vol, serverIndex) if len(cands) == 0 { return AssignmentAsk{}, "", false } @@ -492,17 +492,30 @@ func (c *TopologyController) decideVolume( } other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID) - if len(other) == 0 { - return AssignmentAsk{}, "", false + if len(other) > 0 { + best := chooseFailoverCandidate(other, projectedLoad) + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: best.ReplicaID, + DataAddr: best.DataAddr, + CtrlAddr: best.CtrlAddr, + Intent: IntentReassign, + }, "failover", true } - best := chooseFailoverCandidate(other, projectedLoad) - return AssignmentAsk{ - VolumeID: vol.VolumeID, - ReplicaID: best.ReplicaID, - DataAddr: best.DataAddr, - CtrlAddr: best.CtrlAddr, - Intent: IntentReassign, - }, "failover", true + // No promotion-ready peer exists. Keep the current authority endpoint fresh + // when the current replica is still reachable/eligible; this preserves + // authority continuity without treating that replica as a failover candidate. + if candidatePlaceable(current, serverIndex) && + (current.DataAddr != currentLine.DataAddr || current.CtrlAddr != currentLine.CtrlAddr) { + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: current.ReplicaID, + DataAddr: current.DataAddr, + CtrlAddr: current.CtrlAddr, + Intent: IntentRefreshEndpoint, + }, "endpoint refresh", true + } + return AssignmentAsk{}, "", false } func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool { @@ -536,6 +549,28 @@ func candidateAcceptable(slot ReplicaCandidate, servers map[string]ServerObserva server.Eligible } +func candidatePlaceable(slot ReplicaCandidate, servers map[string]ServerObservation) bool { + server, ok := servers[slot.ServerID] + if !ok { + return false + } + return slot.Reachable && + slot.Eligible && + !slot.Withdrawn && + server.Reachable && + server.Eligible +} + +func placeableCandidates(vol VolumeTopologySnapshot, servers map[string]ServerObservation) []ReplicaCandidate { + var out []ReplicaCandidate + for _, slot := range vol.Slots { + if candidatePlaceable(slot, servers) { + out = append(out, slot) + } + } + return out +} + func acceptableCandidates(vol VolumeTopologySnapshot, servers map[string]ServerObservation) []ReplicaCandidate { var out []ReplicaCandidate for _, slot := range vol.Slots { diff --git a/seaweed-block/core/authority/controller_test.go b/seaweed-block/core/authority/controller_test.go index d311f7708f..80a1bbaf72 100644 --- a/seaweed-block/core/authority/controller_test.go +++ b/seaweed-block/core/authority/controller_test.go @@ -114,6 +114,29 @@ func TestTopologyController_InitialPlacementUsesEvidenceTieBreakOnEqualLoad(t *t } } +func TestTopologyController_InitialPlacementDoesNotRequirePromotionReady(t *testing.T) { + reader := newFakeBasisReader() + ctrl := NewTopologyController(TopologyControllerConfig{ExpectedSlotsPerVolume: 1}, reader) + notReady := candidate("r1", "s1", "d1", "c1", 10) + notReady.ReadyForPrimary = false + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, notReady), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentBind || ask.ReplicaID != "r1" { + t.Fatalf("initial bind should use placeable candidate even before promotion-ready, got %+v", ask) + } +} + func TestTopologyController_FailoverUsesHighestEvidenceCandidate(t *testing.T) { reader := newFakeBasisReader() reader.Set("v1", "r1", AuthorityBasis{ @@ -146,6 +169,77 @@ func TestTopologyController_FailoverUsesHighestEvidenceCandidate(t *testing.T) { } } +func TestTopologyController_NotReadyCurrentRefreshesEndpointWhenNoReadyPeer(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "r1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, + DataAddr: "d1-old", CtrlAddr: "c1-old", + }) + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + r1 := candidate("r1", "s1", "d1-new", "c1-new", 10) + r1.ReadyForPrimary = false + r2 := candidate("r2", "s2", "d2", "c2", 20) + r2.ReadyForPrimary = false + r3 := candidate("r3", "s3", "d3", "c3", 30) + r3.ReadyForPrimary = false + snap := ClusterSnapshot{ + CollectedRevision: 2, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1-old", CtrlAddr: "c1-old"}, + r1, r2, r3, + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentRefreshEndpoint || ask.ReplicaID != "r1" || ask.DataAddr != "d1-new" || ask.CtrlAddr != "c1-new" { + t.Fatalf("not-ready current with no ready peer should only refresh its own endpoint, got %+v", ask) + } +} + +func TestTopologyController_ReadyPeerFailoverBeatsNotReadyCurrentEndpointRefresh(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "r1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, + DataAddr: "d1-old", CtrlAddr: "c1-old", + }) + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + r1 := candidate("r1", "s1", "d1-new", "c1-new", 10) + r1.ReadyForPrimary = false + r2 := candidate("r2", "s2", "d2", "c2", 20) + r3 := candidate("r3", "s3", "d3", "c3", 30) + r3.ReadyForPrimary = false + snap := ClusterSnapshot{ + CollectedRevision: 2, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1-old", CtrlAddr: "c1-old"}, + r1, r2, r3, + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentReassign || ask.ReplicaID != "r2" { + t.Fatalf("ready peer must win over refreshing not-ready current, got %+v", ask) + } +} + func TestTopologyController_RebalanceMovesToLighterServer(t *testing.T) { reader := newFakeBasisReader() reader.Set("v1", "v1r1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}) @@ -189,6 +283,26 @@ func TestTopologyController_RebalanceMovesToLighterServer(t *testing.T) { } } +func TestTopologyController_RebalanceSkipsNotReadyCandidate(t *testing.T) { + notReadyTarget := candidate("v1r3", "s3", "d13", "c13", 30) + notReadyTarget.ReadyForPrimary = false + vol := clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}, + candidate("v1r1", "s1", "d11", "c11", 10), + notReadyTarget, + ) + servers := map[string]ServerObservation{ + "s1": {ServerID: "s1", Reachable: true, Eligible: true}, + "s3": {ServerID: "s3", Reachable: true, Eligible: true}, + } + current := vol.Slots[0] + currentLoad := map[string]int{"s1": 2, "s3": 0} + projectedLoad := map[string]int{"s1": 2, "s3": 0} + if got, ok := chooseRebalanceCandidate(vol, current, servers, currentLoad, projectedLoad, 1); ok { + t.Fatalf("not-ready lighter target must not be chosen for rebalance, got %+v", got) + } +} + func TestTopologyController_RebalanceSkipsWhenLoadAlreadyWithinBound(t *testing.T) { reader := newFakeBasisReader() reader.Set("v1", "v1r1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}) diff --git a/seaweed-block/core/csi/backend.go b/seaweed-block/core/csi/backend.go index dff1b44c6b..1f635c9025 100644 --- a/seaweed-block/core/csi/backend.go +++ b/seaweed-block/core/csi/backend.go @@ -3,6 +3,7 @@ package csi import ( "context" "errors" + "strings" ) var ErrPublishTargetNotFound = errors.New("csi: publish target not found") @@ -13,6 +14,9 @@ type Protocol string const ( ProtocolISCSI Protocol = "iscsi" ProtocolNVMe Protocol = "nvme" + + EventTypeCSIReattachObserved = "csi_reattach_observed" + EventSeverityInfo = "info" ) func normalizeProtocol(p Protocol) Protocol { @@ -22,17 +26,22 @@ func normalizeProtocol(p Protocol) Protocol { return p } -// PublishTarget is a read-only frontend target fact. It is deliberately -// not authority-shaped: no epoch/endpoint_version inputs, no assignment -// intent, no publisher call surface. +// PublishTarget is a read-only frontend target fact. Epoch and +// EndpointVersion are evidence copied from master status so recovery gates can +// compare before/after target generations. They are not exposed in CSI +// publish_context and do not give CSI authority mutation capability. type PublishTarget struct { - VolumeID string - ReplicaID string - Protocol Protocol + VolumeID string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 + Protocol Protocol - ISCSIAddr string - IQN string - LUN uint32 + ISCSIAddr string + ISCSIAddrs []string + IQN string + LUN uint32 + Multipath bool NVMeAddr string NQN string @@ -43,6 +52,26 @@ type PublishTargetLookup interface { LookupPublishTarget(ctx context.Context, volumeID, nodeID string) (PublishTarget, error) } +type ClusterEvent struct { + VolumeID string + ReplicaID string + NodeName string + Type string + Severity string + Message string + Reason string + OldValue string + NewValue string + Epoch uint64 + EndpointVersion uint64 + CorrelationID string + EvidenceRef string +} + +type EventReporter interface { + ReportEvent(ctx context.Context, event ClusterEvent) error +} + // VolumeProvisioner records product-level desired volume intent. It must not // mint assignment, epoch, endpoint_version, readiness, or frontend facts. type VolumeProvisioner interface { @@ -74,6 +103,16 @@ func publishContext(t PublishTarget) map[string]string { ctx["iscsiAddr"] = t.ISCSIAddr ctx["iqn"] = t.IQN } + if len(t.ISCSIAddrs) > 0 && t.IQN != "" { + ctx["iscsiAddrs"] = strings.Join(t.ISCSIAddrs, ",") + if ctx["iscsiAddr"] == "" { + ctx["iscsiAddr"] = t.ISCSIAddrs[0] + } + ctx["iqn"] = t.IQN + } + if t.Multipath { + ctx["stage2_multipath"] = "true" + } if t.NVMeAddr != "" && t.NQN != "" { ctx["nvmeAddr"] = t.NVMeAddr ctx["nqn"] = t.NQN diff --git a/seaweed-block/core/csi/controller_test.go b/seaweed-block/core/csi/controller_test.go index ac70e17cb1..5024da9627 100644 --- a/seaweed-block/core/csi/controller_test.go +++ b/seaweed-block/core/csi/controller_test.go @@ -116,6 +116,32 @@ func TestControllerPublish_DoesNotExposeCHAPSecretsInPublishContext(t *testing.T } } +func TestControllerPublish_DoesNotExposeAuthorityGenerationInPublishContext(t *testing.T) { + lookup := &stubLookup{target: PublishTarget{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 2, + EndpointVersion: 4, + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.2:3260", + IQN: "iqn.2026-05.example.v3:v1-r2", + }} + s := NewControllerServer(lookup) + + resp, err := s.ControllerPublishVolume(context.Background(), &csipb.ControllerPublishVolumeRequest{ + VolumeId: "v1", + NodeId: "node-a", + }) + if err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + for _, key := range []string{"epoch", "endpointVersion", "replicaID", "primary", "ready", "healthy"} { + if _, ok := resp.GetPublishContext()[key]; ok { + t.Fatalf("authority field %q leaked in publish_context: %+v", key, resp.GetPublishContext()) + } + } +} + func TestControllerPublish_FailsClosedWithoutVerifiedTarget(t *testing.T) { s := NewControllerServer(&stubLookup{err: ErrPublishTargetNotFound}) _, err := s.ControllerPublishVolume(context.Background(), &csipb.ControllerPublishVolumeRequest{ diff --git a/seaweed-block/core/csi/linux_util.go b/seaweed-block/core/csi/linux_util.go index 390683c097..6db5d6705c 100644 --- a/seaweed-block/core/csi/linux_util.go +++ b/seaweed-block/core/csi/linux_util.go @@ -13,12 +13,22 @@ import ( ) func NewDefaultNodeServer(nodeID, iqnPrefix string) *NodeServer { + return NewDefaultNodeServerWithLookup(nodeID, iqnPrefix, nil) +} + +func NewDefaultNodeServerWithLookup(nodeID, iqnPrefix string, lookup PublishTargetLookup) *NodeServer { + return NewDefaultNodeServerWithLookupAndEventReporter(nodeID, iqnPrefix, lookup, nil) +} + +func NewDefaultNodeServerWithLookupAndEventReporter(nodeID, iqnPrefix string, lookup PublishTargetLookup, reporter EventReporter) *NodeServer { return NewNodeServer(NodeConfig{ - NodeID: nodeID, - IQNPrefix: iqnPrefix, - ISCSIUtil: &realISCSIUtil{}, - NVMeUtil: &realNVMeUtil{}, - MountUtil: &realMountUtil{}, + NodeID: nodeID, + IQNPrefix: iqnPrefix, + ISCSIUtil: &realISCSIUtil{}, + NVMeUtil: &realNVMeUtil{}, + MountUtil: &realMountUtil{}, + Lookup: lookup, + EventReporter: reporter, }) } @@ -73,7 +83,7 @@ func (r *realISCSIUtil) Logout(ctx context.Context, iqn string) error { return nil } -func (r *realISCSIUtil) GetDeviceByIQN(ctx context.Context, iqn string) (string, error) { +func (r *realISCSIUtil) GetDeviceByIQN(ctx context.Context, iqn, portal string) (string, error) { deadline := time.After(10 * time.Second) ticker := time.NewTicker(200 * time.Millisecond) defer ticker.Stop() @@ -82,7 +92,7 @@ func (r *realISCSIUtil) GetDeviceByIQN(ctx context.Context, iqn string) (string, case <-ctx.Done(): return "", ctx.Err() case <-deadline: - return "", fmt.Errorf("timeout waiting for device for IQN %s", iqn) + return "", fmt.Errorf("timeout waiting for device for IQN %s portal %s", iqn, portal) case <-ticker.C: matches, err := filepath.Glob(fmt.Sprintf("/dev/disk/by-path/*%s*", iqn)) if err != nil { @@ -92,6 +102,9 @@ func (r *realISCSIUtil) GetDeviceByIQN(ctx context.Context, iqn string) (string, if strings.Contains(match, "-part") { continue } + if portal != "" && !iscsiByPathMatchesPortal(match, portal) { + continue + } dev, err := filepath.EvalSymlinks(match) if err != nil { continue @@ -102,7 +115,148 @@ func (r *realISCSIUtil) GetDeviceByIQN(ctx context.Context, iqn string) (string, } } -func (r *realISCSIUtil) IsLoggedIn(ctx context.Context, iqn string) (bool, error) { +func (r *realISCSIUtil) GetMultipathDeviceByIQN(ctx context.Context, iqn string, minPaths int) (string, error) { + if minPaths < 2 { + return "", fmt.Errorf("multipath requires at least two paths, got %d", minPaths) + } + deadline := time.After(20 * time.Second) + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + _ = refreshMultipathMaps(ctx) + for { + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-deadline: + return "", fmt.Errorf("timeout waiting for multipath device for IQN %s paths >= %d", iqn, minPaths) + case <-ticker.C: + dev, paths, err := iscsiMultipathDeviceForIQN(ctx, iqn) + if err != nil || dev == "" || paths < minPaths { + continue + } + return dev, nil + } + } +} + +func refreshMultipathMaps(ctx context.Context) error { + cmdCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(cmdCtx, "multipath", "-r") + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("multipath -r: %s: %w", string(out), err) + } + return nil +} + +func iscsiMultipathDeviceForIQN(ctx context.Context, iqn string) (string, int, error) { + cmdCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(cmdCtx, "multipath", "-ll") + out, err := cmd.CombinedOutput() + if err != nil { + return "", 0, fmt.Errorf("multipath -ll: %s: %w", string(out), err) + } + return parseISCSIMultipathDeviceForIQN(string(out), iqn, iscsiRawDevicesForIQN(iqn)) +} + +func iscsiRawDevicesForIQN(iqn string) map[string]struct{} { + out := map[string]struct{}{} + matches, err := filepath.Glob(fmt.Sprintf("/dev/disk/by-path/*%s*", iqn)) + if err != nil { + return out + } + for _, match := range matches { + if strings.Contains(match, "-part") { + continue + } + dev, err := filepath.EvalSymlinks(match) + if err != nil { + continue + } + base := filepath.Base(dev) + if base != "" { + out[base] = struct{}{} + } + } + return out +} + +func parseISCSIMultipathDeviceForIQN(out, iqn string, rawDevices map[string]struct{}) (string, int, error) { + lines := strings.Split(out, "\n") + for i, line := range lines { + if !multipathLooksLikeMapHeader(line) { + continue + } + if !strings.Contains(line, iqn) && !multipathBlockContainsRawDevice(lines, i+1, rawDevices) { + continue + } + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + device := "/dev/mapper/" + fields[0] + paths := 0 + for j := i + 1; j < len(lines); j++ { + next := lines[j] + if strings.TrimSpace(next) == "" { + break + } + if multipathLooksLikeMapHeader(next) { + break + } + if strings.Contains(next, " active") || strings.Contains(next, " ready") || strings.Contains(next, " running") { + paths++ + } + } + if paths == 0 { + paths = 1 + } + return device, paths, nil + } + return "", 0, nil +} + +func multipathLooksLikeMapHeader(line string) bool { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "|") || strings.HasPrefix(trimmed, "`") { + return false + } + return strings.Contains(trimmed, "(") && strings.Contains(trimmed, ")") +} + +func multipathBlockContainsRawDevice(lines []string, start int, rawDevices map[string]struct{}) bool { + if len(rawDevices) == 0 { + return false + } + for j := start; j < len(lines); j++ { + next := lines[j] + if strings.TrimSpace(next) == "" { + break + } + if multipathLooksLikeMapHeader(next) { + break + } + for dev := range rawDevices { + if multipathLineContainsDevice(next, dev) { + return true + } + } + } + return false +} + +func multipathLineContainsDevice(line, dev string) bool { + for _, field := range strings.Fields(line) { + if field == dev { + return true + } + } + return false +} + +func (r *realISCSIUtil) IsLoggedIn(ctx context.Context, iqn, portal string) (bool, error) { cmd := exec.CommandContext(ctx, "iscsiadm", "-m", "session") out, err := cmd.CombinedOutput() if err != nil { @@ -115,7 +269,30 @@ func (r *realISCSIUtil) IsLoggedIn(ctx context.Context, iqn string) (bool, error } return false, fmt.Errorf("iscsiadm session: %s: %w", outStr, err) } - return strings.Contains(string(out), iqn), nil + return iscsiSessionContainsTarget(string(out), iqn, portal), nil +} + +func iscsiSessionContainsTarget(out, iqn, portal string) bool { + for _, line := range strings.Split(out, "\n") { + if !strings.Contains(line, iqn) { + continue + } + if portal == "" || strings.Contains(line, portal) || strings.Contains(line, iscsiPortalHostPortForByPath(portal)) { + return true + } + } + return false +} + +func iscsiByPathMatchesPortal(path, portal string) bool { + if portal == "" { + return true + } + return strings.Contains(path, portal) || strings.Contains(path, iscsiPortalHostPortForByPath(portal)) +} + +func iscsiPortalHostPortForByPath(portal string) string { + return strings.ReplaceAll(portal, ":", "-") } func (r *realISCSIUtil) RescanDevice(ctx context.Context, iqn string) error { diff --git a/seaweed-block/core/csi/linux_util_test.go b/seaweed-block/core/csi/linux_util_test.go new file mode 100644 index 0000000000..ec60c2d4ed --- /dev/null +++ b/seaweed-block/core/csi/linux_util_test.go @@ -0,0 +1,54 @@ +package csi + +import "testing" + +func TestParseISCSIMultipathDeviceForIQN_UsesRawDeviceMembership(t *testing.T) { + out := `mpatha (36001405f7d3f3e5a) dm-0 LIO-ORG,sw-block +size=1G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw +|-+- policy='service-time 0' prio=50 status=active +| ` + "`" + `- 5:0:0:0 sdb 8:16 active ready running +` + "`" + `-+- policy='service-time 0' prio=10 status=enabled + ` + "`" + `- 6:0:0:0 sdc 8:32 active ready running +` + + dev, paths, err := parseISCSIMultipathDeviceForIQN(out, "iqn.2026-05.io.seaweedfs:v1", map[string]struct{}{ + "sdb": {}, + "sdc": {}, + }) + if err != nil { + t.Fatalf("parse: %v", err) + } + if dev != "/dev/mapper/mpatha" || paths != 2 { + t.Fatalf("dev=%q paths=%d", dev, paths) + } +} + +func TestParseISCSIMultipathDeviceForIQN_FallsBackToIQNLine(t *testing.T) { + out := `mpathz (iqn.2026-05.io.seaweedfs:v1) dm-1 LIO-ORG,sw-block +` + "`" + `- 7:0:0:0 sdd 8:48 active ready running +` + + dev, paths, err := parseISCSIMultipathDeviceForIQN(out, "iqn.2026-05.io.seaweedfs:v1", nil) + if err != nil { + t.Fatalf("parse: %v", err) + } + if dev != "/dev/mapper/mpathz" || paths != 1 { + t.Fatalf("dev=%q paths=%d", dev, paths) + } +} + +func TestParseISCSIMultipathDeviceForIQN_IgnoresUnrelatedMaps(t *testing.T) { + out := `mpatha (36001405f7d3f3e5a) dm-0 LIO-ORG,sw-block +` + "`" + `- 5:0:0:0 sdb 8:16 active ready running +` + + dev, paths, err := parseISCSIMultipathDeviceForIQN(out, "iqn.2026-05.io.seaweedfs:v1", map[string]struct{}{ + "sdc": {}, + }) + if err != nil { + t.Fatalf("parse: %v", err) + } + if dev != "" || paths != 0 { + t.Fatalf("dev=%q paths=%d want empty", dev, paths) + } +} diff --git a/seaweed-block/core/csi/master_backend.go b/seaweed-block/core/csi/master_backend.go index 853e9b045b..b536602fde 100644 --- a/seaweed-block/core/csi/master_backend.go +++ b/seaweed-block/core/csi/master_backend.go @@ -3,6 +3,7 @@ package csi import ( "context" "fmt" + "net" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -12,21 +13,77 @@ import ( // intentionally read-only: it does not call lifecycle, placement, or // authority mutation APIs. type ControlStatusLookup struct { - client control.EvidenceServiceClient + client control.EvidenceServiceClient + enableMultipath bool + rejectLoopback bool } +type ControlStatusLookupOption func(*ControlStatusLookup) + func NewControlStatusLookup(client control.EvidenceServiceClient) *ControlStatusLookup { return &ControlStatusLookup{client: client} } +func NewControlStatusLookupWithMultipath(client control.EvidenceServiceClient) *ControlStatusLookup { + return &ControlStatusLookup{client: client, enableMultipath: true} +} + +func NewControlStatusLookupWithOptions(client control.EvidenceServiceClient, opts ...ControlStatusLookupOption) *ControlStatusLookup { + out := &ControlStatusLookup{client: client} + for _, opt := range opts { + if opt != nil { + opt(out) + } + } + return out +} + +func WithMultipathPublishTargets() ControlStatusLookupOption { + return func(l *ControlStatusLookup) { l.enableMultipath = true } +} + +func WithLoopbackPublishTargetsRejected() ControlStatusLookupOption { + return func(l *ControlStatusLookup) { l.rejectLoopback = true } +} + type ControlLifecycleProvisioner struct { client control.LifecycleServiceClient } +type ControlEventReporter struct { + client control.ObservationServiceClient +} + func NewControlLifecycleProvisioner(client control.LifecycleServiceClient) *ControlLifecycleProvisioner { return &ControlLifecycleProvisioner{client: client} } +func NewControlEventReporter(client control.ObservationServiceClient) *ControlEventReporter { + return &ControlEventReporter{client: client} +} + +func (r *ControlEventReporter) ReportEvent(ctx context.Context, event ClusterEvent) error { + if r == nil || r.client == nil { + return fmt.Errorf("csi: event reporter not configured") + } + _, err := r.client.ReportClusterEvent(ctx, &control.ClusterEvent{ + VolumeId: event.VolumeID, + ReplicaId: event.ReplicaID, + NodeName: event.NodeName, + EventType: event.Type, + Severity: event.Severity, + Message: event.Message, + ReasonCode: event.Reason, + OldValue: event.OldValue, + NewValue: event.NewValue, + Epoch: event.Epoch, + EndpointVersion: event.EndpointVersion, + CorrelationId: event.CorrelationID, + EvidenceRef: event.EvidenceRef, + }) + return err +} + func (p *ControlLifecycleProvisioner) CreateVolume(ctx context.Context, spec VolumeSpec) (VolumeSpec, error) { if p == nil || p.client == nil { return VolumeSpec{}, fmt.Errorf("csi: lifecycle provisioner not configured") @@ -75,27 +132,58 @@ func (l *ControlStatusLookup) LookupPublishTarget(ctx context.Context, volumeID, if !resp.GetAssigned() || resp.GetReplicaId() == "" { return PublishTarget{}, ErrPublishTargetNotFound } - if t, ok := publishTargetFromStatus(resp); ok { + if t, ok := publishTargetFromStatus(resp, l.enableMultipath, l.rejectLoopback); ok { return t, nil } return PublishTarget{}, ErrPublishTargetNotFound } -func publishTargetFromStatus(resp *control.StatusResponse) (PublishTarget, bool) { +func publishTargetFromStatus(resp *control.StatusResponse, enableMultipath bool, rejectLoopback bool) (PublishTarget, bool) { if resp == nil { return PublishTarget{}, false } base := PublishTarget{ - VolumeID: resp.GetVolumeId(), - ReplicaID: resp.GetReplicaId(), + VolumeID: resp.GetVolumeId(), + ReplicaID: resp.GetReplicaId(), + Epoch: resp.GetEpoch(), + EndpointVersion: resp.GetEndpointVersion(), } - for _, ft := range resp.GetFrontends() { - if ft == nil { - continue + if enableMultipath { + iscsiByIQN := map[string][]*control.FrontendTarget{} + iscsiOrder := []string{} + for _, ft := range resp.GetFrontends() { + if ft == nil { + continue + } + if ft.GetProtocol() != string(ProtocolISCSI) || ft.GetAddr() == "" || ft.GetIqn() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback) { + continue + } + if _, ok := iscsiByIQN[ft.GetIqn()]; !ok { + iscsiOrder = append(iscsiOrder, ft.GetIqn()) + } + iscsiByIQN[ft.GetIqn()] = append(iscsiByIQN[ft.GetIqn()], ft) } - switch ft.GetProtocol() { - case string(ProtocolISCSI): - if ft.GetAddr() == "" || ft.GetIqn() == "" { + for _, iqn := range iscsiOrder { + frontends := iscsiByIQN[iqn] + if len(frontends) == 0 { + continue + } + out := base + out.Protocol = ProtocolISCSI + out.ISCSIAddr = frontends[0].GetAddr() + out.IQN = iqn + out.LUN = frontends[0].GetLun() + if len(frontends) > 1 { + out.Multipath = true + for _, ft := range frontends { + out.ISCSIAddrs = append(out.ISCSIAddrs, ft.GetAddr()) + } + } + return out, true + } + } else { + for _, ft := range resp.GetFrontends() { + if ft == nil || ft.GetProtocol() != string(ProtocolISCSI) || ft.GetAddr() == "" || ft.GetIqn() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback) { continue } out := base @@ -104,17 +192,36 @@ func publishTargetFromStatus(resp *control.StatusResponse) (PublishTarget, bool) out.IQN = ft.GetIqn() out.LUN = ft.GetLun() return out, true - case string(ProtocolNVMe): - if ft.GetAddr() == "" || ft.GetNqn() == "" { - continue - } - out := base - out.Protocol = ProtocolNVMe - out.NVMeAddr = ft.GetAddr() - out.NQN = ft.GetNqn() - out.NSID = ft.GetNsid() - return out, true } } + for _, ft := range resp.GetFrontends() { + if ft == nil || ft.GetProtocol() != string(ProtocolNVMe) || ft.GetAddr() == "" || ft.GetNqn() == "" || rejectFrontendAddr(ft.GetAddr(), rejectLoopback) { + continue + } + out := base + out.Protocol = ProtocolNVMe + out.NVMeAddr = ft.GetAddr() + out.NQN = ft.GetNqn() + out.NSID = ft.GetNsid() + return out, true + } return PublishTarget{}, false } + +func rejectFrontendAddr(addr string, rejectLoopback bool) bool { + if !rejectLoopback { + return false + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return true + } + if host == "" { + return true + } + ip := net.ParseIP(host) + if ip == nil { + return false + } + return ip.IsLoopback() +} diff --git a/seaweed-block/core/csi/master_backend_test.go b/seaweed-block/core/csi/master_backend_test.go index 288266f2db..8037b6b3e8 100644 --- a/seaweed-block/core/csi/master_backend_test.go +++ b/seaweed-block/core/csi/master_backend_test.go @@ -23,11 +23,53 @@ func (f *fakeEvidenceClient) QueryVolumeStatus(_ context.Context, req *control.S return f.resp, nil } +type fakeObservationClient struct { + event *control.ClusterEvent + err error +} + +func (f *fakeObservationClient) ReportHeartbeat(context.Context, *control.HeartbeatReport, ...grpc.CallOption) (*control.HeartbeatAck, error) { + return &control.HeartbeatAck{}, nil +} + +func (f *fakeObservationClient) ReportClusterEvent(_ context.Context, event *control.ClusterEvent, _ ...grpc.CallOption) (*control.ClusterEventAck, error) { + f.event = event + if f.err != nil { + return nil, f.err + } + return &control.ClusterEventAck{EventId: "master-1"}, nil +} + +func TestControlEventReporter_ReportsClusterEvent(t *testing.T) { + client := &fakeObservationClient{} + reporter := NewControlEventReporter(client) + + err := reporter.ReportEvent(context.Background(), ClusterEvent{ + VolumeID: "v1", + ReplicaID: "r2", + NodeName: "node-a", + Type: EventTypeCSIReattachObserved, + Severity: EventSeverityInfo, + Reason: EventTypeCSIReattachObserved, + NewValue: "127.0.0.1:3261", + Epoch: 2, + EndpointVersion: 1, + }) + if err != nil { + t.Fatalf("ReportEvent: %v", err) + } + if client.event.GetEventType() != EventTypeCSIReattachObserved || client.event.GetReplicaId() != "r2" || client.event.GetEpoch() != 2 { + t.Fatalf("event=%+v", client.event) + } +} + func TestControlStatusLookup_MapsISCSIStatusFrontend(t *testing.T) { client := &fakeEvidenceClient{resp: &control.StatusResponse{ - VolumeId: "v1", - ReplicaId: "r1", - Assigned: true, + VolumeId: "v1", + ReplicaId: "r1", + Epoch: 7, + EndpointVersion: 3, + Assigned: true, Frontends: []*control.FrontendTarget{{ Protocol: "iscsi", Addr: "127.0.0.1:3260", @@ -35,7 +77,7 @@ func TestControlStatusLookup_MapsISCSIStatusFrontend(t *testing.T) { Lun: 3, }}, }} - lookup := NewControlStatusLookup(client) + lookup := NewControlStatusLookupWithMultipath(client) got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") if err != nil { @@ -44,11 +86,200 @@ func TestControlStatusLookup_MapsISCSIStatusFrontend(t *testing.T) { if got.Protocol != ProtocolISCSI || got.ISCSIAddr != "127.0.0.1:3260" || got.IQN != "iqn.2026-05.example:v1" || got.LUN != 3 { t.Fatalf("target=%+v", got) } + if got.Epoch != 7 || got.EndpointVersion != 3 { + t.Fatalf("target generation=(%d,%d), want (7,3)", got.Epoch, got.EndpointVersion) + } if len(client.reqs) != 1 || client.reqs[0] != "v1" { t.Fatalf("status reqs=%v", client.reqs) } } +func TestControlStatusLookup_MapsMultipleISCSIFrontendsToMultipathTarget(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r2", + Epoch: 2, + EndpointVersion: 1, + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + {Protocol: "iscsi", Addr: "127.0.0.1:3261", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + }, + }} + lookup := NewControlStatusLookupWithMultipath(client) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if !got.Multipath { + t.Fatalf("multipath=false target=%+v", got) + } + if got.IQN != "iqn.2026-05.example:v1" || got.ISCSIAddr != "127.0.0.1:3260" { + t.Fatalf("target=%+v", got) + } + if len(got.ISCSIAddrs) != 2 || got.ISCSIAddrs[0] != "127.0.0.1:3260" || got.ISCSIAddrs[1] != "127.0.0.1:3261" { + t.Fatalf("ISCSIAddrs=%v", got.ISCSIAddrs) + } + ctx := publishContext(got) + if ctx["stage2_multipath"] != "true" { + t.Fatalf("publish_context missing multipath marker: %+v", ctx) + } + if ctx["iscsiAddrs"] != "127.0.0.1:3260,127.0.0.1:3261" { + t.Fatalf("iscsiAddrs=%q", ctx["iscsiAddrs"]) + } +} + +func TestControlStatusLookup_DoesNotMergeISCSIFrontendsWithDifferentIQN(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r2", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.example:v1-r1"}, + {Protocol: "iscsi", Addr: "127.0.0.1:3261", Iqn: "iqn.2026-05.example:v1-r2"}, + }, + }} + lookup := NewControlStatusLookupWithMultipath(client) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.Multipath || len(got.ISCSIAddrs) != 0 { + t.Fatalf("must not merge different IQNs into one multipath target: %+v", got) + } + if got.IQN != "iqn.2026-05.example:v1-r1" || got.ISCSIAddr != "127.0.0.1:3260" { + t.Fatalf("target=%+v", got) + } +} + +func TestControlStatusLookup_DefaultDoesNotEnableMultipath(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r2", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + {Protocol: "iscsi", Addr: "127.0.0.1:3261", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + }, + }} + lookup := NewControlStatusLookup(client) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.Multipath || len(got.ISCSIAddrs) != 0 { + t.Fatalf("default lookup must preserve single-path behavior: %+v", got) + } + if got.ISCSIAddr != "127.0.0.1:3260" || got.IQN != "iqn.2026-05.example:v1" { + t.Fatalf("target=%+v", got) + } +} + +func TestNodeLoss_ControlStatusLookup_UsesFirstRoutableFrontendAsCurrentPrimary(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r2", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "10.0.0.2:3260", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + {Protocol: "iscsi", Addr: "10.0.0.1:3260", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + {Protocol: "iscsi", Addr: "10.0.0.3:3260", Iqn: "iqn.2026-05.example:v1", Lun: 1}, + }, + }} + lookup := NewControlStatusLookupWithOptions(client, WithLoopbackPublishTargetsRejected()) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.Multipath || got.ISCSIAddr != "10.0.0.2:3260" || got.ReplicaID != "r2" { + t.Fatalf("target=%+v want promoted primary r2 first frontend", got) + } +} + +func TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r1", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.example:v1"}, + {Protocol: "iscsi", Addr: "10.0.0.12:3260", Iqn: "iqn.2026-05.example:v1"}, + }, + }} + lookup := NewControlStatusLookupWithOptions(client, WithLoopbackPublishTargetsRejected()) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.ISCSIAddr != "10.0.0.12:3260" { + t.Fatalf("iscsi addr=%q want non-loopback target", got.ISCSIAddr) + } +} + +func TestNodeLoss_ControlStatusLookup_AllowsHostnamePublishTargetsWhenLoopbackRejected(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r1", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "sw-blockvolume-r1.default.svc.cluster.local:3260", Iqn: "iqn.2026-05.example:v1"}, + }, + }} + lookup := NewControlStatusLookupWithOptions(client, WithLoopbackPublishTargetsRejected()) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.ISCSIAddr != "sw-blockvolume-r1.default.svc.cluster.local:3260" { + t.Fatalf("iscsi addr=%q want hostname target", got.ISCSIAddr) + } +} + +func TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets(t *testing.T) { + client := &fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r1", + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.example:v1"}, + }, + }} + lookup := NewControlStatusLookupWithOptions(client, WithLoopbackPublishTargetsRejected()) + + if _, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a"); !errors.Is(err, ErrPublishTargetNotFound) { + t.Fatalf("err=%v want ErrPublishTargetNotFound", err) + } +} + +func TestControlStatusLookup_CarriesGenerationEvidenceForGateOnly(t *testing.T) { + lookup := NewControlStatusLookup(&fakeEvidenceClient{resp: &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r2", + Epoch: 2, + EndpointVersion: 4, + Assigned: true, + Frontends: []*control.FrontendTarget{{ + Protocol: "iscsi", + Addr: "127.0.0.2:3260", + Iqn: "iqn.2026-05.example:v1-r2", + }}, + }}) + + got, err := lookup.LookupPublishTarget(context.Background(), "v1", "node-a") + if err != nil { + t.Fatalf("LookupPublishTarget: %v", err) + } + if got.ReplicaID != "r2" || got.Epoch != 2 || got.EndpointVersion != 4 { + t.Fatalf("target=%+v want r2@2/4", got) + } +} + func TestControlStatusLookup_FailClosedWithoutAssignedFrontend(t *testing.T) { tests := []struct { name string diff --git a/seaweed-block/core/csi/node.go b/seaweed-block/core/csi/node.go index 3960143108..25ea98c7ce 100644 --- a/seaweed-block/core/csi/node.go +++ b/seaweed-block/core/csi/node.go @@ -6,7 +6,9 @@ import ( "log" "os" "path/filepath" + "strings" "sync" + "time" csipb "github.com/container-storage-interface/spec/lib/go/csi" "google.golang.org/grpc/codes" @@ -21,13 +23,19 @@ const ( targetFile = ".target" ) +var ( + stage2MultipathPublishWait = 90 * time.Second + stage2MultipathPublishPoll = time.Second +) + type ISCSIUtil interface { Discovery(ctx context.Context, portal string) error ConfigureCHAP(ctx context.Context, iqn, portal string, auth ISCSIAuth) error Login(ctx context.Context, iqn, portal string) error Logout(ctx context.Context, iqn string) error - GetDeviceByIQN(ctx context.Context, iqn string) (string, error) - IsLoggedIn(ctx context.Context, iqn string) (bool, error) + GetDeviceByIQN(ctx context.Context, iqn, portal string) (string, error) + GetMultipathDeviceByIQN(ctx context.Context, iqn string, minPaths int) (string, error) + IsLoggedIn(ctx context.Context, iqn, portal string) (bool, error) RescanDevice(ctx context.Context, iqn string) error } @@ -53,6 +61,8 @@ type MountUtil interface { type stagedVolumeInfo struct { iqn string iscsiAddr string + iscsiAddrs []string + multipath bool nqn string nvmeAddr string transport string @@ -67,6 +77,8 @@ type NodeServer struct { iscsiUtil ISCSIUtil nvmeUtil NVMeUtil mountUtil MountUtil + lookup PublishTargetLookup + events EventReporter logger *log.Logger stagedMu sync.Mutex @@ -74,12 +86,14 @@ type NodeServer struct { } type NodeConfig struct { - NodeID string - IQNPrefix string - ISCSIUtil ISCSIUtil - NVMeUtil NVMeUtil - MountUtil MountUtil - Logger *log.Logger + NodeID string + IQNPrefix string + ISCSIUtil ISCSIUtil + NVMeUtil NVMeUtil + MountUtil MountUtil + Lookup PublishTargetLookup + EventReporter EventReporter + Logger *log.Logger } func NewNodeServer(cfg NodeConfig) *NodeServer { @@ -93,6 +107,8 @@ func NewNodeServer(cfg NodeConfig) *NodeServer { iscsiUtil: cfg.ISCSIUtil, nvmeUtil: cfg.NVMeUtil, mountUtil: cfg.MountUtil, + lookup: cfg.Lookup, + events: cfg.EventReporter, logger: lg, staged: make(map[string]*stagedVolumeInfo), } @@ -136,13 +152,27 @@ func (s *NodeServer) stageISCSI(ctx context.Context, req *csipb.NodeStageVolumeR if s.iscsiUtil == nil { return nil, status.Error(codes.FailedPrecondition, "iSCSI attach utility is not configured") } - portal, iqn := iscsiFromContext(req.GetPublishContext()) + publish := s.refreshPublishContext(ctx, volumeID, req.GetPublishContext()) + publishContext := publish.Context + multipathRequested := iscsiMultipathFromContext(req.GetPublishContext()) || iscsiMultipathFromContext(req.GetVolumeContext()) + if multipathRequested || iscsiMultipathFromContext(publishContext) { + publish = s.waitForISCSIMultipathPublishContext(ctx, volumeID, publish, 2) + publishContext = publish.Context + } + if multipathRequested && !iscsiMultipathFromContext(publishContext) { + publishContext = cloneStringMap(publishContext) + publishContext["stage2_multipath"] = "true" + publish.Context = publishContext + } + portal, iqn := iscsiFromContext(publishContext) + portals := iscsiPortalsFromContext(publishContext) auth := iscsiAuthFromContext(req.GetSecrets()) if auth == (ISCSIAuth{}) { - auth = iscsiAuthFromContext(req.GetPublishContext()) + auth = iscsiAuthFromContext(publishContext) } if portal == "" || iqn == "" { portal, iqn = iscsiFromContext(req.GetVolumeContext()) + portals = iscsiPortalsFromContext(req.GetVolumeContext()) if auth == (ISCSIAuth{}) { auth = iscsiAuthFromContext(req.GetVolumeContext()) } @@ -150,28 +180,41 @@ func (s *NodeServer) stageISCSI(ctx context.Context, req *csipb.NodeStageVolumeR if portal == "" || iqn == "" { return nil, status.Error(codes.FailedPrecondition, "no iSCSI publish target") } + if len(portals) == 0 { + portals = []string{portal} + } + multipath := iscsiMultipathFromContext(publishContext) + if !multipath { + multipath = iscsiMultipathFromContext(req.GetVolumeContext()) + } + if multipath && len(portals) < 2 { + return nil, status.Errorf(codes.FailedPrecondition, "iSCSI multipath requires at least two portals, got %d", len(portals)) + } if err := validateISCSIAuth(auth); err != nil { return nil, err } - loggedIn, err := s.iscsiUtil.IsLoggedIn(ctx, iqn) - if err != nil { - return nil, status.Errorf(codes.Internal, "check iscsi login: %v", err) - } - if loggedIn && !s.hasStagedIdentity(volumeID, stagingPath) { - return nil, status.Errorf(codes.FailedPrecondition, "iSCSI session for %q is already logged in without staged volume identity", iqn) - } loginStarted := false - if !loggedIn { - if err := s.iscsiUtil.Discovery(ctx, portal); err != nil { + for _, p := range portals { + loggedIn, err := s.iscsiUtil.IsLoggedIn(ctx, iqn, p) + if err != nil { + return nil, status.Errorf(codes.Internal, "check iscsi login: %v", err) + } + if loggedIn && !s.hasStagedIdentity(volumeID, stagingPath) { + return nil, status.Errorf(codes.FailedPrecondition, "iSCSI session for %q at %s is already logged in without staged volume identity", iqn, p) + } + if loggedIn { + continue + } + if err := s.iscsiUtil.Discovery(ctx, p); err != nil { return nil, status.Errorf(codes.Internal, "iscsi discovery: %v", err) } if auth.Secret != "" { - if err := s.iscsiUtil.ConfigureCHAP(ctx, iqn, portal, auth); err != nil { + if err := s.iscsiUtil.ConfigureCHAP(ctx, iqn, p, auth); err != nil { return nil, status.Errorf(codes.Internal, "iscsi chap config: %v", err) } } - if err := s.iscsiUtil.Login(ctx, iqn, portal); err != nil { + if err := s.iscsiUtil.Login(ctx, iqn, p); err != nil { return nil, status.Errorf(codes.Internal, "iscsi login: %v", err) } loginStarted = true @@ -184,7 +227,13 @@ func (s *NodeServer) stageISCSI(ctx context.Context, req *csipb.NodeStageVolumeR } }() - device, err := s.iscsiUtil.GetDeviceByIQN(ctx, iqn) + device := "" + var err error + if multipath { + device, err = s.iscsiUtil.GetMultipathDeviceByIQN(ctx, iqn, len(portals)) + } else { + device, err = s.iscsiUtil.GetDeviceByIQN(ctx, iqn, portal) + } if err != nil { return nil, status.Errorf(codes.Internal, "get device: %v", err) } @@ -215,13 +264,17 @@ func (s *NodeServer) stageISCSI(ctx context.Context, req *csipb.NodeStageVolumeR s.staged[volumeID] = &stagedVolumeInfo{ iqn: iqn, iscsiAddr: portal, + iscsiAddrs: append([]string(nil), portals...), + multipath: multipath, transport: transportISCSI, fsType: fsType, stagingPath: stagingPath, } s.stagedMu.Unlock() + s.logger.Printf("NodeStageVolume: %s staged transport=iscsi portal=%s portals=%s target=%s multipath=%v staging=%s", volumeID, portal, strings.Join(portals, ","), iqn, multipath, stagingPath) success = true + s.reportCSIReattachObserved(ctx, volumeID, transportISCSI, portal, publish) return &csipb.NodeStageVolumeResponse{}, nil } @@ -229,7 +282,9 @@ func (s *NodeServer) stageNVMe(ctx context.Context, req *csipb.NodeStageVolumeRe if s.nvmeUtil == nil { return nil, status.Error(codes.FailedPrecondition, "NVMe attach utility is not configured") } - addr, nqn := nvmeFromContext(req.GetPublishContext()) + publish := s.refreshPublishContext(ctx, volumeID, req.GetPublishContext()) + publishContext := publish.Context + addr, nqn := nvmeFromContext(publishContext) if addr == "" || nqn == "" { addr, nqn = nvmeFromContext(req.GetVolumeContext()) } @@ -294,10 +349,49 @@ func (s *NodeServer) stageNVMe(ctx context.Context, req *csipb.NodeStageVolumeRe } s.stagedMu.Unlock() + s.logger.Printf("NodeStageVolume: %s staged transport=nvme portal=%s target=%s staging=%s", volumeID, addr, nqn, stagingPath) success = true + s.reportCSIReattachObserved(ctx, volumeID, transportNVMe, addr, publish) return &csipb.NodeStageVolumeResponse{}, nil } +func (s *NodeServer) reportCSIReattachObserved(ctx context.Context, volumeID, transport, targetAddr string, publish publishContextResult) { + if s.events == nil { + return + } + event := ClusterEvent{ + VolumeID: volumeID, + NodeName: s.nodeID, + Type: EventTypeCSIReattachObserved, + Severity: EventSeverityInfo, + Reason: EventTypeCSIReattachObserved, + NewValue: targetAddr, + Message: fmt.Sprintf("CSI staged %s volume on node %s", transport, s.nodeID), + EvidenceRef: "csi-node", + } + if publish.HasTarget { + target := publish.Target + event.ReplicaID = target.ReplicaID + event.Epoch = target.Epoch + event.EndpointVersion = target.EndpointVersion + switch target.Protocol { + case ProtocolISCSI: + if target.ISCSIAddr != "" { + event.NewValue = target.ISCSIAddr + } + case ProtocolNVMe: + if target.NVMeAddr != "" { + event.NewValue = target.NVMeAddr + } + } + } + reportCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.events.ReportEvent(reportCtx, event); err != nil { + s.logger.Printf("NodeStageVolume: %s report %s failed: %v (non-fatal)", volumeID, EventTypeCSIReattachObserved, err) + } +} + func (s *NodeServer) NodeUnstageVolume(ctx context.Context, req *csipb.NodeUnstageVolumeRequest) (*csipb.NodeUnstageVolumeResponse, error) { volumeID := req.GetVolumeId() stagingPath := req.GetStagingTargetPath() @@ -449,9 +543,46 @@ func iscsiFromContext(ctx map[string]string) (portal, iqn string) { if ctx == nil { return "", "" } + portals := iscsiPortalsFromContext(ctx) + if len(portals) > 0 { + return portals[0], ctx["iqn"] + } return ctx["iscsiAddr"], ctx["iqn"] } +func iscsiPortalsFromContext(ctx map[string]string) []string { + if ctx == nil { + return nil + } + raw := ctx["iscsiAddrs"] + if raw == "" { + raw = ctx["iscsiAddr"] + } + var out []string + seen := map[string]bool{} + for _, part := range strings.Split(raw, ",") { + portal := strings.TrimSpace(part) + if portal == "" || seen[portal] { + continue + } + seen[portal] = true + out = append(out, portal) + } + return out +} + +func iscsiMultipathFromContext(ctx map[string]string) bool { + if ctx == nil { + return false + } + switch strings.ToLower(strings.TrimSpace(ctx["stage2_multipath"])) { + case "1", "true", "yes", "required": + return true + default: + return false + } +} + func nvmeFromContext(ctx map[string]string) (addr, nqn string) { if ctx == nil { return "", "" @@ -489,6 +620,79 @@ func iscsiAuthFromContext(ctx map[string]string) ISCSIAuth { } } +type publishContextResult struct { + Context map[string]string + Target PublishTarget + HasTarget bool +} + +func (s *NodeServer) refreshPublishContext(ctx context.Context, volumeID string, fallback map[string]string) publishContextResult { + result := publishContextResult{Context: fallback} + if s.lookup == nil || volumeID == "" { + return result + } + target, err := s.lookup.LookupPublishTarget(ctx, volumeID, s.nodeID) + if err != nil { + s.logger.Printf("NodeStageVolume: %s publish target refresh failed: %v", volumeID, err) + return result + } + refreshed := publishContext(target) + if len(refreshed) == 0 { + s.logger.Printf("NodeStageVolume: %s publish target refresh returned no attachable frontend", volumeID) + return result + } + return publishContextResult{Context: refreshed, Target: target, HasTarget: true} +} + +func (s *NodeServer) waitForISCSIMultipathPublishContext(ctx context.Context, volumeID string, current publishContextResult, minPortals int) publishContextResult { + if hasISCSIMultipathPortals(current.Context, minPortals) { + return current + } + if s.lookup == nil || volumeID == "" { + return current + } + deadline := time.NewTimer(stage2MultipathPublishWait) + defer deadline.Stop() + ticker := time.NewTicker(stage2MultipathPublishPoll) + defer ticker.Stop() + + for { + target, err := s.lookup.LookupPublishTarget(ctx, volumeID, s.nodeID) + if err != nil { + s.logger.Printf("NodeStageVolume: %s multipath publish target wait failed: %v", volumeID, err) + } else if refreshed := publishContext(target); len(refreshed) > 0 { + current = publishContextResult{Context: refreshed, Target: target, HasTarget: true} + if hasISCSIMultipathPortals(current.Context, minPortals) { + s.logger.Printf("NodeStageVolume: %s multipath publish target ready portals=%s", volumeID, strings.Join(iscsiPortalsFromContext(current.Context), ",")) + return current + } + if iscsiMultipathFromContext(current.Context) { + s.logger.Printf("NodeStageVolume: %s waiting for multipath publish target portals=%d want>=%d", volumeID, len(iscsiPortalsFromContext(current.Context)), minPortals) + } + } + + select { + case <-ctx.Done(): + return current + case <-deadline.C: + return current + case <-ticker.C: + } + } +} + +func hasISCSIMultipathPortals(ctx map[string]string, minPortals int) bool { + return iscsiMultipathFromContext(ctx) && len(iscsiPortalsFromContext(ctx)) >= minPortals +} + +func cloneStringMap(in map[string]string) map[string]string { + out := make(map[string]string, len(in)+1) + for k, v := range in { + out[k] = v + } + return out +} + func (s *NodeServer) validateMountedStagingVolume(volumeID, stagingPath string) error { s.stagedMu.Lock() info := s.staged[volumeID] diff --git a/seaweed-block/core/csi/node_test.go b/seaweed-block/core/csi/node_test.go index 28150f608d..587cbd590e 100644 --- a/seaweed-block/core/csi/node_test.go +++ b/seaweed-block/core/csi/node_test.go @@ -5,6 +5,7 @@ import ( "errors" "os" "path/filepath" + "strconv" "strings" "testing" @@ -14,18 +15,20 @@ import ( ) type mockISCSIUtil struct { - discoveryErr error - configureErr error - loginErr error - logoutErr error - getDeviceResult string - getDeviceErr error - loggedIn map[string]bool - calls []string + discoveryErr error + configureErr error + loginErr error + logoutErr error + getDeviceResult string + getDeviceErr error + multipathDeviceResult string + multipathDeviceErr error + loggedIn map[string]bool + calls []string } func newMockISCSIUtil() *mockISCSIUtil { - return &mockISCSIUtil{loggedIn: map[string]bool{}, getDeviceResult: "/dev/sda"} + return &mockISCSIUtil{loggedIn: map[string]bool{}, getDeviceResult: "/dev/sda", multipathDeviceResult: "/dev/mapper/mpatha"} } func (m *mockISCSIUtil) Discovery(_ context.Context, portal string) error { @@ -43,7 +46,7 @@ func (m *mockISCSIUtil) Login(_ context.Context, iqn, portal string) error { if m.loginErr != nil { return m.loginErr } - m.loggedIn[iqn] = true + m.loggedIn[iqn+"@"+portal] = true return nil } @@ -53,17 +56,27 @@ func (m *mockISCSIUtil) Logout(_ context.Context, iqn string) error { return m.logoutErr } delete(m.loggedIn, iqn) + for key := range m.loggedIn { + if strings.HasPrefix(key, iqn+"@") { + delete(m.loggedIn, key) + } + } return nil } -func (m *mockISCSIUtil) GetDeviceByIQN(_ context.Context, iqn string) (string, error) { - m.calls = append(m.calls, "getdevice:"+iqn) +func (m *mockISCSIUtil) GetDeviceByIQN(_ context.Context, iqn, portal string) (string, error) { + m.calls = append(m.calls, "getdevice:"+iqn+":"+portal) return m.getDeviceResult, m.getDeviceErr } -func (m *mockISCSIUtil) IsLoggedIn(_ context.Context, iqn string) (bool, error) { - m.calls = append(m.calls, "isloggedin:"+iqn) - return m.loggedIn[iqn], nil +func (m *mockISCSIUtil) GetMultipathDeviceByIQN(_ context.Context, iqn string, minPaths int) (string, error) { + m.calls = append(m.calls, "getmpath:"+iqn+":"+strconv.Itoa(minPaths)) + return m.multipathDeviceResult, m.multipathDeviceErr +} + +func (m *mockISCSIUtil) IsLoggedIn(_ context.Context, iqn, portal string) (bool, error) { + m.calls = append(m.calls, "isloggedin:"+iqn+":"+portal) + return m.loggedIn[iqn+"@"+portal], nil } func (m *mockISCSIUtil) RescanDevice(context.Context, string) error { return nil } @@ -175,6 +188,43 @@ func newTestNodeWithNVMe(mi *mockISCSIUtil, mn *mockNVMeUtil, mm *mockMountUtil) }) } +func newTestNodeWithLookup(mi *mockISCSIUtil, mm *mockMountUtil, lookup PublishTargetLookup) *NodeServer { + return NewNodeServer(NodeConfig{ + NodeID: "node-a", + IQNPrefix: "iqn.2026-05.example.v3", + ISCSIUtil: mi, + MountUtil: mm, + Lookup: lookup, + }) +} + +type recordingEventReporter struct { + events []ClusterEvent + err error +} + +func (r *recordingEventReporter) ReportEvent(_ context.Context, event ClusterEvent) error { + r.events = append(r.events, event) + return r.err +} + +type sequenceLookup struct { + targets []PublishTarget + calls []string +} + +func (s *sequenceLookup) LookupPublishTarget(_ context.Context, volumeID, nodeID string) (PublishTarget, error) { + s.calls = append(s.calls, volumeID+":"+nodeID) + if len(s.targets) == 0 { + return PublishTarget{}, ErrPublishTargetNotFound + } + target := s.targets[0] + if len(s.targets) > 1 { + s.targets = s.targets[1:] + } + return target, nil +} + func testVolumeCapability() *csipb.VolumeCapability { return &csipb.VolumeCapability{ AccessType: &csipb.VolumeCapability_Mount{ @@ -186,6 +236,312 @@ func testVolumeCapability() *csipb.VolumeCapability { } } +func TestNodeStage_RefreshesPublishTargetFromMasterLookup(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + lookup := &stubLookup{target: PublishTarget{ + VolumeID: "v1", + ReplicaID: "r2", + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.1:3261", + IQN: "iqn.2026-05.example.v3:v1-r2", + }} + ns := newTestNodeWithLookup(mi, mm, lookup) + staging := t.TempDir() + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: staging, + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "protocol": "iscsi", + "iscsiAddr": "127.0.0.1:3260", + "iqn": "iqn.2026-05.example.v3:v1-r1", + }, + }) + if err != nil { + t.Fatalf("NodeStageVolume: %v", err) + } + if got := readTargetFile(staging); got != "iqn.2026-05.example.v3:v1-r2" { + t.Fatalf("target file=%q want refreshed promoted target", got) + } + if got := ns.staged["v1"].iscsiAddr; got != "127.0.0.1:3261" { + t.Fatalf("staged portal=%q want refreshed promoted portal", got) + } + for _, want := range []string{ + "discovery:127.0.0.1:3261", + "login:iqn.2026-05.example.v3:v1-r2:127.0.0.1:3261", + } { + found := false + for _, call := range mi.calls { + if call == want { + found = true + break + } + } + if !found { + t.Fatalf("missing call %q in %v", want, mi.calls) + } + } + if len(lookup.calls) != 1 || lookup.calls[0] != "v1:node-a" { + t.Fatalf("lookup calls=%v want v1:node-a", lookup.calls) + } +} + +func TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + lookup := &sequenceLookup{targets: []PublishTarget{{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 2, + EndpointVersion: 1, + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.1:3261", + IQN: "iqn.lookup:v1", + }}} + reporter := &recordingEventReporter{} + ns := NewNodeServer(NodeConfig{ + NodeID: "node-a", + IQNPrefix: "iqn.2026-05.example.v3", + ISCSIUtil: mi, + MountUtil: mm, + Lookup: lookup, + EventReporter: reporter, + }) + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: t.TempDir(), + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "iscsiAddr": "127.0.0.1:3260", + "iqn": "iqn.stale:v1", + }, + }) + if err != nil { + t.Fatalf("NodeStageVolume: %v", err) + } + if len(reporter.events) != 1 { + t.Fatalf("events=%d want 1", len(reporter.events)) + } + event := reporter.events[0] + if event.Type != "csi_reattach_observed" || event.VolumeID != "v1" || event.ReplicaID != "r2" || event.NodeName != "node-a" { + t.Fatalf("event=%+v", event) + } + if event.Epoch != 2 || event.EndpointVersion != 1 { + t.Fatalf("event lineage epoch=%d ev=%d", event.Epoch, event.EndpointVersion) + } +} + +func TestNodeStage_UsesPortalSpecificISCSISessionAfterFailover(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + mi.loggedIn["iqn.2026-05.example.v3:v1@127.0.0.1:3260"] = true + lookup := &stubLookup{target: PublishTarget{ + VolumeID: "v1", + ReplicaID: "r2", + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.1:3261", + IQN: "iqn.2026-05.example.v3:v1", + }} + ns := newTestNodeWithLookup(mi, mm, lookup) + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: t.TempDir(), + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "protocol": "iscsi", + "iscsiAddr": "127.0.0.1:3260", + "iqn": "iqn.2026-05.example.v3:v1", + }, + }) + if err != nil { + t.Fatalf("NodeStageVolume: %v", err) + } + wantPrefix := []string{ + "isloggedin:iqn.2026-05.example.v3:v1:127.0.0.1:3261", + "discovery:127.0.0.1:3261", + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3261", + "getdevice:iqn.2026-05.example.v3:v1:127.0.0.1:3261", + } + for i, want := range wantPrefix { + if i >= len(mi.calls) || mi.calls[i] != want { + t.Fatalf("calls=%v want prefix=%v", mi.calls, wantPrefix) + } + } + if !mi.loggedIn["iqn.2026-05.example.v3:v1@127.0.0.1:3261"] { + t.Fatalf("promoted portal was not logged in; loggedIn=%v", mi.loggedIn) + } +} + +func TestNodeStage_MultipathISCSIRequiresAtLeastTwoPortals(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + ns := newTestNode(mi, mm) + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: t.TempDir(), + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "protocol": "iscsi", + "stage2_multipath": "true", + "iscsiAddr": "127.0.0.1:3260", + "iqn": "iqn.2026-05.example.v3:v1", + }, + }) + if err == nil { + t.Fatal("expected multipath stage to fail closed with one portal") + } + st, _ := status.FromError(err) + if st.Code() != codes.FailedPrecondition { + t.Fatalf("code=%v want FailedPrecondition err=%v", st.Code(), err) + } + if len(mi.calls) != 0 { + t.Fatalf("multipath single-portal refusal should happen before iscsi calls, got %v", mi.calls) + } +} + +func TestNodeStage_MultipathISCSILoginsAllPathsAndMountsMultipathDevice(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + ns := newTestNode(mi, mm) + staging := t.TempDir() + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: staging, + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "protocol": "iscsi", + "stage2_multipath": "true", + "iscsiAddrs": "127.0.0.1:3260,127.0.0.1:3261", + "iqn": "iqn.2026-05.example.v3:v1", + }, + }) + if err != nil { + t.Fatalf("NodeStageVolume: %v", err) + } + for _, want := range []string{ + "discovery:127.0.0.1:3260", + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3260", + "discovery:127.0.0.1:3261", + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3261", + "getmpath:iqn.2026-05.example.v3:v1:2", + } { + if !containsString(mi.calls, want) { + t.Fatalf("missing call %q in %v", want, mi.calls) + } + } + if !containsString(mm.calls, "formatandmount:/dev/mapper/mpatha:"+staging+":ext4") { + t.Fatalf("multipath stage must mount mapper device, calls=%v", mm.calls) + } + info := ns.staged["v1"] + if info == nil || !info.multipath { + t.Fatalf("staged info did not record multipath: %+v", info) + } + if got := strings.Join(info.iscsiAddrs, ","); got != "127.0.0.1:3260,127.0.0.1:3261" { + t.Fatalf("staged portals=%q", got) + } + if got := readTargetFile(staging); got != "iqn.2026-05.example.v3:v1" { + t.Fatalf("target file=%q", got) + } +} + +func TestNodeStage_MultipathISCSIWaitsForRefreshedMultiPortalTarget(t *testing.T) { + mi, mm := newMockISCSIUtil(), newMockMountUtil() + lookup := &sequenceLookup{targets: []PublishTarget{ + { + VolumeID: "v1", + ReplicaID: "r1", + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.1:3260", + IQN: "iqn.2026-05.example.v3:v1", + Multipath: true, + ISCSIAddrs: []string{"127.0.0.1:3260"}, + }, + { + VolumeID: "v1", + ReplicaID: "r1", + Protocol: ProtocolISCSI, + ISCSIAddr: "127.0.0.1:3260", + IQN: "iqn.2026-05.example.v3:v1", + Multipath: true, + ISCSIAddrs: []string{"127.0.0.1:3260", "127.0.0.1:3261", "127.0.0.1:3262"}, + }, + }} + ns := newTestNodeWithLookup(mi, mm, lookup) + staging := t.TempDir() + + _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ + VolumeId: "v1", + StagingTargetPath: staging, + VolumeCapability: testVolumeCapability(), + PublishContext: map[string]string{ + "protocol": "iscsi", + "stage2_multipath": "true", + "iscsiAddr": "127.0.0.1:3260", + "iqn": "iqn.2026-05.example.v3:v1", + }, + }) + if err != nil { + t.Fatalf("NodeStageVolume: %v", err) + } + for _, want := range []string{ + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3260", + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3261", + "login:iqn.2026-05.example.v3:v1:127.0.0.1:3262", + "getmpath:iqn.2026-05.example.v3:v1:3", + } { + if !containsString(mi.calls, want) { + t.Fatalf("missing call %q in %v", want, mi.calls) + } + } + if len(lookup.calls) < 2 { + t.Fatalf("lookup calls=%v, want initial refresh plus multipath wait refresh", lookup.calls) + } + info := ns.staged["v1"] + if info == nil || !info.multipath { + t.Fatalf("staged info did not record multipath: %+v", info) + } + if got := strings.Join(info.iscsiAddrs, ","); got != "127.0.0.1:3260,127.0.0.1:3261,127.0.0.1:3262" { + t.Fatalf("staged portals=%q", got) + } +} + +func containsString(items []string, want string) bool { + for _, item := range items { + if item == want { + return true + } + } + return false +} + +func TestISCSISessionContainsTargetMatchesIQNAndPortal(t *testing.T) { + out := strings.Join([]string{ + "tcp: [1] 127.0.0.1:3260,1 iqn.2026-05.example.v3:v1 (non-flash)", + "tcp: [2] 127.0.0.1:3261,1 iqn.2026-05.example.v3:v1 (non-flash)", + }, "\n") + if !iscsiSessionContainsTarget(out, "iqn.2026-05.example.v3:v1", "127.0.0.1:3261") { + t.Fatal("expected session match on promoted portal") + } + if iscsiSessionContainsTarget(out, "iqn.2026-05.example.v3:v1", "127.0.0.1:3262") { + t.Fatal("must not match a different portal for the same IQN") + } +} + +func TestISCSIByPathMatchesPortal(t *testing.T) { + for _, path := range []string{ + "/dev/disk/by-path/ip-127.0.0.1:3261-iscsi-iqn.2026-05.example.v3:v1-lun-1", + "/dev/disk/by-path/ip-127.0.0.1-3261-iscsi-iqn.2026-05.example.v3:v1-lun-1", + } { + if !iscsiByPathMatchesPortal(path, "127.0.0.1:3261") { + t.Fatalf("expected by-path match on promoted portal for %q", path) + } + } + if iscsiByPathMatchesPortal("/dev/disk/by-path/ip-127.0.0.1:3261-iscsi-iqn.2026-05.example.v3:v1-lun-1", "127.0.0.1:3260") { + t.Fatal("must not match by-path entry from a different portal") + } +} + func TestNodeStage_UsesPublishContextBeforeVolumeContext(t *testing.T) { mi, mm := newMockISCSIUtil(), newMockMountUtil() ns := newTestNode(mi, mm) @@ -310,11 +666,11 @@ func TestNodeStage_ConfiguresCHAPBeforeLogin(t *testing.T) { t.Fatalf("NodeStageVolume: %v", err) } want := []string{ - "isloggedin:iqn.v1", + "isloggedin:iqn.v1:127.0.0.1:3260", "discovery:127.0.0.1:3260", "chap:iqn.v1:127.0.0.1:3260:user1:secret1", "login:iqn.v1:127.0.0.1:3260", - "getdevice:iqn.v1", + "getdevice:iqn.v1:127.0.0.1:3260", } for i, w := range want { if i >= len(mi.calls) || mi.calls[i] != w { @@ -405,7 +761,7 @@ func TestNodeStage_FailsClosedWhenStagingPathMountedForAnotherVolume(t *testing. func TestNodeStage_FailsClosedOnStaleLoggedInSessionWithoutStagedIdentity(t *testing.T) { mi, mm := newMockISCSIUtil(), newMockMountUtil() - mi.loggedIn["iqn.v1"] = true + mi.loggedIn["iqn.v1@127.0.0.1:3260"] = true ns := newTestNode(mi, mm) _, err := ns.NodeStageVolume(context.Background(), &csipb.NodeStageVolumeRequest{ @@ -433,7 +789,7 @@ func TestNodeStage_FailsClosedOnStaleLoggedInSessionWithoutStagedIdentity(t *tes func TestNodeStage_AllowsLoggedInSessionWithRestartIdentityFile(t *testing.T) { mi, mm := newMockISCSIUtil(), newMockMountUtil() - mi.loggedIn["iqn.v1"] = true + mi.loggedIn["iqn.v1@127.0.0.1:3260"] = true ns := newTestNode(mi, mm) staging := t.TempDir() if err := writeVolumeFile(staging, "v1"); err != nil { @@ -456,8 +812,8 @@ func TestNodeStage_AllowsLoggedInSessionWithRestartIdentityFile(t *testing.T) { t.Fatalf("NodeStageVolume: %v", err) } wantPrefix := []string{ - "isloggedin:iqn.v1", - "getdevice:iqn.v1", + "isloggedin:iqn.v1:127.0.0.1:3260", + "getdevice:iqn.v1:127.0.0.1:3260", } for i, w := range wantPrefix { if i >= len(mi.calls) || mi.calls[i] != w { @@ -831,7 +1187,7 @@ func TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage(t *testing.T) { }); err != nil { t.Fatalf("NodeUnstageVolume: %v", err) } - if mi.loggedIn["iqn.2026-05.example.v3:v1-old"] { + if mi.loggedIn["iqn.2026-05.example.v3:v1-old@127.0.0.1:3260"] { t.Fatalf("old IQN still logged in after unstage") } if ns.staged["v1"] != nil { @@ -870,7 +1226,7 @@ func TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage(t *testing.T) { }); err != nil { t.Fatalf("second NodePublishVolume: %v", err) } - if !mi.loggedIn["iqn.2026-05.example.v3:v1-new"] { + if !mi.loggedIn["iqn.2026-05.example.v3:v1-new@127.0.0.2:3260"] { t.Fatalf("fresh IQN was not logged in after reattach; loggedIn=%v", mi.loggedIn) } if got := readTargetFile(staging); got != "iqn.2026-05.example.v3:v1-new" { diff --git a/seaweed-block/core/engine/promotion_ready.go b/seaweed-block/core/engine/promotion_ready.go new file mode 100644 index 0000000000..9f8f8f79e6 --- /dev/null +++ b/seaweed-block/core/engine/promotion_ready.go @@ -0,0 +1,48 @@ +package engine + +const ( + PromotionReadyReasonReady = "promotion_ready" + PromotionReadyReasonNotMember = "not_member" + PromotionReadyReasonNotReachable = "not_reachable" + PromotionReadyReasonNotCaughtUp = "not_caught_up" + PromotionReadyReasonFencePending = "fence_pending" + PromotionReadyReasonPostCloseAckNeeded = "post_close_durable_ack_needed" +) + +// PromotionReadyFact is a control-facing fact derived from the engine's truth +// domains. It intentionally does not reuse ReplicaProjection, which is +// operator-facing and must not be fed back into authority decisions. +type PromotionReadyFact struct { + Ready bool + Reason string + ReplicaID string + Epoch uint64 + EndpointVersion uint64 +} + +func BuildPromotionReadyFact(st *ReplicaState) PromotionReadyFact { + if st == nil { + return PromotionReadyFact{Reason: PromotionReadyReasonNotMember} + } + fact := PromotionReadyFact{ + Reason: PromotionReadyReasonReady, + ReplicaID: st.Identity.ReplicaID, + Epoch: st.Identity.Epoch, + EndpointVersion: st.Identity.EndpointVersion, + } + switch { + case !st.Identity.MemberPresent: + fact.Reason = PromotionReadyReasonNotMember + case st.Reachability.Status != ProbeReachable: + fact.Reason = PromotionReadyReasonNotReachable + case st.Recovery.Decision != DecisionNone: + fact.Reason = PromotionReadyReasonNotCaughtUp + case st.Identity.Epoch > st.Reachability.FencedEpoch: + fact.Reason = PromotionReadyReasonFencePending + case recoveredReplicaWaitingForPostCloseAck(st): + fact.Reason = PromotionReadyReasonPostCloseAckNeeded + default: + fact.Ready = true + } + return fact +} diff --git a/seaweed-block/core/engine/promotion_ready_test.go b/seaweed-block/core/engine/promotion_ready_test.go new file mode 100644 index 0000000000..69a37c85ef --- /dev/null +++ b/seaweed-block/core/engine/promotion_ready_test.go @@ -0,0 +1,76 @@ +package engine + +import "testing" + +func TestBuildPromotionReadyFact_ReadyOnlyFromTruthDomains(t *testing.T) { + st := promotionReadyState() + fact := BuildPromotionReadyFact(st) + if !fact.Ready { + t.Fatalf("fact should be ready: %+v", fact) + } + if fact.Reason != PromotionReadyReasonReady { + t.Fatalf("reason=%q want %q", fact.Reason, PromotionReadyReasonReady) + } + if fact.Epoch != 2 || fact.EndpointVersion != 3 || fact.ReplicaID != "r2" { + t.Fatalf("lineage mismatch: %+v", fact) + } +} + +func TestBuildPromotionReadyFact_RefusesPendingFence(t *testing.T) { + st := promotionReadyState() + st.Reachability.FencedEpoch = 1 + fact := BuildPromotionReadyFact(st) + if fact.Ready { + t.Fatalf("pending fence must not be promotion-ready: %+v", fact) + } + if fact.Reason != PromotionReadyReasonFencePending { + t.Fatalf("reason=%q want %q", fact.Reason, PromotionReadyReasonFencePending) + } +} + +func TestBuildPromotionReadyFact_RefusesPostCloseAckGap(t *testing.T) { + st := promotionReadyState() + st.Recovery.RecoveryWindowClosed = true + st.Recovery.PostCloseDurableAckKnown = false + fact := BuildPromotionReadyFact(st) + if fact.Ready { + t.Fatalf("post-close durable ack gap must not be promotion-ready: %+v", fact) + } + if fact.Reason != PromotionReadyReasonPostCloseAckNeeded { + t.Fatalf("reason=%q want %q", fact.Reason, PromotionReadyReasonPostCloseAckNeeded) + } +} + +func TestBuildPromotionReadyFact_RefusesNotCaughtUp(t *testing.T) { + st := promotionReadyState() + st.Recovery.Decision = DecisionCatchUp + fact := BuildPromotionReadyFact(st) + if fact.Ready { + t.Fatalf("catch-up decision must not be promotion-ready: %+v", fact) + } + if fact.Reason != PromotionReadyReasonNotCaughtUp { + t.Fatalf("reason=%q want %q", fact.Reason, PromotionReadyReasonNotCaughtUp) + } +} + +func promotionReadyState() *ReplicaState { + return &ReplicaState{ + Identity: IdentityTruth{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 2, + EndpointVersion: 3, + MemberPresent: true, + }, + Reachability: ReachabilityTruth{ + Status: ProbeReachable, + FencedEpoch: 2, + }, + Recovery: RecoveryTruth{ + Decision: DecisionNone, + DecisionReason: "caught_up", + RecoveryWindowClosed: true, + PostCloseDurableAckKnown: true, + }, + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 60bc842803..b1aa6d73ba 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -127,6 +127,10 @@ type VolumeStatus struct { EndpointVersion uint64 Latched bool Operational bool + FrontierKnown bool + DurableLSN uint64 + RetainedLSN uint64 + HeadLSN uint64 Evidence string Closed bool } @@ -197,12 +201,17 @@ func (p *DurableProvider) Open(ctx context.Context, volumeID string) (frontend.B proj := p.view.Projection() log.Printf("durable: dp.Open latching identity from projection volume=%s replica=%s epoch=%d ev=%d (post-waitHealthy)", proj.VolumeID, proj.ReplicaID, proj.Epoch, proj.EndpointVersion) - h.backend.SetIdentity(frontend.Identity{ + target := frontend.Identity{ VolumeID: proj.VolumeID, ReplicaID: proj.ReplicaID, Epoch: proj.Epoch, EndpointVersion: proj.EndpointVersion, - }) + } + if !h.backend.SetIdentity(target) { + if got := h.backend.Identity(); got != target { + return nil, durableIdentityConflict(got, target) + } + } return h.backend, nil } @@ -308,6 +317,47 @@ func (p *DurableProvider) Backend(volumeID string) *StorageBackend { return h.backend } +// LatchVolumeIdentity latches an already-open durable backend to the current +// projection lineage without requiring frontend Healthy. Supporting replicas +// intentionally remain frontend-unhealthy while the primary line names another +// replica, but they still need durable lineage evidence for promotion-readiness +// and support-bundle diagnostics. +func (p *DurableProvider) LatchVolumeIdentity(volumeID string) (bool, error) { + p.mu.Lock() + h, ok := p.volumes[volumeID] + p.mu.Unlock() + if !ok { + return false, ErrVolumeNotOpen + } + proj := p.view.Projection() + if proj.VolumeID != volumeID { + return false, fmt.Errorf("durable: projection volume %q does not match %q", proj.VolumeID, volumeID) + } + if proj.Epoch == 0 || proj.EndpointVersion == 0 { + return false, fmt.Errorf("durable: projection lineage missing for volume=%s replica=%s epoch=%d ev=%d", + proj.VolumeID, proj.ReplicaID, proj.Epoch, proj.EndpointVersion) + } + target := frontend.Identity{ + VolumeID: proj.VolumeID, + ReplicaID: proj.ReplicaID, + Epoch: proj.Epoch, + EndpointVersion: proj.EndpointVersion, + } + if h.backend.SetIdentity(target) { + return true, nil + } + if got := h.backend.Identity(); got != target { + return false, durableIdentityConflict(got, target) + } + return false, nil +} + +func durableIdentityConflict(got, want frontend.Identity) error { + return fmt.Errorf("durable: backend already latched to volume=%s replica=%s epoch=%d ev=%d; refusing projection volume=%s replica=%s epoch=%d ev=%d", + got.VolumeID, got.ReplicaID, got.Epoch, got.EndpointVersion, + want.VolumeID, want.ReplicaID, want.Epoch, want.EndpointVersion) +} + // DurableStatuses returns stable, sorted diagnostic snapshots for all opened // volume handles. This is used by status endpoints and TestOps gates to prove // durable lineage latching without scraping logs. diff --git a/seaweed-block/core/frontend/durable/provider_test.go b/seaweed-block/core/frontend/durable/provider_test.go index 88e2a14580..c387bec704 100644 --- a/seaweed-block/core/frontend/durable/provider_test.go +++ b/seaweed-block/core/frontend/durable/provider_test.go @@ -316,6 +316,200 @@ func TestDurableProvider_DurableStatuses_ReportLineageAndOperationalState(t *tes if after[0].Evidence == "" { t.Fatalf("status should include recovery evidence: %+v", after[0]) } + if !after[0].FrontierKnown { + t.Fatalf("status should expose storage frontier evidence: %+v", after[0]) + } + }) + } +} + +func TestDurableProvider_LatchVolumeIdentity_AfterEnsureStorageWithoutFrontendHealthy(t *testing.T) { + for _, impl := range implMatrix() { + impl := impl + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + view := newStubView(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Healthy: false, + }) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: impl, + StorageRoot: root, + BlockSize: 4096, + NumBlocks: 16, + }, view) + if err != nil { + t.Fatalf("NewDurableProvider: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatalf("EnsureStorage: %v", err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatalf("RecoverVolume: %v", err) + } + before := p.DurableStatuses() + if len(before) != 1 || before[0].Latched || !before[0].Operational { + t.Fatalf("pre-latch status should be operational but unlatched: %+v", before) + } + + view.set(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 3, + EndpointVersion: 2, + Healthy: false, // supporting replica remains frontend-gated + }) + latched, err := p.LatchVolumeIdentity("v1") + if err != nil { + t.Fatalf("LatchVolumeIdentity: %v", err) + } + if !latched { + t.Fatal("LatchVolumeIdentity should report a changed identity") + } + + after := p.DurableStatuses() + if len(after) != 1 { + t.Fatalf("status count=%d want 1: %+v", len(after), after) + } + if !after[0].Latched || !after[0].Operational { + t.Fatalf("post-latch status should be latched and operational: %+v", after[0]) + } + if after[0].ReplicaID != "r2" || after[0].Epoch != 3 || after[0].EndpointVersion != 2 { + t.Fatalf("post-latch lineage mismatch: %+v", after[0]) + } + }) + } +} + +func TestDurableProvider_LatchVolumeIdentity_AllowsSameReplicaAuthorityAdvance(t *testing.T) { + for _, impl := range implMatrix() { + impl := impl + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + view := newStubView(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Healthy: false, + }) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: impl, + StorageRoot: root, + BlockSize: 4096, + NumBlocks: 16, + }, view) + if err != nil { + t.Fatalf("NewDurableProvider: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatalf("EnsureStorage: %v", err) + } + view.set(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 3, + EndpointVersion: 2, + Healthy: false, + }) + latched, err := p.LatchVolumeIdentity("v1") + if err != nil { + t.Fatalf("LatchVolumeIdentity initial: %v", err) + } + if !latched { + t.Fatal("initial latch should change identity") + } + + view.set(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 4, + EndpointVersion: 3, + Healthy: false, + }) + latched, err = p.LatchVolumeIdentity("v1") + if err != nil { + t.Fatalf("LatchVolumeIdentity advance: %v", err) + } + if !latched { + t.Fatal("authority advance should report changed identity") + } + + statuses := p.DurableStatuses() + if len(statuses) != 1 { + t.Fatalf("status count=%d want 1: %+v", len(statuses), statuses) + } + if statuses[0].Epoch != 4 || statuses[0].EndpointVersion != 3 { + t.Fatalf("authority advance should update lineage: %+v", statuses[0]) + } + }) + } +} + +func TestDurableProvider_LatchVolumeIdentity_RejectsDifferentReplicaLineage(t *testing.T) { + for _, impl := range implMatrix() { + impl := impl + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + view := newStubView(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Healthy: false, + }) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: impl, + StorageRoot: root, + BlockSize: 4096, + NumBlocks: 16, + }, view) + if err != nil { + t.Fatalf("NewDurableProvider: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatalf("EnsureStorage: %v", err) + } + view.set(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r2", + Epoch: 3, + EndpointVersion: 2, + Healthy: false, + }) + latched, err := p.LatchVolumeIdentity("v1") + if err != nil { + t.Fatalf("LatchVolumeIdentity initial: %v", err) + } + if !latched { + t.Fatal("initial latch should change identity") + } + + view.set(frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r3", + Epoch: 4, + EndpointVersion: 1, + Healthy: false, + }) + latched, err = p.LatchVolumeIdentity("v1") + if err == nil { + t.Fatal("LatchVolumeIdentity should reject different replica lineage") + } + if latched { + t.Fatal("failed latch must not report changed identity") + } + + statuses := p.DurableStatuses() + if len(statuses) != 1 { + t.Fatalf("status count=%d want 1: %+v", len(statuses), statuses) + } + if statuses[0].ReplicaID != "r2" || statuses[0].Epoch != 3 || statuses[0].EndpointVersion != 2 { + t.Fatalf("rejected latch must preserve original lineage: %+v", statuses[0]) + } }) } } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 4b5ccb3669..8d100adb82 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -188,22 +188,18 @@ func (b *StorageBackend) Identity() frontend.Identity { // VolumeID/ReplicaID match is asserted but unchanged. // // Semantic: latch when Epoch is currently zero (transitions from -// pre-assignment to first authoritative lineage). Subsequent calls -// with a different lineage are REJECTED — drift past the latched -// value still fails closed via lineageCheck → ErrStalePrimary -// (failover safety net preserved). +// pre-assignment to first authoritative lineage). After that, only +// master-minted advances for the SAME volume/replica are accepted +// (epoch increase, or endpoint-version increase within the same +// epoch). Cross-volume, cross-replica, or backward lineage changes +// are rejected so old primaries still fail closed via lineageCheck → +// ErrStalePrimary. // -// Returns true if the latch took effect (Epoch was 0, now set). -// Returns false on no-op (already at this Epoch+EV) and on rejected -// drift (already latched to a different non-zero Epoch+EV). +// Returns true if the identity changed. Returns false on no-op and +// on rejected drift. func (b *StorageBackend) SetIdentity(id frontend.Identity) bool { b.mu.Lock() defer b.mu.Unlock() - // Reject drift past a non-zero latched Identity (preserves the - // failover safety net — lineage drift = ErrStalePrimary). - if b.id.Epoch != 0 || b.id.EndpointVersion != 0 { - return false - } // VolumeID/ReplicaID came from CLI config at backend construction // time and don't change; refuse silently if caller tries to install // a different volume/replica (paranoia — should never happen in @@ -212,7 +208,17 @@ func (b *StorageBackend) SetIdentity(id frontend.Identity) bool { (b.id.ReplicaID != "" && b.id.ReplicaID != id.ReplicaID) { return false } - // Latch. + if b.id == id { + return false + } + if b.id.Epoch != 0 || b.id.EndpointVersion != 0 { + if id.VolumeID != b.id.VolumeID || id.ReplicaID != b.id.ReplicaID { + return false + } + if id.Epoch < b.id.Epoch || (id.Epoch == b.id.Epoch && id.EndpointVersion <= b.id.EndpointVersion) { + return false + } + } b.id = id log.Printf("durable: StorageBackend.SetIdentity latched volume=%s replica=%s epoch=%d ev=%d", id.VolumeID, id.ReplicaID, id.Epoch, id.EndpointVersion) @@ -224,6 +230,7 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus id := b.id closed := b.closed b.mu.Unlock() + durableLSN, retainedLSN, headLSN := b.storage.Boundaries() evidence, _ := b.opEvidence.Load().(string) return VolumeStatus{ VolumeID: volumeID, @@ -234,6 +241,10 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus EndpointVersion: id.EndpointVersion, Latched: id.Epoch > 0 && id.EndpointVersion > 0, Operational: b.operational.Load(), + FrontierKnown: true, + DurableLSN: durableLSN, + RetainedLSN: retainedLSN, + HeadLSN: headLSN, Evidence: evidence, Closed: closed, } diff --git a/seaweed-block/core/frontend/durable/storage_adapter_test.go b/seaweed-block/core/frontend/durable/storage_adapter_test.go index 918ed895a7..3309517499 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter_test.go +++ b/seaweed-block/core/frontend/durable/storage_adapter_test.go @@ -521,9 +521,10 @@ func TestT3a_MatrixCoverage(t *testing.T) { // G5-5 test: SetIdentity latches a zero-Epoch backend (the // pre-assignment shape that EnsureStorage produces — VolumeID + -// ReplicaID set from CLI config, Epoch=0+EV=0). Drift past the -// latched value is rejected so lineageCheck fail-closed still -// catches failover. +// ReplicaID set from CLI config, Epoch=0+EV=0). Same-replica +// authority advances are accepted, while backward or cross-replica +// drift is rejected so lineageCheck fail-closed still catches stale +// writers. func TestG5_5_SetIdentity_LatchFromZeroEpoch(t *testing.T) { for _, f := range logicalStorageFactories() { f := f @@ -548,11 +549,26 @@ func TestG5_5_SetIdentity_LatchFromZeroEpoch(t *testing.T) { t.Error("SetIdentity after latch must return false") } id2 := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1} - if b.SetIdentity(id2) { - t.Error("SetIdentity drift must return false (lineageCheck still fail-closed)") + if !b.SetIdentity(id2) { + t.Error("SetIdentity same-replica epoch advance must return true") } - if got := b.Identity(); got != id1 { - t.Errorf("drift attempt mutated identity: got %+v want %+v", got, id1) + if got := b.Identity(); got != id2 { + t.Errorf("epoch advance did not mutate identity: got %+v want %+v", got, id2) + } + id3 := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2} + if !b.SetIdentity(id3) { + t.Error("SetIdentity same-epoch endpoint-version advance must return true") + } + idOld := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 9} + if b.SetIdentity(idOld) { + t.Error("SetIdentity backward epoch must return false") + } + idOtherReplica := frontend.Identity{VolumeID: "v1", ReplicaID: "r2", Epoch: 3, EndpointVersion: 1} + if b.SetIdentity(idOtherReplica) { + t.Error("SetIdentity cross-replica drift must return false") + } + if got := b.Identity(); got != id3 { + t.Errorf("rejected drift mutated identity: got %+v want %+v", got, id3) } }) } diff --git a/seaweed-block/core/host/bootstrap/bootstrap.go b/seaweed-block/core/host/bootstrap/bootstrap.go index 54525d24a0..2b6bf2c4a8 100644 --- a/seaweed-block/core/host/bootstrap/bootstrap.go +++ b/seaweed-block/core/host/bootstrap/bootstrap.go @@ -41,6 +41,11 @@ type DurableAuthorityBootstrap struct { ReloadSkips []error } +// Options customizes durable-authority bootstrap wiring. +type Options struct { + PublishObserver authority.PublishObserver +} + // Bootstrap performs the durable-authority startup sequence and // returns a *DurableAuthorityBootstrap that owns the live store, // lock, and Publisher. Fails closed if the lock cannot be @@ -54,6 +59,11 @@ type DurableAuthorityBootstrap struct { // The logs are the promised operator/startup visibility of // LoadErrors() — architect round-5 finding #3. func Bootstrap(storeDir string, directive authority.Directive) (*DurableAuthorityBootstrap, error) { + return BootstrapWithOptions(storeDir, directive, Options{}) +} + +// BootstrapWithOptions performs Bootstrap with optional observer hooks. +func BootstrapWithOptions(storeDir string, directive authority.Directive, opts Options) (*DurableAuthorityBootstrap, error) { if storeDir == "" { return nil, fmt.Errorf("sparrow: --authority-store is required for durable bootstrap") } @@ -70,7 +80,7 @@ func Bootstrap(storeDir string, directive authority.Directive) (*DurableAuthorit return nil, fmt.Errorf("durable authority store: %w", err) } - return bootstrapFromStoreLocked(storeDir, lock, store, directive) + return bootstrapFromStoreLocked(storeDir, lock, store, directive, opts) } // bootstrapFromStoreLocked performs the durable-authority bring- @@ -83,7 +93,7 @@ func Bootstrap(storeDir string, directive authority.Directive) (*DurableAuthorit // mocked store that produces an index-level failure on any // platform — a filesystem-permission-based approach is not // portable enough to reliably exercise the branch. -func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store authority.AuthorityStore, directive authority.Directive) (*DurableAuthorityBootstrap, error) { +func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store authority.AuthorityStore, directive authority.Directive, opts Options) (*DurableAuthorityBootstrap, error) { // Index-level pre-check BEFORE constructing the Publisher. // NewPublisher with a store panics on index-level reload // failure; without this pre-check Bootstrap would leave the @@ -102,7 +112,11 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store // same healthy index we just verified. Per-record corrupt // skips are still returned via Publisher.LoadErrors() and // logged below. - pub := authority.NewPublisher(directive, authority.WithStore(store)) + pubOpts := []authority.PublisherOption{authority.WithStore(store)} + if opts.PublishObserver != nil { + pubOpts = append(pubOpts, authority.WithPublishObserver(opts.PublishObserver)) + } + pub := authority.NewPublisher(directive, pubOpts...) // Publisher's LoadErrors is the canonical source; prefer it // when both available so we surface exactly what the @@ -135,7 +149,7 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store // lock is released and the store is closed before the error // returns. func BootstrapFromStore(lock *authority.StoreLock, store authority.AuthorityStore, directive authority.Directive) (*DurableAuthorityBootstrap, error) { - return bootstrapFromStoreLocked("", lock, store, directive) + return bootstrapFromStoreLocked("", lock, store, directive, Options{}) } // Close releases the lock and closes the store. Idempotent. diff --git a/seaweed-block/core/host/master/authority_request_bridge_test.go b/seaweed-block/core/host/master/authority_request_bridge_test.go index dbebcc678c..e6c15cd6df 100644 --- a/seaweed-block/core/host/master/authority_request_bridge_test.go +++ b/seaweed-block/core/host/master/authority_request_bridge_test.go @@ -167,3 +167,16 @@ func waitAuthorityLine(t *testing.T, pub *authority.Publisher, volumeID string) t.Fatalf("timeout waiting for authority line %s", volumeID) return authority.AuthorityBasis{} } + +func waitAuthorityReplica(t *testing.T, pub *authority.Publisher, volumeID, replicaID string) authority.AuthorityBasis { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if line, ok := pub.VolumeAuthorityLine(volumeID); ok && line.ReplicaID == replicaID { + return line + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("timeout waiting for authority line %s on replica %s", volumeID, replicaID) + return authority.AuthorityBasis{} +} diff --git a/seaweed-block/core/host/master/event_ring.go b/seaweed-block/core/host/master/event_ring.go new file mode 100644 index 0000000000..a029ffa7f8 --- /dev/null +++ b/seaweed-block/core/host/master/event_ring.go @@ -0,0 +1,138 @@ +package master + +import ( + "context" + "fmt" + "sort" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +type eventRing struct { + mu sync.Mutex + max int + nextID uint64 + events []ops.ClusterEvent + notify chan struct{} +} + +func newEventRing(max int) *eventRing { + if max <= 0 { + max = 512 + } + return &eventRing{max: max, notify: make(chan struct{})} +} + +func (r *eventRing) append(event ops.ClusterEvent) ops.ClusterEvent { + if r == nil { + return event + } + r.mu.Lock() + defer r.mu.Unlock() + r.nextID++ + if event.EventID == "" { + event.EventID = fmt.Sprintf("master-%d", r.nextID) + } + if event.EventTime.IsZero() { + event.EventTime = time.Now().UTC() + } else { + event.EventTime = event.EventTime.UTC() + } + r.events = append(r.events, event) + if len(r.events) > r.max { + r.events = append([]ops.ClusterEvent(nil), r.events[len(r.events)-r.max:]...) + } + close(r.notify) + r.notify = make(chan struct{}) + return event +} + +func (r *eventRing) list(volumeID string) []ops.ClusterEvent { + if r == nil { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + out := make([]ops.ClusterEvent, 0, len(r.events)) + for _, event := range r.events { + if volumeID == "" || event.VolumeID == "" || event.VolumeID == volumeID { + out = append(out, event) + } + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].EventTime.Equal(out[j].EventTime) { + return out[i].EventID < out[j].EventID + } + return out[i].EventTime.Before(out[j].EventTime) + }) + return out +} + +func (r *eventRing) listAfter(volumeID, sinceEventID string) []ops.ClusterEvent { + events := r.list(volumeID) + if sinceEventID == "" { + return events + } + for i, event := range events { + if event.EventID == sinceEventID { + return append([]ops.ClusterEvent(nil), events[i+1:]...) + } + } + // Unknown cursor: return all retained events rather than silently dropping + // evidence. Clients may de-duplicate by event_id. + return events +} + +func (r *eventRing) waitAfter(ctx context.Context, volumeID, sinceEventID string) ([]ops.ClusterEvent, error) { + if r == nil { + <-ctx.Done() + return nil, ctx.Err() + } + for { + events, notify := r.listAfterWithNotify(volumeID, sinceEventID) + if len(events) > 0 { + return events, nil + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-notify: + } + } +} + +func (r *eventRing) listAfterWithNotify(volumeID, sinceEventID string) ([]ops.ClusterEvent, <-chan struct{}) { + r.mu.Lock() + defer r.mu.Unlock() + out := make([]ops.ClusterEvent, 0, len(r.events)) + seenCursor := sinceEventID == "" + for _, event := range r.events { + if volumeID != "" && event.VolumeID != "" && event.VolumeID != volumeID { + continue + } + if !seenCursor { + if event.EventID == sinceEventID { + seenCursor = true + } + continue + } + out = append(out, event) + } + if sinceEventID != "" && !seenCursor { + out = out[:0] + for _, event := range r.events { + if volumeID == "" || event.VolumeID == "" || event.VolumeID == volumeID { + out = append(out, event) + } + } + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].EventTime.Equal(out[j].EventTime) { + return out[i].EventID < out[j].EventID + } + return out[i].EventTime.Before(out[j].EventTime) + }) + return out, r.notify +} diff --git a/seaweed-block/core/host/master/event_ring_test.go b/seaweed-block/core/host/master/event_ring_test.go new file mode 100644 index 0000000000..81fc0454db --- /dev/null +++ b/seaweed-block/core/host/master/event_ring_test.go @@ -0,0 +1,248 @@ +package master + +import ( + "context" + "io" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +func TestMasterTimeline_RecordsPlacementVerified(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + timeline, err := newServices(h).GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("timeline: %v", err) + } + if !timelineHasEvent(timeline.GetEvents(), "placement_verified", "placement_verified") { + t.Fatalf("timeline=%+v missing placement_verified", timeline.GetEvents()) + } +} + +func TestMasterTimeline_RecordsPromotionCandidateEvaluation(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "pvc-a") + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + CurrentKnown: true, + Current: PromotionCandidateEvidence{ + ReplicaID: initial.ReplicaID, + Ready: false, + DurableLSN: 52, + }, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + {ReplicaID: "r3", Ready: true, DurableLSN: 45}, + }, + }, + }) + ingestRF3ObservationForServersWithReady(t, h, "pvc-a", "m01", "m02", "tp01", + false, false, + true, true, + true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("failover product tick: %v", err) + } + + timeline, err := newServices(h).GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("timeline: %v", err) + } + if !timelineHasEvent(timeline.GetEvents(), "promotion_candidate_evaluated", "candidate_covers_required_frontier") { + t.Fatalf("timeline=%+v missing promotion-ready candidate event", timeline.GetEvents()) + } + if !timelineHasEvent(timeline.GetEvents(), "promotion_candidate_evaluated", "candidate_frontier_behind") { + t.Fatalf("timeline=%+v missing behind candidate event", timeline.GetEvents()) + } +} + +func TestMasterTimeline_RecordsAuthorityPublishedAfterMint(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + waitAuthorityLine(t, h.Publisher(), "pvc-a") + + timeline, err := newServices(h).GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("timeline: %v", err) + } + if !timelineHasEvent(timeline.GetEvents(), "authority_published", "candidate_covers_required_frontier") { + t.Fatalf("timeline=%+v missing authority_published", timeline.GetEvents()) + } +} + +func TestClusterEvidenceService_WatchClusterEventsCursor(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + waitAuthorityLine(t, h.Publisher(), "pvc-a") + + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc client: %v", err) + } + defer conn.Close() + client := control.NewClusterEvidenceServiceClient(conn) + + firstCtx, firstCancel := context.WithTimeout(context.Background(), 2*time.Second) + defer firstCancel() + first, err := client.WatchClusterEvents(firstCtx, &control.WatchClusterEventsRequest{}) + if err != nil { + t.Fatalf("first watch: %v", err) + } + firstEvents := drainWatchEvents(t, first) + if len(firstEvents) == 0 { + t.Fatal("first watch returned no events") + } + cursor := firstEvents[0].GetEventId() + + secondCtx, secondCancel := context.WithTimeout(context.Background(), 2*time.Second) + defer secondCancel() + second, err := client.WatchClusterEvents(secondCtx, &control.WatchClusterEventsRequest{SinceEventId: cursor}) + if err != nil { + t.Fatalf("second watch: %v", err) + } + secondEvents := drainWatchEvents(t, second) + for _, event := range secondEvents { + if event.GetEventId() == cursor { + t.Fatalf("cursor event replayed: %s in %+v", cursor, secondEvents) + } + } + if !containsEventType(secondEvents, "authority_published") { + t.Fatalf("events after cursor=%+v missing authority_published", secondEvents) + } +} + +func TestClusterEvidenceService_WatchClusterEventsStreamsNewEvents(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + waitAuthorityLine(t, h.Publisher(), "pvc-a") + + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc client: %v", err) + } + defer conn.Close() + client := control.NewClusterEvidenceServiceClient(conn) + + snapshot, err := client.GetClusterStatus(context.Background(), &control.GetClusterStatusRequest{}) + if err != nil { + t.Fatalf("cluster status: %v", err) + } + if len(snapshot.GetEvents()) == 0 { + t.Fatal("expected seeded events") + } + cursor := snapshot.GetEvents()[len(snapshot.GetEvents())-1].GetEventId() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + stream, err := client.WatchClusterEvents(ctx, &control.WatchClusterEventsRequest{SinceEventId: cursor}) + if err != nil { + t.Fatalf("watch: %v", err) + } + + if _, err := control.NewObservationServiceClient(conn).ReportClusterEvent(context.Background(), &control.ClusterEvent{ + EventType: "csi_reattach_observed", + Severity: "info", + VolumeId: "pvc-a", + NodeName: "m02", + NewValue: "10.0.0.2:3260", + }); err != nil { + t.Fatalf("report event: %v", err) + } + event, err := stream.Recv() + if err != nil { + t.Fatalf("recv new event: %v", err) + } + if event.GetEventType() != "csi_reattach_observed" || event.GetEventId() == "" { + t.Fatalf("event=%+v want streamed csi_reattach_observed with event_id", event) + } +} + +func timelineHasEvent(events []*control.ClusterEvent, eventType, reason string) bool { + for _, event := range events { + if event.GetEventType() == eventType && event.GetReasonCode() == reason && strings.TrimSpace(event.GetEventId()) != "" { + return true + } + } + return false +} + +func drainWatchEvents(t *testing.T, stream control.ClusterEvidenceService_WatchClusterEventsClient) []*control.ClusterEvent { + t.Helper() + var out []*control.ClusterEvent + for { + event, err := stream.Recv() + if err == io.EOF { + return out + } + if status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Canceled { + return out + } + if err != nil { + t.Fatalf("recv watch event: %v", err) + } + out = append(out, event) + } +} + +func containsEventType(events []*control.ClusterEvent, eventType string) bool { + for _, event := range events { + if event.GetEventType() == eventType { + return true + } + } + return false +} diff --git a/seaweed-block/core/host/master/frontend_status_test.go b/seaweed-block/core/host/master/frontend_status_test.go index 08bcaf33a7..8f0757dab8 100644 --- a/seaweed-block/core/host/master/frontend_status_test.go +++ b/seaweed-block/core/host/master/frontend_status_test.go @@ -41,6 +41,78 @@ func TestStatusFrontendsForAssignedLine_ReturnsObservedFrontendFacts(t *testing. } } +func TestStatusFrontendsForAssignedVolume_ReturnsObservedFrontendFactsForAllSlots(t *testing.T) { + obs := authority.NewObservationHost(authority.ObservationHostConfig{}) + for _, hb := range []authority.HeartbeatMessage{ + frontendHeartbeat("node-a", "v1", "r1", "127.0.0.1:3260"), + frontendHeartbeat("node-b", "v1", "r2", "127.0.0.1:3261"), + } { + if err := obs.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest heartbeat: %v", err) + } + } + + got := statusFrontendsForAssignedVolume(obs, "v1", []string{"r1", "r2"}, true) + if len(got) != 2 { + t.Fatalf("frontends=%d want 2", len(got)) + } + if got[0].GetAddr() != "127.0.0.1:3260" || got[1].GetAddr() != "127.0.0.1:3261" { + t.Fatalf("frontends=%+v", got) + } + if got[0].GetIqn() != "iqn.2026-05.example:v1" || got[1].GetIqn() != "iqn.2026-05.example:v1" { + t.Fatalf("frontends must preserve shared multipath IQN: %+v", got) + } +} + +func TestStatusFrontendsForAssignedVolume_DedupesRepeatedFacts(t *testing.T) { + obs := authority.NewObservationHost(authority.ObservationHostConfig{}) + hb := frontendHeartbeat("node-a", "v1", "r1", "127.0.0.1:3260") + hb.Slots = append(hb.Slots, hb.Slots[0]) + if err := obs.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest heartbeat: %v", err) + } + + got := statusFrontendsForAssignedVolume(obs, "v1", []string{"r1", "r1"}, true) + if len(got) != 1 { + t.Fatalf("frontends=%d want 1: %+v", len(got), got) + } +} + +func TestNodeLoss_PrimaryFirstReplicaIDsMovesPromotedReplicaFirst(t *testing.T) { + got := primaryFirstReplicaIDs([]string{"r1", "r2", "r3"}, "r2") + want := []string{"r2", "r1", "r3"} + if len(got) != len(want) { + t.Fatalf("len=%d want %d: %v", len(got), len(want), got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("order=%v want %v", got, want) + } + } +} + +func TestNodeLoss_StatusFrontendsForAssignedVolume_CurrentPrimaryFirstForCSIAttach(t *testing.T) { + obs := authority.NewObservationHost(authority.ObservationHostConfig{}) + for _, hb := range []authority.HeartbeatMessage{ + frontendHeartbeat("node-a", "v1", "r1", "10.0.0.1:3260"), + frontendHeartbeat("node-b", "v1", "r2", "10.0.0.2:3260"), + frontendHeartbeat("node-c", "v1", "r3", "10.0.0.3:3260"), + } { + if err := obs.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest heartbeat: %v", err) + } + } + + replicas := primaryFirstReplicaIDs([]string{"r1", "r2", "r3"}, "r2") + got := statusFrontendsForAssignedVolume(obs, "v1", replicas, true) + if len(got) != 3 { + t.Fatalf("frontends=%d want 3", len(got)) + } + if got[0].GetAddr() != "10.0.0.2:3260" { + t.Fatalf("first frontend=%q want promoted primary r2 address", got[0].GetAddr()) + } +} + func TestStatusFrontendsForAssignedLine_FailClosedWhenUnassignedOrMissing(t *testing.T) { obs := authority.NewObservationHost(authority.ObservationHostConfig{}) if got := statusFrontendsForAssignedLine(obs, "v1", "r1", false); len(got) != 0 { @@ -51,6 +123,27 @@ func TestStatusFrontendsForAssignedLine_FailClosedWhenUnassignedOrMissing(t *tes } } +func frontendHeartbeat(serverID, volumeID, replicaID, frontendAddr string) authority.HeartbeatMessage { + return authority.HeartbeatMessage{ + ServerID: serverID, + SentAt: time.Now().UTC(), + Reachable: true, + Eligible: true, + Slots: []authority.HeartbeatSlot{{ + VolumeID: volumeID, + ReplicaID: replicaID, + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", + Frontends: []authority.FrontendTargetFact{{ + Protocol: "iscsi", + Addr: frontendAddr, + IQN: "iqn.2026-05.example:" + volumeID, + LUN: 0, + }}, + }}, + } +} + func TestValidateHeartbeat_RejectsMalformedFrontendFacts(t *testing.T) { base := func(ft *controlFrontend) error { return validateHeartbeat(ft.report()) diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 2067b73b08..9369f0ce69 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -76,17 +76,20 @@ type LifecycleStores struct { // Host is the composed master-side block product daemon. Lifecycle // is: New -> Start -> (serve requests) -> Close. type Host struct { - cfg Config - log *log.Logger - boot *bootstrap.DurableAuthorityBootstrap - ctrl *authority.TopologyController - obs *authority.ObservationHost - ln net.Listener - grpc *grpc.Server - topo authority.AcceptedTopology - lifecycle *LifecycleStores - cancel context.CancelFunc - wg sync.WaitGroup + cfg Config + log *log.Logger + boot *bootstrap.DurableAuthorityBootstrap + ctrl *authority.TopologyController + obs *authority.ObservationHost + ln net.Listener + grpc *grpc.Server + topo authority.AcceptedTopology + lifecycle *LifecycleStores + events *eventRing + promotionMu sync.RWMutex + promotionProber PromotionEvidenceProvider + cancel context.CancelFunc + wg sync.WaitGroup started atomic.Bool } @@ -155,16 +158,35 @@ func New(cfg Config) (*Host, error) { holder := &publisherHolder{} ctrl := authority.NewTopologyController(cfg.ControllerConfig, holder) - boot, err := bootstrap.Bootstrap(cfg.AuthorityStoreDir, ctrl) + h := &Host{ + cfg: cfg, + log: lg, + ctrl: ctrl, + topo: cfg.Topology, + events: newEventRing(1024), + } + + boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ + PublishObserver: h.recordAuthorityPublishedEvent, + }) if err != nil { return nil, fmt.Errorf("master.New: Bootstrap: %w", err) } holder.set(boot.Publisher) + var sink authority.ControllerSink = ctrl + if len(cfg.Topology.Volumes) == 0 { + // Dynamic lifecycle volumes derive their accepted topology from + // placement intents in RunLifecycleProductTick. With no static + // topology configured, the observation host should collect facts + // but must not submit "unknown volume" reports that would clear + // lifecycle-driven desired authority. + sink = nil + } obs := authority.NewObservationHost(authority.ObservationHostConfig{ Freshness: cfg.Freshness, Topology: cfg.Topology, - Sink: ctrl, + Sink: sink, Reader: boot.Publisher, }) @@ -180,22 +202,17 @@ func New(cfg Config) (*Host, error) { return nil, fmt.Errorf("master.New: listen %q: %w", cfg.Listen, err) } - h := &Host{ - cfg: cfg, - log: lg, - boot: boot, - ctrl: ctrl, - obs: obs, - ln: ln, - topo: cfg.Topology, - lifecycle: lifecycleStores, - } + h.boot = boot + h.obs = obs + h.ln = ln + h.lifecycle = lifecycleStores grpcSrv := grpc.NewServer() svc := newServices(h) control.RegisterObservationServiceServer(grpcSrv, svc) control.RegisterAssignmentServiceServer(grpcSrv, svc) control.RegisterEvidenceServiceServer(grpcSrv, svc) + control.RegisterClusterEvidenceServiceServer(grpcSrv, svc) control.RegisterLifecycleServiceServer(grpcSrv, svc) h.grpc = grpcSrv diff --git a/seaweed-block/core/host/master/launcher_plan.go b/seaweed-block/core/host/master/launcher_plan.go index ca5fafb0cf..9af0fdacfd 100644 --- a/seaweed-block/core/host/master/launcher_plan.go +++ b/seaweed-block/core/host/master/launcher_plan.go @@ -64,11 +64,22 @@ func (h *Host) RunLifecycleWorkloadPlanTick(cfg lifecycle.WorkloadPlanConfig) (L } type workloadPortAllocator struct { - nextOrdinalByServer map[string]int + nextOrdinalByNode map[string]int + baseByNode map[string]nodePortBase +} + +type nodePortBase struct { + iscsi int + nvme int + data string + ctrl string } func newWorkloadPortAllocator() *workloadPortAllocator { - return &workloadPortAllocator{nextOrdinalByServer: make(map[string]int)} + return &workloadPortAllocator{ + nextOrdinalByNode: make(map[string]int), + baseByNode: make(map[string]nodePortBase), + } } func (a *workloadPortAllocator) assign(plan *lifecycle.BlockVolumeWorkloadPlan) { @@ -77,22 +88,29 @@ func (a *workloadPortAllocator) assign(plan *lifecycle.BlockVolumeWorkloadPlan) } for i := range plan.Replicas { replica := &plan.Replicas[i] - ordinal := a.nextOrdinalByServer[replica.ServerID] - a.nextOrdinalByServer[replica.ServerID] = ordinal + 1 - shiftReplicaNodeLocalPorts(replica, ordinal) + key := replica.KubernetesNodeName + if key == "" { + key = replica.ServerID + } + base, ok := a.baseByNode[key] + if !ok { + base = nodePortBase{ + iscsi: replica.ISCSIListenPort - i, + nvme: replica.NVMeListenPort - i, + data: replica.DataAddr, + ctrl: replica.CtrlAddr, + } + a.baseByNode[key] = base + } + ordinal := a.nextOrdinalByNode[key] + a.nextOrdinalByNode[key] = ordinal + 1 + replica.ISCSIListenPort = base.iscsi + ordinal + replica.NVMeListenPort = base.nvme + ordinal + replica.DataAddr = addPortOffset(base.data, ordinal*2) + replica.CtrlAddr = addPortOffset(base.ctrl, ordinal*2) } } -func shiftReplicaNodeLocalPorts(replica *lifecycle.BlockVolumeReplicaWorkload, ordinal int) { - if replica == nil || ordinal <= 0 { - return - } - replica.ISCSIListenPort += ordinal - replica.NVMeListenPort += ordinal - replica.DataAddr = addPortOffset(replica.DataAddr, ordinal*2) - replica.CtrlAddr = addPortOffset(replica.CtrlAddr, ordinal*2) -} - func addPortOffset(addr string, offset int) string { if addr == "" || offset == 0 { return addr diff --git a/seaweed-block/core/host/master/launcher_plan_test.go b/seaweed-block/core/host/master/launcher_plan_test.go index ebcc0f4633..fe59acb845 100644 --- a/seaweed-block/core/host/master/launcher_plan_test.go +++ b/seaweed-block/core/host/master/launcher_plan_test.go @@ -3,6 +3,7 @@ package master import ( "testing" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" ) @@ -125,6 +126,289 @@ func TestG15d_WorkloadPlanTickAllocatesDistinctNodeLocalPortsAcrossVolumes(t *te } } +func TestMountedFailover_WorkloadPlanSupportsLogicalServersOnOneKubernetesNode(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-rf2", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }); err != nil { + t.Fatalf("create volume: %v", err) + } + for _, reg := range []lifecycle.NodeRegistration{ + { + ServerID: "m02-r1", + DataAddr: "127.0.0.1:19101", + CtrlAddr: "127.0.0.1:19102", + Labels: map[string]string{ + lifecycle.KubernetesNodeNameLabel: "m02", + }, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r1", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }, + { + ServerID: "m02-r2", + DataAddr: "127.0.0.1:19103", + CtrlAddr: "127.0.0.1:19104", + Labels: map[string]string{ + lifecycle.KubernetesNodeNameLabel: "m02", + }, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r2", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }, + } { + if _, err := stores.Nodes.RegisterNode(reg); err != nil { + t.Fatalf("register node %s: %v", reg.ServerID, err) + } + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + result, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{ + ISCSIPortBase: 3260, + NVMePortBase: 4420, + }) + if err != nil { + t.Fatalf("workload plan tick: %v", err) + } + if len(result.Plans) != 1 || len(result.Plans[0].Replicas) != 2 { + t.Fatalf("plans=%+v want one RF2 workload plan", result.Plans) + } + for _, replica := range result.Plans[0].Replicas { + if replica.KubernetesNodeName != "m02" { + t.Fatalf("replica %s kube node=%q want m02", replica.ReplicaID, replica.KubernetesNodeName) + } + if replica.ServerID == replica.KubernetesNodeName { + t.Fatalf("replica %s collapsed server identity into k8s node name", replica.ReplicaID) + } + } +} + +func TestMountedFailover_WorkloadPlanAllocatesPortsByKubernetesNode(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + for _, volumeID := range []string{"pvc-rf2-a", "pvc-rf2-b"} { + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: volumeID, + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }); err != nil { + t.Fatalf("create volume %s: %v", volumeID, err) + } + } + for _, reg := range []lifecycle.NodeRegistration{ + { + ServerID: "m02-r1", + DataAddr: "127.0.0.1:19101", + CtrlAddr: "127.0.0.1:19102", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "m02"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + { + ServerID: "m02-r2", + DataAddr: "127.0.0.1:19103", + CtrlAddr: "127.0.0.1:19104", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "m02"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r2", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + } { + if _, err := stores.Nodes.RegisterNode(reg); err != nil { + t.Fatalf("register node %s: %v", reg.ServerID, err) + } + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + result, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{ + ISCSIPortBase: 3260, + NVMePortBase: 4420, + }) + if err != nil { + t.Fatalf("workload plan tick: %v", err) + } + var ports []int + for _, plan := range result.Plans { + for _, replica := range plan.Replicas { + ports = append(ports, replica.ISCSIListenPort) + if replica.KubernetesNodeName != "m02" { + t.Fatalf("replica %s kube node=%q want m02", replica.ReplicaID, replica.KubernetesNodeName) + } + } + } + if len(ports) != 4 { + t.Fatalf("ports=%v want four RF2 replicas across two volumes", ports) + } + want := map[int]bool{3260: true, 3261: true, 3262: true, 3263: true} + for _, port := range ports { + if !want[port] { + t.Fatalf("unexpected or duplicate host-network port %d in %v", port, ports) + } + delete(want, port) + } + if len(want) != 0 { + t.Fatalf("missing expected ports: %v from got %v", want, ports) + } +} + +func TestMountedFailover_WorkloadPlanAllocatesPortsByPhysicalNodeAcrossRF2Volumes(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + for _, volumeID := range []string{"pvc-rf2-a", "pvc-rf2-b"} { + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: volumeID, + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }); err != nil { + t.Fatalf("create volume %s: %v", volumeID, err) + } + } + for _, reg := range []lifecycle.NodeRegistration{ + { + ServerID: "node-a", + DataAddr: "10.0.0.1:19101", + CtrlAddr: "10.0.0.1:19102", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "k8s-a"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "pool-a", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + { + ServerID: "node-b", + DataAddr: "10.0.0.2:19101", + CtrlAddr: "10.0.0.2:19102", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "k8s-b"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "pool-b", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + } { + if _, err := stores.Nodes.RegisterNode(reg); err != nil { + t.Fatalf("register node %s: %v", reg.ServerID, err) + } + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + result, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{ + ISCSIPortBase: 3260, + NVMePortBase: 4420, + }) + if err != nil { + t.Fatalf("workload plan tick: %v", err) + } + portsByNode := map[string]map[int]bool{} + dataByNode := map[string]map[string]bool{} + for _, plan := range result.Plans { + for _, replica := range plan.Replicas { + node := replica.KubernetesNodeName + if portsByNode[node] == nil { + portsByNode[node] = map[int]bool{} + dataByNode[node] = map[string]bool{} + } + if portsByNode[node][replica.ISCSIListenPort] { + t.Fatalf("duplicate iscsi port %d on node %s", replica.ISCSIListenPort, node) + } + portsByNode[node][replica.ISCSIListenPort] = true + if dataByNode[node][replica.DataAddr] { + t.Fatalf("duplicate data addr %s on node %s", replica.DataAddr, node) + } + dataByNode[node][replica.DataAddr] = true + } + } + for _, node := range []string{"k8s-a", "k8s-b"} { + for _, want := range []int{3260, 3261} { + if !portsByNode[node][want] { + t.Fatalf("node %s ports=%v missing %d", node, portsByNode[node], want) + } + } + } +} + +func TestMountedFailover_ProductTickPreservesMaterializedRF2Placement(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 2, + }) + defer closeTestMaster(t, h) + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-rf2", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }); err != nil { + t.Fatalf("create volume: %v", err) + } + for _, reg := range []lifecycle.NodeRegistration{ + { + ServerID: "m02-r1", + DataAddr: "127.0.0.1:19101", + CtrlAddr: "127.0.0.1:19102", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "m02"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + { + ServerID: "m02-r2", + DataAddr: "127.0.0.1:19103", + CtrlAddr: "127.0.0.1:19104", + Labels: map[string]string{lifecycle.KubernetesNodeNameLabel: "m02"}, + Pools: []lifecycle.StoragePool{{ + PoolID: "default-r2", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096, + }}, + }, + } { + if _, err := stores.Nodes.RegisterNode(reg); err != nil { + t.Fatalf("register node %s: %v", reg.ServerID, err) + } + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + if _, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{}); err != nil { + t.Fatalf("workload plan tick: %v", err) + } + before, ok := stores.Placements.GetPlacement("pvc-rf2") + if !ok { + t.Fatal("missing materialized placement") + } + for _, slot := range before.Slots { + if slot.Source != lifecycle.PlacementSourceExistingReplica || slot.ReplicaID == "" { + t.Fatalf("placement not materialized before product tick: %+v", before) + } + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("second product tick: %v", err) + } + after, ok := stores.Placements.GetPlacement("pvc-rf2") + if !ok { + t.Fatal("placement disappeared") + } + for _, slot := range after.Slots { + if slot.Source != lifecycle.PlacementSourceExistingReplica || slot.ReplicaID == "" { + t.Fatalf("product tick overwrote materialized placement: before=%+v after=%+v", before, after) + } + } +} + func TestG15d_ReplicaSlotsForFallsBackToLifecyclePlacement(t *testing.T) { h := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, h) diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index 4cbbc29a0d..61bfa48d24 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -186,6 +186,21 @@ func newTestMaster(t *testing.T, lifecycleDir string) *Host { return h } +func newTestMasterWithControllerConfig(t *testing.T, lifecycleDir string, controller authority.TopologyControllerConfig) *Host { + t.Helper() + h, err := New(Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: lifecycleDir, + Listen: "127.0.0.1:0", + ControllerConfig: controller, + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + return h +} + type parsedStruct struct { Fields map[string]struct{} } diff --git a/seaweed-block/core/host/master/observation_service.go b/seaweed-block/core/host/master/observation_service.go new file mode 100644 index 0000000000..229843dd2f --- /dev/null +++ b/seaweed-block/core/host/master/observation_service.go @@ -0,0 +1,293 @@ +package master + +import ( + "context" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func (s *services) GetClusterStatus(ctx context.Context, req *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + cluster := s.host.ObservationSnapshot(time.Now().UTC()) + return clusterEvidenceToWire(cluster), nil +} + +func (s *services) ListVolumes(ctx context.Context, req *control.ListVolumesRequest) (*control.ListVolumesResponse, error) { + cluster := s.host.ObservationSnapshot(time.Now().UTC()) + out := &control.ListVolumesResponse{ + SchemaVersion: cluster.SchemaVersion, + CapturedAt: timestampOrNil(cluster.CapturedAt), + Volumes: make([]*control.VolumeEvidence, 0, len(cluster.Volumes)), + } + for _, volume := range cluster.Volumes { + out.Volumes = append(out.Volumes, volumeEvidenceToWire(volume)) + } + return out, nil +} + +func (s *services) GetVolumeStatus(ctx context.Context, req *control.GetVolumeStatusRequest) (*control.VolumeEvidence, error) { + if req.GetVolumeId() == "" { + return nil, status.Error(codes.InvalidArgument, "volume_id is required") + } + cluster := s.host.ObservationSnapshot(time.Now().UTC()) + for _, volume := range cluster.Volumes { + if volume.VolumeID == req.GetVolumeId() { + return volumeEvidenceToWire(volume), nil + } + } + return nil, status.Errorf(codes.NotFound, "volume %q not found", req.GetVolumeId()) +} + +func (s *services) GetVolumeTimeline(ctx context.Context, req *control.GetVolumeTimelineRequest) (*control.VolumeTimelineResponse, error) { + if req.GetVolumeId() == "" { + return nil, status.Error(codes.InvalidArgument, "volume_id is required") + } + cluster := s.host.ObservationSnapshot(time.Now().UTC()) + out := &control.VolumeTimelineResponse{ + SchemaVersion: cluster.SchemaVersion, + CapturedAt: timestampOrNil(cluster.CapturedAt), + VolumeId: req.GetVolumeId(), + } + for _, event := range cluster.Events { + if event.VolumeID == "" || event.VolumeID == req.GetVolumeId() { + out.Events = append(out.Events, clusterEventToWire(event)) + } + } + return out, nil +} + +func (s *services) WatchClusterEvents(req *control.WatchClusterEventsRequest, stream control.ClusterEvidenceService_WatchClusterEventsServer) error { + cursor := req.GetSinceEventId() + for { + events, err := s.host.events.waitAfter(stream.Context(), "", cursor) + if err != nil { + return err + } + for _, event := range events { + if err := stream.Send(clusterEventToWire(event)); err != nil { + return err + } + cursor = event.EventID + } + } +} + +func (s *services) ReportClusterEvent(ctx context.Context, req *control.ClusterEvent) (*control.ClusterEventAck, error) { + if err := validateExternalClusterEvent(req); err != nil { + return nil, err + } + event := externalClusterEventFromWire(req) + event = s.host.events.append(event) + return &control.ClusterEventAck{ + AcceptedAt: timestamppb.Now(), + EventId: event.EventID, + }, nil +} + +func validateExternalClusterEvent(req *control.ClusterEvent) error { + if req == nil { + return status.Error(codes.InvalidArgument, "event is required") + } + if req.GetEventType() == "" { + return status.Error(codes.InvalidArgument, "event_type is required") + } + if req.GetSeverity() == "" { + return status.Error(codes.InvalidArgument, "severity is required") + } + switch req.GetEventType() { + case ops.EventTypeCSIReattachObserved: + if req.GetVolumeId() == "" { + return status.Error(codes.InvalidArgument, "volume_id is required for csi_reattach_observed") + } + if req.GetNodeName() == "" { + return status.Error(codes.InvalidArgument, "node_name is required for csi_reattach_observed") + } + default: + return status.Errorf(codes.InvalidArgument, "event_type %q is not accepted from external observation clients", req.GetEventType()) + } + return nil +} + +func externalClusterEventFromWire(req *control.ClusterEvent) ops.ClusterEvent { + switch req.GetEventType() { + case ops.EventTypeCSIReattachObserved: + return ops.ClusterEvent{ + VolumeID: req.GetVolumeId(), + ReplicaID: req.GetReplicaId(), + NodeName: req.GetNodeName(), + Type: ops.EventTypeCSIReattachObserved, + Severity: req.GetSeverity(), + Message: "CSI staged volume on node", + Reason: ops.EventTypeCSIReattachObserved, + NewValue: req.GetNewValue(), + Epoch: req.GetEpoch(), + EndpointVersion: req.GetEndpointVersion(), + EvidenceRef: "csi-node", + } + default: + return ops.ClusterEvent{} + } +} + +func clusterEvidenceToWire(cluster ops.ClusterEvidence) *control.ClusterStatusResponse { + out := &control.ClusterStatusResponse{ + SchemaVersion: cluster.SchemaVersion, + CapturedAt: timestampOrNil(cluster.CapturedAt), + ProductRevision: cluster.ProductRevision, + Status: cluster.Status, + Nodes: make([]*control.NodeEvidence, 0, len(cluster.Nodes)), + Volumes: make([]*control.VolumeEvidence, 0, len(cluster.Volumes)), + Conditions: conditionsToWire(cluster.Conditions), + Events: make([]*control.ClusterEvent, 0, len(cluster.Events)), + NonClaims: append([]string(nil), cluster.NonClaims...), + } + for _, node := range cluster.Nodes { + out.Nodes = append(out.Nodes, nodeEvidenceToWire(node)) + } + for _, volume := range cluster.Volumes { + out.Volumes = append(out.Volumes, volumeEvidenceToWire(volume)) + } + for _, event := range cluster.Events { + out.Events = append(out.Events, clusterEventToWire(event)) + } + return out +} + +func nodeEvidenceToWire(node ops.NodeEvidence) *control.NodeEvidence { + return &control.NodeEvidence{ + NodeName: node.NodeName, + KubernetesNode: node.KubernetesNode, + PhysicalHost: node.PhysicalHost, + InternalIp: node.InternalIP, + Schedulable: node.Schedulable, + Ready: node.Ready, + LastHeartbeatAt: timestampOrNil(node.LastHeartbeatAt), + ReplicaCount: int32(node.ReplicaCount), + RequiredImages: append([]string(nil), node.RequiredImages...), + MissingImages: append([]string(nil), node.MissingImages...), + Conditions: conditionsToWire(node.Conditions), + } +} + +func volumeEvidenceToWire(volume ops.VolumeEvidence) *control.VolumeEvidence { + out := &control.VolumeEvidence{ + VolumeId: volume.VolumeID, + Namespace: volume.Namespace, + PvcName: volume.PVCName, + PvName: volume.PVName, + ReplicationFactor: int32(volume.ReplicationFactor), + AckProfile: volume.AckProfile, + ClaimProfile: volume.ClaimProfile, + DesiredReplicas: int32(volume.DesiredReplicas), + ObservedReplicas: int32(volume.ObservedReplicas), + Status: volume.Status, + Reason: volume.Reason, + PrimaryReplica: volume.PrimaryReplica, + PrimaryNode: volume.PrimaryNode, + PublishTarget: volume.PublishTarget, + Epoch: volume.Epoch, + EndpointVersion: volume.EndpointVersion, + Replicas: make([]*control.ReplicaEvidence, 0, len(volume.Replicas)), + Conditions: conditionsToWire(volume.Conditions), + NextActions: append([]string(nil), volume.NextActions...), + SupportBundleHint: volume.SupportBundleHint, + } + for _, replica := range volume.Replicas { + out.Replicas = append(out.Replicas, replicaEvidenceToWire(replica)) + } + return out +} + +func replicaEvidenceToWire(replica ops.ReplicaEvidence) *control.ReplicaEvidence { + return &control.ReplicaEvidence{ + ReplicaId: replica.ReplicaID, + ServerId: replica.ServerID, + KubernetesNode: replica.KubernetesNode, + PhysicalHost: replica.PhysicalHost, + Observed: replica.Observed, + Role: replica.Role, + ReplicationRole: replica.ReplicationRole, + DurableLatched: replica.DurableLatched, + DurableFrontierKnown: replica.DurableFrontierKnown, + DurableFrontierLsn: replica.DurableFrontierLSN, + CandidateReady: replica.CandidateReady, + CandidateReadyReason: replica.CandidateReadyReason, + FrontendProtocol: replica.FrontendProtocol, + FrontendAddr: replica.FrontendAddr, + StatusAddr: replica.StatusAddr, + StalePrimaryFenced: replica.StalePrimaryFenced, + Conditions: conditionsToWire(replica.Conditions), + SupportBundlePath: replica.SupportBundlePath, + } +} + +func conditionsToWire(in []ops.ObservationCondition) []*control.ObservationCondition { + out := make([]*control.ObservationCondition, 0, len(in)) + for _, condition := range in { + out = append(out, &control.ObservationCondition{ + Type: condition.Type, + Status: condition.Status, + Reason: condition.Reason, + Severity: condition.Severity, + Message: condition.Message, + }) + } + return out +} + +func clusterEventToWire(event ops.ClusterEvent) *control.ClusterEvent { + return &control.ClusterEvent{ + EventId: event.EventID, + EventTime: timestampOrNil(event.EventTime), + VolumeId: event.VolumeID, + ReplicaId: event.ReplicaID, + NodeName: event.NodeName, + EventType: event.Type, + Severity: event.Severity, + Message: event.Message, + ReasonCode: event.Reason, + OldValue: event.OldValue, + NewValue: event.NewValue, + Epoch: event.Epoch, + EndpointVersion: event.EndpointVersion, + CorrelationId: event.CorrelationID, + EvidenceRef: event.EvidenceRef, + } +} + +func clusterEventFromWire(event *control.ClusterEvent) ops.ClusterEvent { + if event == nil { + return ops.ClusterEvent{} + } + out := ops.ClusterEvent{ + EventID: event.GetEventId(), + VolumeID: event.GetVolumeId(), + ReplicaID: event.GetReplicaId(), + NodeName: event.GetNodeName(), + Type: event.GetEventType(), + Severity: event.GetSeverity(), + Message: event.GetMessage(), + Reason: event.GetReasonCode(), + OldValue: event.GetOldValue(), + NewValue: event.GetNewValue(), + Epoch: event.GetEpoch(), + EndpointVersion: event.GetEndpointVersion(), + CorrelationID: event.GetCorrelationId(), + EvidenceRef: event.GetEvidenceRef(), + } + if ts := event.GetEventTime(); ts != nil && ts.IsValid() { + out.EventTime = ts.AsTime() + } + return out +} + +func timestampOrNil(t time.Time) *timestamppb.Timestamp { + if t.IsZero() { + return nil + } + return timestamppb.New(t.UTC()) +} diff --git a/seaweed-block/core/host/master/observation_service_test.go b/seaweed-block/core/host/master/observation_service_test.go new file mode 100644 index 0000000000..427b2bd166 --- /dev/null +++ b/seaweed-block/core/host/master/observation_service_test.go @@ -0,0 +1,239 @@ +package master + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestClusterEvidenceService_GetClusterStatusSharesObservationSnapshot(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + lineBefore := waitAuthorityLine(t, h.Publisher(), "pvc-a") + + resp, err := newServices(h).GetClusterStatus(context.Background(), &control.GetClusterStatusRequest{}) + if err != nil { + t.Fatalf("GetClusterStatus: %v", err) + } + lineAfter, ok := h.Publisher().VolumeAuthorityLine("pvc-a") + if !ok || lineAfter != lineBefore { + t.Fatalf("read-only service mutated authority before=%+v after=%+v ok=%t", lineBefore, lineAfter, ok) + } + + if resp.GetSchemaVersion() == "" || resp.GetStatus() != "ok" { + t.Fatalf("response schema/status=%q/%q", resp.GetSchemaVersion(), resp.GetStatus()) + } + if len(resp.GetNodes()) != 3 || len(resp.GetVolumes()) != 1 { + t.Fatalf("nodes=%d volumes=%d", len(resp.GetNodes()), len(resp.GetVolumes())) + } + volume := resp.GetVolumes()[0] + if volume.GetVolumeId() != "pvc-a" || volume.GetPvcName() != "demo-pvc" { + t.Fatalf("volume=%+v", volume) + } + if volume.GetPrimaryReplica() != lineBefore.ReplicaID || volume.GetEpoch() != lineBefore.Epoch || volume.GetEndpointVersion() != lineBefore.EndpointVersion { + t.Fatalf("volume authority fields=%+v line=%+v", volume, lineBefore) + } + if volume.GetPublishTarget() == "" { + t.Fatalf("missing publish target: %+v", volume) + } +} + +func TestClusterEvidenceService_GRPCRegistered(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc client: %v", err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + resp, err := control.NewClusterEvidenceServiceClient(conn).GetVolumeStatus(ctx, &control.GetVolumeStatusRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("GetVolumeStatus over grpc: %v", err) + } + if resp.GetVolumeId() != "pvc-a" || resp.GetPrimaryReplica() == "" { + t.Fatalf("response=%+v", resp) + } +} + +func TestClusterEvidenceService_ListVolumesAndGetVolumeStatus(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, false) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + svc := newServices(h) + list, err := svc.ListVolumes(context.Background(), &control.ListVolumesRequest{}) + if err != nil { + t.Fatalf("ListVolumes: %v", err) + } + if len(list.GetVolumes()) != 1 { + t.Fatalf("volumes=%d want 1", len(list.GetVolumes())) + } + if list.GetVolumes()[0].GetStatus() != "degraded" || list.GetVolumes()[0].GetReason() != "observed_replicas_below_desired" { + t.Fatalf("volume=%+v", list.GetVolumes()[0]) + } + + volume, err := svc.GetVolumeStatus(context.Background(), &control.GetVolumeStatusRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("GetVolumeStatus: %v", err) + } + if volume.GetObservedReplicas() != 2 || volume.GetDesiredReplicas() != 3 { + t.Fatalf("counts observed=%d desired=%d", volume.GetObservedReplicas(), volume.GetDesiredReplicas()) + } +} + +func TestClusterEvidenceService_GetVolumeStatusNotFound(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + _, err := newServices(h).GetVolumeStatus(context.Background(), &control.GetVolumeStatusRequest{VolumeId: "missing"}) + if status.Code(err) != codes.NotFound { + t.Fatalf("err=%v code=%v want NotFound", err, status.Code(err)) + } +} + +func TestClusterEvidenceService_GetVolumeTimelineEmptyButVersioned(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + resp, err := newServices(h).GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("GetVolumeTimeline: %v", err) + } + if resp.GetSchemaVersion() == "" || resp.GetCapturedAt().AsTime().After(time.Now().Add(time.Second)) { + t.Fatalf("timeline metadata=%+v", resp) + } + if len(resp.GetEvents()) != 0 { + t.Fatalf("events=%d want 0 before D5 event ring", len(resp.GetEvents())) + } +} + +func TestObservationService_ReportClusterEventAppearsInVolumeTimeline(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + svc := newServices(h) + ack, err := svc.ReportClusterEvent(context.Background(), &control.ClusterEvent{ + EventId: "client-supplied", + EventTime: timestamppb.New(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)), + VolumeId: "pvc-a", + ReplicaId: "r2", + NodeName: "m02", + EventType: "csi_reattach_observed", + Severity: "warning", + Message: "authority_published spoof", + ReasonCode: "candidate_covers_required_frontier", + OldValue: "r1", + CorrelationId: "client-correlation", + EvidenceRef: "authority-log", + Epoch: 2, + EndpointVersion: 1, + }) + if err != nil { + t.Fatalf("ReportClusterEvent: %v", err) + } + if ack.GetEventId() == "" || ack.GetAcceptedAt() == nil { + t.Fatalf("ack=%+v", ack) + } + + timeline, err := svc.GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "pvc-a"}) + if err != nil { + t.Fatalf("GetVolumeTimeline: %v", err) + } + if len(timeline.GetEvents()) != 1 { + t.Fatalf("events=%d want 1", len(timeline.GetEvents())) + } + event := timeline.GetEvents()[0] + if event.GetEventId() != ack.GetEventId() || event.GetEventType() != "csi_reattach_observed" || event.GetReplicaId() != "r2" { + t.Fatalf("event=%+v ack=%+v", event, ack) + } + if event.GetEventId() == "client-supplied" || event.GetEventTime().AsTime().Year() == 2000 { + t.Fatalf("master did not mint event identity/time: %+v", event) + } + if event.GetSeverity() != "warning" || event.GetReasonCode() != "csi_reattach_observed" || event.GetMessage() != "CSI staged volume on node" { + t.Fatalf("external event fields were not sanitized: %+v", event) + } + if event.GetOldValue() != "" || event.GetCorrelationId() != "" || event.GetEvidenceRef() != "csi-node" { + t.Fatalf("external authority-looking fields leaked through: %+v", event) + } +} + +func TestObservationService_ReportClusterEventRejectsMissingType(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + _, err := newServices(h).ReportClusterEvent(context.Background(), &control.ClusterEvent{VolumeId: "pvc-a"}) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("err=%v code=%v want InvalidArgument", err, status.Code(err)) + } +} + +func TestObservationService_ReportClusterEventRejectsAuthorityOwnedType(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + _, err := newServices(h).ReportClusterEvent(context.Background(), &control.ClusterEvent{ + VolumeId: "pvc-a", + NodeName: "m02", + EventType: "authority_published", + Severity: "info", + }) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("err=%v code=%v want InvalidArgument", err, status.Code(err)) + } +} + +func TestObservationService_ReportClusterEventRejectsCSIEventWithoutVolumeOrNode(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + + _, err := newServices(h).ReportClusterEvent(context.Background(), &control.ClusterEvent{ + NodeName: "m02", + EventType: "csi_reattach_observed", + Severity: "info", + }) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("missing volume err=%v code=%v want InvalidArgument", err, status.Code(err)) + } + _, err = newServices(h).ReportClusterEvent(context.Background(), &control.ClusterEvent{ + VolumeId: "pvc-a", + EventType: "csi_reattach_observed", + Severity: "info", + }) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("missing node err=%v code=%v want InvalidArgument", err, status.Code(err)) + } +} diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go new file mode 100644 index 0000000000..bdc5528496 --- /dev/null +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -0,0 +1,314 @@ +package master + +import ( + "fmt" + "net" + "sort" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// ObservationSnapshot returns a read-only, operator-facing view of the +// master's current lifecycle, authority, and heartbeat facts. It does not +// mutate lifecycle stores, authority publisher state, observation state, or +// Kubernetes. +func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { + cluster := ops.NewClusterEvidence(now) + snapshot, ok := h.LifecycleSnapshot() + if !ok { + return cluster + } + + cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements) + cluster.Volumes = h.observationVolumes(snapshot) + cluster.Events = h.events.list("") + cluster.Status = clusterStatus(cluster.Volumes, cluster.Nodes) + return cluster +} + +func observationNodes(nodes []lifecycle.NodeRegistration, placements []lifecycle.PlacementIntent) []ops.NodeEvidence { + replicaCounts := map[string]int{} + for _, placement := range placements { + for _, slot := range placement.Slots { + if slot.ServerID != "" { + replicaCounts[slot.ServerID]++ + } + } + } + out := make([]ops.NodeEvidence, 0, len(nodes)) + for _, node := range nodes { + out = append(out, ops.NodeEvidence{ + NodeName: node.ServerID, + KubernetesNode: node.Labels[lifecycle.KubernetesNodeNameLabel], + InternalIP: hostFromAddr(firstNonEmpty(node.DataAddr, node.Addr)), + Schedulable: true, + Ready: true, + LastHeartbeatAt: node.SeenAt, + ReplicaCount: replicaCounts[node.ServerID], + }) + } + sort.SliceStable(out, func(i, j int) bool { + return out[i].NodeName < out[j].NodeName + }) + return out +} + +func (h *Host) observationVolumes(snapshot LifecycleSnapshot) []ops.VolumeEvidence { + records := map[string]lifecycle.VolumeRecord{} + for _, rec := range snapshot.Volumes { + records[rec.Spec.VolumeID] = rec + } + placements := map[string]lifecycle.PlacementIntent{} + for _, placement := range snapshot.Placements { + placements[placement.VolumeID] = placement + } + + ids := make(map[string]struct{}) + for id := range records { + ids[id] = struct{}{} + } + for id := range placements { + ids[id] = struct{}{} + } + for _, v := range h.topo.Volumes { + ids[v.VolumeID] = struct{}{} + } + + ordered := make([]string, 0, len(ids)) + for id := range ids { + ordered = append(ordered, id) + } + sort.Strings(ordered) + + out := make([]ops.VolumeEvidence, 0, len(ordered)) + for _, id := range ordered { + out = append(out, h.observationVolume(id, records[id], placements[id])) + } + return out +} + +func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, placement lifecycle.PlacementIntent) ops.VolumeEvidence { + rf := rec.Spec.ReplicationFactor + if rf == 0 { + rf = placement.DesiredRF + } + volume := ops.VolumeEvidence{ + VolumeID: volumeID, + Namespace: rec.Spec.PVCNamespace, + PVCName: rec.Spec.PVCName, + PVName: rec.Spec.PVName, + ReplicationFactor: rf, + DesiredReplicas: desiredReplicaCount(rf, placement), + Status: ops.ObservationStatusOK, + } + + line, hasLine := h.Publisher().VolumeAuthorityLine(volumeID) + if hasLine && line.Assigned { + volume.PrimaryReplica = line.ReplicaID + volume.Epoch = line.Epoch + volume.EndpointVersion = line.EndpointVersion + } + + replicas := h.observationReplicas(volumeID, placement, line, hasLine) + volume.Replicas = replicas + volume.ObservedReplicas = countObservedReplicas(replicas) + if volume.PrimaryReplica != "" { + volume.PrimaryNode = serverForReplica(placement, volume.PrimaryReplica) + volume.PublishTarget = publishTargetForReplica(replicas, volume.PrimaryReplica) + } + + if volume.DesiredReplicas > 0 && volume.ObservedReplicas < volume.DesiredReplicas { + volume.Status = ops.ObservationStatusDegraded + volume.Reason = ops.ReasonObservedReplicasBelowDesired + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "ReplicasObserved", + Status: "false", + Reason: ops.ReasonObservedReplicasBelowDesired, + Severity: "warning", + Message: fmt.Sprintf("observed %d of %d desired replicas", volume.ObservedReplicas, volume.DesiredReplicas), + }) + } + if !hasLine || !line.Assigned { + if volume.Status == ops.ObservationStatusOK { + volume.Status = ops.ObservationStatusDegraded + volume.Reason = ops.ReasonNoPromotionReadyCandidate + } + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "PrimaryAssigned", + Status: "false", + Reason: ops.ReasonNoPromotionReadyCandidate, + Severity: "warning", + Message: "master has no published primary for this volume", + }) + } + if unsupported, ok := h.Controller().LastUnsupported(volumeID); ok { + volume.Status = ops.ObservationStatusBlocked + volume.Reason = unsupported.Reason + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "AuthoritySupported", + Status: "false", + Reason: unsupported.Reason, + Severity: "error", + Message: "authority controller rejected the latest observed topology", + }) + } + return volume +} + +func (h *Host) observationReplicas(volumeID string, placement lifecycle.PlacementIntent, line authority.AuthorityBasis, hasLine bool) []ops.ReplicaEvidence { + slots := placement.Slots + if len(slots) == 0 { + for _, v := range h.topo.Volumes { + if v.VolumeID != volumeID { + continue + } + for _, slot := range v.Slots { + slots = append(slots, lifecycle.PlacementSlotIntent{ + ServerID: slot.ServerID, + ReplicaID: slot.ReplicaID, + Source: lifecycle.PlacementSourceExistingReplica, + }) + } + } + } + out := make([]ops.ReplicaEvidence, 0, len(slots)) + for _, slot := range slots { + replicaID := slot.ReplicaID + if replicaID == "" { + replicaID = "unknown" + } + replica := ops.ReplicaEvidence{ + ReplicaID: replicaID, + ServerID: slot.ServerID, + KubernetesNode: slot.ServerID, + Role: "unknown", + ReplicationRole: "unavailable", + } + if hasLine && line.Assigned && replicaID == line.ReplicaID { + replica.Role = "primary" + replica.ReplicationRole = "primary" + } + if fact, ok := h.ObservationHost().Store().SlotFact(volumeID, replicaID); ok { + replica.Observed = true + replica.CandidateReady = fact.ReadyForPrimary + replica.CandidateReadyReason = candidateReason(fact.ReadyForPrimary) + if replica.Role != "primary" { + if fact.ReadyForPrimary { + replica.Role = "candidate" + replica.ReplicationRole = "replica_ready" + } else { + replica.ReplicationRole = "not_ready" + } + } + if len(fact.Frontends) > 0 { + replica.FrontendProtocol = fact.Frontends[0].Protocol + replica.FrontendAddr = fact.Frontends[0].Addr + } + } else { + replica.CandidateReadyReason = ops.ReasonStatusEndpointUnreachable + replica.Conditions = append(replica.Conditions, ops.ObservationCondition{ + Type: "ReplicaObserved", + Status: "false", + Reason: ops.ReasonStatusEndpointUnreachable, + Severity: "warning", + Message: "no fresh heartbeat observation for this placement slot", + }) + } + out = append(out, replica) + } + sort.SliceStable(out, func(i, j int) bool { + return out[i].ReplicaID < out[j].ReplicaID + }) + return out +} + +func clusterStatus(volumes []ops.VolumeEvidence, nodes []ops.NodeEvidence) string { + status := ops.ObservationStatusOK + for _, node := range nodes { + for _, condition := range node.Conditions { + if condition.Severity == "error" { + return ops.ObservationStatusBlocked + } + if condition.Severity == "warning" { + status = ops.ObservationStatusDegraded + } + } + } + for _, volume := range volumes { + switch volume.Status { + case ops.ObservationStatusBlocked, ops.ObservationStatusInvalid: + return ops.ObservationStatusBlocked + case ops.ObservationStatusDegraded, ops.ObservationStatusRecovering, ops.ObservationStatusUnavailable: + status = ops.ObservationStatusDegraded + } + } + return status +} + +func desiredReplicaCount(rf int, placement lifecycle.PlacementIntent) int { + if placement.DesiredRF > 0 { + return placement.DesiredRF + } + if len(placement.Slots) > 0 { + return len(placement.Slots) + } + return rf +} + +func countObservedReplicas(replicas []ops.ReplicaEvidence) int { + n := 0 + for _, replica := range replicas { + if replica.Observed { + n++ + } + } + return n +} + +func serverForReplica(placement lifecycle.PlacementIntent, replicaID string) string { + for _, slot := range placement.Slots { + if slot.ReplicaID == replicaID { + return slot.ServerID + } + } + return "" +} + +func publishTargetForReplica(replicas []ops.ReplicaEvidence, replicaID string) string { + for _, replica := range replicas { + if replica.ReplicaID == replicaID { + return replica.FrontendAddr + } + } + return "" +} + +func candidateReason(ready bool) string { + if ready { + return ops.ReasonCandidateCoversRequiredFrontier + } + return ops.ReasonNoPromotionReadyCandidate +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if value != "" { + return value + } + } + return "" +} + +func hostFromAddr(addr string) string { + if addr == "" { + return "" + } + host, _, err := net.SplitHostPort(addr) + if err == nil { + return host + } + return addr +} diff --git a/seaweed-block/core/host/master/observation_snapshot_test.go b/seaweed-block/core/host/master/observation_snapshot_test.go new file mode 100644 index 0000000000..d5b1811a0b --- /dev/null +++ b/seaweed-block/core/host/master/observation_snapshot_test.go @@ -0,0 +1,218 @@ +package master + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +func TestMasterObservationSnapshot_RF3HealthyReadOnly(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + lineBefore := waitAuthorityLine(t, h.Publisher(), "pvc-a") + + snapshot := h.ObservationSnapshot(time.Date(2026, 5, 16, 12, 0, 0, 0, time.UTC)) + lineAfter, ok := h.Publisher().VolumeAuthorityLine("pvc-a") + if !ok { + t.Fatal("authority line disappeared") + } + if lineAfter != lineBefore { + t.Fatalf("observation snapshot mutated authority before=%+v after=%+v", lineBefore, lineAfter) + } + + if snapshot.SchemaVersion != ops.ObservationSchemaVersion { + t.Fatalf("schema=%q want %q", snapshot.SchemaVersion, ops.ObservationSchemaVersion) + } + if snapshot.Status != ops.ObservationStatusOK { + t.Fatalf("cluster status=%q want ok: %+v", snapshot.Status, snapshot) + } + if len(snapshot.Nodes) != 3 { + t.Fatalf("nodes=%d want 3", len(snapshot.Nodes)) + } + if len(snapshot.Volumes) != 1 { + t.Fatalf("volumes=%d want 1", len(snapshot.Volumes)) + } + volume := snapshot.Volumes[0] + if volume.VolumeID != "pvc-a" || volume.PVCName != "demo-pvc" || volume.Namespace != "default" { + t.Fatalf("volume identity=%+v", volume) + } + if volume.ReplicationFactor != 3 || volume.DesiredReplicas != 3 || volume.ObservedReplicas != 3 { + t.Fatalf("replica counts=%+v", volume) + } + if volume.PrimaryReplica != lineBefore.ReplicaID || volume.PrimaryNode == "" || volume.PublishTarget == "" { + t.Fatalf("primary evidence=%+v line=%+v", volume, lineBefore) + } + if volume.Status != ops.ObservationStatusOK { + t.Fatalf("volume status=%q want ok: %+v", volume.Status, volume) + } + if !hasReplicaWithRole(volume.Replicas, volume.PrimaryReplica, "primary") { + t.Fatalf("replicas=%+v missing primary %s", volume.Replicas, volume.PrimaryReplica) + } +} + +func TestMasterObservationSnapshot_MissingReplicaIsDegraded(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, false) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + snapshot := h.ObservationSnapshot(time.Now().UTC()) + if snapshot.Status != ops.ObservationStatusDegraded { + t.Fatalf("cluster status=%q want degraded", snapshot.Status) + } + if len(snapshot.Volumes) != 1 { + t.Fatalf("volumes=%d want 1", len(snapshot.Volumes)) + } + volume := snapshot.Volumes[0] + if volume.Status != ops.ObservationStatusDegraded { + t.Fatalf("volume status=%q want degraded: %+v", volume.Status, volume) + } + if volume.Reason != ops.ReasonObservedReplicasBelowDesired { + t.Fatalf("volume reason=%q want %q", volume.Reason, ops.ReasonObservedReplicasBelowDesired) + } + if volume.ObservedReplicas != 2 || volume.DesiredReplicas != 3 { + t.Fatalf("replica counts observed=%d desired=%d", volume.ObservedReplicas, volume.DesiredReplicas) + } + if !hasReplicaCondition(volume.Replicas, "r3", ops.ReasonStatusEndpointUnreachable) { + t.Fatalf("replicas=%+v missing r3 unreachable condition", volume.Replicas) + } +} + +func TestMasterObservationSnapshot_NoLifecycleStoreReturnsEmptyOK(t *testing.T) { + h := newTestMaster(t, "") + defer closeTestMaster(t, h) + + snapshot := h.ObservationSnapshot(time.Time{}) + if snapshot.Status != ops.ObservationStatusOK { + t.Fatalf("status=%q want ok", snapshot.Status) + } + if len(snapshot.Volumes) != 0 || len(snapshot.Nodes) != 0 { + t.Fatalf("snapshot=%+v want empty observation", snapshot) + } +} + +func seedObservationSnapshotVolume(t *testing.T, h *Host) { + t.Helper() + if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-a", + SizeBytes: 1 << 20, + ReplicationFactor: 3, + Protocol: "iscsi", + PVCName: "demo-pvc", + PVCNamespace: "default", + PVName: "pv-a", + }); err != nil { + t.Fatalf("create volume: %v", err) + } + now := time.Now().UTC() + for _, node := range []struct { + serverID string + ip string + }{ + {serverID: "m01", ip: "192.168.1.181"}, + {serverID: "m02", ip: "192.168.1.184"}, + {serverID: "tp01", ip: "192.168.1.188"}, + } { + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: node.serverID, + DataAddr: node.ip + ":19101", + CtrlAddr: node.ip + ":19102", + Labels: map[string]string{ + lifecycle.KubernetesNodeNameLabel: node.serverID, + }, + Pools: []lifecycle.StoragePool{{ + PoolID: "pool-" + node.serverID, + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + SeenAt: now, + }); err != nil { + t.Fatalf("register node %s: %v", node.serverID, err) + } + } +} + +func ingestObservationSnapshotRF3(t *testing.T, h *Host, r1Ready, r2Ready, r3Ready bool) { + t.Helper() + now := time.Now().UTC() + for i, item := range []struct { + serverID string + replica string + ip string + ready bool + }{ + {serverID: "m01", replica: "r1", ip: "192.168.1.181", ready: r1Ready}, + {serverID: "m02", replica: "r2", ip: "192.168.1.184", ready: r2Ready}, + {serverID: "tp01", replica: "r3", ip: "192.168.1.188", ready: r3Ready}, + } { + if !item.ready { + continue + } + if err := h.ObservationHost().Ingest(authority.Observation{ + ServerID: item.serverID, + ObservedAt: now, + Server: authority.ServerFact{Reachable: true, Eligible: true}, + Slots: []authority.SlotFact{{ + VolumeID: "pvc-a", + ReplicaID: item.replica, + DataAddr: item.ip + ":19101", + CtrlAddr: item.ip + ":19102", + Reachable: true, + ReadyForPrimary: true, + Eligible: true, + EvidenceScore: uint64(30 - i), + Frontends: []authority.FrontendTargetFact{{ + Protocol: "iscsi", + Addr: item.ip + ":3260", + IQN: "iqn.2026-05.io.seaweedfs:pvc-a", + LUN: 1, + }}, + }}, + }); err != nil { + t.Fatalf("ingest %s: %v", item.replica, err) + } + } +} + +func hasReplicaWithRole(replicas []ops.ReplicaEvidence, replicaID, role string) bool { + for _, replica := range replicas { + if replica.ReplicaID == replicaID && replica.Role == role { + return true + } + } + return false +} + +func hasReplicaCondition(replicas []ops.ReplicaEvidence, replicaID, reason string) bool { + for _, replica := range replicas { + if replica.ReplicaID != replicaID { + continue + } + for _, condition := range replica.Conditions { + if condition.Reason == reason { + return true + } + } + } + return false +} diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index ebb3e99b83..c5e582efcc 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -1,6 +1,13 @@ package master -import "github.com/seaweedfs/seaweed-block/core/lifecycle" +import ( + "fmt" + "strings" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/ops" +) // LifecycleProductTickResult summarizes one explicit product-loop tick. type LifecycleProductTickResult struct { @@ -9,6 +16,33 @@ type LifecycleProductTickResult struct { PublishedAsks int SkippedCurrent int SkippedUnverified int + PromotionProbes int + PromotionBlocked int +} + +type PromotionCandidateEvidence struct { + ReplicaID string + Ready bool + DurableLSN uint64 + ProbeAddr string +} + +type PromotionProbeResult struct { + AckProfile string + SyncAckLSN uint64 + CurrentKnown bool + Current PromotionCandidateEvidence + Candidates []PromotionCandidateEvidence +} + +type PromotionEvidenceProvider interface { + ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) +} + +func (h *Host) SetPromotionEvidenceProvider(p PromotionEvidenceProvider) { + h.promotionMu.Lock() + defer h.promotionMu.Unlock() + h.promotionProber = p } // RunLifecycleProductTick drives the first G9G product loop: @@ -28,7 +62,30 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { ReconciledVolumes: len(reconciled), VerifiedPlacements: len(verified), } + h.recordPlacementVerifiedEvents(verified) + submitted, probeCount, blockedCount, directAsks, err := h.submitPlacementSnapshots(placements) + if err != nil { + return result, err + } + result.PromotionProbes += probeCount + result.PromotionBlocked += blockedCount + if submitted { + result.PublishedAsks++ + } + for _, ask := range directAsks { + if h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) { + result.SkippedCurrent++ + continue + } + if err := h.ctrl.SubmitAssignmentAsk(ask); err != nil { + return result, err + } + result.PublishedAsks++ + } for _, placement := range verified { + if len(placement.Slots) > 1 { + continue + } if !placement.Verified { result.SkippedUnverified++ continue @@ -51,6 +108,319 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { return result, nil } +func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent) (bool, int, int, []authority.AssignmentAsk, error) { + if h.obs == nil || h.ctrl == nil { + return false, 0, 0, nil, nil + } + topology, ok := acceptedTopologyFromPlacementIntents(placements) + if !ok { + return false, 0, 0, nil, nil + } + build := authority.BuildSnapshot(h.obs.Store().Snapshot(), topology, h.Publisher()) + probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot) + return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report) +} + +func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) { + if snap == nil || len(snap.Volumes) == 0 { + return 0, 0, nil + } + probeCount, blockedCount := 0, 0 + var directAsks []authority.AssignmentAsk + serverIndex := map[string]authority.ServerObservation{} + for _, server := range snap.Servers { + serverIndex[server.ServerID] = server + } + for vi := range snap.Volumes { + vol := &snap.Volumes[vi] + if len(vol.Slots) < 3 || !vol.Authority.Assigned { + continue + } + currentIdx := replicaIndex(vol.Slots, vol.Authority.ReplicaID) + if currentIdx < 0 { + continue + } + currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) + candidates := make([]authority.ReplicaCandidate, 0, len(vol.Slots)-1) + readyCandidate := false + for _, slot := range vol.Slots { + if slot.ReplicaID != vol.Authority.ReplicaID { + candidates = append(candidates, slot) + if candidateAcceptableForPromotionGate(slot, serverIndex) { + readyCandidate = true + } + } + } + if currentAcceptable && !readyCandidate { + continue + } + probeCount++ + result, ok := h.probePromotionCandidates(vol.VolumeID, vol.Authority, candidates) + allowed := promotionAllowedReplicas(result, ok) + if ok { + h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v", + vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed) + h.recordPromotionEvaluationEvents(vol.VolumeID, result, allowed) + } else { + h.log.Printf("blockmaster: promotion gate volume=%s current=%s probe_unavailable", vol.VolumeID, vol.Authority.ReplicaID) + h.recordPromotionProbeUnavailableEvent(vol.VolumeID, vol.Authority.ReplicaID) + } + enabledCandidate := false + for si := range vol.Slots { + slot := &vol.Slots[si] + if slot.ReplicaID == vol.Authority.ReplicaID { + continue + } + if allowed[slot.ReplicaID] { + slot.ReadyForPrimary = true + enabledCandidate = true + } else { + slot.ReadyForPrimary = false + } + } + if enabledCandidate && result.CurrentKnown && !result.Current.Ready { + current := &vol.Slots[currentIdx] + current.Reachable = false + current.ReadyForPrimary = false + if target, ok := chooseAllowedPromotionTarget(*vol, result, allowed); ok { + h.log.Printf("blockmaster: promotion gate volume=%s direct_reassign=%s current=%s", vol.VolumeID, target.ReplicaID, vol.Authority.ReplicaID) + directAsks = append(directAsks, authority.AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: target.ReplicaID, + DataAddr: target.DataAddr, + CtrlAddr: target.CtrlAddr, + Intent: authority.IntentReassign, + }) + } + } + if !enabledCandidate { + blockedCount++ + h.recordVolumeBlockedEvent(vol.VolumeID, ops.ReasonNoPromotionReadyCandidate) + } + } + return probeCount, blockedCount, directAsks +} + +func (h *Host) recordPlacementVerifiedEvents(placements []lifecycle.VerifiedPlacement) { + for _, placement := range placements { + if !placement.Verified { + continue + } + h.events.append(ops.ClusterEvent{ + VolumeID: placement.VolumeID, + Type: "placement_verified", + Severity: "info", + Message: fmt.Sprintf("placement verified with %d replica slots", len(placement.Slots)), + Reason: "placement_verified", + }) + } +} + +func (h *Host) recordPromotionEvaluationEvents(volumeID string, result PromotionProbeResult, allowed map[string]bool) { + for _, candidate := range result.Candidates { + reason := ops.ReasonNoPromotionReadyCandidate + severity := "warning" + message := fmt.Sprintf("candidate %s is not promotion-ready", candidate.ReplicaID) + if allowed[candidate.ReplicaID] { + reason = ops.ReasonCandidateCoversRequiredFrontier + severity = "info" + message = fmt.Sprintf("candidate %s covers required frontier lsn=%d", candidate.ReplicaID, result.SyncAckLSN) + } else if candidate.Ready { + reason = ops.ReasonCandidateFrontierBehind + message = fmt.Sprintf("candidate %s ready=%t durable_lsn=%d required_lsn=%d", candidate.ReplicaID, candidate.Ready, candidate.DurableLSN, result.SyncAckLSN) + } + h.events.append(ops.ClusterEvent{ + VolumeID: volumeID, + ReplicaID: candidate.ReplicaID, + Type: "promotion_candidate_evaluated", + Severity: severity, + Reason: reason, + Message: message, + }) + } +} + +func (h *Host) recordPromotionProbeUnavailableEvent(volumeID, currentReplica string) { + h.events.append(ops.ClusterEvent{ + VolumeID: volumeID, + ReplicaID: currentReplica, + Type: "promotion_candidate_evaluated", + Severity: "warning", + Reason: ops.ReasonNoPromotionReadyCandidate, + Message: "promotion evidence probe unavailable", + }) +} + +func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) { + h.events.append(ops.ClusterEvent{ + VolumeID: volumeID, + Type: "volume_blocked", + Severity: "warning", + Reason: reason, + Message: "no candidate passed promotion readiness gate", + }) +} + +func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) { + if h == nil || h.events == nil { + return + } + message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion) + if event.Ask.Intent == authority.IntentReassign { + message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion) + } + h.events.append(ops.ClusterEvent{ + VolumeID: event.Info.VolumeID, + ReplicaID: event.Info.ReplicaID, + Type: "authority_published", + Severity: "info", + Reason: ops.ReasonCandidateCoversRequiredFrontier, + Message: message, + NewValue: event.Info.ReplicaID, + Epoch: event.Info.Epoch, + EndpointVersion: event.Info.EndpointVersion, + }) +} + +func replicaIndex(slots []authority.ReplicaCandidate, replicaID string) int { + for i, slot := range slots { + if slot.ReplicaID == replicaID { + return i + } + } + return -1 +} + +func candidateAcceptableForPromotionGate(slot authority.ReplicaCandidate, servers map[string]authority.ServerObservation) bool { + server, ok := servers[slot.ServerID] + return ok && + slot.Reachable && + slot.ReadyForPrimary && + slot.Eligible && + !slot.Withdrawn && + server.Reachable && + server.Eligible +} + +func (h *Host) probePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, bool) { + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + if prober == nil { + return PromotionProbeResult{}, false + } + result, err := prober.ProbePromotionCandidates(volumeID, current, candidates) + if err != nil { + h.log.Printf("blockmaster: promotion probe volume=%s failed: %v", volumeID, err) + return PromotionProbeResult{}, false + } + return result, true +} + +func promotionAllowedReplicas(result PromotionProbeResult, ok bool) map[string]bool { + allowed := map[string]bool{} + if !ok || !isKnownAckProfile(result.AckProfile) { + return allowed + } + if result.SyncAckLSN > 0 && !isQuorumAckProfile(result.AckProfile) { + return allowed + } + var bestLSN uint64 + for _, candidate := range result.Candidates { + if candidate.ReplicaID == "" || !candidate.Ready { + continue + } + if result.SyncAckLSN > 0 && candidate.DurableLSN < result.SyncAckLSN { + continue + } + if result.SyncAckLSN == 0 && candidate.DurableLSN == 0 { + continue + } + if candidate.DurableLSN > bestLSN { + bestLSN = candidate.DurableLSN + allowed = map[string]bool{candidate.ReplicaID: true} + continue + } + if candidate.DurableLSN == bestLSN { + allowed[candidate.ReplicaID] = true + } + } + return allowed +} + +func chooseAllowedPromotionTarget(vol authority.VolumeTopologySnapshot, result PromotionProbeResult, allowed map[string]bool) (authority.ReplicaCandidate, bool) { + durable := map[string]uint64{} + for _, candidate := range result.Candidates { + durable[candidate.ReplicaID] = candidate.DurableLSN + } + var best authority.ReplicaCandidate + var bestLSN uint64 + ok := false + for _, slot := range vol.Slots { + if !allowed[slot.ReplicaID] { + continue + } + lsn := durable[slot.ReplicaID] + if !ok || lsn > bestLSN || (lsn == bestLSN && slot.ReplicaID < best.ReplicaID) { + best = slot + bestLSN = lsn + ok = true + } + } + return best, ok +} + +func isKnownAckProfile(profile string) bool { + switch strings.ToLower(strings.ReplaceAll(profile, "-", "_")) { + case "best_effort", "sync_quorum", "sync_all": + return true + default: + return false + } +} + +func isQuorumAckProfile(profile string) bool { + switch strings.ToLower(strings.ReplaceAll(profile, "-", "_")) { + case "sync_quorum", "sync_all": + return true + default: + return false + } +} + +func acceptedTopologyFromPlacementIntents(placements []lifecycle.PlacementIntent) (authority.AcceptedTopology, bool) { + topology := authority.AcceptedTopology{Volumes: make([]authority.VolumeExpected, 0, len(placements))} + for _, placement := range placements { + if len(placement.Slots) <= 1 { + continue + } + if !placementIsConcreteExistingReplica(placement) { + continue + } + expected := authority.VolumeExpected{ + VolumeID: placement.VolumeID, + Slots: make([]authority.ExpectedSlot, 0, len(placement.Slots)), + } + for _, slot := range placement.Slots { + expected.Slots = append(expected.Slots, authority.ExpectedSlot{ + ReplicaID: slot.ReplicaID, + ServerID: slot.ServerID, + }) + } + topology.Volumes = append(topology.Volumes, expected) + } + return topology, len(topology.Volumes) > 0 +} + +func placementIsConcreteExistingReplica(placement lifecycle.PlacementIntent) bool { + for _, slot := range placement.Slots { + if slot.Source != lifecycle.PlacementSourceExistingReplica || slot.ReplicaID == "" || slot.ServerID == "" { + return false + } + } + return true +} + func (h *Host) assignmentAskAlreadyCurrent(volumeID, replicaID, dataAddr, ctrlAddr string) bool { line, ok := h.Publisher().VolumeAuthorityLine(volumeID) if !ok { diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index 9a506d79cd..ce6860d02d 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -97,6 +97,533 @@ func TestG9G_BlockvolumeSubscriptionReceivesProductLoopAssignment(t *testing.T) } } +func TestMountedFailover_ProductLoopRF2UsesAuthorityControllerForFailover(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 2, + }) + defer closeTestMaster(t, h) + seedRF2Placement(t, h) + ingestRF2Observation(t, h, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2") + if initial.ReplicaID != "r1" || initial.Epoch != 1 || initial.EndpointVersion != 1 { + t.Fatalf("initial line=%+v want r1@1/1", initial) + } + + ingestRF2Observation(t, h, false, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("failover product tick: %v", err) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf2", "r2") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r2@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF2RefusesWhenNoCandidateReady(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 2, + }) + defer closeTestMaster(t, h) + seedRF2Placement(t, h) + ingestRF2Observation(t, h, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF2Observation(t, h, false, false) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("refusal product tick: %v", err) + } + time.Sleep(100 * time.Millisecond) + got, ok := h.Publisher().VolumeAuthorityLine("vol-rf2") + if !ok { + t.Fatal("authority line disappeared") + } + if got.ReplicaID != "r1" || got.Epoch != initial.Epoch || got.EndpointVersion != initial.EndpointVersion { + t.Fatalf("unsafe failover occurred: got %+v want unchanged %+v", got, initial) + } +} + +func TestMountedFailover_ProductLoopRF2SnapshotIncludesAllConcretePlacements(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 2, + }) + defer closeTestMaster(t, h) + seedRF2PlacementForServers(t, h, "vol-rf2-a", "node-a1", "node-a2") + seedRF2PlacementForServers(t, h, "vol-rf2-b", "node-b1", "node-b2") + ingestRF2ObservationForServers(t, h, "vol-rf2-a", "node-a1", "node-a2", true, true) + ingestRF2ObservationForServers(t, h, "vol-rf2-b", "node-b1", "node-b2", true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + for _, volumeID := range []string{"vol-rf2-a", "vol-rf2-b"} { + line := waitAuthorityLine(t, h.Publisher(), volumeID) + if line.ReplicaID != "r1" || line.Epoch != 1 || line.EndpointVersion != 1 { + t.Fatalf("volume %s line=%+v want r1@1/1", volumeID, line) + } + } +} + +func TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 1 { + t.Fatalf("result=%+v want one RF3 promotion probe and one block", result) + } + time.Sleep(100 * time.Millisecond) + got, ok := h.Publisher().VolumeAuthorityLine("vol-rf3") + if !ok { + t.Fatal("authority line disappeared") + } + if got.ReplicaID != "r1" || got.Epoch != initial.Epoch || got.EndpointVersion != initial.EndpointVersion { + t.Fatalf("RF3 failover must not use heartbeat readiness without fresh probe: got %+v want unchanged %+v", got, initial) + } +} + +func TestMountedFailover_ProductLoopRF3BlocksHealthyCurrentRebalanceWithoutProbe(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RebalanceSkew: 1, + }) + defer closeTestMaster(t, h) + seedRF3PlacementForServers(t, h, "vol-rf3-a", "node-a", "node-b", "node-c") + seedRF3PlacementForServers(t, h, "vol-rf3-b", "node-a", "node-b", "node-c") + ingestRF3ObservationForServers(t, h, "vol-rf3-a", "node-a", "node-b", "node-c", true, true, true) + ingestRF3ObservationForServers(t, h, "vol-rf3-b", "node-a", "node-b", "node-c", true, true, true) + + for _, volumeID := range []string{"vol-rf3-a", "vol-rf3-b"} { + if err := h.ctrl.SubmitAssignmentAsk(authority.AssignmentAsk{ + VolumeID: volumeID, + ReplicaID: "r1", + DataAddr: "127.0.0.1:19101", + CtrlAddr: "127.0.0.1:19102", + Intent: authority.IntentBind, + }); err != nil { + t.Fatalf("seed authority line for %s: %v", volumeID, err) + } + } + initialA := waitAuthorityLine(t, h.Publisher(), "vol-rf3-a") + initialB := waitAuthorityLine(t, h.Publisher(), "vol-rf3-b") + if initialA.ReplicaID != "r1" || initialB.ReplicaID != "r1" { + t.Fatalf("initial lines=%+v %+v want both r1", initialA, initialB) + } + + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("rebalance product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 1 { + t.Fatalf("result=%+v want RF3 rebalance candidates blocked without probe", result) + } + time.Sleep(100 * time.Millisecond) + gotA, ok := h.Publisher().VolumeAuthorityLine("vol-rf3-a") + if !ok { + t.Fatal("authority line for vol-rf3-a disappeared") + } + gotB, ok := h.Publisher().VolumeAuthorityLine("vol-rf3-b") + if !ok { + t.Fatal("authority line for vol-rf3-b disappeared") + } + if gotA.ReplicaID != initialA.ReplicaID || gotA.Epoch != initialA.Epoch || + gotB.ReplicaID != initialB.ReplicaID || gotB.Epoch != initialB.Epoch { + t.Fatalf("RF3 rebalance must not use heartbeat readiness without fresh probe: got %+v %+v want unchanged %+v %+v", gotA, gotB, initialA, initialB) + } +} + +func TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + {ReplicaID: "r3", Ready: true, DurableLSN: 51}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want one successful RF3 promotion probe", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r2") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r2@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3PrefersHighestDurableLSNAboveRequired(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + {ReplicaID: "r3", Ready: true, DurableLSN: 60}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want one successful RF3 promotion probe", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r3@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 70}, + {ReplicaID: "r3", Ready: true, DurableLSN: 90}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want unknown required LSN to select highest durable survivor", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r3@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "best-effort", + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 70}, + {ReplicaID: "r3", Ready: true, DurableLSN: 90}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want best-effort unknown required LSN to select highest durable survivor", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r3@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentProbeIsDownDespiteStaleHeartbeat(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: false}, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + {ReplicaID: "r3", Ready: true, DurableLSN: 52}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + // Heartbeat state still says r1 is acceptable. The on-demand + // current-primary probe is the fresher failure signal and must + // force the authority decision to the proven survivor. + ingestRF3Observation(t, h, true, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want one successful RF3 promotion probe", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r2") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r2@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3DoesNotPromoteWhenCurrentProbeIsReady(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 52}, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + ingestRF3Observation(t, h, true, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("healthy product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want probe without blocked promotion", result) + } + time.Sleep(100 * time.Millisecond) + got, ok := h.Publisher().VolumeAuthorityLine("vol-rf3") + if !ok { + t.Fatal("authority line disappeared") + } + if got.ReplicaID != initial.ReplicaID || got.Epoch != initial.Epoch || got.EndpointVersion != initial.EndpointVersion { + t.Fatalf("ready current primary must not be replaced: got %+v want unchanged %+v", got, initial) + } +} + +func TestMountedFailover_ProductLoopRF3ProbeCanAuthorizeStaleHeartbeatReadiness(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + + ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", + false, false, + true, false, + true, false) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 0 { + t.Fatalf("result=%+v want one successful RF3 promotion probe", result) + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r2") + if failover.Epoch != 2 || failover.EndpointVersion != 1 { + t.Fatalf("failover line=%+v want r2@2/1", failover) + } +} + +func TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "best-effort", + SyncAckLSN: 52, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 52}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 1 { + t.Fatalf("result=%+v want best-effort probe blocked for RF3 HA", result) + } + time.Sleep(100 * time.Millisecond) + got, ok := h.Publisher().VolumeAuthorityLine("vol-rf3") + if !ok { + t.Fatal("authority line disappeared") + } + if got.ReplicaID != initial.ReplicaID || got.Epoch != initial.Epoch || got.EndpointVersion != initial.EndpointVersion { + t.Fatalf("best-effort evidence must not satisfy RF3 HA promotion: got %+v want unchanged %+v", got, initial) + } +} + +func TestMountedFailover_ProductLoopRF3UnknownProbeCandidateCountsBlocked(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{ + result: PromotionProbeResult{ + AckProfile: "sync-quorum", + SyncAckLSN: 52, + Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r9", Ready: true, DurableLSN: 52}, + }, + }, + }) + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + + ingestRF3Observation(t, h, false, true, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes != 1 || result.PromotionBlocked != 1 { + t.Fatalf("result=%+v want unknown probe candidate counted as blocked", result) + } + time.Sleep(100 * time.Millisecond) + got, ok := h.Publisher().VolumeAuthorityLine("vol-rf3") + if !ok { + t.Fatal("authority line disappeared") + } + if got.ReplicaID != initial.ReplicaID || got.Epoch != initial.Epoch || got.EndpointVersion != initial.EndpointVersion { + t.Fatalf("unknown probe candidate must not satisfy RF3 promotion: got %+v want unchanged %+v", got, initial) + } +} + func TestG15c_ProductLoopReconcilesCreatedVolumeBeforePublishing(t *testing.T) { h := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, h) @@ -180,6 +707,168 @@ func seedVerifiedExistingReplicaPlacement(t *testing.T, h *Host) { } } +func seedRF2Placement(t *testing.T, h *Host) { + t.Helper() + seedRF2PlacementFor(t, h, "vol-rf2") +} + +func seedRF3Placement(t *testing.T, h *Host) { + t.Helper() + seedRF3PlacementForServers(t, h, "vol-rf3", "node-a", "node-b", "node-c") +} + +func seedRF2PlacementFor(t *testing.T, h *Host, volumeID string) { + t.Helper() + seedRF2PlacementForServers(t, h, volumeID, "node-a", "node-b") +} + +func seedRF2PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID string) { + t.Helper() + stores := h.Lifecycle() + if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ + VolumeID: volumeID, + DesiredRF: 2, + Candidates: []lifecycle.PlacementCandidate{ + { + VolumeID: volumeID, + ServerID: r1ServerID, + ReplicaID: "r1", + Source: lifecycle.PlacementSourceExistingReplica, + }, + { + VolumeID: volumeID, + ServerID: r2ServerID, + ReplicaID: "r2", + Source: lifecycle.PlacementSourceExistingReplica, + }, + }, + }); err != nil { + t.Fatalf("apply RF2 placement: %v", err) + } +} + +func ingestRF2Observation(t *testing.T, h *Host, r1Ready, r2Ready bool) { + t.Helper() + ingestRF2ObservationFor(t, h, "vol-rf2", r1Ready, r2Ready) +} + +func ingestRF3Observation(t *testing.T, h *Host, r1Ready, r2Ready, r3Ready bool) { + t.Helper() + ingestRF3ObservationForServers(t, h, "vol-rf3", "node-a", "node-b", "node-c", r1Ready, r2Ready, r3Ready) +} + +func ingestRF2ObservationFor(t *testing.T, h *Host, volumeID string, r1Ready, r2Ready bool) { + t.Helper() + ingestRF2ObservationForServers(t, h, volumeID, "node-a", "node-b", r1Ready, r2Ready) +} + +func ingestRF2ObservationForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID string, r1Ready, r2Ready bool) { + t.Helper() + now := time.Now().UTC() + for _, obs := range []authority.Observation{ + { + ServerID: r1ServerID, + ObservedAt: now, + Server: authority.ServerFact{Reachable: r1Ready, Eligible: r1Ready}, + Slots: []authority.SlotFact{{ + VolumeID: volumeID, + ReplicaID: "r1", + DataAddr: "127.0.0.1:19101", + CtrlAddr: "127.0.0.1:19102", + Reachable: r1Ready, + ReadyForPrimary: r1Ready, + Eligible: r1Ready, + EvidenceScore: 20, + }}, + }, + { + ServerID: r2ServerID, + ObservedAt: now, + Server: authority.ServerFact{Reachable: r2Ready, Eligible: r2Ready}, + Slots: []authority.SlotFact{{ + VolumeID: volumeID, + ReplicaID: "r2", + DataAddr: "127.0.0.1:19201", + CtrlAddr: "127.0.0.1:19202", + Reachable: r2Ready, + ReadyForPrimary: r2Ready, + Eligible: r2Ready, + EvidenceScore: 10, + }}, + }, + } { + if err := h.ObservationHost().Ingest(obs); err != nil { + t.Fatalf("ingest RF2 observation: %v", err) + } + } +} + +func seedRF3PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string) { + t.Helper() + stores := h.Lifecycle() + if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ + VolumeID: volumeID, + DesiredRF: 3, + Candidates: []lifecycle.PlacementCandidate{ + {VolumeID: volumeID, ServerID: r1ServerID, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}, + {VolumeID: volumeID, ServerID: r2ServerID, ReplicaID: "r2", Source: lifecycle.PlacementSourceExistingReplica}, + {VolumeID: volumeID, ServerID: r3ServerID, ReplicaID: "r3", Source: lifecycle.PlacementSourceExistingReplica}, + }, + }); err != nil { + t.Fatalf("apply RF3 placement: %v", err) + } +} + +func ingestRF3ObservationForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string, r1Ready, r2Ready, r3Ready bool) { + t.Helper() + ingestRF3ObservationForServersWithReady(t, h, volumeID, r1ServerID, r2ServerID, r3ServerID, + r1Ready, r1Ready, + r2Ready, r2Ready, + r3Ready, r3Ready) +} + +func ingestRF3ObservationForServersWithReady(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string, r1Reachable, r1Ready, r2Reachable, r2Ready, r3Reachable, r3Ready bool) { + t.Helper() + now := time.Now().UTC() + for i, obs := range []struct { + serverID string + replicaID string + reachable bool + ready bool + }{ + {serverID: r1ServerID, replicaID: "r1", reachable: r1Reachable, ready: r1Ready}, + {serverID: r2ServerID, replicaID: "r2", reachable: r2Reachable, ready: r2Ready}, + {serverID: r3ServerID, replicaID: "r3", reachable: r3Reachable, ready: r3Ready}, + } { + if err := h.ObservationHost().Ingest(authority.Observation{ + ServerID: obs.serverID, + ObservedAt: now, + Server: authority.ServerFact{Reachable: obs.reachable, Eligible: obs.reachable}, + Slots: []authority.SlotFact{{ + VolumeID: volumeID, + ReplicaID: obs.replicaID, + DataAddr: "127.0.0.1:19" + string(rune('1'+i)) + "01", + CtrlAddr: "127.0.0.1:19" + string(rune('1'+i)) + "02", + Reachable: obs.reachable, + ReadyForPrimary: obs.ready, + Eligible: obs.reachable, + EvidenceScore: uint64(30 - i), + }}, + }); err != nil { + t.Fatalf("ingest RF3 observation: %v", err) + } + } +} + +type staticPromotionProbe struct { + result PromotionProbeResult + err error +} + +func (s staticPromotionProbe) ProbePromotionCandidates(string, authority.AuthorityBasis, []authority.ReplicaCandidate) (PromotionProbeResult, error) { + return s.result, s.err +} + func recvAssignmentInfo(t *testing.T, ch <-chan adapter.AssignmentInfo) adapter.AssignmentInfo { t.Helper() select { diff --git a/seaweed-block/core/host/master/promotion_probe.go b/seaweed-block/core/host/master/promotion_probe.go new file mode 100644 index 0000000000..f0f7e66439 --- /dev/null +++ b/seaweed-block/core/host/master/promotion_probe.go @@ -0,0 +1,218 @@ +package master + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +type WorkloadPlanPromotionProbeConfig struct { + AckProfile string + RequiredLSNByVolume map[string]uint64 + ExternalStatus bool + HTTPClient *http.Client +} + +func NewWorkloadPlanPromotionEvidenceProvider(plans []lifecycle.BlockVolumeWorkloadPlan, cfg WorkloadPlanPromotionProbeConfig) PromotionEvidenceProvider { + httpClient := cfg.HTTPClient + if httpClient == nil { + httpClient = &http.Client{Timeout: 2 * time.Second} + } + statusAddrs := map[string]map[string]string{} + for _, plan := range plans { + for _, replica := range plan.Replicas { + port := replica.ISCSIListenPort + if plan.Protocol == "nvme" && replica.NVMeListenPort > 0 { + port = replica.NVMeListenPort + } + if port <= 0 { + continue + } + if statusAddrs[plan.VolumeID] == nil { + statusAddrs[plan.VolumeID] = map[string]string{} + } + host := "127.0.0.1" + if cfg.ExternalStatus { + h, err := promotionProbeHostFromAddr(replica.DataAddr) + if err != nil { + continue + } + host = h + } + statusAddrs[plan.VolumeID][replica.ReplicaID] = fmt.Sprintf("%s:%d", host, port+20000) + } + } + return &workloadPlanPromotionEvidenceProvider{ + ackProfile: cfg.AckProfile, + required: cloneRequiredLSNMap(cfg.RequiredLSNByVolume), + status: statusAddrs, + client: httpClient, + } +} + +type workloadPlanPromotionEvidenceProvider struct { + ackProfile string + required map[string]uint64 + status map[string]map[string]string + client *http.Client +} + +func (p *workloadPlanPromotionEvidenceProvider) ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) { + result := PromotionProbeResult{ + AckProfile: p.ackProfile, + SyncAckLSN: p.required[volumeID], + Candidates: make([]PromotionCandidateEvidence, 0, len(candidates)), + } + if current.ReplicaID != "" { + statusAddr := p.status[volumeID][current.ReplicaID] + if statusAddr == "" { + result.Current = PromotionCandidateEvidence{ReplicaID: current.ReplicaID, ProbeAddr: "missing"} + } else if evidence, err := p.probeCurrent(volumeID, current.ReplicaID, statusAddr); err == nil { + result.CurrentKnown = true + result.Current = evidence + } else { + result.Current = PromotionCandidateEvidence{ReplicaID: current.ReplicaID, ProbeAddr: statusAddr} + } + } + for _, candidate := range candidates { + statusAddr := p.status[volumeID][candidate.ReplicaID] + if statusAddr == "" { + result.Candidates = append(result.Candidates, PromotionCandidateEvidence{ReplicaID: candidate.ReplicaID, ProbeAddr: "missing"}) + continue + } + evidence, err := p.probeCandidate(volumeID, candidate.ReplicaID, statusAddr) + if err != nil { + result.Candidates = append(result.Candidates, PromotionCandidateEvidence{ReplicaID: candidate.ReplicaID}) + continue + } + result.Candidates = append(result.Candidates, evidence) + } + return result, nil +} + +func (p *workloadPlanPromotionEvidenceProvider) probeCandidate(volumeID, replicaID, statusAddr string) (PromotionCandidateEvidence, error) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + var local volume.StatusProjection + if err := getPromotionProbeJSON(ctx, p.client, statusAddr, "/status", volumeID, &local); err != nil { + return PromotionCandidateEvidence{ReplicaID: replicaID, ProbeAddr: statusAddr}, err + } + var durableBody struct { + Volumes []durable.VolumeStatus + } + if err := getPromotionProbeJSON(ctx, p.client, statusAddr, "/status/durable", volumeID, &durableBody); err != nil { + return PromotionCandidateEvidence{ReplicaID: replicaID, ProbeAddr: statusAddr}, err + } + var best durable.VolumeStatus + for _, st := range durableBody.Volumes { + if st.VolumeID != volumeID || st.ReplicaID != replicaID || !st.FrontierKnown { + continue + } + if st.DurableLSN >= best.DurableLSN { + best = st + } + } + return PromotionCandidateEvidence{ + ReplicaID: replicaID, + ProbeAddr: statusAddr, + Ready: local.VolumeID == volumeID && + local.ReplicaID == replicaID && + strings.EqualFold(local.ReplicationRole, "replica_ready") && + best.FrontierKnown, + DurableLSN: best.DurableLSN, + }, nil +} + +func (p *workloadPlanPromotionEvidenceProvider) probeCurrent(volumeID, replicaID, statusAddr string) (PromotionCandidateEvidence, error) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + var local volume.StatusProjection + if err := getPromotionProbeJSON(ctx, p.client, statusAddr, "/status", volumeID, &local); err != nil { + return PromotionCandidateEvidence{ReplicaID: replicaID, ProbeAddr: statusAddr}, err + } + return PromotionCandidateEvidence{ + ReplicaID: replicaID, + ProbeAddr: statusAddr, + Ready: local.VolumeID == volumeID && + local.ReplicaID == replicaID && + strings.EqualFold(local.AuthorityRole, volume.AuthorityRolePrimary) && + local.Healthy && + local.FrontendPrimaryReady, + }, nil +} + +func getPromotionProbeJSON(ctx context.Context, client *http.Client, base, suffix, volumeID string, out any) error { + endpoint, err := promotionProbeEndpoint(base, suffix, volumeID) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("GET %s: %s", endpoint, resp.Status) + } + return json.NewDecoder(resp.Body).Decode(out) +} + +func promotionProbeEndpoint(base, suffix, volumeID string) (string, error) { + if !strings.Contains(base, "://") { + base = "http://" + base + } + u, err := url.Parse(base) + if err != nil { + return "", err + } + u.Path = path.Join(strings.TrimRight(u.Path, "/"), suffix) + q := u.Query() + q.Set("volume", volumeID) + u.RawQuery = q.Encode() + return u.String(), nil +} + +func promotionProbeHostFromAddr(addr string) (string, error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return "", fmt.Errorf("node address %q is not host:port: %w", addr, err) + } + if host == "" { + return "", fmt.Errorf("node address %q has empty host", addr) + } + if isLocalhostOrLoopbackHost(host) { + return "", fmt.Errorf("node address %q is loopback; external promotion probes require non-loopback node addresses", addr) + } + return host, nil +} + +func isLocalhostOrLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func cloneRequiredLSNMap(in map[string]uint64) map[string]uint64 { + out := make(map[string]uint64, len(in)) + for k, v := range in { + out[k] = v + } + return out +} diff --git a/seaweed-block/core/host/master/promotion_probe_test.go b/seaweed-block/core/host/master/promotion_probe_test.go new file mode 100644 index 0000000000..ec81e5e621 --- /dev/null +++ b/seaweed-block/core/host/master/promotion_probe_test.go @@ -0,0 +1,259 @@ +package master + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestWorkloadPlanPromotionEvidenceProvider_ProbesDurableFrontiers(t *testing.T) { + var statusHits, durableHits int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("volume") != "vol-rf3" { + t.Fatalf("volume query=%q want vol-rf3", r.URL.Query().Get("volume")) + } + switch r.URL.Path { + case "/status": + statusHits++ + _ = json.NewEncoder(w).Encode(volume.StatusProjection{ + Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: "r2"}, + ReplicationRole: "replica_ready", + }) + case "/status/durable": + durableHits++ + _ = json.NewEncoder(w).Encode(struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{ + VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52, + }}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + provider := NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{ + VolumeID: "vol-rf3", + Protocol: "iscsi", + Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ + ReplicaID: "r2", ISCSIListenPort: 3260, + }}, + }}, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + RequiredLSNByVolume: map[string]uint64{"vol-rf3": 52}, + HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"), + }) + + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2"}}) + if err != nil { + t.Fatalf("probe: %v", err) + } + if result.AckProfile != "sync-quorum" || result.SyncAckLSN != 52 { + t.Fatalf("result profile/lsn=%+v", result) + } + if len(result.Candidates) != 1 { + t.Fatalf("candidates=%d want 1", len(result.Candidates)) + } + got := result.Candidates[0] + if got.ReplicaID != "r2" || !got.Ready || got.DurableLSN != 52 { + t.Fatalf("candidate=%+v want r2 ready durable 52", got) + } + if statusHits != 1 || durableHits != 1 { + t.Fatalf("hits status=%d durable=%d want 1/1", statusHits, durableHits) + } +} + +func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + _ = json.NewEncoder(w).Encode(volume.StatusProjection{ + Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: "r2"}, + ReplicationRole: "not_ready", + }) + case "/status/durable": + _ = json.NewEncoder(w).Encode(struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{ + VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 90, + }}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + provider := NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{ + VolumeID: "vol-rf3", + Protocol: "iscsi", + Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ + ReplicaID: "r2", ISCSIListenPort: 3260, + }}, + }}, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"), + }) + + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2"}}) + if err != nil { + t.Fatalf("probe: %v", err) + } + got := result.Candidates[0] + if got.Ready || got.DurableLSN != 90 { + t.Fatalf("candidate=%+v want durable evidence but not ready", got) + } +} + +func TestWorkloadPlanPromotionEvidenceProvider_CurrentUnknownWithoutProbeAddress(t *testing.T) { + provider := NewWorkloadPlanPromotionEvidenceProvider(nil, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + }) + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{ReplicaID: "r1"}, nil) + if err != nil { + t.Fatalf("probe: %v", err) + } + if result.CurrentKnown { + t.Fatalf("current without probe address must not be marked known: %+v", result) + } + if result.Current.ReplicaID != "r1" || result.Current.ProbeAddr != "missing" { + t.Fatalf("current evidence=%+v", result.Current) + } +} + +func TestWorkloadPlanPromotionEvidenceProvider_CurrentKnownAfterSuccessfulProbe(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + _ = json.NewEncoder(w).Encode(volume.StatusProjection{ + Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: "r1", Healthy: true}, + AuthorityRole: volume.AuthorityRolePrimary, + FrontendPrimaryReady: true, + }) + case "/status/durable": + _ = json.NewEncoder(w).Encode(struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{ + VolumeID: "vol-rf3", ReplicaID: "r1", FrontierKnown: true, DurableLSN: 52, + }}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + provider := NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{ + VolumeID: "vol-rf3", + Protocol: "iscsi", + Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ + ReplicaID: "r1", ISCSIListenPort: 3260, + }}, + }}, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"), + }) + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{ReplicaID: "r1"}, nil) + if err != nil { + t.Fatalf("probe: %v", err) + } + if !result.CurrentKnown || result.Current.ReplicaID != "r1" || !result.Current.Ready { + t.Fatalf("current evidence=%+v known=%t", result.Current, result.CurrentKnown) + } +} + +func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusUsesNodeAddress(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + _ = json.NewEncoder(w).Encode(volume.StatusProjection{ + Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: "r2"}, + ReplicationRole: volume.ReplicationRoleReady, + }) + case "/status/durable": + _ = json.NewEncoder(w).Encode(struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{ + VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52, + }}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + provider := NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{ + VolumeID: "vol-rf3", + Protocol: "iscsi", + Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ + ReplicaID: "r2", DataAddr: "10.0.0.2:19103", ISCSIListenPort: 3260, + }}, + }}, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + ExternalStatus: true, + HTTPClient: rewriteHTTPClient(server.URL, "10.0.0.2:23260"), + }) + + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2"}}) + if err != nil { + t.Fatalf("probe: %v", err) + } + if len(result.Candidates) != 1 || !result.Candidates[0].Ready { + t.Fatalf("candidates=%+v want r2 ready", result.Candidates) + } + if result.Candidates[0].ProbeAddr != "10.0.0.2:23260" { + t.Fatalf("probe addr=%q want external node status addr", result.Candidates[0].ProbeAddr) + } +} + +func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusRejectsLoopbackNodeAddress(t *testing.T) { + provider := NewWorkloadPlanPromotionEvidenceProvider([]lifecycle.BlockVolumeWorkloadPlan{{ + VolumeID: "vol-rf3", + Protocol: "iscsi", + Replicas: []lifecycle.BlockVolumeReplicaWorkload{{ + ReplicaID: "r2", DataAddr: "127.0.0.1:19103", ISCSIListenPort: 3260, + }}, + }}, WorkloadPlanPromotionProbeConfig{ + AckProfile: "sync-quorum", + ExternalStatus: true, + }) + + result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2"}}) + if err != nil { + t.Fatalf("probe: %v", err) + } + if len(result.Candidates) != 1 || result.Candidates[0].ProbeAddr != "missing" { + t.Fatalf("candidates=%+v want missing probe addr for loopback node address", result.Candidates) + } +} + +func rewriteHTTPClient(targetBase, wantHost string) *http.Client { + return &http.Client{Transport: rewriteRoundTripper{ + base: strings.TrimRight(targetBase, "/"), + host: wantHost, + }} +} + +type rewriteRoundTripper struct { + base string + host string +} + +func (r rewriteRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Host == r.host { + rewritten := *req.URL + baseReq, _ := http.NewRequest(http.MethodGet, r.base, nil) + rewritten.Scheme = baseReq.URL.Scheme + rewritten.Host = baseReq.URL.Host + req = req.Clone(req.Context()) + req.URL = &rewritten + req.Host = rewritten.Host + } + return http.DefaultTransport.RoundTrip(req) +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 8c48ac6ae9..6c2f157882 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -32,6 +32,7 @@ type services struct { control.UnimplementedObservationServiceServer control.UnimplementedAssignmentServiceServer control.UnimplementedEvidenceServiceServer + control.UnimplementedClusterEvidenceServiceServer control.UnimplementedLifecycleServiceServer host *Host @@ -303,7 +304,12 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq resp.ReplicaId = line.ReplicaID resp.Epoch = line.Epoch resp.EndpointVersion = line.EndpointVersion - resp.Frontends = statusFrontendsForAssignedLine(s.host.obs, req.VolumeId, line.ReplicaID, line.Assigned) + replicaIDs := s.host.replicaSlotsFor(req.VolumeId) + if len(replicaIDs) == 0 && line.ReplicaID != "" { + replicaIDs = []string{line.ReplicaID} + } + replicaIDs = primaryFirstReplicaIDs(replicaIDs, line.ReplicaID) + resp.Frontends = statusFrontendsForAssignedVolume(s.host.obs, req.VolumeId, replicaIDs, line.Assigned) } if ev, ok := ctrl.LastUnsupported(req.VolumeId); ok { resp.LastUnsupportedReason = ev.Reason @@ -315,13 +321,67 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq } func statusFrontendsForAssignedLine(obs *authority.ObservationHost, volumeID, replicaID string, assigned bool) []*control.FrontendTarget { + return statusFrontendsForAssignedVolume(obs, volumeID, []string{replicaID}, assigned) +} + +func primaryFirstReplicaIDs(replicaIDs []string, primaryReplicaID string) []string { + if primaryReplicaID == "" || len(replicaIDs) == 0 { + return replicaIDs + } + out := make([]string, 0, len(replicaIDs)) + seenPrimary := false + for _, replicaID := range replicaIDs { + if replicaID == primaryReplicaID { + if !seenPrimary { + out = append(out, replicaID) + seenPrimary = true + } + continue + } + } + if !seenPrimary { + out = append(out, primaryReplicaID) + } + for _, replicaID := range replicaIDs { + if replicaID == "" || replicaID == primaryReplicaID { + continue + } + out = append(out, replicaID) + } + return out +} + +func statusFrontendsForAssignedVolume(obs *authority.ObservationHost, volumeID string, replicaIDs []string, assigned bool) []*control.FrontendTarget { if !assigned || obs == nil { return nil } - if slot, ok := obs.Store().SlotFact(volumeID, replicaID); ok { - return frontendTargetsToWire(slot.Frontends) + out := make([]*control.FrontendTarget, 0, len(replicaIDs)) + seen := map[string]struct{}{} + for _, replicaID := range replicaIDs { + if replicaID == "" { + continue + } + slot, ok := obs.Store().SlotFact(volumeID, replicaID) + if !ok { + continue + } + for _, ft := range frontendTargetsToWire(slot.Frontends) { + key := frontendTargetKey(ft) + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + out = append(out, ft) + } } - return nil + return out +} + +func frontendTargetKey(ft *control.FrontendTarget) string { + if ft == nil { + return "" + } + return fmt.Sprintf("%s|%s|%s|%s|%d|%d", ft.GetProtocol(), ft.GetAddr(), ft.GetIqn(), ft.GetNqn(), ft.GetLun(), ft.GetNsid()) } // validateHeartbeat rejects reports that are missing required diff --git a/seaweed-block/core/host/master/services_g5_5a_test.go b/seaweed-block/core/host/master/services_g5_5a_test.go index 4e2adec768..7dddbbe5a9 100644 --- a/seaweed-block/core/host/master/services_g5_5a_test.go +++ b/seaweed-block/core/host/master/services_g5_5a_test.go @@ -38,9 +38,10 @@ func (s *stubObs) SlotFact(volumeID, replicaID string) (authority.SlotFact, bool // TestResolvePeers_R1Bound_R2ObservedOnly_R2InPeersWithHeartbeatAddr // is the headline G5-5A pin per architect binding 2026-04-27: -// "with r1 bound and r2 only heartbeat-observed as a supporting -// slot member, the assignment fact delivered to r1 includes r2 in -// peers with its heartbeat-reported DataAddr" +// +// "with r1 bound and r2 only heartbeat-observed as a supporting +// slot member, the assignment fact delivered to r1 includes r2 in +// peers with its heartbeat-reported DataAddr" func TestResolvePeers_R1Bound_R2ObservedOnly_R2InPeersWithHeartbeatAddr(t *testing.T) { pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "10.0.0.1:9220", CtrlAddr: "10.0.0.1:9210"}, diff --git a/seaweed-block/core/host/volume/apply_fact_test.go b/seaweed-block/core/host/volume/apply_fact_test.go index 23f4bc6177..0b26dcbe8e 100644 --- a/seaweed-block/core/host/volume/apply_fact_test.go +++ b/seaweed-block/core/host/volume/apply_fact_test.go @@ -17,8 +17,10 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -66,11 +68,11 @@ func (s *stubAdapter) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog } type stubReplication struct { - rec *orderingRecorder - callCount atomic.Int64 - lastGeneration uint64 - lastTargetIDs []string - returnErr error + rec *orderingRecorder + callCount atomic.Int64 + lastGeneration uint64 + lastTargetIDs []string + returnErr error } func (s *stubReplication) UpdateReplicaSet(generation uint64, targets []replication.ReplicaTarget) error { @@ -236,6 +238,207 @@ func TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication(t *testing.T) { } } +func TestHost_ApplyFact_SupportingReplica_UsesSelfPeerDescriptorWithoutReplication(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r2", rec) + readyCh := make(chan adapter.AssignmentInfo, 1) + h.cfg.ReadyMarker = readyCh + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", // active primary, not self + Epoch: 5, + EndpointVersion: 2, + DataAddr: "127.0.0.1:1000", + CtrlAddr: "127.0.0.1:1001", + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r2", + Epoch: 5, + EndpointVersion: 2, + DataAddr: "127.0.0.1:2000", + CtrlAddr: "127.0.0.1:2001", + }}, + PeerSetGeneration: 100, + } + + h.applyFact(fact) + + if got := a.callCount.Load(); got != 1 { + t.Fatalf("supporting replica should apply self peer lineage once: got %d calls", got) + } + if got := r.callCount.Load(); got != 0 { + t.Fatalf("supporting replica must not install primary fan-out peer set: got %d calls", got) + } + if h.LastOtherLine() == nil || h.LastOtherLine().ReplicaId != "r1" { + t.Fatalf("supporting replica did not record active primary line: %+v", h.LastOtherLine()) + } + if a.lastInfo.VolumeID != "vol1" || a.lastInfo.ReplicaID != "r2" { + t.Fatalf("adapter identity: got volume=%q replica=%q want vol1/r2", a.lastInfo.VolumeID, a.lastInfo.ReplicaID) + } + if a.lastInfo.Epoch != 5 || a.lastInfo.EndpointVersion != 2 { + t.Fatalf("adapter lineage: got epoch=%d ev=%d want 5/2", a.lastInfo.Epoch, a.lastInfo.EndpointVersion) + } + if a.lastInfo.DataAddr != "127.0.0.1:2000" || a.lastInfo.CtrlAddr != "127.0.0.1:2001" { + t.Fatalf("adapter addrs: got data=%q ctrl=%q", a.lastInfo.DataAddr, a.lastInfo.CtrlAddr) + } + seq := rec.snapshot() + if len(seq) != 1 || seq[0] != "OnAssignment" { + t.Fatalf("supporting replica sequence: got %v want [OnAssignment]", seq) + } + select { + case got := <-readyCh: + if got.ReplicaID != "r2" || got.Epoch != 5 || got.EndpointVersion != 2 { + t.Fatalf("ready marker identity: %+v", got) + } + default: + t.Fatal("supporting replica did not emit ready marker for durable lineage latch") + } + + primaryFact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r2", + Epoch: 6, + EndpointVersion: 3, + DataAddr: "127.0.0.1:3000", + CtrlAddr: "127.0.0.1:3001", + PeerSetGeneration: 101, + } + + h.applyFact(primaryFact) + + if got := a.callCount.Load(); got != 2 { + t.Fatalf("promotion after supporting assignment should apply adapter again: got %d calls", got) + } + if got := r.callCount.Load(); got != 1 { + t.Fatalf("promotion after supporting assignment should install primary peer set: got %d calls", got) + } + select { + case got := <-readyCh: + if got.ReplicaID != "r2" || got.Epoch != 6 || got.EndpointVersion != 3 { + t.Fatalf("promoted ready marker identity: %+v", got) + } + default: + t.Fatal("supporting marker must not consume primary ready marker") + } +} + +func TestHost_ApplyFact_SupportingReplica_InvalidSelfPeerDescriptorStaysSuperseded(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r2", rec) + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 5, + EndpointVersion: 2, + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r2", + Epoch: 5, + EndpointVersion: 2, + DataAddr: "", // invalid: do not invent local identity + CtrlAddr: "127.0.0.1:2001", + }}, + } + + h.applyFact(fact) + + if got := a.callCount.Load(); got != 0 { + t.Fatalf("invalid supporting peer descriptor must not call adapter: got %d calls", got) + } + if got := r.callCount.Load(); got != 0 { + t.Fatalf("invalid supporting peer descriptor must not call replication: got %d calls", got) + } + if h.LastOtherLine() == nil || h.LastOtherLine().ReplicaId != "r1" { + t.Fatalf("invalid supporting peer descriptor should still record active primary line: %+v", h.LastOtherLine()) + } +} + +func TestHost_ApplyFact_SupportingReplica_MismatchedSelfPeerLineageStaysSuperseded(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r2", rec) + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 5, + EndpointVersion: 2, + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r2", + Epoch: 5, + EndpointVersion: 3, // newer than the active primary line: reject + DataAddr: "127.0.0.1:2000", + CtrlAddr: "127.0.0.1:2001", + }}, + } + + h.applyFact(fact) + + if got := a.callCount.Load(); got != 0 { + t.Fatalf("mismatched supporting peer lineage must not call adapter: got %d calls", got) + } + if got := r.callCount.Load(); got != 0 { + t.Fatalf("mismatched supporting peer lineage must not call replication: got %d calls", got) + } + if h.LastOtherLine() == nil || h.LastOtherLine().ReplicaId != "r1" { + t.Fatalf("mismatched supporting peer lineage should still record active primary line: %+v", h.LastOtherLine()) + } +} + +func TestHost_ApplyFact_SupportingReplica_ReportsReplicaReadyButNotFrontendPrimary(t *testing.T) { + exec := NewHealthyPathExecutor() + a := adapter.NewVolumeReplicaAdapter(exec) + h := &Host{ + cfg: Config{ + VolumeID: "vol1", + ReplicaID: "r2", + }, + log: newDiscardLogger(), + adpt: a, + } + h.view = NewAdapterProjectionView(a, "vol1", "r2", h) + s := NewStatusServer(h.view) + + h.applyFact(&control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 7, + EndpointVersion: 3, + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r2", + Epoch: 7, + EndpointVersion: 3, + DataAddr: "127.0.0.1:2000", + CtrlAddr: "127.0.0.1:2001", + }}, + }) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if a.Projection().Mode == engine.ModeHealthy { + break + } + time.Sleep(10 * time.Millisecond) + } + if got := a.Projection().Mode; got != engine.ModeHealthy { + t.Fatalf("supporting adapter mode=%s want %s; commands=%v", got, engine.ModeHealthy, exec.Commands()) + } + + body := s.statusProjection() + if body.AuthorityRole != AuthorityRoleUnknown { + t.Fatalf("supporting authority role=%q want %q", body.AuthorityRole, AuthorityRoleUnknown) + } + if body.ReplicationRole != ReplicationRoleReady { + t.Fatalf("supporting replication role=%q want %q", body.ReplicationRole, ReplicationRoleReady) + } + if body.FrontendPrimaryReady { + t.Fatalf("supporting replica_ready must not become frontend primary: %+v", body) + } + report := h.buildReport() + if len(report.GetSlots()) != 1 || !report.GetSlots()[0].GetReadyForPrimary() { + t.Fatalf("supporting replica did not advertise ReadyForPrimary after engine readiness: %+v", report.GetSlots()) + } +} + // --- Test 4: observer-only mode (replication == nil) --- // TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment — diff --git a/seaweed-block/core/host/volume/boundary_guard_test.go b/seaweed-block/core/host/volume/boundary_guard_test.go index a8c6e44b94..935bd91bcf 100644 --- a/seaweed-block/core/host/volume/boundary_guard_test.go +++ b/seaweed-block/core/host/volume/boundary_guard_test.go @@ -13,10 +13,9 @@ import ( // TestNoOtherAssignmentInfoConstruction is the PCDD-STUFFING-001 // AST guard required by T0 sketch §9 / §6.4 rule 5 / §10.7. // -// Rule: at most ONE adapter.AssignmentInfo composite literal in -// core/host/volume/*.go, and that one literal MUST live inside -// the single named decoder decodeAssignmentFact in subscribe.go. -// Scattered literals anywhere else in this package fail the test. +// Rule: adapter.AssignmentInfo construction in core/host/volume/*.go must be +// limited to named boundary functions. Scattered literals anywhere else in this +// package fail the test. // // This is the durable enforcement of the volume-side decode // boundary (sketch §3.1). Without it, a future patch could @@ -77,7 +76,12 @@ func TestNoOtherAssignmentInfoConstruction(t *testing.T) { // Allowed construction sites (PCDD-STUFFING-001 scope): // 1. decodeAssignmentFact in subscribe.go — the master-to-host // fact decoder (T0 sketch §3.1). - // 2. OnPeerAdded in peer_adapter_registry.go — G5-5C Batch #7 + // 2. decodeSelfPeerAssignment in subscribe.go — supporting-replica + // lineage copied from the master's peer descriptor inside an + // AssignmentFact for the active primary. This is still a master-minted + // decode site and is deliberately bounded so a supporting replica can + // become promotion-ready without becoming frontend-primary. + // 3. OnPeerAdded in peer_adapter_registry.go — G5-5C Batch #7 // per-peer engine identity priming. The registry constructs // one AssignmentInfo per admitted peer to seed the per-peer // adapter's engine state (so engine.checkReplicaID accepts @@ -86,20 +90,23 @@ func TestNoOtherAssignmentInfoConstruction(t *testing.T) { // data already decoded upstream and routed through // ReplicaTarget. // - // Any literal outside these two named functions fails the test — + // Any literal outside these named functions fails the test — // the rule predates Batch #7 but the per-peer-adapter shape - // requires a 2nd site that is bounded, named, and AST-pinned + // requires extra sites that are bounded, named, and AST-pinned // here. allowed := map[string]string{ - "decodeAssignmentFact": "subscribe.go", - "OnPeerAdded": "peer_adapter_registry.go", + "decodeAssignmentFact": "subscribe.go", + "decodeSelfPeerAssignment": "subscribe.go", + "OnPeerAdded": "peer_adapter_registry.go", } if len(hits) != len(allowed) { t.Fatalf("expected exactly %d adapter.AssignmentInfo composite literals in core/host/volume (outside tests); got %d: %+v", len(allowed), len(hits), hits) } + countByFn := make(map[string]int, len(hits)) for _, h := range hits { + countByFn[h.fn]++ wantFile, ok := allowed[h.fn] if !ok { t.Errorf("adapter.AssignmentInfo literal in disallowed function %s (file %s, line %d). Allowed: %v", @@ -111,6 +118,11 @@ func TestNoOtherAssignmentInfoConstruction(t *testing.T) { h.fn, wantFile, h.file, h.line) } } + for fn := range allowed { + if countByFn[fn] != 1 { + t.Errorf("adapter.AssignmentInfo literal count for %s = %d; want exactly 1", fn, countByFn[fn]) + } + } } // isAssignmentInfoType returns true if the composite-literal type diff --git a/seaweed-block/core/host/volume/frontend_targets_test.go b/seaweed-block/core/host/volume/frontend_targets_test.go index 9611d3b8c8..c9d2866c7c 100644 --- a/seaweed-block/core/host/volume/frontend_targets_test.go +++ b/seaweed-block/core/host/volume/frontend_targets_test.go @@ -3,6 +3,7 @@ package volume import ( "testing" + "github.com/seaweedfs/seaweed-block/core/engine" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -60,6 +61,83 @@ func TestHost_SetFrontendTargets_ReplacesPreviousSet(t *testing.T) { } } +func TestHost_BuildReport_NotReadyForPrimaryFromHeartbeatAlone(t *testing.T) { + h := newTestVolumeHost(t) + defer func() { _ = h.Close() }() + + slot := h.buildReport().GetSlots()[0] + if slot.GetReadyForPrimary() { + t.Fatalf("fresh observed process must not be promotion-ready from heartbeat alone: %+v", slot) + } +} + +func TestHost_BuildReport_SupportingReplicaReadyCanBePromotionCandidate(t *testing.T) { + h := &Host{ + cfg: Config{ + ServerID: "node-a", + VolumeID: "v1", + ReplicaID: "r2", + DataAddr: "127.0.0.1:9202", + CtrlAddr: "127.0.0.1:9102", + }, + } + h.view = NewAdapterProjectionView( + stubProjector{ + p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}, + ready: &engine.PromotionReadyFact{ + Ready: true, + Reason: engine.PromotionReadyReasonReady, + ReplicaID: "r2", + Epoch: 1, + EndpointVersion: 1, + }, + }, + "v1", + "r2", + stubProbe{other: &control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 1, EndpointVersion: 1}}, + ) + + if h.view.Projection().Healthy { + t.Fatal("supporting replica must remain frontend-unhealthy before authority moves") + } + slot := h.buildReport().GetSlots()[0] + if !slot.GetReadyForPrimary() { + t.Fatalf("caught-up supporting replica should be a promotion candidate: %+v", slot) + } +} + +func TestHost_BuildReport_SupersededReplicaNotReadyForPrimary(t *testing.T) { + h := &Host{ + cfg: Config{ + ServerID: "node-a", + VolumeID: "v1", + ReplicaID: "r1", + DataAddr: "127.0.0.1:9201", + CtrlAddr: "127.0.0.1:9101", + }, + } + h.view = NewAdapterProjectionView( + stubProjector{ + p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}, + ready: &engine.PromotionReadyFact{ + Ready: true, + Reason: engine.PromotionReadyReasonReady, + ReplicaID: "r1", + Epoch: 1, + EndpointVersion: 1, + }, + }, + "v1", + "r1", + stubProbe{yes: true}, + ) + + slot := h.buildReport().GetSlots()[0] + if slot.GetReadyForPrimary() { + t.Fatalf("superseded replica must not be re-promoted from stale healthy projection: %+v", slot) + } +} + func newTestVolumeHost(t *testing.T) *Host { t.Helper() h, err := New(Config{ diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index cba7d8b208..a14229600a 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -119,7 +119,9 @@ type Host struct { wg sync.WaitGroup started atomic.Bool - readyOnce atomic.Bool + readyOnce atomic.Bool + readyMarkerMu sync.Mutex + supportingReadyMarks map[string]struct{} // lastOtherLine captures the most recent AssignmentFact that // named a REPLICA OTHER than self for this host's VolumeID. @@ -404,13 +406,31 @@ func (h *Host) buildReport() *control.HeartbeatReport { CtrlAddr: h.cfg.CtrlAddr, Frontends: h.frontendTargetsSnapshot(), Reachable: true, - ReadyForPrimary: true, + ReadyForPrimary: h.readyForPrimaryFact(), Eligible: true, }, }, } } +// readyForPrimaryFact is the volume-side promotion-readiness fact used by the +// authority controller for failover/rebalance candidates. A live process or +// Kubernetes Ready pod is not enough; the adapter must expose an engine +// truth-domain promotion fact, and this replica must not have been superseded by +// a newer authority line. Supporting replica-ready at the same lineage is still +// a valid candidate fact even though it remains frontend-unhealthy until +// authority moves. +func (h *Host) readyForPrimaryFact() bool { + if h == nil || h.view == nil { + return false + } + fact := h.view.PromotionReadyFact() + if !fact.Ready { + return false + } + return !h.view.isSupersededLine(fact.Epoch, fact.EndpointVersion) +} + // runSubscribe maintains a SubscribeAssignments stream. Reconnects // on stream end / error with bounded backoff. Every delivered // AssignmentFact flows through decodeAssignmentFact → OnAssignment. @@ -498,14 +518,14 @@ func (h *Host) streamOnce(ctx context.Context) error { // 2. Otherwise (self-replica fact): // a. Install replication peer set first (if configured). // b. On UpdateReplicaSet failure, LOG and RETURN WITHOUT -// calling OnAssignment. The adapter's projection stays at -// its prior (not-Healthy until first successful install) -// state; StorageBackend.lineageCheck keeps writes blocked. -// Master's stream replay redelivers this fact on the next -// cycle; natural eventual convergence. +// calling OnAssignment. The adapter's projection stays at +// its prior (not-Healthy until first successful install) +// state; StorageBackend.lineageCheck keeps writes blocked. +// Master's stream replay redelivers this fact on the next +// cycle; natural eventual convergence. // c. Only after replication install succeeds (or observer-only -// mode): apply OnAssignment, driving the adapter's -// projection to Healthy. +// mode): apply OnAssignment, driving the adapter's +// projection to Healthy. // // This preserves the V2 BlockVol.SetReplicaAddrs-then-admit-writes // atomicity that V3 lost when adapter + ReplicationVolume got split @@ -514,10 +534,20 @@ func (h *Host) streamOnce(ctx context.Context) error { // installed, admitting local-only writes with zero fan-out. func (h *Host) applyFact(fact *control.AssignmentFact) { if fact.ReplicaId != h.cfg.ReplicaID { - // Superseded. The volume currently serving - // (vid, self.ReplicaID) is no longer the current - // authoritative line for this volume. + // Another replica is authoritative for this volume line. Record that + // line first so AdapterProjectionView can keep this replica frontend- + // unhealthy even if its local engine is otherwise caught up. h.recordOtherLine(fact) + if info, ok := decodeSelfPeerAssignment(fact, h.cfg.ReplicaID); ok { + h.adpt.OnAssignment(info) + h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated", + h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, fact.ReplicaId) + // Supporting replicas need durable lineage latching for promotion-readiness, + // but this must not consume the primary readyOnce. A later promotion to + // PRIMARY has to emit its own marker for the promoted lineage. + h.emitSupportingReadyMarker(info) + return + } h.log.Printf("blockvolume: volume %s authority is now %s@%d (not this replica %s); recording supersede, not applying to adapter", h.cfg.VolumeID, fact.ReplicaId, fact.Epoch, h.cfg.ReplicaID) return @@ -561,3 +591,24 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { } } } + +func (h *Host) emitSupportingReadyMarker(info adapter.AssignmentInfo) { + if h.cfg.ReadyMarker == nil || info.Epoch == 0 { + return + } + key := fmt.Sprintf("%s/%d/%d", info.ReplicaID, info.Epoch, info.EndpointVersion) + h.readyMarkerMu.Lock() + if h.supportingReadyMarks == nil { + h.supportingReadyMarks = make(map[string]struct{}) + } + if _, ok := h.supportingReadyMarks[key]; ok { + h.readyMarkerMu.Unlock() + return + } + h.supportingReadyMarks[key] = struct{}{} + h.readyMarkerMu.Unlock() + select { + case h.cfg.ReadyMarker <- info: + default: + } +} diff --git a/seaweed-block/core/host/volume/projection_bridge.go b/seaweed-block/core/host/volume/projection_bridge.go index 1d996411fd..ca8db13db3 100644 --- a/seaweed-block/core/host/volume/projection_bridge.go +++ b/seaweed-block/core/host/volume/projection_bridge.go @@ -13,6 +13,10 @@ type adapterProjector interface { Projection() engine.ReplicaProjection } +type promotionReadyProjector interface { + PromotionReadyFact() engine.PromotionReadyFact +} + // SupersedeProbe reports whether this replica's locally-reported // Healthy should be overridden to fail-closed because the master // has published an authoritative line naming a DIFFERENT replica @@ -97,7 +101,7 @@ func (v *AdapterProjectionView) Projection() frontend.Projection { func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection, bool) { p := v.projector.Projection() healthy := p.Mode == engine.ModeHealthy - superseded := healthy && v.probe != nil && v.probe.IsSuperseded(v.replicaID, p.Epoch, p.EndpointVersion) + superseded := healthy && v.isSupersededLine(p.Epoch, p.EndpointVersion) if superseded || (healthy && v.supportingReplicaReady(p.Epoch, p.EndpointVersion)) { healthy = false } @@ -129,6 +133,31 @@ func (v *AdapterProjectionView) supportingReplicaReady(selfEpoch, selfEV uint64) other.GetEndpointVersion() == selfEV } +func (v *AdapterProjectionView) isSupersededLine(epoch, endpointVersion uint64) bool { + return v != nil && + v.probe != nil && + v.probe.IsSuperseded(v.replicaID, epoch, endpointVersion) +} + +// PromotionReadyFact returns a control-facing readiness fact when the wrapped +// adapter exposes one. Test-only projectors that only implement Projection() +// fail closed by returning Ready=false. +func (v *AdapterProjectionView) PromotionReadyFact() engine.PromotionReadyFact { + if v == nil || v.projector == nil { + return engine.PromotionReadyFact{Reason: engine.PromotionReadyReasonNotMember} + } + projector, ok := v.projector.(promotionReadyProjector) + if !ok { + return engine.PromotionReadyFact{ + Reason: engine.PromotionReadyReasonNotCaughtUp, + ReplicaID: v.replicaID, + Epoch: 0, + EndpointVersion: 0, + } + } + return projector.PromotionReadyFact() +} + // EngineProjection returns the underlying engine.ReplicaProjection // (Mode, R/S/H, RecoveryDecision, SessionKind/Phase, Reason). Used // by the G5-5 opt-in `/status/recovery` endpoint to surface recovery diff --git a/seaweed-block/core/host/volume/projection_bridge_test.go b/seaweed-block/core/host/volume/projection_bridge_test.go index 0f6bb9cac5..3a57879e0e 100644 --- a/seaweed-block/core/host/volume/projection_bridge_test.go +++ b/seaweed-block/core/host/volume/projection_bridge_test.go @@ -12,9 +12,18 @@ import ( control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) -type stubProjector struct{ p engine.ReplicaProjection } +type stubProjector struct { + p engine.ReplicaProjection + ready *engine.PromotionReadyFact +} func (s stubProjector) Projection() engine.ReplicaProjection { return s.p } +func (s stubProjector) PromotionReadyFact() engine.PromotionReadyFact { + if s.ready == nil { + return engine.PromotionReadyFact{Reason: engine.PromotionReadyReasonNotCaughtUp} + } + return *s.ready +} type stubProbe struct { yes bool diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 4aec436d0b..aba1d222da 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "net/http" + "strings" "sync" "time" @@ -49,6 +50,7 @@ type StatusServer struct { srv *http.Server addr string recoveryEnabled bool // G5-5: gates /status/recovery; off by default + allowExternal bool peerSource peerStatusSource durableSource durableStatusSource } @@ -109,6 +111,19 @@ func (s *StatusServer) EnableRecoveryEndpoint() { s.recoveryEnabled = true } +// AllowExternalAccess opts into binding and serving on non-loopback addresses. +// This is for controlled Kubernetes node-loss gates where blockmaster must +// probe surviving replicas across nodes. The default remains loopback-only. +// Must be called BEFORE Start. +func (s *StatusServer) AllowExternalAccess() { + s.mu.Lock() + defer s.mu.Unlock() + if s.ln != nil { + return + } + s.allowExternal = true +} + // SetPeerStatusSource enables /status/peers by wiring a primary-side // replication status source. It may be called before or after Start: // the route is registered at Start, and returns 404 until a source is @@ -139,8 +154,14 @@ func (s *StatusServer) Start(addr string) (string, error) { if s.ln != nil { return "", fmt.Errorf("status: already started") } - if err := enforceLoopbackBind(addr); err != nil { - return "", err + if s.allowExternal { + if err := enforceExplicitExternalBind(addr); err != nil { + return "", err + } + } else { + if err := enforceLoopbackBind(addr); err != nil { + return "", err + } } ln, err := net.Listen("tcp", addr) if err != nil { @@ -170,6 +191,12 @@ func (s *StatusServer) Addr() string { return s.addr } +func (s *StatusServer) externalAccessAllowed() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.allowExternal +} + // Close gracefully shuts the server down. Idempotent. func (s *StatusServer) Close(ctx context.Context) error { s.mu.Lock() @@ -183,7 +210,7 @@ func (s *StatusServer) Close(ctx context.Context) error { } func (s *StatusServer) handleStatus(w http.ResponseWriter, r *http.Request) { - if !isLoopbackRemote(r.RemoteAddr) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) return } @@ -248,7 +275,7 @@ func (s *StatusServer) supportingReplicaReady(selfEpoch, selfEV uint64) bool { // G5-5 close (per `v3-batch-process.md` no engine/adapter behavior // change rule); future field additions are append-only. func (s *StatusServer) handleStatusRecovery(w http.ResponseWriter, r *http.Request) { - if !isLoopbackRemote(r.RemoteAddr) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) return } @@ -270,7 +297,7 @@ func (s *StatusServer) handleStatusRecovery(w http.ResponseWriter, r *http.Reque } func (s *StatusServer) handleStatusPeers(w http.ResponseWriter, r *http.Request) { - if !isLoopbackRemote(r.RemoteAddr) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) return } @@ -308,7 +335,7 @@ func (s *StatusServer) handleStatusPeers(w http.ResponseWriter, r *http.Request) } func (s *StatusServer) handleStatusDurable(w http.ResponseWriter, r *http.Request) { - if !isLoopbackRemote(r.RemoteAddr) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) return } @@ -374,6 +401,32 @@ func enforceLoopbackBind(addr string) error { return nil } +func enforceExplicitExternalBind(addr string) error { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return fmt.Errorf("status: bind addr %q not host:port: %w", addr, err) + } + if host == "" { + return fmt.Errorf("status: bind addr %q has empty host; external status bind requires an explicit node address", addr) + } + ip := net.ParseIP(host) + if ip != nil && ip.IsUnspecified() { + return fmt.Errorf("status: bind addr %q is unspecified; external status bind requires a concrete node address", addr) + } + if isLocalhostOrLoopbackHost(host) { + return fmt.Errorf("status: bind addr %q is loopback; external status bind requires a non-loopback node address", addr) + } + return nil +} + +func isLocalhostOrLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + // isLoopbackRemote returns true if RemoteAddr parses to a // loopback IP. Used at request time as a defence-in-depth // check against a reverse-proxy or kernel-level surprise. diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index c473fbe69e..e327522430 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "net/http" + "net/http/httptest" "strings" "testing" "time" @@ -59,6 +60,39 @@ func TestStatusServer_AcceptsLoopbackBindAndServesJSON(t *testing.T) { } } +func TestNodeLoss_StatusServer_ExternalBindPolicyRequiresConcreteHost(t *testing.T) { + if err := enforceExplicitExternalBind("10.0.0.12:23260"); err != nil { + t.Fatalf("concrete node address rejected: %v", err) + } + for _, addr := range []string{":23260", "0.0.0.0:23260", "[::]:23260", "127.0.0.1:23260", "localhost:23260"} { + t.Run(addr, func(t *testing.T) { + if err := enforceExplicitExternalBind(addr); err == nil { + t.Fatalf("external status bind %q must be rejected", addr) + } + }) + } +} + +func TestNodeLoss_StatusServer_AllowExternalAccessServesNonLoopbackClient(t *testing.T) { + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 5, EndpointVersion: 3}} + s := NewStatusServer(NewAdapterProjectionView(p, "v1", "r1", nil)) + + req := httptest.NewRequest(http.MethodGet, "/status?volume=v1", nil) + req.RemoteAddr = "10.0.0.9:44100" + w := httptest.NewRecorder() + s.handleStatus(w, req) + if w.Code != http.StatusForbidden { + t.Fatalf("default non-loopback client status=%d want 403", w.Code) + } + + s.AllowExternalAccess() + w = httptest.NewRecorder() + s.handleStatus(w, req) + if w.Code != http.StatusOK { + t.Fatalf("external non-loopback client status=%d want 200 body=%s", w.Code, w.Body.String()) + } +} + func TestG9A_StatusProjection_ReturnedOldPrimarySupersededNotReady(t *testing.T) { proj := &mutableProjector{p: engine.ReplicaProjection{ Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1, diff --git a/seaweed-block/core/host/volume/subscribe.go b/seaweed-block/core/host/volume/subscribe.go index d6499b49d9..d25f9965d7 100644 --- a/seaweed-block/core/host/volume/subscribe.go +++ b/seaweed-block/core/host/volume/subscribe.go @@ -17,8 +17,8 @@ // - volume host imports core/rpc (wire types) + core/adapter // (consumer API). It MUST NOT import core/authority mint // symbols (Publisher.apply, SubmitObservedState, AssignmentAsk). -// - The ONLY adapter.AssignmentInfo composite literal allowed -// in this package sits in decodeAssignmentFact below. +// - adapter.AssignmentInfo composite literals are allowed only +// in named decode/identity boundary functions. // TestNoOtherAssignmentInfoConstruction (L0) enforces this // as a static guard. package volume @@ -29,16 +29,15 @@ import ( control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) -// decodeAssignmentFact is the SOLE permitted translator from a +// decodeAssignmentFact is the primary translator from a // master-minted wire fact into the adapter's ingress type. It is // a strict field-copy: every field in the output comes directly // from the input's corresponding field. No mutation, no local // defaults, no fields from any other source. // // This is the round-3 architect-pinned boundary (T0 sketch §3.1). -// If a second AssignmentInfo composite literal appears anywhere -// in core/host/volume/ the AST guard in -// TestNoOtherAssignmentInfoConstruction fails. +// Additional supporting-replica decode sites must be named and AST-pinned by +// TestNoOtherAssignmentInfoConstruction. func decodeAssignmentFact(f *control.AssignmentFact) adapter.AssignmentInfo { return adapter.AssignmentInfo{ VolumeID: f.VolumeId, @@ -50,6 +49,36 @@ func decodeAssignmentFact(f *control.AssignmentFact) adapter.AssignmentInfo { } } +// decodeSelfPeerAssignment extracts this host's supporting-replica lineage from +// a master-minted primary AssignmentFact. It is deliberately parallel to +// decodeAssignmentFact and still field-copy only: the peer descriptor is the +// master's statement that this replica belongs to the current volume lineage. +func decodeSelfPeerAssignment(f *control.AssignmentFact, selfReplicaID string) (adapter.AssignmentInfo, bool) { + var zero adapter.AssignmentInfo + for _, p := range f.Peers { + if p.GetReplicaId() != selfReplicaID { + continue + } + if p.GetEpoch() == 0 || + p.GetEndpointVersion() == 0 || + p.GetEpoch() != f.GetEpoch() || + p.GetEndpointVersion() != f.GetEndpointVersion() || + p.GetDataAddr() == "" || + p.GetCtrlAddr() == "" { + return zero, false + } + return adapter.AssignmentInfo{ + VolumeID: f.VolumeId, + ReplicaID: p.ReplicaId, + Epoch: p.Epoch, + EndpointVersion: p.EndpointVersion, + DataAddr: p.DataAddr, + CtrlAddr: p.CtrlAddr, + }, true + } + return zero, false +} + // decodeReplicaTargets is the T4a-5 peer-set decode path. Parallel // to decodeAssignmentFact but produces replication.ReplicaTarget // values + the monotonic peer_set_generation — NOT adapter.Assignment diff --git a/seaweed-block/core/launcher/k8s_client.go b/seaweed-block/core/launcher/k8s_client.go index 3c3e5a277d..0c7488c68d 100644 --- a/seaweed-block/core/launcher/k8s_client.go +++ b/seaweed-block/core/launcher/k8s_client.go @@ -117,6 +117,9 @@ func (c *KubernetesDeploymentClient) ListBlockVolumeDeployments(ctx context.Cont Namespace string `json:"namespace"` Labels map[string]string `json:"labels"` } `json:"metadata"` + Spec struct { + Replicas *int `json:"replicas"` + } `json:"spec"` } `json:"items"` } if err := c.doJSON(req, http.StatusOK, &out); err != nil { @@ -125,9 +128,10 @@ func (c *KubernetesDeploymentClient) ListBlockVolumeDeployments(ctx context.Cont identities := make([]DeploymentIdentity, 0, len(out.Items)) for _, item := range out.Items { identities = append(identities, DeploymentIdentity{ - Namespace: item.Metadata.Namespace, - Name: item.Metadata.Name, - Labels: item.Metadata.Labels, + Namespace: item.Metadata.Namespace, + Name: item.Metadata.Name, + Labels: item.Metadata.Labels, + SpecReplicas: item.Spec.Replicas, }) } return identities, nil diff --git a/seaweed-block/core/launcher/k8s_client_test.go b/seaweed-block/core/launcher/k8s_client_test.go index 0e481a481c..d89eed616a 100644 --- a/seaweed-block/core/launcher/k8s_client_test.go +++ b/seaweed-block/core/launcher/k8s_client_test.go @@ -32,6 +32,7 @@ func TestKubernetesDeploymentClient_ListApplyDelete(t *testing.T) { LabelReplica: "r1", }, }, + "spec": map[string]any{"replicas": 0}, }}, }) case r.Method == http.MethodPatch && r.URL.Path == "/apis/apps/v1/namespaces/default/deployments/sw-blockvolume-pvc-a-r1": @@ -63,6 +64,9 @@ func TestKubernetesDeploymentClient_ListApplyDelete(t *testing.T) { if len(existing) != 1 || existing[0].Name != "sw-blockvolume-pvc-a-r1" { t.Fatalf("existing=%+v", existing) } + if existing[0].SpecReplicas == nil || *existing[0].SpecReplicas != 0 { + t.Fatalf("existing replicas=%v want 0", existing[0].SpecReplicas) + } manifest := RenderedManifest{ Name: "sw-blockvolume-pvc-a-r1", YAML: []byte(`--- diff --git a/seaweed-block/core/launcher/k8s_reconciler.go b/seaweed-block/core/launcher/k8s_reconciler.go index 05017780a4..bf4f0f9daf 100644 --- a/seaweed-block/core/launcher/k8s_reconciler.go +++ b/seaweed-block/core/launcher/k8s_reconciler.go @@ -15,9 +15,10 @@ const ( ) type DeploymentIdentity struct { - Namespace string - Name string - Labels map[string]string + Namespace string + Name string + Labels map[string]string + SpecReplicas *int } type DeploymentClient interface { @@ -55,6 +56,10 @@ func ReconcileBlockVolumeDeployments(ctx context.Context, in ReconcileDeployment } var result ReconcileDeploymentsResult desiredKeys := make(map[string]bool, len(in.Desired)) + existingByKey := make(map[string]DeploymentIdentity, len(in.Existing)) + for _, existing := range in.Existing { + existingByKey[deploymentKey(existing)] = existing + } for _, manifest := range in.Desired { identity, err := DecodeRenderedDeploymentIdentity(manifest) if err != nil { @@ -69,6 +74,21 @@ func ReconcileBlockVolumeDeployments(ctx context.Context, in ReconcileDeployment manifest.Name, identity.Namespace, in.Namespace, ) } + desiredKeys[deploymentKey(identity)] = true + if existing, ok := existingByKey[deploymentKey(identity)]; ok { + reason := "already-exists" + if existing.SpecReplicas != nil && *existing.SpecReplicas == 0 { + reason = "preserve-replicas-zero" + } + result.Skipped++ + result.Actions = append(result.Actions, ReconcileDeploymentAction{ + Action: "skip", + Namespace: identity.Namespace, + Name: identity.Name, + Reason: reason, + }) + continue + } if err := in.Client.ApplyDeployment(ctx, manifest); err != nil { return result, fmt.Errorf("launcher: apply %s: %w", manifest.Name, err) } @@ -79,7 +99,6 @@ func ReconcileBlockVolumeDeployments(ctx context.Context, in ReconcileDeployment Name: identity.Name, Reason: "desired", }) - desiredKeys[deploymentKey(identity)] = true } for _, existing := range in.Existing { diff --git a/seaweed-block/core/launcher/k8s_reconciler_test.go b/seaweed-block/core/launcher/k8s_reconciler_test.go index a10795a4da..4337e724af 100644 --- a/seaweed-block/core/launcher/k8s_reconciler_test.go +++ b/seaweed-block/core/launcher/k8s_reconciler_test.go @@ -22,7 +22,7 @@ func (c *recordingDeploymentClient) DeleteDeployment(_ context.Context, ref Depl return nil } -func TestK8sReconciler_AppliesDesiredAndDeletesOnlyOwnedStaleDeployments(t *testing.T) { +func TestK8sReconciler_AppliesMissingDesiredAndDeletesOnlyOwnedStaleDeployments(t *testing.T) { desired := RenderedManifest{ Name: "sw-blockvolume-pvc-a-r1", YAML: []byte(`--- @@ -42,15 +42,6 @@ metadata: Namespace: "default", Desired: []RenderedManifest{desired}, Existing: []DeploymentIdentity{ - { - Namespace: "default", - Name: "sw-blockvolume-pvc-a-r1", - Labels: map[string]string{ - LabelApp: AppBlockVolume, - LabelVolume: "pvc-a", - LabelReplica: "r1", - }, - }, { Namespace: "default", Name: "sw-blockvolume-pvc-old-r1", @@ -77,6 +68,98 @@ metadata: } } +func TestK8sReconciler_SkipsExistingDesiredDeployment(t *testing.T) { + desired := RenderedManifest{ + Name: "sw-blockvolume-pvc-a-r1", + YAML: []byte(`--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-blockvolume-pvc-a-r1 + namespace: default + labels: + app: sw-blockvolume + sw-block.seaweedfs.com/volume: pvc-a + sw-block.seaweedfs.com/replica: r1 +`), + } + one := 1 + client := &recordingDeploymentClient{} + result, err := ReconcileBlockVolumeDeployments(context.Background(), ReconcileDeploymentsInput{ + Namespace: "default", + Desired: []RenderedManifest{desired}, + Existing: []DeploymentIdentity{{ + Namespace: "default", + Name: "sw-blockvolume-pvc-a-r1", + Labels: map[string]string{ + LabelApp: AppBlockVolume, + LabelVolume: "pvc-a", + LabelReplica: "r1", + }, + SpecReplicas: &one, + }}, + Client: client, + }) + if err != nil { + t.Fatalf("ReconcileBlockVolumeDeployments: %v", err) + } + if len(client.applied) != 0 { + t.Fatalf("existing deployment should not be reapplied: %v", client.applied) + } + if result.Applied != 0 || result.Deleted != 0 || result.Skipped != 1 { + t.Fatalf("result=%+v", result) + } + if got := result.Actions[0].Reason; got != "already-exists" { + t.Fatalf("reason=%q", got) + } +} + +func TestK8sReconciler_PreservesOperatorScaledZeroReplicaDeployment(t *testing.T) { + desired := RenderedManifest{ + Name: "sw-blockvolume-pvc-a-r1", + YAML: []byte(`--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-blockvolume-pvc-a-r1 + namespace: default + labels: + app: sw-blockvolume + sw-block.seaweedfs.com/volume: pvc-a + sw-block.seaweedfs.com/replica: r1 +`), + } + zero := 0 + client := &recordingDeploymentClient{} + result, err := ReconcileBlockVolumeDeployments(context.Background(), ReconcileDeploymentsInput{ + Namespace: "default", + Desired: []RenderedManifest{desired}, + Existing: []DeploymentIdentity{{ + Namespace: "default", + Name: "sw-blockvolume-pvc-a-r1", + Labels: map[string]string{ + LabelApp: AppBlockVolume, + LabelVolume: "pvc-a", + LabelReplica: "r1", + }, + SpecReplicas: &zero, + }}, + Client: client, + }) + if err != nil { + t.Fatalf("ReconcileBlockVolumeDeployments: %v", err) + } + if len(client.applied) != 0 { + t.Fatalf("scaled-zero deployment should not be reapplied: %v", client.applied) + } + if result.Applied != 0 || result.Deleted != 0 || result.Skipped != 1 { + t.Fatalf("result=%+v", result) + } + if got := result.Actions[0].Reason; got != "preserve-replicas-zero" { + t.Fatalf("reason=%q", got) + } +} + func TestK8sReconciler_SkipsUnownedOrAmbiguousDeployments(t *testing.T) { client := &recordingDeploymentClient{} result, err := ReconcileBlockVolumeDeployments(context.Background(), ReconcileDeploymentsInput{ diff --git a/seaweed-block/core/launcher/k8s_renderer.go b/seaweed-block/core/launcher/k8s_renderer.go index dec6615b3b..faef00e81e 100644 --- a/seaweed-block/core/launcher/k8s_renderer.go +++ b/seaweed-block/core/launcher/k8s_renderer.go @@ -3,6 +3,7 @@ package launcher import ( "bytes" "fmt" + "net" "path" "strings" @@ -19,8 +20,11 @@ type K8sRenderConfig struct { DurableRootBase string StateHostPathBase string RecoveryMode string + ReplicationAck string OwnerReferenceToPVC bool EnableStatus bool + ExternalISCSI bool + ExternalStatus bool ISCSICHAP CHAPSecretRef } @@ -51,6 +55,20 @@ func RenderBlockVolumeDeployments(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8 if cfg.RecoveryMode == "" { cfg.RecoveryMode = "dual-lane" } + if cfg.ReplicationAck == "" { + cfg.ReplicationAck = "best-effort" + } + switch cfg.ReplicationAck { + case "best-effort", "sync-quorum", "sync-all": + default: + return nil, fmt.Errorf("launcher: replication ack %q invalid; want best-effort, sync-quorum, or sync-all", cfg.ReplicationAck) + } + if cfg.ExternalISCSI && cfg.ISCSICHAP.Name == "" { + return nil, fmt.Errorf("launcher: external iSCSI requires CHAP secret") + } + if cfg.ExternalStatus && !cfg.ExternalISCSI { + return nil, fmt.Errorf("launcher: external status requires external iSCSI mode") + } if cfg.MasterAddr == "" { return nil, fmt.Errorf("launcher: master addr is required") } @@ -95,7 +113,7 @@ func RenderBlockVolumeDeployments(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8 Spec: podSpec{ HostNetwork: true, DNSPolicy: "ClusterFirstWithHostNet", - NodeSelector: map[string]string{"kubernetes.io/hostname": replica.ServerID}, + NodeSelector: map[string]string{"kubernetes.io/hostname": replicaKubernetesNodeName(replica)}, InitContainers: blockVolumeInitContainers(plan, replica, cfg), Containers: []container{{ Name: "blockvolume", @@ -159,13 +177,25 @@ func blockVolumeArgs(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.B fmt.Sprintf("--durable-blocks=%d", plan.SizeBytes/4096), "--durable-blocksize=4096", "--recovery-mode=" + cfg.RecoveryMode, + "--replication-ack=" + cfg.ReplicationAck, } if cfg.EnableStatus { port, err := blockVolumeStatusPort(plan, replica) if err != nil { return nil, err } - args = append(args, fmt.Sprintf("--status-addr=127.0.0.1:%d", port)) + statusHost := "127.0.0.1" + if cfg.ExternalStatus { + host, err := hostFromAddr(replica.DataAddr) + if err != nil { + return nil, fmt.Errorf("launcher: external status volume=%s replica=%s: %w", plan.VolumeID, replica.ReplicaID, err) + } + statusHost = host + } + args = append(args, fmt.Sprintf("--status-addr=%s:%d", statusHost, port)) + if cfg.ExternalStatus { + args = append(args, "--allow-external-status-bind") + } } switch plan.Protocol { case "nvme": @@ -175,14 +205,52 @@ func blockVolumeArgs(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.B fmt.Sprintf("--nvme-ns=%d", replica.NVMeNSID), ) default: + iscsiListen := fmt.Sprintf("127.0.0.1:%d", replica.ISCSIListenPort) + if cfg.ExternalISCSI { + host, err := hostFromAddr(replica.DataAddr) + if err != nil { + return nil, fmt.Errorf("launcher: external iSCSI volume=%s replica=%s: %w", plan.VolumeID, replica.ReplicaID, err) + } + iscsiListen = fmt.Sprintf("%s:%d", host, replica.ISCSIListenPort) + args = append(args, "--allow-external-iscsi-bind") + } args = append(args, - fmt.Sprintf("--iscsi-listen=127.0.0.1:%d", replica.ISCSIListenPort), + "--iscsi-listen="+iscsiListen, "--iscsi-iqn="+replica.ISCSIQualifiedName, ) } return args, nil } +func hostFromAddr(addr string) (string, error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return "", fmt.Errorf("node address %q is not host:port: %w", addr, err) + } + if host == "" { + return "", fmt.Errorf("node address %q has empty host", addr) + } + if isLocalhostOrLoopbackHost(host) { + return "", fmt.Errorf("node address %q is loopback; external node-loss endpoints require non-loopback node addresses", addr) + } + return host, nil +} + +func isLocalhostOrLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func replicaKubernetesNodeName(replica lifecycle.BlockVolumeReplicaWorkload) string { + if replica.KubernetesNodeName != "" { + return replica.KubernetesNodeName + } + return replica.ServerID +} + func blockVolumeStatusPort(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.BlockVolumeReplicaWorkload) (int, error) { const offset = 20000 base := replica.ISCSIListenPort diff --git a/seaweed-block/core/launcher/k8s_renderer_test.go b/seaweed-block/core/launcher/k8s_renderer_test.go index 08e6afad3e..a8aeb1ac6f 100644 --- a/seaweed-block/core/launcher/k8s_renderer_test.go +++ b/seaweed-block/core/launcher/k8s_renderer_test.go @@ -37,6 +37,7 @@ func TestG15d_K8sRenderer_RendersBlockVolumeDeploymentArgs(t *testing.T) { "--replica-id=r1", "--durable-root=/var/lib/sw-block/pvc-a/r1", "--recovery-mode=dual-lane", + "--replication-ack=best-effort", "sw-block.seaweedfs.com/volume: pvc-a", "--iscsi-listen=127.0.0.1:3260", "--iscsi-iqn=iqn.test:pvc-a", @@ -72,6 +73,35 @@ func TestG15d_K8sRenderer_RF2UsesDistinctNamesAndPorts(t *testing.T) { } } +func TestMountedFailover_K8sRendererCanRenderSyncQuorumAckProfile(t *testing.T) { + manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + ReplicationAck: "sync-quorum", + }) + if err != nil { + t.Fatalf("RenderBlockVolumeDeployments: %v", err) + } + for _, manifest := range manifests { + raw := string(manifest.YAML) + if !strings.Contains(raw, "--replication-ack=sync-quorum") { + t.Fatalf("manifest %s missing sync-quorum ack profile:\n%s", manifest.Name, raw) + } + } +} + +func TestMountedFailover_K8sRendererRejectsInvalidAckProfile(t *testing.T) { + _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + ReplicationAck: "maybe", + }) + if err == nil { + t.Fatal("expected error") + } + if !strings.Contains(err.Error(), "replication ack") { + t.Fatalf("error=%v", err) + } +} + func TestG15d_K8sRenderer_SameNodeLoopbackPlacementContract(t *testing.T) { manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ MasterAddr: "m:9333", @@ -95,6 +125,28 @@ func TestG15d_K8sRenderer_SameNodeLoopbackPlacementContract(t *testing.T) { } } +func TestMountedFailover_K8sRendererUsesKubernetesNodeNameForScheduling(t *testing.T) { + plan := sampleWorkloadPlan() + plan.Replicas[0].ServerID = "m02-r1" + plan.Replicas[0].KubernetesNodeName = "m02" + manifests, err := RenderBlockVolumeDeployments(plan, K8sRenderConfig{MasterAddr: "m:9333"}) + if err != nil { + t.Fatalf("RenderBlockVolumeDeployments: %v", err) + } + raw := string(manifests[0].YAML) + for _, want := range []string{ + "--server-id=m02-r1", + "kubernetes.io/hostname: m02", + } { + if !strings.Contains(raw, want) { + t.Fatalf("manifest missing %q:\n%s", want, raw) + } + } + if strings.Contains(raw, "kubernetes.io/hostname: m02-r1") { + t.Fatalf("scheduler node selector must use Kubernetes node name, not logical server id:\n%s", raw) + } +} + func TestG15d_K8sRenderer_ManifestsAreSafeToConcatenate(t *testing.T) { manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{MasterAddr: "m:9333"}) if err != nil { @@ -325,6 +377,104 @@ func TestG15d_K8sRenderer_CanWireCHAPSecret(t *testing.T) { } } +func TestNodeLoss_K8sRenderer_ExternalISCSIRequiresCHAP(t *testing.T) { + _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + ExternalISCSI: true, + }) + if err == nil { + t.Fatal("RenderBlockVolumeDeployments succeeded; want CHAP requirement") + } + if !strings.Contains(err.Error(), "external iSCSI requires CHAP") { + t.Fatalf("error = %q, want CHAP requirement", err) + } +} + +func TestNodeLoss_K8sRenderer_ExternalISCSIUsesNodeAddress(t *testing.T) { + manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + ExternalISCSI: true, + ISCSICHAP: CHAPSecretRef{ + Name: "sw-block-iscsi-chap", + }, + }) + if err != nil { + t.Fatalf("RenderBlockVolumeDeployments: %v", err) + } + raw := string(manifests[0].YAML) + for _, want := range []string{ + "--allow-external-iscsi-bind", + "--iscsi-listen=10.0.0.1:3260", + "name: SW_BLOCK_ISCSI_CHAP_USERNAME", + "name: SW_BLOCK_ISCSI_CHAP_SECRET", + } { + if !strings.Contains(raw, want) { + t.Fatalf("manifest missing %q:\n%s", want, raw) + } + } + if strings.Contains(raw, "--iscsi-listen=127.0.0.1:3260") { + t.Fatalf("external iSCSI must not render loopback listen:\n%s", raw) + } +} + +func TestNodeLoss_K8sRenderer_ExternalISCSIRejectsLoopbackNodeAddress(t *testing.T) { + plan := sampleWorkloadPlan() + plan.Replicas[0].DataAddr = "127.0.0.1:19101" + _, err := RenderBlockVolumeDeployments(plan, K8sRenderConfig{ + MasterAddr: "m:9333", + ExternalISCSI: true, + ISCSICHAP: CHAPSecretRef{ + Name: "sw-block-iscsi-chap", + }, + }) + if err == nil { + t.Fatal("RenderBlockVolumeDeployments succeeded; want loopback external endpoint rejected") + } + if !strings.Contains(err.Error(), "non-loopback") { + t.Fatalf("error = %q, want non-loopback requirement", err) + } +} + +func TestNodeLoss_K8sRenderer_ExternalStatusRequiresExternalISCSI(t *testing.T) { + _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + EnableStatus: true, + ExternalStatus: true, + }) + if err == nil { + t.Fatal("RenderBlockVolumeDeployments succeeded; want external status guard") + } + if !strings.Contains(err.Error(), "external status requires external iSCSI") { + t.Fatalf("error = %q, want external status guard", err) + } +} + +func TestNodeLoss_K8sRenderer_ExternalStatusUsesNodeAddress(t *testing.T) { + manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + EnableStatus: true, + ExternalISCSI: true, + ExternalStatus: true, + ISCSICHAP: CHAPSecretRef{ + Name: "sw-block-iscsi-chap", + }, + }) + if err != nil { + t.Fatalf("RenderBlockVolumeDeployments: %v", err) + } + raw := string(manifests[0].YAML) + for _, want := range []string{ + "--status-addr=10.0.0.1:23260", + "--allow-external-status-bind", + "--allow-external-iscsi-bind", + "--iscsi-listen=10.0.0.1:3260", + } { + if !strings.Contains(raw, want) { + t.Fatalf("manifest missing %q:\n%s", want, raw) + } + } +} + func TestG15d_K8sRenderer_OutputIsNotAuthorityShaped(t *testing.T) { manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{MasterAddr: "m:9333"}) if err != nil { diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index c6209b19a4..056eafcbac 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -16,6 +16,12 @@ var ( ErrNodeNotFound = errors.New("lifecycle: node not found") ) +const ( + // KubernetesNodeNameLabel lets a logical Seaweed Block server identity map + // to the Kubernetes node that should host its generated workload. + KubernetesNodeNameLabel = "kubernetes.io/hostname" +) + // StoragePool reports allocatable local capacity. It is placement input, // not a create decision. type StoragePool struct { diff --git a/seaweed-block/core/lifecycle/reconciler.go b/seaweed-block/core/lifecycle/reconciler.go index 639aefe39d..c16765ec2d 100644 --- a/seaweed-block/core/lifecycle/reconciler.go +++ b/seaweed-block/core/lifecycle/reconciler.go @@ -22,6 +22,13 @@ func ReconcilePlacement(volumes []VolumeRecord, nodes []NodeRegistration, placem VolumeID: volume.Spec.VolumeID, Plan: plan, } + if existing, ok := placements.GetPlacement(volume.Spec.VolumeID); ok && + shouldPreserveMaterializedPlacement(volume, existing, nodes) { + result.Intent = existing + result.Applied = true + results = append(results, result) + continue + } intent, err := placements.ApplyPlan(plan) if err != nil { result.Err = err @@ -34,3 +41,25 @@ func ReconcilePlacement(volumes []VolumeRecord, nodes []NodeRegistration, placem } return results } + +func shouldPreserveMaterializedPlacement(volume VolumeRecord, intent PlacementIntent, nodes []NodeRegistration) bool { + if intent.VolumeID != volume.Spec.VolumeID || intent.DesiredRF != volume.Spec.ReplicationFactor { + return false + } + if len(intent.Slots) != intent.DesiredRF || len(intent.Slots) == 0 { + return false + } + currentNodes := make(map[string]bool, len(nodes)) + for _, node := range nodes { + currentNodes[node.ServerID] = true + } + for _, slot := range intent.Slots { + if slot.Source != PlacementSourceExistingReplica || slot.ServerID == "" || slot.ReplicaID == "" { + return false + } + if !currentNodes[slot.ServerID] { + return false + } + } + return true +} diff --git a/seaweed-block/core/lifecycle/reconciler_test.go b/seaweed-block/core/lifecycle/reconciler_test.go index c2f2dc941d..258f5d8cc2 100644 --- a/seaweed-block/core/lifecycle/reconciler_test.go +++ b/seaweed-block/core/lifecycle/reconciler_test.go @@ -179,6 +179,49 @@ func TestReconcilePlacement_DesiredRFChangeUpdatesExistingIntent(t *testing.T) { } } +func TestReconcilePlacement_PreservesMaterializedReplicaPlacement(t *testing.T) { + store, err := OpenPlacementIntentStore(t.TempDir()) + if err != nil { + t.Fatalf("open: %v", err) + } + if _, err := store.ApplyPlan(PlacementPlan{ + VolumeID: "vol-a", + DesiredRF: 2, + Candidates: []PlacementCandidate{ + {VolumeID: "vol-a", ServerID: "node-a", ReplicaID: "r1", Source: PlacementSourceExistingReplica}, + {VolumeID: "vol-a", ServerID: "node-b", ReplicaID: "r2", Source: PlacementSourceExistingReplica}, + }, + }); err != nil { + t.Fatalf("seed materialized placement: %v", err) + } + nodes := []NodeRegistration{ + nodeWithPool("node-a", "pool-a", 1<<30), + nodeWithPool("node-b", "pool-b", 1<<30), + } + nodes[0].Replicas = []ReplicaInventory{{VolumeID: "vol-a", ReplicaID: "r1", StoreUUID: "store-a", SizeBytes: 1 << 20, State: "ready"}} + nodes[1].Replicas = []ReplicaInventory{{VolumeID: "vol-a", ReplicaID: "r2", StoreUUID: "store-b", SizeBytes: 1 << 20, State: "ready"}} + results := ReconcilePlacement([]VolumeRecord{{Spec: VolumeSpec{ + VolumeID: "vol-a", + SizeBytes: 1 << 20, + ReplicationFactor: 2, + }}}, nodes, store) + if len(results) != 1 || !results[0].Applied { + t.Fatalf("reconcile failed: %+v", results) + } + got, ok := store.GetPlacement("vol-a") + if !ok { + t.Fatal("missing placement") + } + if len(got.Slots) != 2 { + t.Fatalf("slot count=%d want 2: %+v", len(got.Slots), got) + } + for _, slot := range got.Slots { + if slot.Source != PlacementSourceExistingReplica || slot.ReplicaID == "" { + t.Fatalf("materialized placement was overwritten: %+v", got) + } + } +} + func TestReconcilePlacement_ExistingIntentSameInputsOverwritesSameValue(t *testing.T) { store, err := OpenPlacementIntentStore(t.TempDir()) if err != nil { diff --git a/seaweed-block/core/lifecycle/workload_plan.go b/seaweed-block/core/lifecycle/workload_plan.go index 677e52ea5b..6133793ec1 100644 --- a/seaweed-block/core/lifecycle/workload_plan.go +++ b/seaweed-block/core/lifecycle/workload_plan.go @@ -20,6 +20,7 @@ type BlockVolumeWorkloadPlan struct { type BlockVolumeReplicaWorkload struct { ServerID string + KubernetesNodeName string PoolID string ReplicaID string Source string @@ -87,6 +88,7 @@ func PlanBlockVolumeWorkloads(volume VolumeRecord, placement PlacementIntent, no dataAddr, ctrlAddr := nodePlacementAddrs(node) out.Replicas = append(out.Replicas, BlockVolumeReplicaWorkload{ ServerID: slot.ServerID, + KubernetesNodeName: kubernetesNodeName(node), PoolID: slot.PoolID, ReplicaID: replicaID, Source: slot.Source, @@ -114,3 +116,12 @@ func SortWorkloadPlans(plans []BlockVolumeWorkloadPlan) { return plans[i].VolumeID < plans[j].VolumeID }) } + +func kubernetesNodeName(node NodeRegistration) string { + if node.Labels != nil { + if name := node.Labels[KubernetesNodeNameLabel]; name != "" { + return name + } + } + return node.ServerID +} diff --git a/seaweed-block/core/ops/k8s_inventory.go b/seaweed-block/core/ops/k8s_inventory.go index d17fdc5bdd..5dbc61a9d2 100644 --- a/seaweed-block/core/ops/k8s_inventory.go +++ b/seaweed-block/core/ops/k8s_inventory.go @@ -17,12 +17,14 @@ import ( const seaweedBlockCSIDriver = "block.csi.seaweedfs.com" type KubernetesInventoryConfig struct { - Namespace string - MasterAddr string - StatusBundleRoot string - ProductRevision string - RunnerRevision string - RunCommand func(context.Context, string, ...string) ([]byte, error) + Namespace string + MasterAddr string + StatusBundleRoot string + ProductRevision string + RunnerRevision string + ClaimProfile string + RequiredFrontiers map[string]uint64 + RunCommand func(context.Context, string, ...string) ([]byte, error) } func NewKubernetesVolumeInventoryCollector(cfg KubernetesInventoryConfig) VolumeInventoryCollector { @@ -92,26 +94,36 @@ func collectKubernetesVolumeInventory(ctx context.Context, cfg KubernetesInvento if !isSeaweedBlockPVC(pvc, pv, hasPV) { continue } - volumeID := pvc.Spec.VolumeName pvName := pvc.Spec.VolumeName + volumeID := pvc.Spec.VolumeName + var replicationFactorIssue string if hasPV { pvName = pv.Metadata.Name if pv.Spec.CSI.VolumeHandle != "" { volumeID = pv.Spec.CSI.VolumeHandle } } + replicationFactor := max(1, len(replicasByVolume[volumeID])) + if hasPV { + replicationFactor, replicationFactorIssue = replicationFactorFromVolumeAttributes(pv.Spec.CSI.VolumeAttributes, replicationFactor) + } volume := VolumeInventoryVolumeInput{ VolumeID: volumeID, Namespace: pvc.Metadata.Namespace, PVCName: pvc.Metadata.Name, PVName: pvName, - ReplicationFactor: max(1, len(replicasByVolume[volumeID])), + ReplicationFactor: replicationFactor, SupportBundle: "volumes/" + volumeID, Replicas: replicasByVolume[volumeID], } + if replicationFactorIssue != "" { + volume.Issues = append(volume.Issues, replicationFactorIssue) + } if len(volume.Replicas) == 0 { volume.Issues = append(volume.Issues, "generated_deployment_missing") } + applyRequiredFrontierEvidence(&volume, cfg.RequiredFrontiers) + applyClaimProfile(&volume, cfg.ClaimProfile) volumes = append(volumes, volume) claimedVolumeIDs[volumeID] = true } @@ -132,6 +144,7 @@ func collectKubernetesVolumeInventory(ctx context.Context, cfg KubernetesInvento "heartbeat-without-placement=" + strings.Join(replicaServerIDs(replicas), ",") + " state=unadmitted-by-master reason=no-matching-pvc-or-pv", }, } + applyClaimProfile(&orphan, cfg.ClaimProfile) volumes = append(volumes, orphan) } for volumeID, replicas := range processReplicasByVolume { @@ -151,6 +164,7 @@ func collectKubernetesVolumeInventory(ctx context.Context, cfg KubernetesInvento "heartbeat-without-placement=" + strings.Join(replicaServerIDs(replicas), ",") + " state=unadmitted-by-master reason=local-process-without-pvc-or-pv", }, } + applyClaimProfile(&orphan, cfg.ClaimProfile) volumes = append(volumes, orphan) } volumes = collectKubernetesReplicaStatusBundles(ctx, cfg, volumes) @@ -163,6 +177,29 @@ func collectKubernetesVolumeInventory(ctx context.Context, cfg KubernetesInvento }), nil } +func applyRequiredFrontierEvidence(volume *VolumeInventoryVolumeInput, required map[string]uint64) { + if volume == nil || len(required) == 0 { + return + } + lsn, ok := required[volume.VolumeID] + if !ok { + return + } + for i := range volume.Replicas { + volume.Replicas[i].RequiredFrontierKnown = true + volume.Replicas[i].RequiredFrontierLSN = lsn + } +} + +func applyClaimProfile(volume *VolumeInventoryVolumeInput, claimProfile string) { + if volume == nil || claimProfile == "" { + return + } + for i := range volume.Replicas { + volume.Replicas[i].ClaimProfile = claimProfile + } +} + func localBlockvolumeProcessReplicas(ctx context.Context, run func(context.Context, string, ...string) ([]byte, error)) map[string][]VolumeInventoryReplicaInput { out := map[string][]VolumeInventoryReplicaInput{} if run == nil { @@ -208,6 +245,7 @@ func replicaFromProcessArgs(line string) (VolumeInventoryReplicaInput, string, b Protocol: protocol, FrontendAddress: frontend, StatusAddress: argValue(args, "--status-addr"), + AckProfile: defaultString(argValue(args, "--replication-ack"), PromotionAckProfileBestEffort), DataAddr: argValue(args, "--data-addr"), CtrlAddr: argValue(args, "--ctrl-addr"), Observed: true, @@ -288,13 +326,22 @@ func applyStatusReportToInventoryReplica(replica *VolumeInventoryReplicaInput, r replica.ReplicationRole = report.Replication.ReplicationRole replica.Epoch = report.Authority.Epoch replica.EndpointVersion = report.Authority.EndpointVersion - if report.Volume.ReplicaID != "" && report.Volume.ReplicaID != Unavailable { - replica.ReplicaID = report.Volume.ReplicaID + for _, durable := range report.Durable { + if durable.ReplicaID == report.Volume.ReplicaID || durable.ReplicaID == replica.ReplicaID { + replica.DurableLatched = durable.Latched + replica.DurableOperational = durable.Operational + if durable.FrontierKnown { + replica.CandidateFrontierKnown = true + replica.CandidateFrontierLSN = durable.DurableLSN + } + break + } } if len(report.Volume.Protocols) > 0 { replica.Protocol = strings.Join(report.Volume.Protocols, ",") } - if len(report.Volume.Frontends) > 0 && report.Volume.Frontends[0].Addr != "" { + if (replica.FrontendAddress == "" || replica.FrontendAddress == Unavailable) && + len(report.Volume.Frontends) > 0 && report.Volume.Frontends[0].Addr != "" { replica.FrontendAddress = report.Volume.Frontends[0].Addr } } @@ -503,6 +550,7 @@ func replicaFromDeployment(deploy k8sDeployment) VolumeInventoryReplicaInput { Protocol: protocol, FrontendAddress: frontend, StatusAddress: argValue(args, "--status-addr"), + AckProfile: defaultString(argValue(args, "--replication-ack"), PromotionAckProfileBestEffort), DataAddr: argValue(args, "--data-addr"), CtrlAddr: argValue(args, "--ctrl-addr"), Observed: true, @@ -577,6 +625,18 @@ func firstNonEmpty(values ...string) string { return "" } +func replicationFactorFromVolumeAttributes(attrs map[string]string, fallback int) (int, string) { + raw := strings.TrimSpace(attrs["replicationFactor"]) + if raw == "" { + return max(1, fallback), "" + } + rf, err := strconv.Atoi(raw) + if err != nil || rf <= 0 { + return max(1, fallback), "invalid: replication_factor_attribute=" + raw + } + return rf, "" +} + func max(a, b int) int { if a > b { return a @@ -625,8 +685,9 @@ type k8sPV struct { UID string `json:"uid"` } `json:"claimRef"` CSI struct { - Driver string `json:"driver"` - VolumeHandle string `json:"volumeHandle"` + Driver string `json:"driver"` + VolumeHandle string `json:"volumeHandle"` + VolumeAttributes map[string]string `json:"volumeAttributes"` } `json:"csi"` } `json:"spec"` } diff --git a/seaweed-block/core/ops/k8s_inventory_test.go b/seaweed-block/core/ops/k8s_inventory_test.go index 4e63086374..b51fc513ab 100644 --- a/seaweed-block/core/ops/k8s_inventory_test.go +++ b/seaweed-block/core/ops/k8s_inventory_test.go @@ -91,6 +91,80 @@ func TestKubernetesInventoryCollector_OrphanPVCIsActionable(t *testing.T) { } } +func TestKubernetesInventoryCollector_RF2PVCWithoutPlacementKeepsDesiredReplicaCount(t *testing.T) { + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + ProductRevision: "product-rev", + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": singlePVCListJSON, + "kubectl get pv -o json": singleRF2PVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + if got := ClassifyVolumeInventory(inventory); got != VolumeStatusExitUnhealthy { + t.Fatalf("exit=%d issues=%v", got, VolumeInventoryIssues(inventory)) + } + if len(inventory.Volumes) != 1 { + t.Fatalf("volumes=%d", len(inventory.Volumes)) + } + volume := inventory.Volumes[0] + if volume.ReplicationFactor != 2 || volume.DesiredReplicas != 2 || volume.ObservedReplicas != 0 { + t.Fatalf("replica counts rf=%d desired=%d observed=%d", volume.ReplicationFactor, volume.DesiredReplicas, volume.ObservedReplicas) + } + for _, want := range []string{ + "generated_deployment_missing", + "observed_replicas=0 desired_replicas=2", + "replica_slot_missing=unknown", + } { + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "volume: id=pvc-a namespace=default pvc=app-a pv=pvc-a rf=2 desired=2 observed=0 primary=unavailable status=unhealthy protocols= replicas=0", + "- volume pvc-a generated_deployment_missing", + "- volume pvc-a observed_replicas=0 desired_replicas=2", + "- volume pvc-a replica_slot_missing=unknown", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestKubernetesInventoryCollector_UsesPVHandleBeforeReplicaFallback(t *testing.T) { + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + ProductRevision: "product-rev", + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[{"metadata":{"name":"app-a","namespace":"default","uid":"uid-a"},"spec":{"volumeName":"pv-claim-name","storageClassName":"sw-block-dynamic"},"status":{"phase":"Bound"}}]}`, + "kubectl get pv -o json": `{"items":[{"metadata":{"name":"pv-claim-name"},"spec":{"claimRef":{"namespace":"default","name":"app-a","uid":"uid-a"},"csi":{"driver":"block.csi.seaweedfs.com","volumeHandle":"pvc-remapped"}}}]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[ + {"metadata":{"name":"sw-blockvolume-pvc-remapped-r1","namespace":"default","labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-remapped","sw-block.seaweedfs.com/replica":"r1"}},"spec":{"template":{"spec":{"containers":[{"name":"blockvolume","args":["--server-id=m01","--volume-id=pvc-remapped","--replica-id=r1","--iscsi-listen=10.0.0.1:3260"]}]}}},"status":{"replicas":1,"readyReplicas":1}}, + {"metadata":{"name":"sw-blockvolume-pvc-remapped-r2","namespace":"default","labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-remapped","sw-block.seaweedfs.com/replica":"r2"}},"spec":{"template":{"spec":{"containers":[{"name":"blockvolume","args":["--server-id=m02","--volume-id=pvc-remapped","--replica-id=r2","--iscsi-listen=10.0.0.2:3260"]}]}}},"status":{"replicas":1,"readyReplicas":1}} + ]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + if len(inventory.Volumes) != 1 { + t.Fatalf("volumes=%d want 1: %+v", len(inventory.Volumes), inventory.Volumes) + } + volume := inventory.Volumes[0] + if volume.VolumeID != "pvc-remapped" || volume.ReplicationFactor != 2 || volume.ObservedReplicas != 2 { + t.Fatalf("volume=%+v", volume) + } +} + func TestKubernetesInventoryCollector_OrphanDeploymentIsActionable(t *testing.T) { collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ Namespace: "default", @@ -249,6 +323,315 @@ func TestKubernetesInventoryCollector_AttachesReplicaStatusBundles(t *testing.T) } } +func TestKubernetesInventoryCollector_RF2ReadyReplicaStillNamesMissingFrontier(t *testing.T) { + masterAddr, closeMaster := startOpsFakeMaster(t) + defer closeMaster() + statusServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + writeLiveJSON(t, w, hostvolume.StatusProjection{ + Projection: frontend.Projection{ + VolumeID: "pvc-a", + ReplicaID: "r2", + Healthy: true, + }, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + FrontendPrimaryReady: false, + ReplicationRole: hostvolume.ReplicationRoleReady, + }) + case "/status/peers": + writeLiveJSON(t, w, struct { + Peers []replication.ReplicaPeerStatus + }{}) + case "/status/durable": + writeLiveJSON(t, w, struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{VolumeID: "pvc-a", ReplicaID: "r2", Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 53, RetainedLSN: 1, HeadLSN: 53}}}) + default: + http.NotFound(w, r) + } + })) + defer statusServer.Close() + + deploymentJSON := fmt.Sprintf(`{"items":[ + {"metadata":{"name":"sw-blockvolume-pvc-a-r2","namespace":"default","labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-a","sw-block.seaweedfs.com/replica":"r2"},"ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-a","uid":"uid-a"}]}, + "status":{"replicas":1,"readyReplicas":1}, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02-r2","--volume-id=pvc-a","--replica-id=r2","--data-addr=127.0.0.1:19103","--ctrl-addr=127.0.0.1:19104","--status-addr=%s","--replication-ack=sync-quorum","--iscsi-listen=127.0.0.1:3261","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-a"]}]}}}} +]}`, statusServer.URL) + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + MasterAddr: masterAddr, + StatusBundleRoot: t.TempDir(), + ProductRevision: "product-rev", + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": singlePVCListJSON, + "kubectl get pv -o json": singleRF2PVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": deploymentJSON, + "iscsiadm -m session": "iscsiadm: No active sessions.\n", + "nvme list-subsys -o json": `{"Subsystems":[]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + volume := inventory.Volumes[0] + if volume.ReplicationFactor != 2 || volume.DesiredReplicas != 2 { + t.Fatalf("rf/desired not preserved: %+v", volume) + } + replica := volume.Replicas[0] + if replica.PromotionReadiness.CandidateReady { + t.Fatalf("live collector must not infer readiness without frontier evidence: %+v", replica.PromotionReadiness) + } + if replica.PromotionReadiness.Reason != PromotionReasonRequiredFrontierMissing { + t.Fatalf("reason=%q want %q", replica.PromotionReadiness.Reason, PromotionReasonRequiredFrontierMissing) + } + if !replica.PromotionReadiness.CandidateFrontierKnown || replica.PromotionReadiness.CandidateFrontierLSN != 53 { + t.Fatalf("candidate frontier not propagated from durable status: %+v", replica.PromotionReadiness) + } + for _, want := range []string{ + "candidate_not_promotion_ready=r2 reason=required_frontier_missing ack_profile=sync-quorum", + "observed_replicas=1 desired_replicas=2", + } { + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + } + summary := RenderVolumeInventorySummary(inventory) + if !strings.Contains(summary, "promotion: volume=pvc-a replica=r2 candidate_ready=false reason=required_frontier_missing claim_profile=beta-recovery ack_profile=sync-quorum required_frontier_known=false required_frontier_lsn=0 candidate_frontier_known=true candidate_frontier_lsn=53") { + t.Fatalf("summary missing promotion blocker:\n%s", summary) + } +} + +func TestKubernetesInventoryCollector_RequiredFrontierMakesCoveredCandidateReady(t *testing.T) { + masterAddr, closeMaster := startOpsFakeMaster(t) + defer closeMaster() + statusServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + writeLiveJSON(t, w, hostvolume.StatusProjection{ + Projection: frontend.Projection{ + VolumeID: "pvc-a", + ReplicaID: "r2", + Healthy: true, + }, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + FrontendPrimaryReady: false, + ReplicationRole: hostvolume.ReplicationRoleReady, + }) + case "/status/peers": + writeLiveJSON(t, w, struct { + Peers []replication.ReplicaPeerStatus + }{}) + case "/status/durable": + writeLiveJSON(t, w, struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{VolumeID: "pvc-a", ReplicaID: "r2", Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 53, RetainedLSN: 1, HeadLSN: 53}}}) + default: + http.NotFound(w, r) + } + })) + defer statusServer.Close() + + deploymentJSON := fmt.Sprintf(`{"items":[ + {"metadata":{"name":"sw-blockvolume-pvc-a-r2","namespace":"default","labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-a","sw-block.seaweedfs.com/replica":"r2"},"ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-a","uid":"uid-a"}]}, + "status":{"replicas":1,"readyReplicas":1}, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02-r2","--volume-id=pvc-a","--replica-id=r2","--data-addr=127.0.0.1:19103","--ctrl-addr=127.0.0.1:19104","--status-addr=%s","--replication-ack=sync-quorum","--iscsi-listen=127.0.0.1:3261","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-a"]}]}}}} +]}`, statusServer.URL) + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + MasterAddr: masterAddr, + StatusBundleRoot: t.TempDir(), + ProductRevision: "product-rev", + RequiredFrontiers: map[string]uint64{"pvc-a": 53}, + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": singlePVCListJSON, + "kubectl get pv -o json": singleRF2PVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": deploymentJSON, + "iscsiadm -m session": "iscsiadm: No active sessions.\n", + "nvme list-subsys -o json": `{"Subsystems":[]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + replica := inventory.Volumes[0].Replicas[0] + if !replica.PromotionReadiness.CandidateReady { + t.Fatalf("candidate should be ready when required and candidate frontiers match: %+v", replica.PromotionReadiness) + } + if !replica.PromotionReadiness.RequiredFrontierKnown || replica.PromotionReadiness.RequiredFrontierLSN != 53 { + t.Fatalf("required frontier not propagated: %+v", replica.PromotionReadiness) + } + summary := RenderVolumeInventorySummary(inventory) + if !strings.Contains(summary, "promotion: volume=pvc-a replica=r2 candidate_ready=true reason=promotion_ready claim_profile=beta-recovery ack_profile=sync-quorum required_frontier_known=true required_frontier_lsn=53 candidate_frontier_known=true candidate_frontier_lsn=53 frontier_covered=true") { + t.Fatalf("summary missing covered promotion evidence:\n%s", summary) + } + if strings.Contains(summary, "candidate_not_promotion_ready=r2") { + t.Fatalf("summary should not include candidate-not-ready issue when frontier is covered:\n%s", summary) + } +} + +func TestKubernetesInventoryCollector_Stage2ClaimRejectsBestEffortCandidate(t *testing.T) { + masterAddr, closeMaster := startOpsFakeMaster(t) + defer closeMaster() + statusServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + writeLiveJSON(t, w, hostvolume.StatusProjection{ + Projection: frontend.Projection{ + VolumeID: "pvc-a", + ReplicaID: "r2", + Healthy: true, + }, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + FrontendPrimaryReady: false, + ReplicationRole: hostvolume.ReplicationRoleReady, + }) + case "/status/peers": + writeLiveJSON(t, w, struct { + Peers []replication.ReplicaPeerStatus + }{}) + case "/status/durable": + writeLiveJSON(t, w, struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{VolumeID: "pvc-a", ReplicaID: "r2", Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 53, RetainedLSN: 1, HeadLSN: 53}}}) + default: + http.NotFound(w, r) + } + })) + defer statusServer.Close() + + deploymentJSON := fmt.Sprintf(`{"items":[ + {"metadata":{"name":"sw-blockvolume-pvc-a-r2","namespace":"default","labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-a","sw-block.seaweedfs.com/replica":"r2"},"ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-a","uid":"uid-a"}]}, + "status":{"replicas":1,"readyReplicas":1}, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02-r2","--volume-id=pvc-a","--replica-id=r2","--data-addr=127.0.0.1:19103","--ctrl-addr=127.0.0.1:19104","--status-addr=%s","--replication-ack=best-effort","--iscsi-listen=127.0.0.1:3261","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-a"]}]}}}} +]}`, statusServer.URL) + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + MasterAddr: masterAddr, + StatusBundleRoot: t.TempDir(), + ProductRevision: "product-rev", + ClaimProfile: PromotionClaimStage2ISCSIALUAMultipath, + RequiredFrontiers: map[string]uint64{"pvc-a": 53}, + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": singlePVCListJSON, + "kubectl get pv -o json": singleRF2PVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": deploymentJSON, + "iscsiadm -m session": "iscsiadm: No active sessions.\n", + "nvme list-subsys -o json": `{"Subsystems":[]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + replica := inventory.Volumes[0].Replicas[0] + if replica.PromotionReadiness.CandidateReady { + t.Fatalf("stage2 claim must not accept best-effort candidate: %+v", replica.PromotionReadiness) + } + if replica.PromotionReadiness.Reason != PromotionReasonReplicationAckProfileBad { + t.Fatalf("reason=%q want %q", replica.PromotionReadiness.Reason, PromotionReasonReplicationAckProfileBad) + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "promotion: volume=pvc-a replica=r2 candidate_ready=false reason=replication_ack_profile_unmet claim_profile=stage2-iscsi-alua-multipath ack_profile=best-effort", + "- volume pvc-a candidate_not_promotion_ready=r2 reason=replication_ack_profile_unmet ack_profile=best-effort", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestKubernetesInventoryCollector_PreservesReplicaFrontendWhenMasterReportsPrimaryFrontend(t *testing.T) { + masterAddr, closeMaster := startOpsFakeMaster(t) + defer closeMaster() + statusServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + writeLiveJSON(t, w, hostvolume.StatusProjection{ + Projection: frontend.Projection{ + VolumeID: "pvc-a", + ReplicaID: "r2", + }, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + ReplicationRole: hostvolume.ReplicationRoleNotReady, + }) + case "/status/peers": + writeLiveJSON(t, w, struct { + Peers []replication.ReplicaPeerStatus + }{}) + case "/status/durable": + writeLiveJSON(t, w, struct { + Volumes []durable.VolumeStatus + }{}) + default: + http.NotFound(w, r) + } + })) + defer statusServer.Close() + + deploymentJSON := fmt.Sprintf(`{"items":[ + {"metadata":{"name":"sw-blockvolume-pvc-a-r2","namespace":"default","ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-a"}]}, + "status":{"readyReplicas":1}, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02-r2","--volume-id=pvc-a","--replica-id=r2","--data-addr=127.0.0.1:19103","--ctrl-addr=127.0.0.1:19104","--status-addr=%s","--iscsi-listen=127.0.0.1:3261","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-a"]}]}}}} +]}`, statusServer.URL) + collector := NewKubernetesVolumeInventoryCollector(KubernetesInventoryConfig{ + Namespace: "default", + MasterAddr: masterAddr, + StatusBundleRoot: t.TempDir(), + RunCommand: fixtureKubectl(map[string]string{ + "kubectl -n default get pvc -o json": singlePVCListJSON, + "kubectl get pv -o json": singlePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": deploymentJSON, + "iscsiadm -m session": "iscsiadm: No active sessions.\n", + "nvme list-subsys -o json": `{"Subsystems":[]}`, + }), + }) + + inventory, err := collector.Collect(context.Background()) + if err != nil { + t.Fatalf("collect: %v", err) + } + replica := inventory.Volumes[0].Replicas[0] + if replica.FrontendAddress != "127.0.0.1:3261" { + t.Fatalf("frontend address overwritten by master primary frontend: %+v", replica) + } +} + +func TestKubernetesInventoryCollector_PreservesDeploymentReplicaIdentityWhenStatusReportsCurrentPrimary(t *testing.T) { + replica := VolumeInventoryReplicaInput{ + ReplicaID: "r1", + ServerID: "node-loss-r1", + NodeName: "m01", + FrontendAddress: "192.168.1.181:3260", + StatusAddress: "192.168.1.181:23260", + Observed: true, + } + report := BuildVolumeStatusReport(VolumeStatusReportInput{ + MasterStatus: &control.StatusResponse{ + VolumeId: "pvc-a", + ReplicaId: "r2", + Assigned: true, + Epoch: 2, + EndpointVersion: 1, + }, + }) + + applyStatusReportToInventoryReplica(&replica, report) + + if replica.ReplicaID != "r1" { + t.Fatalf("inventory row identity was overwritten by current primary status: got %q want r1", replica.ReplicaID) + } + if replica.ServerID != "node-loss-r1" || replica.NodeName != "m01" { + t.Fatalf("inventory row placement changed unexpectedly: %+v", replica) + } +} + func TestOpsStatusInventoryIssue_UsesReportEvidence(t *testing.T) { report := BuildVolumeStatusReport(VolumeStatusReportInput{ ProductRevision: "product-rev", @@ -343,6 +726,12 @@ const singlePVListJSON = `{ ] }` +const singleRF2PVListJSON = `{ + "items": [ + {"metadata":{"name":"pvc-a"},"spec":{"claimRef":{"namespace":"default","name":"app-a","uid":"uid-a"},"csi":{"driver":"block.csi.seaweedfs.com","volumeHandle":"pvc-a","volumeAttributes":{"replicationFactor":"2","protocol":"iscsi"}}}} + ] +}` + const singleDeploymentListJSONTemplate = `{ "items": [ { diff --git a/seaweed-block/core/ops/observation.go b/seaweed-block/core/ops/observation.go new file mode 100644 index 0000000000..5a963f83e4 --- /dev/null +++ b/seaweed-block/core/ops/observation.go @@ -0,0 +1,242 @@ +package ops + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + "time" +) + +const ( + ObservationSchemaVersion = "1.0" + + ObservationStatusOK = "ok" + ObservationStatusDegraded = "degraded" + ObservationStatusRecovering = "recovering" + ObservationStatusBlocked = "blocked" + ObservationStatusInvalid = "invalid" + ObservationStatusUnavailable = "unavailable" + + ReasonPrimaryNodeLost = "primary_node_lost" + ReasonCandidateCoversRequiredFrontier = "candidate_covers_required_frontier" + ReasonNoPromotionReadyCandidate = "no_promotion_ready_candidate" + ReasonDurableFrontierMissing = "durable_frontier_missing" + ReasonCandidateFrontierBehind = "candidate_frontier_behind" + ReasonStatusEndpointUnreachable = "status_endpoint_unreachable" + ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed" + ReasonImageMissingOnNode = "image_missing_on_node" + ReasonGeneratedDeploymentMissing = "generated_deployment_missing" + ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired" + ReasonLoopbackFrontendRejected = "loopback_frontend_rejected" + ReasonStalePrimaryFenced = "stale_primary_fenced" + + EventTypeCSIReattachObserved = "csi_reattach_observed" +) + +type ObservationCondition struct { + Type string `json:"type"` + Status string `json:"status"` + Reason string `json:"reason"` + Severity string `json:"severity"` + Message string `json:"message,omitempty"` +} + +type ClusterEvidence struct { + SchemaVersion string `json:"schema_version"` + CapturedAt time.Time `json:"captured_at"` + ProductRevision string `json:"product_revision,omitempty"` + Status string `json:"status"` + Nodes []NodeEvidence `json:"nodes"` + Volumes []VolumeEvidence `json:"volumes"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + Events []ClusterEvent `json:"events,omitempty"` + NonClaims []string `json:"non_claims,omitempty"` +} + +type NodeEvidence struct { + NodeName string `json:"node_name"` + KubernetesNode string `json:"kubernetes_node,omitempty"` + PhysicalHost string `json:"physical_host,omitempty"` + InternalIP string `json:"internal_ip,omitempty"` + Schedulable bool `json:"schedulable"` + Ready bool `json:"ready"` + LastHeartbeatAt time.Time `json:"last_heartbeat_at,omitempty"` + ReplicaCount int `json:"replica_count"` + RequiredImages []string `json:"required_images,omitempty"` + MissingImages []string `json:"missing_images,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` +} + +type VolumeEvidence struct { + VolumeID string `json:"volume_id"` + Namespace string `json:"namespace,omitempty"` + PVCName string `json:"pvc_name,omitempty"` + PVName string `json:"pv_name,omitempty"` + ReplicationFactor int `json:"replication_factor"` + AckProfile string `json:"ack_profile,omitempty"` + ClaimProfile string `json:"claim_profile,omitempty"` + DesiredReplicas int `json:"desired_replicas"` + ObservedReplicas int `json:"observed_replicas"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` + PrimaryReplica string `json:"primary_replica,omitempty"` + PrimaryNode string `json:"primary_node,omitempty"` + PublishTarget string `json:"publish_target,omitempty"` + Epoch uint64 `json:"epoch,omitempty"` + EndpointVersion uint64 `json:"endpoint_version,omitempty"` + Replicas []ReplicaEvidence `json:"replicas"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + NextActions []string `json:"next_actions,omitempty"` + SupportBundleHint string `json:"support_bundle_hint,omitempty"` +} + +type ReplicaEvidence struct { + ReplicaID string `json:"replica_id"` + ServerID string `json:"server_id,omitempty"` + KubernetesNode string `json:"kubernetes_node,omitempty"` + PhysicalHost string `json:"physical_host,omitempty"` + Observed bool `json:"observed"` + Role string `json:"role,omitempty"` + ReplicationRole string `json:"replication_role,omitempty"` + DurableLatched bool `json:"durable_latched"` + DurableFrontierKnown bool `json:"durable_frontier_known"` + DurableFrontierLSN uint64 `json:"durable_frontier_lsn,omitempty"` + CandidateReady bool `json:"candidate_ready"` + CandidateReadyReason string `json:"candidate_ready_reason,omitempty"` + FrontendProtocol string `json:"frontend_protocol,omitempty"` + FrontendAddr string `json:"frontend_addr,omitempty"` + StatusAddr string `json:"status_addr,omitempty"` + StalePrimaryFenced bool `json:"stale_primary_fenced"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + SupportBundlePath string `json:"support_bundle_path,omitempty"` +} + +type ClusterEvent struct { + EventID string `json:"event_id"` + EventTime time.Time `json:"event_time"` + VolumeID string `json:"volume_id,omitempty"` + ReplicaID string `json:"replica_id,omitempty"` + NodeName string `json:"node_name,omitempty"` + Type string `json:"event_type"` + Severity string `json:"severity"` + Message string `json:"message"` + Reason string `json:"reason_code,omitempty"` + OldValue string `json:"old_value,omitempty"` + NewValue string `json:"new_value,omitempty"` + Epoch uint64 `json:"epoch,omitempty"` + EndpointVersion uint64 `json:"endpoint_version,omitempty"` + CorrelationID string `json:"correlation_id,omitempty"` + EvidenceRef string `json:"evidence_ref,omitempty"` +} + +func NewClusterEvidence(capturedAt time.Time) ClusterEvidence { + if capturedAt.IsZero() { + capturedAt = time.Now().UTC() + } + return ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: capturedAt.UTC(), + Status: ObservationStatusOK, + NonClaims: []string{ + "read-only-observation: does not mutate product, Kubernetes, iSCSI, or replica state", + "not-an-admin-action: no promote, repair, rebuild, backup, restore, or cleanup is authorized", + }, + } +} + +func RenderClusterEvidenceText(cluster ClusterEvidence) string { + status := defaultString(cluster.Status, ObservationStatusUnavailable) + var b strings.Builder + fmt.Fprintf(&b, "cluster status=%s volumes=%d nodes=%d\n", status, len(cluster.Volumes), len(cluster.Nodes)) + for _, condition := range cluster.Conditions { + fmt.Fprintf(&b, "condition %s severity=%s reason=%s %s\n", condition.Type, condition.Severity, condition.Reason, condition.Message) + } + for _, volume := range cluster.Volumes { + b.WriteString(RenderVolumeEvidenceText(volume)) + } + return b.String() +} + +func RenderVolumeEvidenceText(volume VolumeEvidence) string { + var b strings.Builder + fmt.Fprintf(&b, "volume %s status=%s", explicitUnavailable(volume.VolumeID), defaultString(volume.Status, ObservationStatusUnavailable)) + if volume.ReplicationFactor > 0 { + fmt.Fprintf(&b, " rf=%d", volume.ReplicationFactor) + } + if volume.AckProfile != "" { + fmt.Fprintf(&b, " ack=%s", volume.AckProfile) + } + if volume.Reason != "" { + fmt.Fprintf(&b, " reason=%s", volume.Reason) + } + b.WriteByte('\n') + if volume.PVCName != "" || volume.Namespace != "" { + fmt.Fprintf(&b, "pvc %s/%s\n", emptyAsDash(volume.Namespace), emptyAsDash(volume.PVCName)) + } + if volume.PrimaryReplica != "" || volume.PrimaryNode != "" || volume.PublishTarget != "" { + fmt.Fprintf(&b, "primary %s on %s frontend=%s\n", emptyAsDash(volume.PrimaryReplica), emptyAsDash(volume.PrimaryNode), emptyAsDash(volume.PublishTarget)) + } + if volume.DesiredReplicas > 0 || volume.ObservedReplicas > 0 { + fmt.Fprintf(&b, "replicas desired=%d observed=%d\n", volume.DesiredReplicas, volume.ObservedReplicas) + } + for _, replica := range volume.Replicas { + fmt.Fprintf(&b, "%s %s %s %s", explicitUnavailable(replica.ReplicaID), emptyAsDash(replica.KubernetesNode), emptyAsDash(replica.Role), emptyAsDash(replica.ReplicationRole)) + if replica.DurableFrontierKnown { + fmt.Fprintf(&b, " durable_lsn=%d", replica.DurableFrontierLSN) + } + if replica.CandidateReady { + b.WriteString(" candidate_ready=true") + } else if replica.CandidateReadyReason != "" { + fmt.Fprintf(&b, " candidate_ready=false reason=%s", replica.CandidateReadyReason) + } + if replica.StalePrimaryFenced { + b.WriteString(" stale_primary_fenced=true") + } + b.WriteByte('\n') + for _, condition := range replica.Conditions { + fmt.Fprintf(&b, " condition %s severity=%s reason=%s %s\n", condition.Type, condition.Severity, condition.Reason, condition.Message) + } + } + for _, condition := range volume.Conditions { + fmt.Fprintf(&b, "condition %s severity=%s reason=%s %s\n", condition.Type, condition.Severity, condition.Reason, condition.Message) + } + for _, action := range volume.NextActions { + fmt.Fprintf(&b, "next action: %s\n", action) + } + if volume.SupportBundleHint != "" { + fmt.Fprintf(&b, "support bundle: %s\n", volume.SupportBundleHint) + } + return b.String() +} + +func MarshalObservationJSON(v any) ([]byte, error) { + raw, err := json.MarshalIndent(v, "", " ") + if err != nil { + return nil, err + } + return append(raw, '\n'), nil +} + +func RenderClusterEventsJSONL(events []ClusterEvent) (string, error) { + ordered := append([]ClusterEvent(nil), events...) + fallbackNow := time.Now().UTC() + for i := range ordered { + if ordered[i].EventTime.IsZero() { + ordered[i].EventTime = fallbackNow + } else { + ordered[i].EventTime = ordered[i].EventTime.UTC() + } + } + sort.SliceStable(ordered, func(i, j int) bool { + return ordered[i].EventTime.Before(ordered[j].EventTime) + }) + var b strings.Builder + enc := json.NewEncoder(&b) + for _, event := range ordered { + if err := enc.Encode(event); err != nil { + return "", err + } + } + return b.String(), nil +} diff --git a/seaweed-block/core/ops/observation_bundle.go b/seaweed-block/core/ops/observation_bundle.go new file mode 100644 index 0000000000..37f83c795e --- /dev/null +++ b/seaweed-block/core/ops/observation_bundle.go @@ -0,0 +1,590 @@ +package ops + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +const ( + ClusterEvidenceArtifact = "cluster-evidence.json" + ObservationReportHTMLArtifact = "index.html" + ObservationReportJSONArtifact = ClusterEvidenceArtifact + ObservationReportTextArtifact = "summary.txt" + ObservationReportJSONLArtifact = "timeline.jsonl" + + NodeLossRecoverySummaryArtifact = "node-loss-recovery-summary.txt" + PrimaryFailureRecoveryArtifact = "primary-failure-recovery.txt" + ControlPlaneTimelineArtifact = "control-plane-timeline.txt" + KubeSystemPodsDeploysArtifact = "kube-system-pods-deploys.txt" +) + +type ObservationBundleOptions struct { + Dir string + VolumeID string +} + +func BuildObservationFromBundle(opts ObservationBundleOptions) (ClusterEvidence, error) { + if strings.TrimSpace(opts.Dir) == "" { + return ClusterEvidence{}, fmt.Errorf("bundle dir is required") + } + cluster := NewClusterEvidence(time.Time{}) + cluster.ProductRevision = "from-bundle" + sourceLoaded := false + + productCluster, _, productErr := loadBestClusterEvidence(opts.Dir) + if productErr == nil { + cluster = filterObservationCluster(productCluster, opts.VolumeID) + sourceLoaded = true + } else { + inventory, inventoryPath, inventoryErr := loadBestVolumeInventory(opts.Dir) + if inventoryErr == nil { + fromInventory, err := BuildObservationFromInventory(inventory, opts.VolumeID, inventoryPath) + if err != nil { + return cluster, err + } + cluster = fromInventory + sourceLoaded = true + } else if opts.VolumeID != "" { + cluster = filterObservationCluster(cluster, opts.VolumeID) + } + } + + summary, summaryPath, _ := loadKeyValueArtifact(opts.Dir, NodeLossRecoverySummaryArtifact) + if len(summary) > 0 { + applyNodeLossSummary(&cluster, summary, summaryPath) + } + timeline, timelinePath, _ := loadTimelineArtifact(opts.Dir) + if len(timeline) > 0 && len(cluster.Events) == 0 { + cluster.Events = append(cluster.Events, timeline...) + for i := range cluster.Events { + if cluster.Events[i].EvidenceRef == "" { + cluster.Events[i].EvidenceRef = timelinePath + } + } + } + if blocked, blockedVolume := buildImagePullBlockedEvidence(opts.Dir); blocked { + cluster.Status = ObservationStatusBlocked + sourceLoaded = true + if len(cluster.Volumes) == 0 { + if opts.VolumeID != "" { + blockedVolume.VolumeID = opts.VolumeID + } + cluster.Volumes = append(cluster.Volumes, blockedVolume) + } + } + if len(cluster.Volumes) == 0 { + if opts.VolumeID == "" && sourceLoaded { + return cluster, nil + } + if !sourceLoaded && productErr != nil { + return cluster, productErr + } + return cluster, fmt.Errorf("volume %q not found in bundle", opts.VolumeID) + } + return cluster, nil +} + +func BuildObservationFromInventory(inventory VolumeInventory, volumeID string, evidencePath string) (ClusterEvidence, error) { + cluster := NewClusterEvidence(inventory.CapturedAt) + cluster.ProductRevision = inventory.ProductRevision + cluster.Status = observationStatusFromInventoryCode(ClassifyVolumeInventory(inventory)) + cluster.NonClaims = append(cluster.NonClaims, inventory.NonClaims...) + for _, volume := range inventory.Volumes { + if volumeID != "" && volume.VolumeID != volumeID { + continue + } + cluster.Volumes = append(cluster.Volumes, observationVolumeFromInventory(volume, evidencePath)) + } + if len(cluster.Volumes) == 0 { + if volumeID == "" { + return cluster, nil + } + return cluster, fmt.Errorf("volume %q not found in inventory", volumeID) + } + return cluster, nil +} + +func RenderObservationExplainText(cluster ClusterEvidence) string { + var b strings.Builder + b.WriteString(RenderClusterEvidenceText(cluster)) + if len(cluster.Events) > 0 { + b.WriteString("timeline:\n") + events := append([]ClusterEvent(nil), cluster.Events...) + sort.SliceStable(events, func(i, j int) bool { + return events[i].EventID < events[j].EventID + }) + for _, event := range events { + fmt.Fprintf(&b, "- %s severity=%s reason=%s volume=%s replica=%s %s\n", + event.Type, + emptyAsDash(event.Severity), + emptyAsDash(event.Reason), + emptyAsDash(event.VolumeID), + emptyAsDash(event.ReplicaID), + event.Message) + } + } + return b.String() +} + +func loadBestVolumeInventory(root string) (VolumeInventory, string, error) { + paths, err := findArtifactPaths(root, VolumeInventoryArtifact) + if err != nil { + return VolumeInventory{}, "", err + } + if len(paths) == 0 { + return VolumeInventory{}, "", fmt.Errorf("%s not found under %s", VolumeInventoryArtifact, root) + } + sort.SliceStable(paths, func(i, j int) bool { + return inventoryPathRank(paths[i]) < inventoryPathRank(paths[j]) + }) + raw, err := os.ReadFile(paths[0]) + if err != nil { + return VolumeInventory{}, paths[0], fmt.Errorf("read %s: %w", paths[0], err) + } + var inventory VolumeInventory + if err := json.Unmarshal(raw, &inventory); err != nil { + return VolumeInventory{}, paths[0], fmt.Errorf("decode %s: %w", paths[0], err) + } + return inventory, paths[0], nil +} + +func loadBestClusterEvidence(root string) (ClusterEvidence, string, error) { + paths, err := findArtifactPaths(root, ClusterEvidenceArtifact) + if err != nil { + return ClusterEvidence{}, "", err + } + if len(paths) == 0 { + return ClusterEvidence{}, "", fmt.Errorf("%s not found under %s", ClusterEvidenceArtifact, root) + } + sort.SliceStable(paths, func(i, j int) bool { + return clusterEvidencePathRank(paths[i]) < clusterEvidencePathRank(paths[j]) + }) + raw, err := os.ReadFile(paths[0]) + if err != nil { + return ClusterEvidence{}, paths[0], fmt.Errorf("read %s: %w", paths[0], err) + } + var cluster ClusterEvidence + if err := json.Unmarshal(raw, &cluster); err != nil { + return ClusterEvidence{}, paths[0], fmt.Errorf("decode %s: %w", paths[0], err) + } + return normalizeObservationCluster(cluster), paths[0], nil +} + +func clusterEvidencePathRank(path string) int { + path = filepath.ToSlash(path) + switch { + case strings.Contains(path, "product-observation"): + return 0 + case strings.Contains(path, "/status/"): + return 1 + default: + return 10 + } +} + +func normalizeObservationCluster(cluster ClusterEvidence) ClusterEvidence { + if cluster.SchemaVersion == "" { + cluster.SchemaVersion = ObservationSchemaVersion + } + if cluster.CapturedAt.IsZero() { + cluster.CapturedAt = time.Now().UTC() + } else { + cluster.CapturedAt = cluster.CapturedAt.UTC() + } + if cluster.Status == "" { + cluster.Status = ObservationStatusUnavailable + } + if len(cluster.NonClaims) == 0 { + cluster.NonClaims = NewClusterEvidence(cluster.CapturedAt).NonClaims + } + return cluster +} + +func filterObservationCluster(cluster ClusterEvidence, volumeID string) ClusterEvidence { + cluster = normalizeObservationCluster(cluster) + if strings.TrimSpace(volumeID) == "" { + return cluster + } + filtered := cluster + filtered.Volumes = nil + for _, volume := range cluster.Volumes { + if volume.VolumeID == volumeID { + filtered.Volumes = append(filtered.Volumes, volume) + } + } + filtered.Events = nil + for _, event := range cluster.Events { + if event.VolumeID == "" || event.VolumeID == volumeID { + filtered.Events = append(filtered.Events, event) + } + } + return filtered +} + +func inventoryPathRank(path string) int { + path = filepath.ToSlash(path) + switch { + case strings.Contains(path, "ops-inventory-reader-verified"): + return 0 + case strings.Contains(path, "ops-inventory-after-primary-failure"): + return 1 + case strings.Contains(path, "ops-inventory-before-primary-failure"): + return 2 + default: + return 10 + } +} + +func observationVolumeFromInventory(volume VolumeInventoryVolume, evidencePath string) VolumeEvidence { + out := VolumeEvidence{ + VolumeID: volume.VolumeID, + Namespace: volume.Namespace, + PVCName: volume.PVCName, + PVName: volume.PVName, + ReplicationFactor: volume.ReplicationFactor, + DesiredReplicas: volume.DesiredReplicas, + ObservedReplicas: volume.ObservedReplicas, + Status: observationStatusFromInventoryStatus(volume.Status), + PrimaryReplica: volume.PrimaryReplicaID, + Epoch: maxInventoryEpoch(volume.Replicas), + EndpointVersion: maxInventoryEndpointVersion(volume.Replicas), + SupportBundleHint: evidencePath, + Replicas: make([]ReplicaEvidence, 0, len(volume.Replicas)), + } + if len(volume.Issues) > 0 { + out.Reason = reasonFromIssueList(volume.Issues) + } + for _, replica := range volume.Replicas { + ev := ReplicaEvidence{ + ReplicaID: replica.ReplicaID, + ServerID: replica.ServerID, + KubernetesNode: replica.NodeName, + Observed: replica.Observed, + Role: replica.AuthorityRole, + ReplicationRole: replica.ReplicationRole, + DurableLatched: replica.PromotionReadiness.FrontierCovered, + DurableFrontierKnown: replica.PromotionReadiness.CandidateFrontierKnown, + DurableFrontierLSN: replica.PromotionReadiness.CandidateFrontierLSN, + CandidateReady: replica.PromotionReadiness.CandidateReady, + CandidateReadyReason: replica.PromotionReadiness.Reason, + FrontendProtocol: replica.Protocol, + FrontendAddr: replica.FrontendAddress, + StatusAddr: replica.StatusAddress, + StalePrimaryFenced: containsIssuePrefix(replica.Issues, "stale_primary_frontend_ready=") || replica.AuthorityRole == "superseded", + SupportBundlePath: replica.SupportBundle, + } + if replica.ReplicaID == volume.PrimaryReplicaID { + out.PrimaryNode = replica.NodeName + out.PublishTarget = replica.FrontendAddress + out.AckProfile = replica.AckProfile + out.ClaimProfile = replica.PromotionReadiness.ClaimProfile + } + out.Replicas = append(out.Replicas, ev) + } + if len(out.NextActions) == 0 { + out.NextActions = []string{"none"} + if out.Status != ObservationStatusOK { + out.NextActions = []string{"collect support bundle and inspect timeline"} + } + } + return out +} + +func applyNodeLossSummary(cluster *ClusterEvidence, summary map[string]string, evidencePath string) { + volume := ensureObservationVolume(cluster, "") + volume.AckProfile = defaultString(summary["ack_profile"], volume.AckProfile) + volume.Status = ObservationStatusRecovering + volume.Reason = ReasonPrimaryNodeLost + volume.SupportBundleHint = evidencePath + if summary["result"] == "promoted" && summary["reader_verified"] == "true" { + volume.Status = ObservationStatusOK + } + if promoted := summary["promoted"]; promoted != "" { + replicaID, node := splitReplicaNode(promoted) + volume.PrimaryReplica = defaultString(replicaID, volume.PrimaryReplica) + volume.PrimaryNode = defaultString(node, volume.PrimaryNode) + } + if after := summary["after_frontend"]; after != "" { + volume.PublishTarget = after + } + volume.Conditions = append(volume.Conditions, ObservationCondition{ + Type: "NodeLossRecovery", + Status: summary["result"], + Reason: ReasonPrimaryNodeLost, + Severity: "info", + Message: fmt.Sprintf("CSI target changed %s -> %s; reader_verified=%s; pod_recreate_used=%s", + emptyAsDash(summary["before_frontend"]), + emptyAsDash(summary["after_frontend"]), + emptyAsDash(summary["reader_verified"]), + emptyAsDash(summary["pod_recreate_used"])), + }) + if summary["old_primary_stale_io_success_count"] == "0" { + volume.Conditions = append(volume.Conditions, ObservationCondition{ + Type: "StalePrimary", + Status: "false", + Reason: ReasonStalePrimaryFenced, + Severity: "info", + Message: "old primary stale I/O success count is 0", + }) + } + volume.NextActions = []string{"none"} + cluster.Volumes[0] = volume +} + +func buildImagePullBlockedEvidence(root string) (bool, VolumeEvidence) { + paths, err := findArtifactPaths(root, KubeSystemPodsDeploysArtifact) + if err != nil || len(paths) == 0 { + return false, VolumeEvidence{} + } + for _, path := range paths { + raw, err := os.ReadFile(path) + if err != nil { + continue + } + text := string(raw) + if !(strings.Contains(text, "ImagePullBackOff") || strings.Contains(text, "ErrImagePull")) { + continue + } + node := parseImagePullNode(text) + volume := VolumeEvidence{ + VolumeID: "unknown", + ReplicationFactor: 3, + Status: ObservationStatusBlocked, + Reason: ReasonCSINodeImagePullFailed, + Conditions: []ObservationCondition{{ + Type: "Attach", + Status: "false", + Reason: ReasonCSINodeImagePullFailed, + Severity: "error", + Message: fmt.Sprintf("pod kube-system/sw-block-csi-node waiting=ImagePullBackOff on node %s image sw-block-csi:local", emptyAsDash(node)), + }}, + NextActions: []string{"import sw-block-csi:local to the blocked node or use a registry reachable by all nodes"}, + SupportBundleHint: path, + } + return true, volume + } + return false, VolumeEvidence{} +} + +func parseImagePullNode(text string) string { + scanner := bufio.NewScanner(strings.NewReader(text)) + for scanner.Scan() { + line := scanner.Text() + if !strings.Contains(line, "sw-block-csi-node") || !(strings.Contains(line, "ImagePullBackOff") || strings.Contains(line, "ErrImagePull")) { + continue + } + fields := strings.Fields(line) + if len(fields) >= 7 { + return fields[6] + } + } + return Unavailable +} + +func loadTimelineArtifact(root string) ([]ClusterEvent, string, error) { + paths, err := findArtifactPaths(root, ControlPlaneTimelineArtifact) + if err != nil || len(paths) == 0 { + return nil, "", err + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + return nil, paths[0], err + } + var events []ClusterEvent + scanner := bufio.NewScanner(strings.NewReader(string(raw))) + ordinal := 0 + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + ordinal++ + fields := parseSpaceKeyValues(line) + eventType := fields["event"] + if eventType == "" { + eventType = "unknown" + } + event := ClusterEvent{ + EventID: fmt.Sprintf("%04d", ordinal), + EventTime: time.Unix(int64(ordinal), 0).UTC(), + Type: eventType, + Severity: "info", + VolumeID: defaultString(fields["volume"], parseVolumeIDFromEvidence(fields["evidence"])), + ReplicaID: defaultString(fields["replica"], fields["to"]), + NodeName: fields["node"], + Message: line, + Reason: reasonForTimelineEvent(eventType, fields), + EvidenceRef: paths[0], + } + if primaryCount, err := strconv.ParseUint(fields["primary_count"], 10, 64); err == nil { + event.NewValue = fmt.Sprintf("primary_count=%d", primaryCount) + } + events = append(events, event) + } + return events, paths[0], scanner.Err() +} + +func loadKeyValueArtifact(root, name string) (map[string]string, string, error) { + paths, err := findArtifactPaths(root, name) + if err != nil || len(paths) == 0 { + return nil, "", err + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + return nil, paths[0], err + } + out := map[string]string{} + scanner := bufio.NewScanner(strings.NewReader(string(raw))) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + key, value, ok := strings.Cut(line, "=") + if ok { + out[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + } + return out, paths[0], scanner.Err() +} + +func findArtifactPaths(root, name string) ([]string, error) { + var paths []string + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + if d.Name() == name { + paths = append(paths, path) + } + return nil + }) + sort.Strings(paths) + return paths, err +} + +func ensureObservationVolume(cluster *ClusterEvidence, volumeID string) VolumeEvidence { + if len(cluster.Volumes) == 0 { + if volumeID == "" { + volumeID = "unknown" + } + cluster.Volumes = append(cluster.Volumes, VolumeEvidence{VolumeID: volumeID, Status: ObservationStatusUnavailable}) + } + return cluster.Volumes[0] +} + +func observationStatusFromInventoryStatus(status string) string { + switch status { + case "ok": + return ObservationStatusOK + case "invalid": + return ObservationStatusInvalid + case "unhealthy": + return ObservationStatusDegraded + default: + return ObservationStatusUnavailable + } +} + +func observationStatusFromInventoryCode(code int) string { + switch code { + case VolumeStatusExitOK: + return ObservationStatusOK + case VolumeStatusExitInvalid: + return ObservationStatusInvalid + default: + return ObservationStatusDegraded + } +} + +func reasonFromIssueList(issues []string) string { + joined := strings.Join(issues, "\n") + switch { + case strings.Contains(joined, "status_endpoint_unreachable"): + return ReasonStatusEndpointUnreachable + case strings.Contains(joined, "generated_deployment_missing"): + return ReasonGeneratedDeploymentMissing + case strings.Contains(joined, "observed_replicas="): + return ReasonObservedReplicasBelowDesired + case strings.Contains(joined, "candidate_frontier_behind"): + return ReasonCandidateFrontierBehind + case strings.Contains(joined, "durable_frontier_missing"): + return ReasonDurableFrontierMissing + case strings.Contains(joined, "stale_primary"): + return ReasonStalePrimaryFenced + default: + return "inventory_issue" + } +} + +func parseSpaceKeyValues(line string) map[string]string { + out := map[string]string{} + for _, token := range strings.Fields(line) { + key, value, ok := strings.Cut(token, "=") + if ok { + out[key] = value + } + } + return out +} + +func reasonForTimelineEvent(eventType string, fields map[string]string) string { + if reason := fields["reason"]; reason != "" { + return reason + } + switch eventType { + case "candidate_evaluated": + if fields["candidate_ready"] == "true" { + return ReasonCandidateCoversRequiredFrontier + } + return ReasonNoPromotionReadyCandidate + case "authority_published": + return ReasonCandidateCoversRequiredFrontier + case "primary_failure_injected": + return ReasonPrimaryNodeLost + case "data_check": + return "reader_checksum_passed" + default: + return "" + } +} + +func parseVolumeIDFromEvidence(evidence string) string { + fields := parseSpaceKeyValues(evidence) + return fields["volume"] +} + +func splitReplicaNode(raw string) (string, string) { + replica, node, ok := strings.Cut(raw, "@") + if !ok { + return raw, "" + } + return replica, node +} + +func maxInventoryEpoch(replicas []VolumeInventoryReplica) uint64 { + var max uint64 + for _, replica := range replicas { + if replica.Epoch > max { + max = replica.Epoch + } + } + return max +} + +func maxInventoryEndpointVersion(replicas []VolumeInventoryReplica) uint64 { + var max uint64 + for _, replica := range replicas { + if replica.EndpointVersion > max { + max = replica.EndpointVersion + } + } + return max +} diff --git a/seaweed-block/core/ops/observation_bundle_test.go b/seaweed-block/core/ops/observation_bundle_test.go new file mode 100644 index 0000000000..360d5f2663 --- /dev/null +++ b/seaweed-block/core/ops/observation_bundle_test.go @@ -0,0 +1,170 @@ +package ops + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestObservationBundle_RendersNodeLossRecoveryStory(t *testing.T) { + dir := t.TempDir() + inventoryDir := filepath.Join(dir, "demo", "ops-inventory-reader-verified") + if err := os.MkdirAll(inventoryDir, 0o755); err != nil { + t.Fatal(err) + } + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 16, 16, 3, 6, 0, time.UTC), + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-node-loss", + Namespace: "default", + PVCName: "sw-block-demo-pvc", + PVName: "pvc-node-loss", + ReplicationFactor: 3, + Replicas: []VolumeInventoryReplicaInput{ + { + ReplicaID: "r1", + ServerID: "node-loss-r1", + NodeName: "m01", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.181:3260", + AuthorityRole: "unavailable", + ReplicationRole: "unavailable", + AckProfile: PromotionAckProfileSyncQuorum, + Issues: []string{"status_endpoint_unreachable=192.168.1.181:23260"}, + }, + { + ReplicaID: "r2", + ServerID: "node-loss-r2", + NodeName: "m02", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.184:3260", + AuthorityRole: "primary", + ReplicationRole: "none", + Healthy: true, + FrontendPrimaryReady: true, + Epoch: 2, + EndpointVersion: 1, + AckProfile: PromotionAckProfileSyncQuorum, + ClaimProfile: PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + { + ReplicaID: "r3", + ServerID: "node-loss-r3", + NodeName: "tp01", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.188:3260", + AuthorityRole: "unknown", + ReplicationRole: "replica_ready", + AckProfile: PromotionAckProfileSyncQuorum, + ClaimProfile: PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + }, + }}, + }) + mustWriteInventory(t, inventoryDir, inventory) + mustWrite(t, filepath.Join(dir, "demo", NodeLossRecoverySummaryArtifact), strings.Join([]string{ + "node_loss_recovery_summary_version=1", + "result=promoted", + "ack_profile=sync-quorum", + "before_primary=r1@m01", + "failed=r1@m01", + "promoted=r2@m02", + "before_frontend=192.168.1.181:3260", + "after_frontend=192.168.1.184:3260", + "pod_recreate_used=true", + "reader_verified=true", + "data_check_after_node_loss=reader_checksum_passed", + "old_primary_stale_io_success_count=0", + }, "\n")) + mustWrite(t, filepath.Join(dir, "demo", ControlPlaneTimelineArtifact), strings.Join([]string{ + "event=primary_observed replica=r1 volume=pvc-node-loss", + "event=candidate_evaluated replica=r2 candidate_ready=true reason=promotion_ready volume=pvc-node-loss", + "event=authority_published from=r1 to=r2 primary=r2 primary_count=1 volume=pvc-node-loss", + "event=data_check reader_verified=true result=reader_checksum_passed volume=pvc-node-loss", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-node-loss"}) + if err != nil { + t.Fatal(err) + } + text := RenderObservationExplainText(cluster) + for _, want := range []string{ + "volume pvc-node-loss status=ok rf=3 ack=sync-quorum", + "primary r2 on m02 frontend=192.168.1.184:3260", + "CSI target changed 192.168.1.181:3260 -> 192.168.1.184:3260", + "old primary stale I/O success count is 0", + "timeline:", + "authority_published severity=info reason=candidate_covers_required_frontier volume=pvc-node-loss replica=r2", + } { + if !strings.Contains(text, want) { + t.Fatalf("text missing %q:\n%s", want, text) + } + } + jsonl, err := RenderClusterEventsJSONL(cluster.Events) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(jsonl, `"event_type":"authority_published"`) || !strings.Contains(jsonl, `"reason_code":"candidate_covers_required_frontier"`) { + t.Fatalf("jsonl missing event evidence:\n%s", jsonl) + } +} + +func TestObservationBundle_RendersImagePullBlockedStoryWithoutInventory(t *testing.T) { + dir := t.TempDir() + mustWrite(t, filepath.Join(dir, "demo", KubeSystemPodsDeploysArtifact), `NAME READY STATUS RESTARTS AGE IP NODE +pod/sw-block-csi-node-n948t 0/2 Init:ErrImagePull 0 2m3s 192.168.1.184 m02 +deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:local`) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-blocked"}) + if err != nil { + t.Fatal(err) + } + text := RenderClusterEvidenceText(cluster) + for _, want := range []string{ + "cluster status=blocked volumes=1 nodes=0", + "volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed", + "waiting=ImagePullBackOff on node m02 image sw-block-csi:local", + "next action: import sw-block-csi:local to the blocked node", + } { + if !strings.Contains(text, want) { + t.Fatalf("text missing %q:\n%s", want, text) + } + } +} + +func mustWriteInventory(t *testing.T, dir string, inventory VolumeInventory) { + t.Helper() + raw, err := MarshalObservationJSON(inventory) + if err != nil { + t.Fatal(err) + } + mustWrite(t, filepath.Join(dir, VolumeInventoryArtifact), string(raw)) +} + +func mustWrite(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content+"\n"), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/ops/observation_report.go b/seaweed-block/core/ops/observation_report.go new file mode 100644 index 0000000000..5ff1f6c8a7 --- /dev/null +++ b/seaweed-block/core/ops/observation_report.go @@ -0,0 +1,142 @@ +package ops + +import ( + "fmt" + "html" + "os" + "path/filepath" + "sort" + "strings" +) + +func WriteObservationReportArtifacts(outDir string, cluster ClusterEvidence) error { + if strings.TrimSpace(outDir) == "" { + return fmt.Errorf("report out dir is required") + } + cluster = normalizeObservationCluster(cluster) + if err := os.MkdirAll(outDir, 0o755); err != nil { + return err + } + jsonRaw, err := MarshalObservationJSON(cluster) + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(outDir, ObservationReportJSONArtifact), jsonRaw, 0o644); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(outDir, ObservationReportTextArtifact), []byte(RenderObservationReportSummary(cluster)), 0o644); err != nil { + return err + } + jsonl, err := RenderClusterEventsJSONL(cluster.Events) + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(outDir, ObservationReportJSONLArtifact), []byte(jsonl), 0o644); err != nil { + return err + } + return os.WriteFile(filepath.Join(outDir, ObservationReportHTMLArtifact), []byte(RenderObservationReportHTML(cluster)), 0o644) +} + +func RenderObservationReportSummary(cluster ClusterEvidence) string { + cluster = normalizeObservationCluster(cluster) + var b strings.Builder + fmt.Fprintf(&b, "sw-block report\n") + fmt.Fprintf(&b, "status=%s\n", emptyAsDash(cluster.Status)) + fmt.Fprintf(&b, "captured_at=%s\n", cluster.CapturedAt.Format("2006-01-02T15:04:05Z07:00")) + fmt.Fprintf(&b, "volumes=%d\n", len(cluster.Volumes)) + fmt.Fprintf(&b, "nodes=%d\n", len(cluster.Nodes)) + fmt.Fprintf(&b, "events=%d\n", len(cluster.Events)) + for _, volume := range cluster.Volumes { + fmt.Fprintf(&b, "volume=%s status=%s pvc=%s/%s primary=%s@%s frontend=%s rf=%d ack=%s\n", + emptyAsDash(volume.VolumeID), + emptyAsDash(volume.Status), + emptyAsDash(volume.Namespace), + emptyAsDash(volume.PVCName), + emptyAsDash(volume.PrimaryReplica), + emptyAsDash(volume.PrimaryNode), + emptyAsDash(volume.PublishTarget), + volume.ReplicationFactor, + emptyAsDash(volume.AckProfile)) + } + fmt.Fprintf(&b, "read_only=true\n") + return b.String() +} + +func RenderObservationReportHTML(cluster ClusterEvidence) string { + cluster = normalizeObservationCluster(cluster) + events := append([]ClusterEvent(nil), cluster.Events...) + sort.SliceStable(events, func(i, j int) bool { + return events[i].EventTime.Before(events[j].EventTime) + }) + if len(events) > 25 { + events = events[len(events)-25:] + } + + var b strings.Builder + b.WriteString("") + b.WriteString("") + b.WriteString("sw-block status report") + b.WriteString("") + fmt.Fprintf(&b, "

sw-block read-only status

status=%s captured=%s product=%s

This report is observation-only. It does not promote, repair, delete, or mutate Kubernetes resources.

", + esc(emptyAsDash(cluster.Status)), esc(cluster.CapturedAt.Format("2006-01-02T15:04:05Z07:00")), esc(emptyAsDash(cluster.ProductRevision))) + b.WriteString("
") + b.WriteString("
") + reportCard(&b, "Volumes", fmt.Sprintf("%d", len(cluster.Volumes)), "") + reportCard(&b, "Nodes", fmt.Sprintf("%d", len(cluster.Nodes)), "") + reportCard(&b, "Events", fmt.Sprintf("%d", len(cluster.Events)), "") + reportCard(&b, "Read Only", "true", "ok") + b.WriteString("
") + + b.WriteString("

Volumes

") + for _, volume := range cluster.Volumes { + class := "ok" + if volume.Status != ObservationStatusOK { + class = "bad" + } + fmt.Fprintf(&b, "", + esc(emptyAsDash(volume.VolumeID)), esc(emptyAsDash(volume.Namespace)), esc(emptyAsDash(volume.PVCName)), + class, esc(emptyAsDash(volume.Status)), volume.ReplicationFactor, + esc(emptyAsDash(volume.PrimaryReplica)), esc(emptyAsDash(volume.PrimaryNode)), + esc(emptyAsDash(volume.PublishTarget)), esc(emptyAsDash(volume.Reason))) + } + b.WriteString("
VolumePVCStatusRFPrimaryFrontendReason
%s%s/%s%s%d%s@%s%s%s
") + + b.WriteString("

Nodes

") + for _, node := range cluster.Nodes { + fmt.Fprintf(&b, "", + esc(emptyAsDash(node.NodeName)), esc(emptyAsDash(node.InternalIP)), node.Ready, node.Schedulable, node.ReplicaCount, esc(strings.Join(node.MissingImages, ", "))) + } + b.WriteString("
NodeIPReadySchedulableReplicasMissing Images
%s%s%t%t%d%s
") + + b.WriteString("

Recent Timeline

") + for _, event := range events { + fmt.Fprintf(&b, "", + esc(event.EventTime.Format("15:04:05")), esc(emptyAsDash(event.Type)), esc(emptyAsDash(event.Reason)), + esc(emptyAsDash(event.VolumeID)), esc(emptyAsDash(event.ReplicaID)), esc(emptyAsDash(event.Message))) + } + b.WriteString("
TimeTypeReasonVolumeReplicaMessage
%s%s%s%s%s%s
") + b.WriteString("

Machine Artifacts

cluster-evidence.json, timeline.jsonl, and summary.txt are generated next to this page.

") + b.WriteString("
\n") + return b.String() +} + +func reportCard(b *strings.Builder, label, value, class string) { + if class != "" { + fmt.Fprintf(b, "
%s
%s
", esc(label), class, esc(value)) + return + } + fmt.Fprintf(b, "
%s
%s
", esc(label), esc(value)) +} + +func esc(value string) string { + return html.EscapeString(value) +} diff --git a/seaweed-block/core/ops/observation_test.go b/seaweed-block/core/ops/observation_test.go new file mode 100644 index 0000000000..4397c240ee --- /dev/null +++ b/seaweed-block/core/ops/observation_test.go @@ -0,0 +1,242 @@ +package ops + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestObservation_RenderHealthyVolumeTextAndJSON(t *testing.T) { + volume := healthyObservationVolume() + + text := RenderVolumeEvidenceText(volume) + for _, want := range []string{ + "volume pvc-healthy status=ok rf=3 ack=sync-quorum", + "primary r1 on m01 frontend=192.168.1.181:3260", + "r2 m02 unknown replica_ready durable_lsn=44 candidate_ready=true", + "next action: none", + } { + if !strings.Contains(text, want) { + t.Fatalf("text missing %q:\n%s", want, text) + } + } + + raw, err := MarshalObservationJSON(volume) + if err != nil { + t.Fatalf("marshal json: %v", err) + } + var decoded VolumeEvidence + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatalf("decode json: %v\n%s", err, raw) + } + if len(decoded.Replicas) < 2 { + t.Fatalf("expected at least 2 replicas, got %d: %+v", len(decoded.Replicas), decoded.Replicas) + } + if decoded.Status != ObservationStatusOK || decoded.Replicas[1].CandidateReadyReason != PromotionReasonReady { + t.Fatalf("decoded evidence lost stable fields: %+v", decoded) + } +} + +func TestObservation_RenderRecoveringNodeLossStory(t *testing.T) { + volume := VolumeEvidence{ + VolumeID: "pvc-recovering", + Namespace: "default", + PVCName: "mysql-data", + ReplicationFactor: 3, + AckProfile: PromotionAckProfileSyncQuorum, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ObservationStatusRecovering, + Reason: ReasonPrimaryNodeLost, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + Replicas: []ReplicaEvidence{ + { + ReplicaID: "r1", + KubernetesNode: "m01", + Role: "unavailable", + ReplicationRole: "unavailable", + StalePrimaryFenced: true, + Conditions: []ObservationCondition{{ + Type: "StalePrimary", + Status: "true", + Reason: ReasonStalePrimaryFenced, + Severity: "info", + Message: "old primary endpoint is not ready", + }}, + }, + { + ReplicaID: "r2", + KubernetesNode: "m02", + Role: "primary", + ReplicationRole: "none", + DurableFrontierKnown: true, + DurableFrontierLSN: 52, + }, + }, + Conditions: []ObservationCondition{{ + Type: "Recovery", + Status: "true", + Reason: ReasonPrimaryNodeLost, + Severity: "info", + Message: "CSI target changed 192.168.1.181:3260 -> 192.168.1.184:3260", + }}, + NextActions: []string{"wait for app pod readiness, then collect support bundle if stuck"}, + } + + text := RenderVolumeEvidenceText(volume) + for _, want := range []string{ + "volume pvc-recovering status=recovering rf=3 ack=sync-quorum reason=primary_node_lost", + "primary r2 on m02 frontend=192.168.1.184:3260", + "r1 m01 unavailable unavailable stale_primary_fenced=true", + "condition Recovery severity=info reason=primary_node_lost CSI target changed 192.168.1.181:3260 -> 192.168.1.184:3260", + "next action: wait for app pod readiness, then collect support bundle if stuck", + } { + if !strings.Contains(text, want) { + t.Fatalf("text missing %q:\n%s", want, text) + } + } +} + +func TestObservation_RenderBlockedImagePullStory(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 5, 16, 16, 3, 6, 0, time.UTC)) + cluster.Status = ObservationStatusBlocked + cluster.Nodes = []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + RequiredImages: []string{"sw-block:local", "sw-block-csi:local"}, + MissingImages: []string{"sw-block-csi:local"}, + Conditions: []ObservationCondition{{ + Type: "ImageInventory", + Status: "false", + Reason: ReasonImageMissingOnNode, + Severity: "error", + Message: "node m02 missing image sw-block-csi:local", + }}, + }} + cluster.Volumes = []VolumeEvidence{{ + VolumeID: "pvc-blocked", + Namespace: "default", + PVCName: "mysql-data", + ReplicationFactor: 3, + Status: ObservationStatusBlocked, + Reason: ReasonCSINodeImagePullFailed, + Conditions: []ObservationCondition{{ + Type: "Attach", + Status: "false", + Reason: ReasonCSINodeImagePullFailed, + Severity: "error", + Message: "pod kube-system/sw-block-csi-node-abc waiting=ImagePullBackOff", + }}, + NextActions: []string{"import the image to m02 or use a registry reachable by all nodes"}, + }} + + text := RenderClusterEvidenceText(cluster) + for _, want := range []string{ + "cluster status=blocked volumes=1 nodes=1", + "volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed", + "condition Attach severity=error reason=csi_node_image_pull_failed pod kube-system/sw-block-csi-node-abc waiting=ImagePullBackOff", + "next action: import the image to m02 or use a registry reachable by all nodes", + } { + if !strings.Contains(text, want) { + t.Fatalf("text missing %q:\n%s", want, text) + } + } +} + +func TestObservation_RenderEventsJSONLStableOrder(t *testing.T) { + events := []ClusterEvent{ + { + EventID: "2", + EventTime: time.Date(2026, 5, 16, 16, 3, 8, 0, time.UTC), + Type: "authority_published", + Severity: "info", + VolumeID: "pvc-a", + ReplicaID: "r2", + Reason: ReasonCandidateCoversRequiredFrontier, + Message: "r2 promoted after required frontier was covered", + }, + { + EventID: "1", + EventTime: time.Date(2026, 5, 16, 16, 3, 6, 0, time.UTC), + Type: "promotion_candidate_evaluated", + Severity: "info", + VolumeID: "pvc-a", + ReplicaID: "r2", + Reason: PromotionReasonReady, + Message: "r2 candidate_ready=true", + }, + } + + jsonl, err := RenderClusterEventsJSONL(events) + if err != nil { + t.Fatalf("render jsonl: %v", err) + } + lines := strings.Split(strings.TrimSpace(jsonl), "\n") + if len(lines) != 2 { + t.Fatalf("jsonl lines=%d:\n%s", len(lines), jsonl) + } + if !strings.Contains(lines[0], `"event_id":"1"`) || !strings.Contains(lines[1], `"event_id":"2"`) { + t.Fatalf("events not sorted by time:\n%s", jsonl) + } + if !strings.Contains(lines[1], `"reason_code":"candidate_covers_required_frontier"`) { + t.Fatalf("missing stable reason code:\n%s", jsonl) + } +} + +func healthyObservationVolume() VolumeEvidence { + return VolumeEvidence{ + VolumeID: "pvc-healthy", + Namespace: "default", + PVCName: "mysql-data", + ReplicationFactor: 3, + AckProfile: PromotionAckProfileSyncQuorum, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + Epoch: 1, + EndpointVersion: 1, + Replicas: []ReplicaEvidence{ + { + ReplicaID: "r1", + KubernetesNode: "m01", + Role: "primary", + ReplicationRole: "none", + DurableFrontierKnown: true, + DurableFrontierLSN: 44, + }, + { + ReplicaID: "r2", + KubernetesNode: "m02", + Role: "unknown", + ReplicationRole: "replica_ready", + DurableFrontierKnown: true, + DurableFrontierLSN: 44, + CandidateReady: true, + CandidateReadyReason: PromotionReasonReady, + }, + { + ReplicaID: "r3", + KubernetesNode: "tp01", + Role: "unknown", + ReplicationRole: "replica_ready", + DurableFrontierKnown: true, + DurableFrontierLSN: 44, + CandidateReady: true, + CandidateReadyReason: PromotionReasonReady, + }, + }, + NextActions: []string{"none"}, + SupportBundleHint: "sw-block ops bundle volume pvc-healthy --out /tmp/sw-block-pvc-healthy", + } +} diff --git a/seaweed-block/core/ops/promotion_readiness.go b/seaweed-block/core/ops/promotion_readiness.go new file mode 100644 index 0000000000..a53bb46883 --- /dev/null +++ b/seaweed-block/core/ops/promotion_readiness.go @@ -0,0 +1,138 @@ +package ops + +import hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" + +const ( + PromotionClaimBetaRecovery = "beta-recovery" + PromotionClaimControlledBestEffortDemo = "controlled-best-effort-demo" + PromotionClaimStage2ISCSIALUAMultipath = "stage2-iscsi-alua-multipath" + + PromotionAckProfileBestEffort = "best-effort" + PromotionAckProfileSyncQuorum = "sync-quorum" + PromotionAckProfileSyncAll = "sync-all" + + PromotionReasonReady = "promotion_ready" + PromotionReasonCandidateNotReady = "candidate_not_ready_for_primary" + PromotionReasonReplicationRoleNotReady = "replication_role_not_ready" + PromotionReasonDurableFrontierMissing = "durable_frontier_missing" + PromotionReasonRequiredFrontierMissing = "required_frontier_missing" + PromotionReasonCandidateFrontierMissing = "candidate_frontier_missing" + PromotionReasonCandidateFrontierBehind = "candidate_frontier_behind" + PromotionReasonReplicationAckProfileBad = "replication_ack_profile_unmet" + PromotionReasonClaimProfileBad = "claim_profile_unaccepted" +) + +// PromotionReadinessInput is the ops-level, evidence-only contract for deciding +// whether a non-primary replica can be described as promotion-ready. It does not +// mutate authority. Runner gates and support bundles use it to avoid turning a +// live heartbeat or a vague "healthy" bit into an RF=2 recovery claim. +type PromotionReadinessInput struct { + CandidateReplicaID string + ClaimProfile string + AckProfile string + + Observed bool + Reachable bool + + AuthorityRole string + ReplicationRole string + + DurableLatched bool + DurableOperational bool + + RequiredFrontierLSN uint64 + RequiredFrontierKnown bool + CandidateFrontierLSN uint64 + CandidateFrontierKnown bool +} + +type PromotionReadinessReport struct { + CandidateReplicaID string `json:"candidate_replica_id"` + CandidateReady bool `json:"candidate_ready"` + Reason string `json:"reason"` + ClaimProfile string `json:"claim_profile"` + AckProfile string `json:"ack_profile"` + + RequiredFrontierLSN uint64 `json:"required_frontier_lsn"` + RequiredFrontierKnown bool `json:"required_frontier_known"` + CandidateFrontierLSN uint64 `json:"candidate_frontier_lsn"` + CandidateFrontierKnown bool `json:"candidate_frontier_known"` + FrontierCovered bool `json:"frontier_covered"` +} + +func EvaluatePromotionReadiness(in PromotionReadinessInput) PromotionReadinessReport { + claimProfile := in.ClaimProfile + if claimProfile == "" { + claimProfile = PromotionClaimBetaRecovery + } + out := PromotionReadinessReport{ + CandidateReplicaID: explicitUnavailable(in.CandidateReplicaID), + Reason: PromotionReasonReady, + ClaimProfile: claimProfile, + AckProfile: explicitUnavailable(in.AckProfile), + RequiredFrontierLSN: in.RequiredFrontierLSN, + RequiredFrontierKnown: in.RequiredFrontierKnown, + CandidateFrontierLSN: in.CandidateFrontierLSN, + CandidateFrontierKnown: in.CandidateFrontierKnown, + } + + if !in.Observed || !in.Reachable || in.CandidateReplicaID == "" { + out.Reason = PromotionReasonCandidateNotReady + return out + } + if !PromotionClaimProfileAccepted(claimProfile) { + out.Reason = PromotionReasonClaimProfileBad + return out + } + if in.AuthorityRole == hostvolume.AuthorityRolePrimary { + out.Reason = PromotionReasonCandidateNotReady + return out + } + if in.ReplicationRole != hostvolume.ReplicationRoleReady { + out.Reason = PromotionReasonReplicationRoleNotReady + return out + } + if !promotionAckProfileAccepted(in.AckProfile, claimProfile) { + out.Reason = PromotionReasonReplicationAckProfileBad + return out + } + if !in.DurableLatched || !in.DurableOperational { + out.Reason = PromotionReasonDurableFrontierMissing + return out + } + if !in.RequiredFrontierKnown { + out.Reason = PromotionReasonRequiredFrontierMissing + return out + } + if !in.CandidateFrontierKnown { + out.Reason = PromotionReasonCandidateFrontierMissing + return out + } + if in.CandidateFrontierLSN < in.RequiredFrontierLSN { + out.Reason = PromotionReasonCandidateFrontierBehind + return out + } + out.CandidateReady = true + out.FrontierCovered = true + return out +} + +func promotionAckProfileAccepted(ackProfile, claimProfile string) bool { + switch ackProfile { + case PromotionAckProfileSyncQuorum, PromotionAckProfileSyncAll: + return true + case PromotionAckProfileBestEffort: + return claimProfile == PromotionClaimControlledBestEffortDemo + default: + return false + } +} + +func PromotionClaimProfileAccepted(claimProfile string) bool { + switch claimProfile { + case "", PromotionClaimBetaRecovery, PromotionClaimControlledBestEffortDemo, PromotionClaimStage2ISCSIALUAMultipath: + return true + default: + return false + } +} diff --git a/seaweed-block/core/ops/promotion_readiness_test.go b/seaweed-block/core/ops/promotion_readiness_test.go new file mode 100644 index 0000000000..a23ac08c21 --- /dev/null +++ b/seaweed-block/core/ops/promotion_readiness_test.go @@ -0,0 +1,200 @@ +package ops + +import ( + "testing" + + hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +func TestEvaluatePromotionReadiness_HeartbeatOnlyIsNotReady(t *testing.T) { + report := EvaluatePromotionReadiness(PromotionReadinessInput{ + CandidateReplicaID: "r2", + Observed: true, + Reachable: true, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + ReplicationRole: hostvolume.ReplicationRoleNotReady, + AckProfile: PromotionAckProfileSyncQuorum, + }) + if report.CandidateReady { + t.Fatalf("heartbeat-only candidate must not be promotion-ready: %+v", report) + } + if report.Reason != PromotionReasonReplicationRoleNotReady { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonReplicationRoleNotReady) + } +} + +func TestEvaluatePromotionReadiness_BetaRecoveryRejectsBestEffortAck(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.AckProfile = PromotionAckProfileBestEffort + })) + if report.CandidateReady { + t.Fatalf("beta-facing recovery must not pass on best-effort ACK: %+v", report) + } + if report.Reason != PromotionReasonReplicationAckProfileBad { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonReplicationAckProfileBad) + } + if !report.CandidateFrontierKnown || report.CandidateFrontierLSN != report.RequiredFrontierLSN { + t.Fatalf("frontier evidence should remain visible when ACK profile fails: %+v", report) + } +} + +func TestEvaluatePromotionReadiness_RejectsUnknownClaimProfile(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.ClaimProfile = "stage2-typo" + in.AckProfile = PromotionAckProfileSyncQuorum + })) + if report.CandidateReady { + t.Fatalf("unknown claim profile must not be promotion-ready: %+v", report) + } + if report.Reason != PromotionReasonClaimProfileBad { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonClaimProfileBad) + } +} + +func TestEvaluatePromotionReadiness_MissingDurableFrontierIsNotReady(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.DurableLatched = false + in.DurableOperational = false + in.RequiredFrontierKnown = false + in.CandidateFrontierKnown = false + in.CandidateFrontierLSN = 0 + })) + if report.CandidateReady { + t.Fatalf("candidate without frontier evidence must not be ready: %+v", report) + } + if report.Reason != PromotionReasonDurableFrontierMissing { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonDurableFrontierMissing) + } +} + +func TestEvaluatePromotionReadiness_MissingRequiredFrontierIsNotReady(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.RequiredFrontierKnown = false + in.RequiredFrontierLSN = 0 + in.CandidateFrontierKnown = true + in.CandidateFrontierLSN = 90 + })) + if report.CandidateReady { + t.Fatalf("candidate without writer-required frontier must not be ready: %+v", report) + } + if report.Reason != PromotionReasonRequiredFrontierMissing { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonRequiredFrontierMissing) + } +} + +func TestEvaluatePromotionReadiness_MissingCandidateFrontierIsNotReady(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.CandidateFrontierKnown = false + in.CandidateFrontierLSN = 0 + })) + if report.CandidateReady { + t.Fatalf("candidate without own frontier must not be ready: %+v", report) + } + if report.Reason != PromotionReasonCandidateFrontierMissing { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonCandidateFrontierMissing) + } +} + +func TestEvaluatePromotionReadiness_EmptyVolumeFrontierZeroCanBeReadyWhenKnown(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.RequiredFrontierLSN = 0 + in.CandidateFrontierLSN = 0 + in.RequiredFrontierKnown = true + in.CandidateFrontierKnown = true + })) + if !report.CandidateReady { + t.Fatalf("known empty-volume frontier should be accepted: %+v", report) + } + if !report.FrontierCovered { + t.Fatalf("frontier_covered should be true for known zero frontier: %+v", report) + } +} + +func TestEvaluatePromotionReadiness_BehindFrontierIsNotReady(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.RequiredFrontierLSN = 90 + in.CandidateFrontierLSN = 89 + })) + if report.CandidateReady { + t.Fatalf("candidate behind writer frontier must not be ready: %+v", report) + } + if report.Reason != PromotionReasonCandidateFrontierBehind { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonCandidateFrontierBehind) + } + if report.FrontierCovered { + t.Fatalf("frontier_covered must be false when candidate is behind: %+v", report) + } +} + +func TestEvaluatePromotionReadiness_SyncQuorumCoveredFrontierIsReady(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(nil)) + if !report.CandidateReady { + t.Fatalf("sync-quorum candidate with covered frontier should be ready: %+v", report) + } + if report.Reason != PromotionReasonReady { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonReady) + } + if !report.FrontierCovered { + t.Fatalf("frontier_covered should be true: %+v", report) + } +} + +func TestEvaluatePromotionReadiness_Stage2ISCSIALUAMultipathAcceptsSyncQuorum(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.ClaimProfile = PromotionClaimStage2ISCSIALUAMultipath + in.AckProfile = PromotionAckProfileSyncQuorum + })) + if !report.CandidateReady { + t.Fatalf("stage2 multipath claim should accept covered sync-quorum frontier: %+v", report) + } + if report.ClaimProfile != PromotionClaimStage2ISCSIALUAMultipath { + t.Fatalf("claim_profile=%q want %q", report.ClaimProfile, PromotionClaimStage2ISCSIALUAMultipath) + } +} + +func TestEvaluatePromotionReadiness_Stage2ISCSIALUAMultipathRejectsBestEffort(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.ClaimProfile = PromotionClaimStage2ISCSIALUAMultipath + in.AckProfile = PromotionAckProfileBestEffort + })) + if report.CandidateReady { + t.Fatalf("stage2 multipath claim must not pass on best-effort ACK: %+v", report) + } + if report.Reason != PromotionReasonReplicationAckProfileBad { + t.Fatalf("reason=%q want %q", report.Reason, PromotionReasonReplicationAckProfileBad) + } +} + +func TestEvaluatePromotionReadiness_ControlledBestEffortDemoCanBeReadyWithExplicitProfile(t *testing.T) { + report := EvaluatePromotionReadiness(promotionReadyInput(func(in *PromotionReadinessInput) { + in.ClaimProfile = PromotionClaimControlledBestEffortDemo + in.AckProfile = PromotionAckProfileBestEffort + })) + if !report.CandidateReady { + t.Fatalf("controlled best-effort demo may be ready for its explicit narrow claim: %+v", report) + } + if report.ClaimProfile != PromotionClaimControlledBestEffortDemo { + t.Fatalf("claim_profile=%q want %q", report.ClaimProfile, PromotionClaimControlledBestEffortDemo) + } +} + +func promotionReadyInput(mut func(*PromotionReadinessInput)) PromotionReadinessInput { + in := PromotionReadinessInput{ + CandidateReplicaID: "r2", + Observed: true, + Reachable: true, + AuthorityRole: hostvolume.AuthorityRoleUnknown, + ReplicationRole: hostvolume.ReplicationRoleReady, + DurableLatched: true, + DurableOperational: true, + AckProfile: PromotionAckProfileSyncQuorum, + RequiredFrontierLSN: 90, + RequiredFrontierKnown: true, + CandidateFrontierLSN: 90, + CandidateFrontierKnown: true, + } + if mut != nil { + mut(&in) + } + return in +} diff --git a/seaweed-block/core/ops/volume_inventory.go b/seaweed-block/core/ops/volume_inventory.go index 51c0e2c54a..e1ce0fa2c1 100644 --- a/seaweed-block/core/ops/volume_inventory.go +++ b/seaweed-block/core/ops/volume_inventory.go @@ -2,6 +2,8 @@ package ops import ( "fmt" + "net" + "net/netip" "sort" "strings" "time" @@ -34,32 +36,41 @@ type VolumeInventoryVolumeInput struct { CollectionErrors []string Residue ResidueReport Issues []string + FailoverTimeline []VolumeInventoryFailoverEvent Replicas []VolumeInventoryReplicaInput } type VolumeInventoryReplicaInput struct { - ReplicaID string - ServerID string - NodeName string - GeneratedDeployment string - LifecycleOwner string - OwnerReference string - Protocol string - FrontendAddress string - StatusAddress string - SupportBundle string - DataAddr string - CtrlAddr string - Observed bool - AuthorityRole string - Healthy bool - FrontendPrimaryReady bool - ReplicationRole string - Epoch uint64 - EndpointVersion uint64 - Residue ResidueReport - CollectionErrors []string - Issues []string + ReplicaID string + ServerID string + NodeName string + GeneratedDeployment string + LifecycleOwner string + OwnerReference string + Protocol string + FrontendAddress string + StatusAddress string + SupportBundle string + DataAddr string + CtrlAddr string + Observed bool + AuthorityRole string + Healthy bool + FrontendPrimaryReady bool + ReplicationRole string + Epoch uint64 + EndpointVersion uint64 + ClaimProfile string + AckProfile string + DurableLatched bool + DurableOperational bool + RequiredFrontierLSN uint64 + RequiredFrontierKnown bool + CandidateFrontierLSN uint64 + CandidateFrontierKnown bool + Residue ResidueReport + CollectionErrors []string + Issues []string } type VolumeInventory struct { @@ -75,49 +86,64 @@ type VolumeInventory struct { } type VolumeInventoryVolume struct { - VolumeID string `json:"volume_id"` - Namespace string `json:"namespace"` - PVCName string `json:"pvc_name"` - PVName string `json:"pv_name"` - ReplicationFactor int `json:"replication_factor"` - DesiredReplicas int `json:"desired_replicas"` - ObservedReplicas int `json:"observed_replicas"` - PrimaryReplicaID string `json:"primary_replica_id"` - Protocols []string `json:"protocols"` - ProductRevision string `json:"product_revision"` - Status string `json:"status"` - Residue ResidueReport `json:"residue"` - Issues []string `json:"issues"` - Unchecked []string `json:"unchecked"` - CollectionErrors []string `json:"collection_errors"` - SupportBundle string `json:"support_bundle"` - Replicas []VolumeInventoryReplica `json:"replicas"` + VolumeID string `json:"volume_id"` + Namespace string `json:"namespace"` + PVCName string `json:"pvc_name"` + PVName string `json:"pv_name"` + ReplicationFactor int `json:"replication_factor"` + DesiredReplicas int `json:"desired_replicas"` + ObservedReplicas int `json:"observed_replicas"` + PrimaryReplicaID string `json:"primary_replica_id"` + Protocols []string `json:"protocols"` + ProductRevision string `json:"product_revision"` + Status string `json:"status"` + ReplicasOnDistinctNodes bool `json:"replicas_on_distinct_nodes"` + FrontendsNonLoopback bool `json:"frontends_non_loopback"` + Residue ResidueReport `json:"residue"` + Issues []string `json:"issues"` + Unchecked []string `json:"unchecked"` + CollectionErrors []string `json:"collection_errors"` + SupportBundle string `json:"support_bundle"` + FailoverTimeline []VolumeInventoryFailoverEvent `json:"failover_timeline,omitempty"` + Replicas []VolumeInventoryReplica `json:"replicas"` +} + +type VolumeInventoryFailoverEvent struct { + Phase string `json:"phase"` + ReplicaID string `json:"replica_id"` + Role string `json:"role"` + Epoch uint64 `json:"epoch"` + EndpointVersion uint64 `json:"endpoint_version"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` } type VolumeInventoryReplica struct { - ReplicaID string `json:"replica_id"` - ServerID string `json:"server_id"` - NodeName string `json:"node_name"` - GeneratedDeployment string `json:"generated_deployment"` - LifecycleOwner string `json:"lifecycle_owner"` - OwnerReference string `json:"owner_reference"` - Protocol string `json:"protocol"` - FrontendAddress string `json:"frontend_address"` - StatusAddress string `json:"status_address"` - SupportBundle string `json:"support_bundle"` - DataAddr string `json:"data_addr"` - CtrlAddr string `json:"ctrl_addr"` - Observed bool `json:"observed"` - Status string `json:"status"` - AuthorityRole string `json:"authority_role"` - Healthy bool `json:"healthy"` - FrontendPrimaryReady bool `json:"frontend_primary_ready"` - ReplicationRole string `json:"replication_role"` - Epoch uint64 `json:"epoch"` - EndpointVersion uint64 `json:"endpoint_version"` - Residue ResidueReport `json:"residue"` - Issues []string `json:"issues"` - CollectionErrors []string `json:"collection_errors"` + ReplicaID string `json:"replica_id"` + ServerID string `json:"server_id"` + NodeName string `json:"node_name"` + GeneratedDeployment string `json:"generated_deployment"` + LifecycleOwner string `json:"lifecycle_owner"` + OwnerReference string `json:"owner_reference"` + Protocol string `json:"protocol"` + FrontendAddress string `json:"frontend_address"` + StatusAddress string `json:"status_address"` + SupportBundle string `json:"support_bundle"` + DataAddr string `json:"data_addr"` + CtrlAddr string `json:"ctrl_addr"` + Observed bool `json:"observed"` + Status string `json:"status"` + AuthorityRole string `json:"authority_role"` + Healthy bool `json:"healthy"` + FrontendPrimaryReady bool `json:"frontend_primary_ready"` + ReplicationRole string `json:"replication_role"` + Epoch uint64 `json:"epoch"` + EndpointVersion uint64 `json:"endpoint_version"` + AckProfile string `json:"ack_profile"` + PromotionReadiness PromotionReadinessReport `json:"promotion_readiness"` + Residue ResidueReport `json:"residue"` + Issues []string `json:"issues"` + CollectionErrors []string `json:"collection_errors"` } func BuildVolumeInventory(in VolumeInventoryInput) VolumeInventory { @@ -172,6 +198,7 @@ func buildInventoryVolume(productRevision string, in VolumeInventoryVolumeInput) } observed := 0 primary := Unavailable + primaryCount := 0 protocolsSeen := map[string]bool{} for _, replica := range replicas { if replica.Observed { @@ -179,6 +206,7 @@ func buildInventoryVolume(productRevision string, in VolumeInventoryVolumeInput) } if replica.AuthorityRole == hostvolume.AuthorityRolePrimary { primary = replica.ReplicaID + primaryCount++ } if replica.Protocol != "" && replica.Protocol != Unavailable { protocolsSeen[replica.Protocol] = true @@ -191,27 +219,37 @@ func buildInventoryVolume(productRevision string, in VolumeInventoryVolumeInput) sort.Strings(protocols) volume := VolumeInventoryVolume{ - VolumeID: explicitUnavailable(in.VolumeID), - Namespace: explicitUnavailable(in.Namespace), - PVCName: explicitUnavailable(in.PVCName), - PVName: explicitUnavailable(in.PVName), - ReplicationFactor: desired, - DesiredReplicas: desired, - ObservedReplicas: observed, - PrimaryReplicaID: primary, - Protocols: protocols, - ProductRevision: productRevision, - Residue: copyResidue(in.Residue), - Unchecked: copyStringSlice(in.Residue.Unchecked), - CollectionErrors: copyStringSlice(in.CollectionErrors), - SupportBundle: in.SupportBundle, - Replicas: replicas, + VolumeID: explicitUnavailable(in.VolumeID), + Namespace: explicitUnavailable(in.Namespace), + PVCName: explicitUnavailable(in.PVCName), + PVName: explicitUnavailable(in.PVName), + ReplicationFactor: desired, + DesiredReplicas: desired, + ObservedReplicas: observed, + PrimaryReplicaID: primaryReplicaID(primary, primaryCount), + Protocols: protocols, + ProductRevision: productRevision, + ReplicasOnDistinctNodes: replicasOnDistinctNodes(replicas, desired), + FrontendsNonLoopback: frontendsNonLoopback(replicas, desired), + Residue: copyResidue(in.Residue), + Unchecked: copyStringSlice(in.Residue.Unchecked), + CollectionErrors: copyStringSlice(in.CollectionErrors), + SupportBundle: in.SupportBundle, + FailoverTimeline: copyFailoverTimeline(in.FailoverTimeline), + Replicas: replicas, } volume.Issues = append(copyStringSlice(in.Issues), volumeInventoryVolumeIssues(volume)...) volume.Status = inventoryIssueStatus(volume.Issues) return volume } +func primaryReplicaID(primary string, count int) string { + if count == 1 { + return explicitUnavailable(primary) + } + return Unavailable +} + func buildInventoryReplica(in VolumeInventoryReplicaInput) VolumeInventoryReplica { replica := VolumeInventoryReplica{ ReplicaID: explicitUnavailable(in.ReplicaID), @@ -233,10 +271,26 @@ func buildInventoryReplica(in VolumeInventoryReplicaInput) VolumeInventoryReplic ReplicationRole: explicitUnavailable(in.ReplicationRole), Epoch: in.Epoch, EndpointVersion: in.EndpointVersion, + AckProfile: explicitUnavailable(defaultString(in.AckProfile, PromotionAckProfileBestEffort)), Residue: copyResidue(in.Residue), Issues: copyStringSlice(in.Issues), CollectionErrors: copyStringSlice(in.CollectionErrors), } + replica.PromotionReadiness = EvaluatePromotionReadiness(PromotionReadinessInput{ + CandidateReplicaID: replica.ReplicaID, + ClaimProfile: in.ClaimProfile, + AckProfile: replica.AckProfile, + Observed: replica.Observed, + Reachable: !containsIssuePrefix(replica.Issues, "status_endpoint_unavailable") && !containsIssuePrefix(replica.Issues, "status_endpoint_unreachable="), + AuthorityRole: replica.AuthorityRole, + ReplicationRole: replica.ReplicationRole, + DurableLatched: in.DurableLatched, + DurableOperational: in.DurableOperational, + RequiredFrontierLSN: in.RequiredFrontierLSN, + RequiredFrontierKnown: in.RequiredFrontierKnown, + CandidateFrontierLSN: in.CandidateFrontierLSN, + CandidateFrontierKnown: in.CandidateFrontierKnown, + }) replica.Issues = append(replica.Issues, volumeInventoryReplicaIssues(replica)...) replica.Status = inventoryReplicaStatus(replica) return replica @@ -322,6 +376,10 @@ func RenderVolumeInventorySummary(in VolumeInventory) string { volume.Status, strings.Join(volume.Protocols, ","), len(volume.Replicas)) + fmt.Fprintf(&b, "eligibility: volume=%s replicas_on_distinct_nodes=%t frontends_non_loopback=%t\n", + volume.VolumeID, + volume.ReplicasOnDistinctNodes, + volume.FrontendsNonLoopback) for _, replica := range volume.Replicas { fmt.Fprintf(&b, "replica: volume=%s replica=%s server=%s node=%s observed=%t status=%s lifecycle_owner=%s owner_ref=%s role=%s replication=%s healthy=%t epoch=%d endpoint_version=%d frontend=%s status_addr=%s support_bundle=%s\n", volume.VolumeID, @@ -340,6 +398,29 @@ func RenderVolumeInventorySummary(in VolumeInventory) string { replica.FrontendAddress, replica.StatusAddress, replica.SupportBundle) + fmt.Fprintf(&b, "promotion: volume=%s replica=%s candidate_ready=%t reason=%s claim_profile=%s ack_profile=%s required_frontier_known=%t required_frontier_lsn=%d candidate_frontier_known=%t candidate_frontier_lsn=%d frontier_covered=%t\n", + volume.VolumeID, + replica.ReplicaID, + replica.PromotionReadiness.CandidateReady, + replica.PromotionReadiness.Reason, + replica.PromotionReadiness.ClaimProfile, + replica.PromotionReadiness.AckProfile, + replica.PromotionReadiness.RequiredFrontierKnown, + replica.PromotionReadiness.RequiredFrontierLSN, + replica.PromotionReadiness.CandidateFrontierKnown, + replica.PromotionReadiness.CandidateFrontierLSN, + replica.PromotionReadiness.FrontierCovered) + } + for _, ev := range volume.FailoverTimeline { + fmt.Fprintf(&b, "failover: volume=%s phase=%s replica=%s role=%s epoch=%d endpoint_version=%d status=%s reason=%s\n", + volume.VolumeID, + explicitUnavailable(ev.Phase), + explicitUnavailable(ev.ReplicaID), + explicitUnavailable(ev.Role), + ev.Epoch, + ev.EndpointVersion, + explicitUnavailable(ev.Status), + emptyAsDash(ev.Reason)) } } if len(issues) == 0 { @@ -367,6 +448,16 @@ func volumeInventoryVolumeIssues(volume VolumeInventoryVolume) []string { if volume.PrimaryReplicaID == Unavailable && volume.ObservedReplicas > 0 { issues = append(issues, "primary_replica_id unavailable") } + var primaryReplicas []string + for _, replica := range volume.Replicas { + if replica.Observed && replica.AuthorityRole == hostvolume.AuthorityRolePrimary { + primaryReplicas = append(primaryReplicas, replica.ReplicaID) + } + } + if len(primaryReplicas) > 1 { + sort.Strings(primaryReplicas) + issues = append(issues, "conflicting_primary_replicas="+strings.Join(primaryReplicas, ",")) + } for _, errText := range volume.CollectionErrors { if errText != "" { issues = append(issues, fmt.Sprintf("collection_error: %s", errText)) @@ -382,6 +473,15 @@ func volumeInventoryVolumeIssues(volume VolumeInventoryVolume) []string { for _, issue := range replica.Issues { issues = append(issues, fmt.Sprintf("replica %s %s", replica.ReplicaID, issue)) } + if volume.DesiredReplicas > 1 && + replica.Observed && + replica.AuthorityRole != hostvolume.AuthorityRolePrimary && + !replica.PromotionReadiness.CandidateReady { + issues = append(issues, fmt.Sprintf("candidate_not_promotion_ready=%s reason=%s ack_profile=%s", + replica.ReplicaID, + replica.PromotionReadiness.Reason, + replica.PromotionReadiness.AckProfile)) + } } if volume.ObservedReplicas < volume.DesiredReplicas && len(volume.Replicas) == volume.ObservedReplicas { issues = append(issues, "replica_slot_missing=unknown") @@ -389,6 +489,90 @@ func volumeInventoryVolumeIssues(volume VolumeInventoryVolume) []string { return issues } +func replicasOnDistinctNodes(replicas []VolumeInventoryReplica, desired int) bool { + if desired <= 1 { + return true + } + seen := map[string]struct{}{} + observed := 0 + for _, replica := range replicas { + if !replica.Observed { + continue + } + node := strings.TrimSpace(replica.NodeName) + if node == "" || node == Unavailable { + return false + } + if _, ok := seen[node]; ok { + return false + } + seen[node] = struct{}{} + observed++ + } + return observed >= desired +} + +func frontendsNonLoopback(replicas []VolumeInventoryReplica, desired int) bool { + if desired <= 0 { + return false + } + observed := 0 + for _, replica := range replicas { + if !replica.Observed { + continue + } + observed++ + if !endpointHostNonLoopback(replica.FrontendAddress) { + return false + } + } + return observed >= desired +} + +func endpointHostNonLoopback(addr string) bool { + addr = strings.TrimSpace(addr) + if addr == "" || addr == Unavailable { + return false + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return false + } + host = strings.Trim(host, "[]") + if host == "" || strings.EqualFold(host, "localhost") { + return false + } + if ip, err := netip.ParseAddr(host); err == nil { + return !ip.IsLoopback() && !ip.IsUnspecified() + } + return isValidDNSHost(host) +} + +func isValidDNSHost(host string) bool { + if len(host) == 0 || len(host) > 253 { + return false + } + host = strings.TrimSuffix(host, ".") + if host == "" { + return false + } + for _, label := range strings.Split(host, ".") { + if len(label) == 0 || len(label) > 63 { + return false + } + if label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for _, ch := range label { + if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' { + continue + } + return false + } + } + return true +} + func volumeInventoryReplicaIssues(replica VolumeInventoryReplica) []string { var issues []string if replica.ReplicaID == "" || replica.ReplicaID == Unavailable { @@ -410,6 +594,27 @@ func volumeInventoryReplicaIssues(replica VolumeInventoryReplica) []string { if replica.AuthorityRole == hostvolume.AuthorityRolePrimary && !replica.FrontendPrimaryReady { issues = append(issues, "primary frontend_primary_ready=false") } + if replica.AuthorityRole == hostvolume.AuthorityRolePrimary && replica.ReplicationRole != hostvolume.ReplicationRoleNone { + issues = append(issues, fmt.Sprintf("primary replication_role=%s want %s", + replica.ReplicationRole, hostvolume.ReplicationRoleNone)) + } + if replica.AuthorityRole != "" && + replica.AuthorityRole != Unavailable && + replica.AuthorityRole != hostvolume.AuthorityRolePrimary && + replica.FrontendPrimaryReady { + if replica.AuthorityRole == hostvolume.AuthorityRoleSuperseded { + issues = append(issues, fmt.Sprintf("stale_primary_frontend_ready=true role=%s epoch=%d endpoint_version=%d", + replica.AuthorityRole, replica.Epoch, replica.EndpointVersion)) + } + issues = append(issues, fmt.Sprintf("non-primary authority_role=%s frontend_primary_ready=true", replica.AuthorityRole)) + } + if replica.AuthorityRole != "" && + replica.AuthorityRole != Unavailable && + replica.AuthorityRole != hostvolume.AuthorityRolePrimary && + replica.ReplicationRole == hostvolume.ReplicationRoleNone { + issues = append(issues, fmt.Sprintf("non-primary authority_role=%s replication_role=%s", + replica.AuthorityRole, replica.ReplicationRole)) + } for _, errText := range replica.CollectionErrors { if errText != "" { issues = append(issues, fmt.Sprintf("collection_error: %s", errText)) @@ -460,3 +665,28 @@ func inventoryExitLabel(code int) string { return "invalid" } } + +func defaultString(value, fallback string) string { + if strings.TrimSpace(value) == "" { + return fallback + } + return value +} + +func containsIssuePrefix(issues []string, prefix string) bool { + for _, issue := range issues { + if strings.HasPrefix(issue, prefix) { + return true + } + } + return false +} + +func copyFailoverTimeline(in []VolumeInventoryFailoverEvent) []VolumeInventoryFailoverEvent { + if len(in) == 0 { + return nil + } + out := make([]VolumeInventoryFailoverEvent, len(in)) + copy(out, in) + return out +} diff --git a/seaweed-block/core/ops/volume_inventory_test.go b/seaweed-block/core/ops/volume_inventory_test.go index 47bb1cec91..909489e39c 100644 --- a/seaweed-block/core/ops/volume_inventory_test.go +++ b/seaweed-block/core/ops/volume_inventory_test.go @@ -96,6 +96,82 @@ func TestBuildVolumeInventory_MultiVolumeRFShapes(t *testing.T) { } } +func TestNodeLoss_BuildVolumeInventory_EmitsTopologyEligibilityMarkers(t *testing.T) { + r1 := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary) + r1.FrontendAddress = "10.0.0.11:3260" + r2 := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + r2.FrontendAddress = "10.0.0.12:3260" + r3 := healthyInventoryReplica("r3", "s3", "node-c", hostvolume.AuthorityRoleUnknown) + r3.FrontendAddress = "storage-c.example:3260" + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 15, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "node-loss-eligibility"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-node-loss", + Namespace: "default", + PVCName: "app-node-loss", + PVName: "pvc-node-loss", + ReplicationFactor: 3, + Replicas: []VolumeInventoryReplicaInput{r1, r2, r3}, + }}, + }) + + volume := inventory.Volumes[0] + if !volume.ReplicasOnDistinctNodes || !volume.FrontendsNonLoopback { + t.Fatalf("eligibility markers distinct=%t non_loopback=%t", volume.ReplicasOnDistinctNodes, volume.FrontendsNonLoopback) + } + raw, err := json.Marshal(inventory) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + `"replicas_on_distinct_nodes":true`, + `"frontends_non_loopback":true`, + } { + if !strings.Contains(string(raw), want) { + t.Fatalf("json missing %s:\n%s", want, raw) + } + } + summary := RenderVolumeInventorySummary(inventory) + if !strings.Contains(summary, "eligibility: volume=pvc-node-loss replicas_on_distinct_nodes=true frontends_non_loopback=true") { + t.Fatalf("summary missing node-loss eligibility line:\n%s", summary) + } +} + +func TestNodeLoss_BuildVolumeInventory_EligibilityMarkersFailClosedWithoutHealthImpact(t *testing.T) { + r1 := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary) + r2 := healthyInventoryReplica("r2", "s2", "node-a", hostvolume.AuthorityRoleUnknown) + r2.FrontendAddress = "127.0.0.1:3261" + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 15, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "node-loss-ineligible"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-ineligible", + Namespace: "default", + PVCName: "app-ineligible", + PVName: "pvc-ineligible", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{r1, r2}, + }}, + }) + + volume := inventory.Volumes[0] + if volume.ReplicasOnDistinctNodes || volume.FrontendsNonLoopback { + t.Fatalf("eligibility markers distinct=%t non_loopback=%t want both false", volume.ReplicasOnDistinctNodes, volume.FrontendsNonLoopback) + } + if volume.Status != "ok" { + t.Fatalf("eligibility markers must not change health status: status=%s issues=%v", volume.Status, volume.Issues) + } + summary := RenderVolumeInventorySummary(inventory) + if !strings.Contains(summary, "eligibility: volume=pvc-ineligible replicas_on_distinct_nodes=false frontends_non_loopback=false") { + t.Fatalf("summary missing ineligible marker line:\n%s", summary) + } +} + func TestBuildVolumeInventory_EmptyClusterIsTrustworthyOK(t *testing.T) { inventory := BuildVolumeInventory(VolumeInventoryInput{ CapturedAt: time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC), @@ -121,6 +197,127 @@ func TestBuildVolumeInventory_EmptyClusterIsTrustworthyOK(t *testing.T) { } } +func TestBuildVolumeInventory_RF2CandidateNamesPromotionReadinessBlocker(t *testing.T) { + candidate := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + candidate.AckProfile = PromotionAckProfileBestEffort + candidate.RequiredFrontierKnown = true + candidate.RequiredFrontierLSN = 90 + candidate.CandidateFrontierKnown = true + candidate.CandidateFrontierLSN = 90 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "promotion-blocker"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-rf2", + Namespace: "default", + PVCName: "app-rf2", + PVName: "pvc-rf2", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary), + candidate, + }, + }}, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("RF=2 best-effort candidate should block recovery claim: status=%s issues=%v", volume.Status, volume.Issues) + } + want := "candidate_not_promotion_ready=r2 reason=replication_ack_profile_unmet ack_profile=best-effort" + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + replica := volume.Replicas[1] + if replica.PromotionReadiness.CandidateReady { + t.Fatalf("candidate should not be promotion-ready: %+v", replica.PromotionReadiness) + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "promotion: volume=pvc-rf2 replica=r2 candidate_ready=false reason=replication_ack_profile_unmet claim_profile=beta-recovery ack_profile=best-effort", + "- volume pvc-rf2 candidate_not_promotion_ready=r2 reason=replication_ack_profile_unmet ack_profile=best-effort", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestBuildVolumeInventory_RF2BestEffortControlledDemoCanBePromotionReady(t *testing.T) { + candidate := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + candidate.ClaimProfile = PromotionClaimControlledBestEffortDemo + candidate.AckProfile = PromotionAckProfileBestEffort + candidate.RequiredFrontierKnown = true + candidate.RequiredFrontierLSN = 90 + candidate.CandidateFrontierKnown = true + candidate.CandidateFrontierLSN = 90 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "best-effort-demo"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-rf2-best-effort", + Namespace: "default", + PVCName: "app-rf2-best-effort", + PVName: "pvc-rf2-best-effort", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary), + candidate, + }, + }}, + }) + + replica := inventory.Volumes[0].Replicas[1] + if !replica.PromotionReadiness.CandidateReady { + t.Fatalf("controlled best-effort demo candidate should be promotion-ready: %+v", replica.PromotionReadiness) + } + if replica.PromotionReadiness.ClaimProfile != PromotionClaimControlledBestEffortDemo { + t.Fatalf("claim_profile=%q", replica.PromotionReadiness.ClaimProfile) + } + summary := RenderVolumeInventorySummary(inventory) + if !strings.Contains(summary, "promotion: volume=pvc-rf2-best-effort replica=r2 candidate_ready=true reason=promotion_ready claim_profile=controlled-best-effort-demo ack_profile=best-effort") { + t.Fatalf("summary missing controlled best-effort profile:\n%s", summary) + } +} + +func TestBuildVolumeInventory_RF2CandidateRequiresKnownFrontier(t *testing.T) { + candidate := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + candidate.AckProfile = PromotionAckProfileSyncQuorum + candidate.RequiredFrontierKnown = false + candidate.CandidateFrontierKnown = true + candidate.CandidateFrontierLSN = 90 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "frontier-blocker"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-rf2-frontier", + Namespace: "default", + PVCName: "app-rf2-frontier", + PVName: "pvc-rf2-frontier", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary), + candidate, + }, + }}, + }) + + volume := inventory.Volumes[0] + want := "candidate_not_promotion_ready=r2 reason=required_frontier_missing ack_profile=sync-quorum" + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + if volume.Replicas[1].PromotionReadiness.Reason != PromotionReasonRequiredFrontierMissing { + t.Fatalf("promotion reason=%q", volume.Replicas[1].PromotionReadiness.Reason) + } +} + func TestBuildVolumeInventory_MissingReplicaIsUnhealthyNotCollapsed(t *testing.T) { inventory := BuildVolumeInventory(VolumeInventoryInput{ CapturedAt: time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC), @@ -264,6 +461,329 @@ func TestBuildVolumeInventory_SameNodeAttachEvidenceIsVisible(t *testing.T) { } } +func TestBuildVolumeInventory_FailoverTimelineIsSelfExplanatory(t *testing.T) { + r1 := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRoleSuperseded) + r1.Healthy = false + r1.FrontendPrimaryReady = false + r1.Epoch = 1 + r1.EndpointVersion = 1 + r1.Issues = append(r1.Issues, "stale_primary_fenced=true superseded_by=r2 epoch=2 endpoint_version=1") + r2 := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRolePrimary) + r2.Epoch = 2 + r2.EndpointVersion = 1 + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-failover", + Namespace: "default", + PVCName: "app-failover", + PVName: "pvc-failover", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{r1, r2}, + FailoverTimeline: []VolumeInventoryFailoverEvent{ + {Phase: "before_failure", ReplicaID: "r1", Role: "primary", Epoch: 1, EndpointVersion: 1, Status: "serving"}, + {Phase: "failure_injected", ReplicaID: "r1", Role: "old_primary", Epoch: 1, EndpointVersion: 1, Status: "stopped", Reason: "primary-blockvolume-controlled-stop"}, + {Phase: "after_failover", ReplicaID: "r2", Role: "primary", Epoch: 2, EndpointVersion: 1, Status: "serving"}, + {Phase: "old_primary_fenced", ReplicaID: "r1", Role: "old_primary", Epoch: 1, EndpointVersion: 1, Status: "fenced", Reason: "superseded_by=r2"}, + }, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.PrimaryReplicaID != "r2" { + t.Fatalf("primary=%q want r2", volume.PrimaryReplicaID) + } + if len(volume.FailoverTimeline) != 4 { + t.Fatalf("timeline=%+v", volume.FailoverTimeline) + } + if !containsString(volume.Issues, "replica r1 stale_primary_fenced=true superseded_by=r2 epoch=2 endpoint_version=1") { + t.Fatalf("stale primary issue missing: %v", volume.Issues) + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "volume: id=pvc-failover namespace=default pvc=app-failover pv=pvc-failover rf=2 desired=2 observed=2 primary=r2 status=unhealthy", + "replica: volume=pvc-failover replica=r1 server=s1 node=node-a observed=true status=unhealthy lifecycle_owner=pvc-owner-ref owner_ref=PersistentVolumeClaim/default/app-r1 role=superseded replication=replica_ready healthy=false epoch=1 endpoint_version=1", + "replica: volume=pvc-failover replica=r2 server=s2 node=node-b observed=true status=ok lifecycle_owner=pvc-owner-ref owner_ref=PersistentVolumeClaim/default/app-r2 role=primary replication=none healthy=true epoch=2 endpoint_version=1", + "failover: volume=pvc-failover phase=before_failure replica=r1 role=primary epoch=1 endpoint_version=1 status=serving reason=-", + "failover: volume=pvc-failover phase=failure_injected replica=r1 role=old_primary epoch=1 endpoint_version=1 status=stopped reason=primary-blockvolume-controlled-stop", + "failover: volume=pvc-failover phase=after_failover replica=r2 role=primary epoch=2 endpoint_version=1 status=serving reason=-", + "failover: volume=pvc-failover phase=old_primary_fenced replica=r1 role=old_primary epoch=1 endpoint_version=1 status=fenced reason=superseded_by=r2", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + + raw, err := json.Marshal(inventory) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + `"failover_timeline"`, + `"phase":"after_failover"`, + `"replica_id":"r2"`, + `"epoch":2`, + } { + if !strings.Contains(string(raw), want) { + t.Fatalf("json missing %s:\n%s", want, raw) + } + } +} + +func TestBuildVolumeInventory_StalePrimaryFrontendReadyBlocksRecoveryClaim(t *testing.T) { + oldPrimary := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRoleSuperseded) + oldPrimary.Healthy = true + oldPrimary.FrontendPrimaryReady = true + oldPrimary.Epoch = 1 + oldPrimary.EndpointVersion = 1 + newPrimary := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRolePrimary) + newPrimary.Epoch = 2 + newPrimary.EndpointVersion = 1 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover-negative"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-stale-primary", + Namespace: "default", + PVCName: "app-stale-primary", + PVName: "pvc-stale-primary", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{oldPrimary, newPrimary}, + FailoverTimeline: []VolumeInventoryFailoverEvent{ + {Phase: "before_failure", ReplicaID: "r1", Role: "primary", Epoch: 1, EndpointVersion: 1, Status: "serving"}, + {Phase: "after_failover", ReplicaID: "r2", Role: "primary", Epoch: 2, EndpointVersion: 1, Status: "serving"}, + }, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("stale primary with frontend ready must not look recovered: status=%s issues=%v", volume.Status, volume.Issues) + } + for _, want := range []string{ + "replica_degraded=r1 status=unhealthy", + "replica r1 stale_primary_frontend_ready=true role=superseded epoch=1 endpoint_version=1", + } { + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "inventory_status: unhealthy", + "replica: volume=pvc-stale-primary replica=r1 server=s1 node=node-a observed=true status=unhealthy", + "- volume pvc-stale-primary replica r1 stale_primary_frontend_ready=true role=superseded epoch=1 endpoint_version=1", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestBuildVolumeInventory_NonPrimaryFrontendReadyBlocksRecoveryClaim(t *testing.T) { + candidate := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + candidate.Healthy = true + candidate.FrontendPrimaryReady = true + candidate.ReplicationRole = hostvolume.ReplicationRoleReady + candidate.Epoch = 2 + candidate.EndpointVersion = 1 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover-negative"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-non-primary-ready", + Namespace: "default", + PVCName: "app-non-primary-ready", + PVName: "pvc-non-primary-ready", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary), + candidate, + }, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("non-primary frontend-ready replica must be unhealthy: status=%s issues=%v", volume.Status, volume.Issues) + } + want := "replica r2 non-primary authority_role=unknown frontend_primary_ready=true" + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } +} + +func TestBuildVolumeInventory_PrimaryWithReplicaRoleIsNotEligiblePrimary(t *testing.T) { + candidate := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRolePrimary) + candidate.ReplicationRole = hostvolume.ReplicationRoleNotReady + candidate.Epoch = 2 + candidate.EndpointVersion = 1 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover-negative"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-not-ready-candidate", + Namespace: "default", + PVCName: "app-not-ready-candidate", + PVName: "pvc-not-ready-candidate", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRoleSuperseded), + candidate, + }, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("primary candidate with replication_role=not_ready must not look recovered: status=%s issues=%v", volume.Status, volume.Issues) + } + for _, want := range []string{ + "replica_degraded=r2 status=unhealthy", + "replica r2 primary replication_role=not_ready want none", + } { + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "volume: id=pvc-not-ready-candidate namespace=default pvc=app-not-ready-candidate pv=pvc-not-ready-candidate rf=2 desired=2 observed=2 primary=r2 status=unhealthy", + "replica: volume=pvc-not-ready-candidate replica=r2 server=s2 node=node-b observed=true status=unhealthy", + "- volume pvc-not-ready-candidate replica r2 primary replication_role=not_ready want none", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestBuildVolumeInventory_NonPrimaryWithPrimaryReplicationRoleIsUnsafe(t *testing.T) { + oldPrimary := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRoleSuperseded) + oldPrimary.Healthy = false + oldPrimary.FrontendPrimaryReady = false + oldPrimary.ReplicationRole = hostvolume.ReplicationRoleNone + oldPrimary.Epoch = 1 + oldPrimary.EndpointVersion = 1 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover-negative"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-demoted-primary-role", + Namespace: "default", + PVCName: "app-demoted-primary-role", + PVName: "pvc-demoted-primary-role", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{ + oldPrimary, + healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRolePrimary), + }, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("non-primary replication_role=none must be unhealthy: status=%s issues=%v", volume.Status, volume.Issues) + } + want := "replica r1 non-primary authority_role=superseded replication_role=none" + if !containsString(volume.Issues, want) { + t.Fatalf("volume issues missing %q: %v", want, volume.Issues) + } +} + +func TestBuildVolumeInventory_ConflictingPrimariesAreUnsafe(t *testing.T) { + r1 := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary) + r1.Epoch = 1 + r1.EndpointVersion = 1 + r2 := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRolePrimary) + r2.Epoch = 2 + r2.EndpointVersion = 1 + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "mounted-failover"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{ + { + VolumeID: "pvc-split-brain", + Namespace: "default", + PVCName: "app-split-brain", + PVName: "pvc-split-brain", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{r1, r2}, + }, + }, + }) + + volume := inventory.Volumes[0] + if volume.Status != "unhealthy" { + t.Fatalf("status=%s issues=%v", volume.Status, volume.Issues) + } + if !containsString(volume.Issues, "conflicting_primary_replicas=r1,r2") { + t.Fatalf("conflict issue missing: %v", volume.Issues) + } + if volume.PrimaryReplicaID != Unavailable { + t.Fatalf("split-brain primary=%q want unavailable", volume.PrimaryReplicaID) + } + summary := RenderVolumeInventorySummary(inventory) + for _, want := range []string{ + "volume: id=pvc-split-brain namespace=default pvc=app-split-brain pv=pvc-split-brain rf=2 desired=2 observed=2 primary=unavailable status=unhealthy", + "replica: volume=pvc-split-brain replica=r1 server=s1 node=node-a observed=true status=ok", + "replica: volume=pvc-split-brain replica=r2 server=s2 node=node-b observed=true status=ok", + "- volume pvc-split-brain conflicting_primary_replicas=r1,r2", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestNodeLoss_BuildVolumeInventory_NonLoopbackMarkerRejectsMalformedFrontend(t *testing.T) { + r1 := healthyInventoryReplica("r1", "s1", "node-a", hostvolume.AuthorityRolePrimary) + r1.FrontendAddress = "10.0.0.11:3260" + r2 := healthyInventoryReplica("r2", "s2", "node-b", hostvolume.AuthorityRoleUnknown) + r2.FrontendAddress = "bad host:3260" + + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 15, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test", Scenario: "node-loss-malformed-frontend"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-node-loss", + Namespace: "default", + PVCName: "app-node-loss", + PVName: "pvc-node-loss", + ReplicationFactor: 2, + Replicas: []VolumeInventoryReplicaInput{r1, r2}, + }}, + }) + + volume := inventory.Volumes[0] + if volume.FrontendsNonLoopback { + t.Fatalf("malformed frontend must fail closed for non-loopback eligibility: %+v", volume) + } +} + func TestBuildVolumeInventory_InvalidIdentityAndCollectionErrors(t *testing.T) { inventory := BuildVolumeInventory(VolumeInventoryInput{ Source: ReportSource{}, @@ -305,23 +825,30 @@ func healthyInventoryReplica(replicaID, serverID, nodeName, role string) VolumeI primaryReady = true } return VolumeInventoryReplicaInput{ - ReplicaID: replicaID, - ServerID: serverID, - NodeName: nodeName, - GeneratedDeployment: "sw-blockvolume-" + replicaID, - LifecycleOwner: "pvc-owner-ref", - OwnerReference: "PersistentVolumeClaim/default/app-" + replicaID, - Protocol: "iscsi", - FrontendAddress: "127.0.0.1:3260", - StatusAddress: "127.0.0.1:23260", - DataAddr: "127.0.0.1:19000", - CtrlAddr: "127.0.0.1:19001", - Observed: true, - AuthorityRole: role, - Healthy: healthy, - FrontendPrimaryReady: primaryReady, - ReplicationRole: replicationRole, - Epoch: 7, - EndpointVersion: 2, + ReplicaID: replicaID, + ServerID: serverID, + NodeName: nodeName, + GeneratedDeployment: "sw-blockvolume-" + replicaID, + LifecycleOwner: "pvc-owner-ref", + OwnerReference: "PersistentVolumeClaim/default/app-" + replicaID, + Protocol: "iscsi", + FrontendAddress: "127.0.0.1:3260", + StatusAddress: "127.0.0.1:23260", + DataAddr: "127.0.0.1:19000", + CtrlAddr: "127.0.0.1:19001", + Observed: true, + AuthorityRole: role, + Healthy: healthy, + FrontendPrimaryReady: primaryReady, + ReplicationRole: replicationRole, + Epoch: 7, + EndpointVersion: 2, + AckProfile: PromotionAckProfileSyncQuorum, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierLSN: 90, + RequiredFrontierKnown: true, + CandidateFrontierLSN: 90, + CandidateFrontierKnown: true, } } diff --git a/seaweed-block/core/ops/volume_status_report.go b/seaweed-block/core/ops/volume_status_report.go index 99230a85f6..c4bb5e24c4 100644 --- a/seaweed-block/core/ops/volume_status_report.go +++ b/seaweed-block/core/ops/volume_status_report.go @@ -109,6 +109,10 @@ type DurableReport struct { EndpointVersion uint64 `json:"endpoint_version"` Latched bool `json:"latched"` Operational bool `json:"operational"` + FrontierKnown bool `json:"frontier_known"` + DurableLSN uint64 `json:"durable_lsn"` + RetainedLSN uint64 `json:"retained_lsn"` + HeadLSN uint64 `json:"head_lsn"` Closed bool `json:"closed"` Evidence string `json:"evidence,omitempty"` } @@ -275,6 +279,10 @@ func durableSnapshots(statuses []durable.VolumeStatus) []DurableReport { EndpointVersion: st.EndpointVersion, Latched: st.Latched, Operational: st.Operational, + FrontierKnown: st.FrontierKnown, + DurableLSN: st.DurableLSN, + RetainedLSN: st.RetainedLSN, + HeadLSN: st.HeadLSN, Closed: st.Closed, Evidence: st.Evidence, }) diff --git a/seaweed-block/core/ops/volume_status_report_test.go b/seaweed-block/core/ops/volume_status_report_test.go index a9ca21d0e4..13ed654fb8 100644 --- a/seaweed-block/core/ops/volume_status_report_test.go +++ b/seaweed-block/core/ops/volume_status_report_test.go @@ -71,6 +71,10 @@ func TestBuildVolumeStatusReport_ComposesExistingStatusSurfaces(t *testing.T) { EndpointVersion: 3, Latched: true, Operational: true, + FrontierKnown: true, + DurableLSN: 53, + RetainedLSN: 1, + HeadLSN: 53, Evidence: "recover ok", }, }, @@ -127,6 +131,9 @@ func TestBuildVolumeStatusReport_ComposesExistingStatusSurfaces(t *testing.T) { if len(report.Durable) != 1 || !report.Durable[0].Latched || !report.Durable[0].Operational { t.Fatalf("durable status mismatch: %+v", report.Durable) } + if !report.Durable[0].FrontierKnown || report.Durable[0].DurableLSN != 53 || report.Durable[0].HeadLSN != 53 { + t.Fatalf("durable frontier mismatch: %+v", report.Durable[0]) + } if len(report.Residue.HostInitiator.ISCSISessions) != 1 || len(report.Residue.HostInitiator.NVMESubsystems) != 1 { t.Fatalf("residue mismatch: %+v", report.Residue) } @@ -204,7 +211,7 @@ func TestBuildVolumeStatusReport_JSONSchemaShapeIsStable(t *testing.T) { {ReplicaID: "r2", State: "healthy", DataAddr: "127.0.0.1:10001", CtrlAddr: "127.0.0.1:10002", SessionID: 10}, }, Durable: []durable.VolumeStatus{ - {VolumeID: "v1", Impl: "smartwal", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 3, EndpointVersion: 4, Latched: true, Operational: true}, + {VolumeID: "v1", Impl: "smartwal", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 3, EndpointVersion: 4, Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 9, RetainedLSN: 1, HeadLSN: 10}, }, Residue: ResidueReport{ HostInitiator: HostInitiatorResidue{ISCSISessions: []string{}, NVMESubsystems: []string{}}, @@ -269,6 +276,10 @@ func TestBuildVolumeStatusReport_JSONSchemaShapeIsStable(t *testing.T) { "endpoint_version", "latched", "operational", + "frontier_known", + "durable_lsn", + "retained_lsn", + "head_lsn", "closed", }) assertJSONKeys(t, "residue", asMap(t, doc["residue"]), []string{"host_initiator", "processes", "kubernetes", "storage_paths"}) diff --git a/seaweed-block/core/ops/volume_status_summary.go b/seaweed-block/core/ops/volume_status_summary.go index 1dde99d930..eb35d78068 100644 --- a/seaweed-block/core/ops/volume_status_summary.go +++ b/seaweed-block/core/ops/volume_status_summary.go @@ -64,7 +64,7 @@ func RenderVolumeStatusSummary(r VolumeStatusReport) string { } fmt.Fprintf(&b, "durable: entries=%d\n", len(r.Durable)) for _, d := range r.Durable { - fmt.Fprintf(&b, "durable_entry: impl=%s path=%s replica=%s latched=%t operational=%t closed=%t epoch=%d endpoint_version=%d\n", d.Impl, emptyAsDash(d.Path), d.ReplicaID, d.Latched, d.Operational, d.Closed, d.Epoch, d.EndpointVersion) + fmt.Fprintf(&b, "durable_entry: impl=%s path=%s replica=%s latched=%t operational=%t closed=%t epoch=%d endpoint_version=%d frontier_known=%t durable_lsn=%d retained_lsn=%d head_lsn=%d\n", d.Impl, emptyAsDash(d.Path), d.ReplicaID, d.Latched, d.Operational, d.Closed, d.Epoch, d.EndpointVersion, d.FrontierKnown, d.DurableLSN, d.RetainedLSN, d.HeadLSN) } fmt.Fprintf(&b, "residue: iscsi_sessions=%d nvme_subsystems=%d processes=%d kubernetes=%d storage_paths=%d\n", len(r.Residue.HostInitiator.ISCSISessions), diff --git a/seaweed-block/core/ops/volume_status_summary_test.go b/seaweed-block/core/ops/volume_status_summary_test.go index 51c58eb466..b7c77d14f4 100644 --- a/seaweed-block/core/ops/volume_status_summary_test.go +++ b/seaweed-block/core/ops/volume_status_summary_test.go @@ -23,6 +23,7 @@ func TestVolumeStatusSummary_OKReport(t *testing.T) { "frontend: protocol=iscsi addr=127.0.0.1:3260 iqn=iqn.2026-05.io.seaweedfs:v1 nqn=- lun=0 nsid=0", "frontend: protocol=nvme addr=127.0.0.1:4420 iqn=- nqn=nqn.2026-05.io.seaweedfs:v1 lun=0 nsid=1", "authority: role=primary healthy=true primary_ready=true assigned=true epoch=7 endpoint_version=2", + "durable_entry: impl=walstore path=/var/lib/sw-block/v1/r1 replica=r1 latched=true operational=true closed=false epoch=7 endpoint_version=2 frontier_known=true durable_lsn=90 retained_lsn=10 head_lsn=90", "residue: iscsi_sessions=0 nvme_subsystems=0 processes=0 kubernetes=0 storage_paths=0", "issues: none", } { @@ -162,7 +163,7 @@ func healthySummaryReport() VolumeStatusReport { }, }, Durable: []DurableReport{ - {VolumeID: "v1", Impl: "walstore", Path: "/var/lib/sw-block/v1/r1", ReplicaID: "r1", Epoch: 7, EndpointVersion: 2, Latched: true, Operational: true}, + {VolumeID: "v1", Impl: "walstore", Path: "/var/lib/sw-block/v1/r1", ReplicaID: "r1", Epoch: 7, EndpointVersion: 2, Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 90, RetainedLSN: 10, HeadLSN: 90}, }, Residue: ResidueReport{ HostInitiator: HostInitiatorResidue{ diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index d86d47fff8..36857bb270 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -266,6 +266,26 @@ func (p *ReplicaPeer) RefreshLiveShipSessionAfter(completedSessionID, achievedLS return nil } +// SeedLiveShipCursor records that an already-authoritative peer has +// proven durability through achievedLSN before this primary emits its +// first post-assignment live write. Promotion uses this after a barrier +// proof so the first write after failover starts at frontier+1 instead +// of tripping the WalShipper tail-gap guard. +func (p *ReplicaPeer) SeedLiveShipCursor(achievedLSN uint64, reason string) { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + replicaID := p.target.ReplicaID + executor := p.executor + p.mu.Unlock() + + executor.AdvanceLiveShipCursor(replicaID, achievedLSN) + log.Printf("replication: peer %s seeded live cursor lsn=%d reason=%s", + replicaID, achievedLSN, reason) +} + // SetProbeCooldownConfig overrides the default probe cooldown config // for this peer. Safe to call from any goroutine; takes effect from // the next ProbeIfDegraded / OnProbeAttempt call. Cap < Base diff --git a/seaweed-block/core/replication/volume.go b/seaweed-block/core/replication/volume.go index d853557183..b8a51bc3de 100644 --- a/seaweed-block/core/replication/volume.go +++ b/seaweed-block/core/replication/volume.go @@ -71,6 +71,8 @@ type ReplicationVolume struct { onPeerRemoved func(string) // by ReplicaID } +const promotionSeedBarrierTimeout = 5 * time.Second + // executorFactory lets tests inject a BlockExecutor constructor that // binds to a specific replica address. Production uses the real // transport.NewBlockExecutor. @@ -214,8 +216,8 @@ func (v *ReplicationVolume) Sync(ctx context.Context, targetLSN uint64) error { // - generation == 0: unversioned apply. Peer map IS mutated, but // lastAppliedGeneration is NOT advanced. Intended for test / // fake-master use only; production master MUST emit >= 1. -// - generation > 0 && generation > lastAppliedGeneration: apply -// + advance lastAppliedGeneration. +// - generation > 0 && generation > lastAppliedGeneration: apply and +// advance lastAppliedGeneration. // - generation > 0 && generation <= lastAppliedGeneration: stale // replay. Peer map NOT mutated; replayedGens counter increments; // debug log emits a peer-ID-set delta diff for forensics. Returns @@ -283,6 +285,7 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic } // Add new peers + recreate on lineage bump. + addedPeers := make([]*ReplicaPeer, 0, len(want)) for id, t := range want { if existing, ok := v.peers[id]; ok { cur := existing.Target() @@ -328,8 +331,11 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic if v.onPeerAdded != nil { v.onPeerAdded(peer) } + addedPeers = append(addedPeers, peer) } + v.seedNewPeerLiveCursorsLocked(addedPeers) + // Advance the monotonic guard only for real (non-zero) generations. if generation > 0 { v.lastAppliedGeneration = generation @@ -337,6 +343,50 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic return nil } +// seedNewPeerLiveCursorsLocked verifies that newly installed peers have +// durably reached this node's local frontier, then seeds their live +// ship cursor so the first post-promotion write starts at frontier+1. +// This is the promoted-primary handoff proof: peers that cannot answer +// the barrier, or answer below the frontier, are degraded and therefore +// cannot satisfy sync-quorum/sync-all write acknowledgement. +func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) { + if len(peers) == 0 { + return + } + frontier, err := v.store.Sync() + if err != nil { + log.Printf("replication: volume %s live cursor seed skipped: local sync failed: %v", + v.volumeID, err) + return + } + if frontier == 0 { + return + } + for _, peer := range peers { + if peer == nil { + continue + } + ctx, cancel := context.WithTimeout(context.Background(), promotionSeedBarrierTimeout) + ack, err := peer.Barrier(ctx, frontier) + cancel() + if err != nil { + peer.Invalidate(fmt.Sprintf("promotion seed barrier failed: required=%d err=%v", + frontier, err)) + log.Printf("replication: volume %s live cursor seed failed peer=%s frontier=%d: %v", + v.volumeID, peer.Target().ReplicaID, frontier, err) + continue + } + if ack.AchievedLSN < frontier { + peer.Invalidate(fmt.Sprintf("promotion seed barrier below frontier: achieved=%d required=%d", + ack.AchievedLSN, frontier)) + log.Printf("replication: volume %s live cursor seed rejected peer=%s achieved=%d required=%d", + v.volumeID, peer.Target().ReplicaID, ack.AchievedLSN, frontier) + continue + } + peer.SeedLiveShipCursor(frontier, "assignment frontier barrier") + } +} + // peerIDSet extracts the set of peer IDs from the current peers map. // Caller must hold v.mu. func peerIDSet(peers map[string]*ReplicaPeer) map[string]struct{} { diff --git a/seaweed-block/core/replication/volume_test.go b/seaweed-block/core/replication/volume_test.go index 278357ab3e..6fc7647de3 100644 --- a/seaweed-block/core/replication/volume_test.go +++ b/seaweed-block/core/replication/volume_test.go @@ -544,6 +544,121 @@ func TestReplicationVolume_OnLocalWrite_Closed_Errors(t *testing.T) { } } +func TestReplicationVolume_UpdateReplicaSet_SeedsLiveCursorFromBarrierFrontier(t *testing.T) { + const blockSize = 4096 + primary := storage.NewBlockStore(64, blockSize) + replica := storage.NewBlockStore(64, blockSize) + + for i := uint32(0); i < 3; i++ { + data := make([]byte, blockSize) + data[0] = byte(i + 1) + data[1] = 0xA0 + lsn, err := primary.Write(i, data) + if err != nil { + t.Fatalf("primary seed write %d: %v", i, err) + } + if err := replica.ApplyEntry(i, data, lsn); err != nil { + t.Fatalf("replica seed apply %d: %v", i, err) + } + } + frontier, err := primary.Sync() + if err != nil { + t.Fatalf("primary seed sync: %v", err) + } + if got, err := replica.Sync(); err != nil || got != frontier { + t.Fatalf("replica seed sync=(%d,%v), want frontier %d", got, err, frontier) + } + + listener, err := transport.NewReplicaListener("127.0.0.1:0", replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(func() { listener.Stop() }) + + v := NewReplicationVolume("vol-promoted", primary) + v.SetDurabilityMode(DurabilitySyncQuorum) + t.Cleanup(func() { _ = v.Close() }) + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r3", listener.Addr(), 2, 1)}); err != nil { + t.Fatalf("UpdateReplicaSet: %v", err) + } + + next := make([]byte, blockSize) + next[0] = 0x44 + next[1] = 0x55 + lsn, err := primary.Write(9, next) + if err != nil { + t.Fatalf("primary post-promotion write: %v", err) + } + if lsn != frontier+1 { + t.Fatalf("post-promotion lsn=%d want frontier+1=%d", lsn, frontier+1) + } + if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 9, Data: next, LSN: lsn}); err != nil { + t.Fatalf("OnLocalWrite after promoted peer install: %v", err) + } + waitForReplicaLBA(t, replica, 9, 0x44, 0x55, 2*time.Second) +} + +func TestReplicationVolume_UpdateReplicaSet_DegradesPeerBelowLocalFrontier(t *testing.T) { + const blockSize = 4096 + primary := storage.NewBlockStore(64, blockSize) + replica := storage.NewBlockStore(64, blockSize) + + for i := uint32(0); i < 3; i++ { + data := make([]byte, blockSize) + data[0] = byte(i + 1) + data[1] = 0xB0 + lsn, err := primary.Write(i, data) + if err != nil { + t.Fatalf("primary seed write %d: %v", i, err) + } + if i < 2 { + if err := replica.ApplyEntry(i, data, lsn); err != nil { + t.Fatalf("replica partial apply %d: %v", i, err) + } + } + } + frontier, err := primary.Sync() + if err != nil { + t.Fatalf("primary seed sync: %v", err) + } + if got, err := replica.Sync(); err != nil || got >= frontier { + t.Fatalf("replica partial sync=(%d,%v), want below frontier %d", got, err, frontier) + } + + listener, err := transport.NewReplicaListener("127.0.0.1:0", replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(func() { listener.Stop() }) + + v := NewReplicationVolume("vol-promoted", primary) + v.SetDurabilityMode(DurabilitySyncQuorum) + t.Cleanup(func() { _ = v.Close() }) + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r3", listener.Addr(), 2, 1)}); err != nil { + t.Fatalf("UpdateReplicaSet: %v", err) + } + v.mu.Lock() + state := v.peers["r3"].State() + v.mu.Unlock() + if state != ReplicaDegraded { + t.Fatalf("peer state=%s want degraded for below-frontier survivor", state) + } + + next := make([]byte, blockSize) + next[0] = 0x66 + next[1] = 0x77 + lsn, err := primary.Write(9, next) + if err != nil { + t.Fatalf("primary post-promotion write: %v", err) + } + err = v.OnLocalWrite(context.Background(), LocalWrite{LBA: 9, Data: next, LSN: lsn}) + if err == nil || !strings.Contains(err.Error(), ErrDurabilityQuorumLost.Error()) { + t.Fatalf("OnLocalWrite err=%v, want quorum loss for below-frontier survivor", err) + } +} + // --- Small helpers --- func waitForReplicaLBA(t *testing.T, replica *storage.BlockStore, lba uint32, want0, want1 byte, timeout time.Duration) { diff --git a/seaweed-block/core/rpc/control/control.pb.go b/seaweed-block/core/rpc/control/control.pb.go index e4bb184f11..ea45f6afe8 100644 --- a/seaweed-block/core/rpc/control/control.pb.go +++ b/seaweed-block/core/rpc/control/control.pb.go @@ -4,6 +4,7 @@ // volume -> master: ObservationService.ReportHeartbeat (unary) // volume -> master: AssignmentService.SubscribeAssignments (server-streaming) // operator -> master: EvidenceService.QueryVolumeStatus (unary, read-only) +// operator/dashboard -> master: ClusterEvidenceService read-only observation // CSI/operator -> master: LifecycleService.CreateVolume/DeleteVolume (desired intent only) // // Boundary (T0 sketch §3 load-bearing): @@ -397,6 +398,61 @@ func (x *HeartbeatAck) GetSequence() uint64 { return 0 } +type ClusterEventAck struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AcceptedAt *timestamp.Timestamp `protobuf:"bytes,1,opt,name=accepted_at,json=acceptedAt,proto3" json:"accepted_at,omitempty"` + EventId string `protobuf:"bytes,2,opt,name=event_id,json=eventId,proto3" json:"event_id,omitempty"` +} + +func (x *ClusterEventAck) Reset() { + *x = ClusterEventAck{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ClusterEventAck) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ClusterEventAck) ProtoMessage() {} + +func (x *ClusterEventAck) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ClusterEventAck.ProtoReflect.Descriptor instead. +func (*ClusterEventAck) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{4} +} + +func (x *ClusterEventAck) GetAcceptedAt() *timestamp.Timestamp { + if x != nil { + return x.AcceptedAt + } + return nil +} + +func (x *ClusterEventAck) GetEventId() string { + if x != nil { + return x.EventId + } + return "" +} + type SubscribeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -410,7 +466,7 @@ type SubscribeRequest struct { func (x *SubscribeRequest) Reset() { *x = SubscribeRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[4] + mi := &file_control_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -423,7 +479,7 @@ func (x *SubscribeRequest) String() string { func (*SubscribeRequest) ProtoMessage() {} func (x *SubscribeRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[4] + mi := &file_control_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -436,7 +492,7 @@ func (x *SubscribeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SubscribeRequest.ProtoReflect.Descriptor instead. func (*SubscribeRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{4} + return file_control_proto_rawDescGZIP(), []int{5} } func (x *SubscribeRequest) GetVolumeId() string { @@ -482,7 +538,7 @@ type ReplicaDescriptor struct { func (x *ReplicaDescriptor) Reset() { *x = ReplicaDescriptor{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[5] + mi := &file_control_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -495,7 +551,7 @@ func (x *ReplicaDescriptor) String() string { func (*ReplicaDescriptor) ProtoMessage() {} func (x *ReplicaDescriptor) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[5] + mi := &file_control_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -508,7 +564,7 @@ func (x *ReplicaDescriptor) ProtoReflect() protoreflect.Message { // Deprecated: Use ReplicaDescriptor.ProtoReflect.Descriptor instead. func (*ReplicaDescriptor) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{5} + return file_control_proto_rawDescGZIP(), []int{6} } func (x *ReplicaDescriptor) GetReplicaId() string { @@ -586,7 +642,7 @@ type AssignmentFact struct { func (x *AssignmentFact) Reset() { *x = AssignmentFact{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[6] + mi := &file_control_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -599,7 +655,7 @@ func (x *AssignmentFact) String() string { func (*AssignmentFact) ProtoMessage() {} func (x *AssignmentFact) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[6] + mi := &file_control_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -612,7 +668,7 @@ func (x *AssignmentFact) ProtoReflect() protoreflect.Message { // Deprecated: Use AssignmentFact.ProtoReflect.Descriptor instead. func (*AssignmentFact) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{6} + return file_control_proto_rawDescGZIP(), []int{7} } func (x *AssignmentFact) GetVolumeId() string { @@ -682,7 +738,7 @@ type StatusRequest struct { func (x *StatusRequest) Reset() { *x = StatusRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[7] + mi := &file_control_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -695,7 +751,7 @@ func (x *StatusRequest) String() string { func (*StatusRequest) ProtoMessage() {} func (x *StatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[7] + mi := &file_control_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -708,7 +764,7 @@ func (x *StatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StatusRequest.ProtoReflect.Descriptor instead. func (*StatusRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{7} + return file_control_proto_rawDescGZIP(), []int{8} } func (x *StatusRequest) GetVolumeId() string { @@ -739,7 +795,7 @@ type StatusResponse struct { func (x *StatusResponse) Reset() { *x = StatusResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[8] + mi := &file_control_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -752,7 +808,7 @@ func (x *StatusResponse) String() string { func (*StatusResponse) ProtoMessage() {} func (x *StatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[8] + mi := &file_control_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -765,7 +821,7 @@ func (x *StatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StatusResponse.ProtoReflect.Descriptor instead. func (*StatusResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{8} + return file_control_proto_rawDescGZIP(), []int{9} } func (x *StatusResponse) GetVolumeId() string { @@ -824,6 +880,1215 @@ func (x *StatusResponse) GetFrontends() []*FrontendTarget { return nil } +type GetClusterStatusRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *GetClusterStatusRequest) Reset() { + *x = GetClusterStatusRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetClusterStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetClusterStatusRequest) ProtoMessage() {} + +func (x *GetClusterStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetClusterStatusRequest.ProtoReflect.Descriptor instead. +func (*GetClusterStatusRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{10} +} + +type ListVolumesRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *ListVolumesRequest) Reset() { + *x = ListVolumesRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListVolumesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListVolumesRequest) ProtoMessage() {} + +func (x *ListVolumesRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListVolumesRequest.ProtoReflect.Descriptor instead. +func (*ListVolumesRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{11} +} + +type GetVolumeStatusRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` +} + +func (x *GetVolumeStatusRequest) Reset() { + *x = GetVolumeStatusRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetVolumeStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetVolumeStatusRequest) ProtoMessage() {} + +func (x *GetVolumeStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetVolumeStatusRequest.ProtoReflect.Descriptor instead. +func (*GetVolumeStatusRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{12} +} + +func (x *GetVolumeStatusRequest) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +type GetVolumeTimelineRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` +} + +func (x *GetVolumeTimelineRequest) Reset() { + *x = GetVolumeTimelineRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetVolumeTimelineRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetVolumeTimelineRequest) ProtoMessage() {} + +func (x *GetVolumeTimelineRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetVolumeTimelineRequest.ProtoReflect.Descriptor instead. +func (*GetVolumeTimelineRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{13} +} + +func (x *GetVolumeTimelineRequest) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +type WatchClusterEventsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SinceEventId string `protobuf:"bytes,1,opt,name=since_event_id,json=sinceEventId,proto3" json:"since_event_id,omitempty"` +} + +func (x *WatchClusterEventsRequest) Reset() { + *x = WatchClusterEventsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *WatchClusterEventsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WatchClusterEventsRequest) ProtoMessage() {} + +func (x *WatchClusterEventsRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WatchClusterEventsRequest.ProtoReflect.Descriptor instead. +func (*WatchClusterEventsRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{14} +} + +func (x *WatchClusterEventsRequest) GetSinceEventId() string { + if x != nil { + return x.SinceEventId + } + return "" +} + +type ObservationCondition struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` + Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"` + Severity string `protobuf:"bytes,4,opt,name=severity,proto3" json:"severity,omitempty"` + Message string `protobuf:"bytes,5,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *ObservationCondition) Reset() { + *x = ObservationCondition{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ObservationCondition) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ObservationCondition) ProtoMessage() {} + +func (x *ObservationCondition) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ObservationCondition.ProtoReflect.Descriptor instead. +func (*ObservationCondition) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{15} +} + +func (x *ObservationCondition) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *ObservationCondition) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *ObservationCondition) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *ObservationCondition) GetSeverity() string { + if x != nil { + return x.Severity + } + return "" +} + +func (x *ObservationCondition) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type ClusterStatusResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SchemaVersion string `protobuf:"bytes,1,opt,name=schema_version,json=schemaVersion,proto3" json:"schema_version,omitempty"` + CapturedAt *timestamp.Timestamp `protobuf:"bytes,2,opt,name=captured_at,json=capturedAt,proto3" json:"captured_at,omitempty"` + ProductRevision string `protobuf:"bytes,3,opt,name=product_revision,json=productRevision,proto3" json:"product_revision,omitempty"` + Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` + Nodes []*NodeEvidence `protobuf:"bytes,5,rep,name=nodes,proto3" json:"nodes,omitempty"` + Volumes []*VolumeEvidence `protobuf:"bytes,6,rep,name=volumes,proto3" json:"volumes,omitempty"` + Conditions []*ObservationCondition `protobuf:"bytes,7,rep,name=conditions,proto3" json:"conditions,omitempty"` + Events []*ClusterEvent `protobuf:"bytes,8,rep,name=events,proto3" json:"events,omitempty"` + NonClaims []string `protobuf:"bytes,9,rep,name=non_claims,json=nonClaims,proto3" json:"non_claims,omitempty"` +} + +func (x *ClusterStatusResponse) Reset() { + *x = ClusterStatusResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ClusterStatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ClusterStatusResponse) ProtoMessage() {} + +func (x *ClusterStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ClusterStatusResponse.ProtoReflect.Descriptor instead. +func (*ClusterStatusResponse) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{16} +} + +func (x *ClusterStatusResponse) GetSchemaVersion() string { + if x != nil { + return x.SchemaVersion + } + return "" +} + +func (x *ClusterStatusResponse) GetCapturedAt() *timestamp.Timestamp { + if x != nil { + return x.CapturedAt + } + return nil +} + +func (x *ClusterStatusResponse) GetProductRevision() string { + if x != nil { + return x.ProductRevision + } + return "" +} + +func (x *ClusterStatusResponse) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *ClusterStatusResponse) GetNodes() []*NodeEvidence { + if x != nil { + return x.Nodes + } + return nil +} + +func (x *ClusterStatusResponse) GetVolumes() []*VolumeEvidence { + if x != nil { + return x.Volumes + } + return nil +} + +func (x *ClusterStatusResponse) GetConditions() []*ObservationCondition { + if x != nil { + return x.Conditions + } + return nil +} + +func (x *ClusterStatusResponse) GetEvents() []*ClusterEvent { + if x != nil { + return x.Events + } + return nil +} + +func (x *ClusterStatusResponse) GetNonClaims() []string { + if x != nil { + return x.NonClaims + } + return nil +} + +type NodeEvidence struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + NodeName string `protobuf:"bytes,1,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` + KubernetesNode string `protobuf:"bytes,2,opt,name=kubernetes_node,json=kubernetesNode,proto3" json:"kubernetes_node,omitempty"` + PhysicalHost string `protobuf:"bytes,3,opt,name=physical_host,json=physicalHost,proto3" json:"physical_host,omitempty"` + InternalIp string `protobuf:"bytes,4,opt,name=internal_ip,json=internalIp,proto3" json:"internal_ip,omitempty"` + Schedulable bool `protobuf:"varint,5,opt,name=schedulable,proto3" json:"schedulable,omitempty"` + Ready bool `protobuf:"varint,6,opt,name=ready,proto3" json:"ready,omitempty"` + LastHeartbeatAt *timestamp.Timestamp `protobuf:"bytes,7,opt,name=last_heartbeat_at,json=lastHeartbeatAt,proto3" json:"last_heartbeat_at,omitempty"` + ReplicaCount int32 `protobuf:"varint,8,opt,name=replica_count,json=replicaCount,proto3" json:"replica_count,omitempty"` + RequiredImages []string `protobuf:"bytes,9,rep,name=required_images,json=requiredImages,proto3" json:"required_images,omitempty"` + MissingImages []string `protobuf:"bytes,10,rep,name=missing_images,json=missingImages,proto3" json:"missing_images,omitempty"` + Conditions []*ObservationCondition `protobuf:"bytes,11,rep,name=conditions,proto3" json:"conditions,omitempty"` +} + +func (x *NodeEvidence) Reset() { + *x = NodeEvidence{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *NodeEvidence) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NodeEvidence) ProtoMessage() {} + +func (x *NodeEvidence) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use NodeEvidence.ProtoReflect.Descriptor instead. +func (*NodeEvidence) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{17} +} + +func (x *NodeEvidence) GetNodeName() string { + if x != nil { + return x.NodeName + } + return "" +} + +func (x *NodeEvidence) GetKubernetesNode() string { + if x != nil { + return x.KubernetesNode + } + return "" +} + +func (x *NodeEvidence) GetPhysicalHost() string { + if x != nil { + return x.PhysicalHost + } + return "" +} + +func (x *NodeEvidence) GetInternalIp() string { + if x != nil { + return x.InternalIp + } + return "" +} + +func (x *NodeEvidence) GetSchedulable() bool { + if x != nil { + return x.Schedulable + } + return false +} + +func (x *NodeEvidence) GetReady() bool { + if x != nil { + return x.Ready + } + return false +} + +func (x *NodeEvidence) GetLastHeartbeatAt() *timestamp.Timestamp { + if x != nil { + return x.LastHeartbeatAt + } + return nil +} + +func (x *NodeEvidence) GetReplicaCount() int32 { + if x != nil { + return x.ReplicaCount + } + return 0 +} + +func (x *NodeEvidence) GetRequiredImages() []string { + if x != nil { + return x.RequiredImages + } + return nil +} + +func (x *NodeEvidence) GetMissingImages() []string { + if x != nil { + return x.MissingImages + } + return nil +} + +func (x *NodeEvidence) GetConditions() []*ObservationCondition { + if x != nil { + return x.Conditions + } + return nil +} + +type VolumeEvidence struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + Namespace string `protobuf:"bytes,2,opt,name=namespace,proto3" json:"namespace,omitempty"` + PvcName string `protobuf:"bytes,3,opt,name=pvc_name,json=pvcName,proto3" json:"pvc_name,omitempty"` + PvName string `protobuf:"bytes,4,opt,name=pv_name,json=pvName,proto3" json:"pv_name,omitempty"` + ReplicationFactor int32 `protobuf:"varint,5,opt,name=replication_factor,json=replicationFactor,proto3" json:"replication_factor,omitempty"` + AckProfile string `protobuf:"bytes,6,opt,name=ack_profile,json=ackProfile,proto3" json:"ack_profile,omitempty"` + ClaimProfile string `protobuf:"bytes,7,opt,name=claim_profile,json=claimProfile,proto3" json:"claim_profile,omitempty"` + DesiredReplicas int32 `protobuf:"varint,8,opt,name=desired_replicas,json=desiredReplicas,proto3" json:"desired_replicas,omitempty"` + ObservedReplicas int32 `protobuf:"varint,9,opt,name=observed_replicas,json=observedReplicas,proto3" json:"observed_replicas,omitempty"` + Status string `protobuf:"bytes,10,opt,name=status,proto3" json:"status,omitempty"` + Reason string `protobuf:"bytes,11,opt,name=reason,proto3" json:"reason,omitempty"` + PrimaryReplica string `protobuf:"bytes,12,opt,name=primary_replica,json=primaryReplica,proto3" json:"primary_replica,omitempty"` + PrimaryNode string `protobuf:"bytes,13,opt,name=primary_node,json=primaryNode,proto3" json:"primary_node,omitempty"` + PublishTarget string `protobuf:"bytes,14,opt,name=publish_target,json=publishTarget,proto3" json:"publish_target,omitempty"` + Epoch uint64 `protobuf:"varint,15,opt,name=epoch,proto3" json:"epoch,omitempty"` + EndpointVersion uint64 `protobuf:"varint,16,opt,name=endpoint_version,json=endpointVersion,proto3" json:"endpoint_version,omitempty"` + Replicas []*ReplicaEvidence `protobuf:"bytes,17,rep,name=replicas,proto3" json:"replicas,omitempty"` + Conditions []*ObservationCondition `protobuf:"bytes,18,rep,name=conditions,proto3" json:"conditions,omitempty"` + NextActions []string `protobuf:"bytes,19,rep,name=next_actions,json=nextActions,proto3" json:"next_actions,omitempty"` + SupportBundleHint string `protobuf:"bytes,20,opt,name=support_bundle_hint,json=supportBundleHint,proto3" json:"support_bundle_hint,omitempty"` +} + +func (x *VolumeEvidence) Reset() { + *x = VolumeEvidence{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *VolumeEvidence) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*VolumeEvidence) ProtoMessage() {} + +func (x *VolumeEvidence) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use VolumeEvidence.ProtoReflect.Descriptor instead. +func (*VolumeEvidence) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{18} +} + +func (x *VolumeEvidence) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *VolumeEvidence) GetNamespace() string { + if x != nil { + return x.Namespace + } + return "" +} + +func (x *VolumeEvidence) GetPvcName() string { + if x != nil { + return x.PvcName + } + return "" +} + +func (x *VolumeEvidence) GetPvName() string { + if x != nil { + return x.PvName + } + return "" +} + +func (x *VolumeEvidence) GetReplicationFactor() int32 { + if x != nil { + return x.ReplicationFactor + } + return 0 +} + +func (x *VolumeEvidence) GetAckProfile() string { + if x != nil { + return x.AckProfile + } + return "" +} + +func (x *VolumeEvidence) GetClaimProfile() string { + if x != nil { + return x.ClaimProfile + } + return "" +} + +func (x *VolumeEvidence) GetDesiredReplicas() int32 { + if x != nil { + return x.DesiredReplicas + } + return 0 +} + +func (x *VolumeEvidence) GetObservedReplicas() int32 { + if x != nil { + return x.ObservedReplicas + } + return 0 +} + +func (x *VolumeEvidence) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *VolumeEvidence) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *VolumeEvidence) GetPrimaryReplica() string { + if x != nil { + return x.PrimaryReplica + } + return "" +} + +func (x *VolumeEvidence) GetPrimaryNode() string { + if x != nil { + return x.PrimaryNode + } + return "" +} + +func (x *VolumeEvidence) GetPublishTarget() string { + if x != nil { + return x.PublishTarget + } + return "" +} + +func (x *VolumeEvidence) GetEpoch() uint64 { + if x != nil { + return x.Epoch + } + return 0 +} + +func (x *VolumeEvidence) GetEndpointVersion() uint64 { + if x != nil { + return x.EndpointVersion + } + return 0 +} + +func (x *VolumeEvidence) GetReplicas() []*ReplicaEvidence { + if x != nil { + return x.Replicas + } + return nil +} + +func (x *VolumeEvidence) GetConditions() []*ObservationCondition { + if x != nil { + return x.Conditions + } + return nil +} + +func (x *VolumeEvidence) GetNextActions() []string { + if x != nil { + return x.NextActions + } + return nil +} + +func (x *VolumeEvidence) GetSupportBundleHint() string { + if x != nil { + return x.SupportBundleHint + } + return "" +} + +type ReplicaEvidence struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ReplicaId string `protobuf:"bytes,1,opt,name=replica_id,json=replicaId,proto3" json:"replica_id,omitempty"` + ServerId string `protobuf:"bytes,2,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` + KubernetesNode string `protobuf:"bytes,3,opt,name=kubernetes_node,json=kubernetesNode,proto3" json:"kubernetes_node,omitempty"` + PhysicalHost string `protobuf:"bytes,4,opt,name=physical_host,json=physicalHost,proto3" json:"physical_host,omitempty"` + Observed bool `protobuf:"varint,5,opt,name=observed,proto3" json:"observed,omitempty"` + Role string `protobuf:"bytes,6,opt,name=role,proto3" json:"role,omitempty"` + ReplicationRole string `protobuf:"bytes,7,opt,name=replication_role,json=replicationRole,proto3" json:"replication_role,omitempty"` + DurableLatched bool `protobuf:"varint,8,opt,name=durable_latched,json=durableLatched,proto3" json:"durable_latched,omitempty"` + DurableFrontierKnown bool `protobuf:"varint,9,opt,name=durable_frontier_known,json=durableFrontierKnown,proto3" json:"durable_frontier_known,omitempty"` + DurableFrontierLsn uint64 `protobuf:"varint,10,opt,name=durable_frontier_lsn,json=durableFrontierLsn,proto3" json:"durable_frontier_lsn,omitempty"` + CandidateReady bool `protobuf:"varint,11,opt,name=candidate_ready,json=candidateReady,proto3" json:"candidate_ready,omitempty"` + CandidateReadyReason string `protobuf:"bytes,12,opt,name=candidate_ready_reason,json=candidateReadyReason,proto3" json:"candidate_ready_reason,omitempty"` + FrontendProtocol string `protobuf:"bytes,13,opt,name=frontend_protocol,json=frontendProtocol,proto3" json:"frontend_protocol,omitempty"` + FrontendAddr string `protobuf:"bytes,14,opt,name=frontend_addr,json=frontendAddr,proto3" json:"frontend_addr,omitempty"` + StatusAddr string `protobuf:"bytes,15,opt,name=status_addr,json=statusAddr,proto3" json:"status_addr,omitempty"` + StalePrimaryFenced bool `protobuf:"varint,16,opt,name=stale_primary_fenced,json=stalePrimaryFenced,proto3" json:"stale_primary_fenced,omitempty"` + Conditions []*ObservationCondition `protobuf:"bytes,17,rep,name=conditions,proto3" json:"conditions,omitempty"` + SupportBundlePath string `protobuf:"bytes,18,opt,name=support_bundle_path,json=supportBundlePath,proto3" json:"support_bundle_path,omitempty"` +} + +func (x *ReplicaEvidence) Reset() { + *x = ReplicaEvidence{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ReplicaEvidence) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReplicaEvidence) ProtoMessage() {} + +func (x *ReplicaEvidence) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReplicaEvidence.ProtoReflect.Descriptor instead. +func (*ReplicaEvidence) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{19} +} + +func (x *ReplicaEvidence) GetReplicaId() string { + if x != nil { + return x.ReplicaId + } + return "" +} + +func (x *ReplicaEvidence) GetServerId() string { + if x != nil { + return x.ServerId + } + return "" +} + +func (x *ReplicaEvidence) GetKubernetesNode() string { + if x != nil { + return x.KubernetesNode + } + return "" +} + +func (x *ReplicaEvidence) GetPhysicalHost() string { + if x != nil { + return x.PhysicalHost + } + return "" +} + +func (x *ReplicaEvidence) GetObserved() bool { + if x != nil { + return x.Observed + } + return false +} + +func (x *ReplicaEvidence) GetRole() string { + if x != nil { + return x.Role + } + return "" +} + +func (x *ReplicaEvidence) GetReplicationRole() string { + if x != nil { + return x.ReplicationRole + } + return "" +} + +func (x *ReplicaEvidence) GetDurableLatched() bool { + if x != nil { + return x.DurableLatched + } + return false +} + +func (x *ReplicaEvidence) GetDurableFrontierKnown() bool { + if x != nil { + return x.DurableFrontierKnown + } + return false +} + +func (x *ReplicaEvidence) GetDurableFrontierLsn() uint64 { + if x != nil { + return x.DurableFrontierLsn + } + return 0 +} + +func (x *ReplicaEvidence) GetCandidateReady() bool { + if x != nil { + return x.CandidateReady + } + return false +} + +func (x *ReplicaEvidence) GetCandidateReadyReason() string { + if x != nil { + return x.CandidateReadyReason + } + return "" +} + +func (x *ReplicaEvidence) GetFrontendProtocol() string { + if x != nil { + return x.FrontendProtocol + } + return "" +} + +func (x *ReplicaEvidence) GetFrontendAddr() string { + if x != nil { + return x.FrontendAddr + } + return "" +} + +func (x *ReplicaEvidence) GetStatusAddr() string { + if x != nil { + return x.StatusAddr + } + return "" +} + +func (x *ReplicaEvidence) GetStalePrimaryFenced() bool { + if x != nil { + return x.StalePrimaryFenced + } + return false +} + +func (x *ReplicaEvidence) GetConditions() []*ObservationCondition { + if x != nil { + return x.Conditions + } + return nil +} + +func (x *ReplicaEvidence) GetSupportBundlePath() string { + if x != nil { + return x.SupportBundlePath + } + return "" +} + +type ClusterEvent struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + EventId string `protobuf:"bytes,1,opt,name=event_id,json=eventId,proto3" json:"event_id,omitempty"` + EventTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=event_time,json=eventTime,proto3" json:"event_time,omitempty"` + VolumeId string `protobuf:"bytes,3,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + ReplicaId string `protobuf:"bytes,4,opt,name=replica_id,json=replicaId,proto3" json:"replica_id,omitempty"` + NodeName string `protobuf:"bytes,5,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"` + EventType string `protobuf:"bytes,6,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` + Severity string `protobuf:"bytes,7,opt,name=severity,proto3" json:"severity,omitempty"` + Message string `protobuf:"bytes,8,opt,name=message,proto3" json:"message,omitempty"` + ReasonCode string `protobuf:"bytes,9,opt,name=reason_code,json=reasonCode,proto3" json:"reason_code,omitempty"` + OldValue string `protobuf:"bytes,10,opt,name=old_value,json=oldValue,proto3" json:"old_value,omitempty"` + NewValue string `protobuf:"bytes,11,opt,name=new_value,json=newValue,proto3" json:"new_value,omitempty"` + Epoch uint64 `protobuf:"varint,12,opt,name=epoch,proto3" json:"epoch,omitempty"` + EndpointVersion uint64 `protobuf:"varint,13,opt,name=endpoint_version,json=endpointVersion,proto3" json:"endpoint_version,omitempty"` + CorrelationId string `protobuf:"bytes,14,opt,name=correlation_id,json=correlationId,proto3" json:"correlation_id,omitempty"` + EvidenceRef string `protobuf:"bytes,15,opt,name=evidence_ref,json=evidenceRef,proto3" json:"evidence_ref,omitempty"` +} + +func (x *ClusterEvent) Reset() { + *x = ClusterEvent{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ClusterEvent) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ClusterEvent) ProtoMessage() {} + +func (x *ClusterEvent) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ClusterEvent.ProtoReflect.Descriptor instead. +func (*ClusterEvent) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{20} +} + +func (x *ClusterEvent) GetEventId() string { + if x != nil { + return x.EventId + } + return "" +} + +func (x *ClusterEvent) GetEventTime() *timestamp.Timestamp { + if x != nil { + return x.EventTime + } + return nil +} + +func (x *ClusterEvent) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *ClusterEvent) GetReplicaId() string { + if x != nil { + return x.ReplicaId + } + return "" +} + +func (x *ClusterEvent) GetNodeName() string { + if x != nil { + return x.NodeName + } + return "" +} + +func (x *ClusterEvent) GetEventType() string { + if x != nil { + return x.EventType + } + return "" +} + +func (x *ClusterEvent) GetSeverity() string { + if x != nil { + return x.Severity + } + return "" +} + +func (x *ClusterEvent) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *ClusterEvent) GetReasonCode() string { + if x != nil { + return x.ReasonCode + } + return "" +} + +func (x *ClusterEvent) GetOldValue() string { + if x != nil { + return x.OldValue + } + return "" +} + +func (x *ClusterEvent) GetNewValue() string { + if x != nil { + return x.NewValue + } + return "" +} + +func (x *ClusterEvent) GetEpoch() uint64 { + if x != nil { + return x.Epoch + } + return 0 +} + +func (x *ClusterEvent) GetEndpointVersion() uint64 { + if x != nil { + return x.EndpointVersion + } + return 0 +} + +func (x *ClusterEvent) GetCorrelationId() string { + if x != nil { + return x.CorrelationId + } + return "" +} + +func (x *ClusterEvent) GetEvidenceRef() string { + if x != nil { + return x.EvidenceRef + } + return "" +} + +type ListVolumesResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SchemaVersion string `protobuf:"bytes,1,opt,name=schema_version,json=schemaVersion,proto3" json:"schema_version,omitempty"` + CapturedAt *timestamp.Timestamp `protobuf:"bytes,2,opt,name=captured_at,json=capturedAt,proto3" json:"captured_at,omitempty"` + Volumes []*VolumeEvidence `protobuf:"bytes,3,rep,name=volumes,proto3" json:"volumes,omitempty"` +} + +func (x *ListVolumesResponse) Reset() { + *x = ListVolumesResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListVolumesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListVolumesResponse) ProtoMessage() {} + +func (x *ListVolumesResponse) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListVolumesResponse.ProtoReflect.Descriptor instead. +func (*ListVolumesResponse) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{21} +} + +func (x *ListVolumesResponse) GetSchemaVersion() string { + if x != nil { + return x.SchemaVersion + } + return "" +} + +func (x *ListVolumesResponse) GetCapturedAt() *timestamp.Timestamp { + if x != nil { + return x.CapturedAt + } + return nil +} + +func (x *ListVolumesResponse) GetVolumes() []*VolumeEvidence { + if x != nil { + return x.Volumes + } + return nil +} + +type VolumeTimelineResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SchemaVersion string `protobuf:"bytes,1,opt,name=schema_version,json=schemaVersion,proto3" json:"schema_version,omitempty"` + CapturedAt *timestamp.Timestamp `protobuf:"bytes,2,opt,name=captured_at,json=capturedAt,proto3" json:"captured_at,omitempty"` + VolumeId string `protobuf:"bytes,3,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + Events []*ClusterEvent `protobuf:"bytes,4,rep,name=events,proto3" json:"events,omitempty"` +} + +func (x *VolumeTimelineResponse) Reset() { + *x = VolumeTimelineResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *VolumeTimelineResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*VolumeTimelineResponse) ProtoMessage() {} + +func (x *VolumeTimelineResponse) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[22] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use VolumeTimelineResponse.ProtoReflect.Descriptor instead. +func (*VolumeTimelineResponse) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{22} +} + +func (x *VolumeTimelineResponse) GetSchemaVersion() string { + if x != nil { + return x.SchemaVersion + } + return "" +} + +func (x *VolumeTimelineResponse) GetCapturedAt() *timestamp.Timestamp { + if x != nil { + return x.CapturedAt + } + return nil +} + +func (x *VolumeTimelineResponse) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *VolumeTimelineResponse) GetEvents() []*ClusterEvent { + if x != nil { + return x.Events + } + return nil +} + type CreateVolumeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -842,7 +2107,7 @@ type CreateVolumeRequest struct { func (x *CreateVolumeRequest) Reset() { *x = CreateVolumeRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[9] + mi := &file_control_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -855,7 +2120,7 @@ func (x *CreateVolumeRequest) String() string { func (*CreateVolumeRequest) ProtoMessage() {} func (x *CreateVolumeRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[9] + mi := &file_control_proto_msgTypes[23] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -868,7 +2133,7 @@ func (x *CreateVolumeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateVolumeRequest.ProtoReflect.Descriptor instead. func (*CreateVolumeRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{9} + return file_control_proto_rawDescGZIP(), []int{23} } func (x *CreateVolumeRequest) GetVolumeId() string { @@ -945,7 +2210,7 @@ type CreateVolumeResponse struct { func (x *CreateVolumeResponse) Reset() { *x = CreateVolumeResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[10] + mi := &file_control_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -958,7 +2223,7 @@ func (x *CreateVolumeResponse) String() string { func (*CreateVolumeResponse) ProtoMessage() {} func (x *CreateVolumeResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[10] + mi := &file_control_proto_msgTypes[24] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -971,7 +2236,7 @@ func (x *CreateVolumeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateVolumeResponse.ProtoReflect.Descriptor instead. func (*CreateVolumeResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{10} + return file_control_proto_rawDescGZIP(), []int{24} } func (x *CreateVolumeResponse) GetVolumeId() string { @@ -1041,7 +2306,7 @@ type DeleteVolumeRequest struct { func (x *DeleteVolumeRequest) Reset() { *x = DeleteVolumeRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[11] + mi := &file_control_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1054,7 +2319,7 @@ func (x *DeleteVolumeRequest) String() string { func (*DeleteVolumeRequest) ProtoMessage() {} func (x *DeleteVolumeRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[11] + mi := &file_control_proto_msgTypes[25] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1067,7 +2332,7 @@ func (x *DeleteVolumeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteVolumeRequest.ProtoReflect.Descriptor instead. func (*DeleteVolumeRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{11} + return file_control_proto_rawDescGZIP(), []int{25} } func (x *DeleteVolumeRequest) GetVolumeId() string { @@ -1086,7 +2351,7 @@ type DeleteVolumeResponse struct { func (x *DeleteVolumeResponse) Reset() { *x = DeleteVolumeResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[12] + mi := &file_control_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1099,7 +2364,7 @@ func (x *DeleteVolumeResponse) String() string { func (*DeleteVolumeResponse) ProtoMessage() {} func (x *DeleteVolumeResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[12] + mi := &file_control_proto_msgTypes[26] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1112,7 +2377,7 @@ func (x *DeleteVolumeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteVolumeResponse.ProtoReflect.Descriptor instead. func (*DeleteVolumeResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{12} + return file_control_proto_rawDescGZIP(), []int{26} } var File_control_proto protoreflect.FileDescriptor @@ -1178,71 +2443,335 @@ var file_control_proto_rawDesc = []byte{ 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, - 0x65, 0x22, 0x71, 0x0a, 0x10, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, - 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x65, 0x70, 0x6f, 0x63, - 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x65, 0x45, - 0x70, 0x6f, 0x63, 0x68, 0x22, 0xad, 0x01, 0x0a, 0x11, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, - 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, - 0x63, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, - 0x29, 0x0a, 0x10, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, - 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, - 0x69, 0x6e, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x61, - 0x74, 0x61, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, - 0x61, 0x74, 0x61, 0x41, 0x64, 0x64, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x74, 0x72, 0x6c, 0x5f, - 0x61, 0x64, 0x64, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x74, 0x72, 0x6c, - 0x41, 0x64, 0x64, 0x72, 0x22, 0xb9, 0x02, 0x0a, 0x0e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, - 0x65, 0x6e, 0x74, 0x46, 0x61, 0x63, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, - 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, - 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, - 0x61, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x6e, 0x64, - 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x56, 0x65, 0x72, - 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x61, 0x64, 0x64, - 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x41, 0x64, 0x64, - 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x06, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x74, 0x72, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x12, 0x40, - 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, - 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x44, - 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, - 0x12, 0x2e, 0x0a, 0x13, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x74, 0x5f, 0x67, 0x65, 0x6e, - 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x11, 0x70, - 0x65, 0x65, 0x72, 0x53, 0x65, 0x74, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x22, 0x2c, 0x0a, 0x0d, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, 0xe3, - 0x02, 0x0a, 0x0e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, - 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x14, 0x0a, - 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, + 0x65, 0x22, 0x69, 0x0a, 0x0f, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, + 0x74, 0x41, 0x63, 0x6b, 0x12, 0x3b, 0x0a, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, + 0x5f, 0x61, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x41, + 0x74, 0x12, 0x19, 0x0a, 0x08, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x07, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x22, 0x71, 0x0a, 0x10, + 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, + 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, + 0x72, 0x65, 0x73, 0x75, 0x6d, 0x65, 0x5f, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x04, 0x52, 0x0b, 0x72, 0x65, 0x73, 0x75, 0x6d, 0x65, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x22, + 0xad, 0x01, 0x0a, 0x11, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x44, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, + 0x63, 0x61, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x6e, + 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x61, 0x64, + 0x64, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x41, 0x64, + 0x64, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x74, 0x72, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x22, + 0xb9, 0x02, 0x0a, 0x0e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x46, 0x61, + 0x63, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, + 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x14, + 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, + 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, + 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, + 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, + 0x1b, 0x0a, 0x09, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x41, 0x64, 0x64, 0x72, 0x12, 0x1b, 0x0a, 0x09, + 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x63, 0x74, 0x72, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x12, 0x40, 0x0a, 0x05, 0x70, 0x65, 0x65, + 0x72, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x6f, 0x72, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x70, + 0x65, 0x65, 0x72, 0x5f, 0x73, 0x65, 0x74, 0x5f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x11, 0x70, 0x65, 0x65, 0x72, 0x53, 0x65, + 0x74, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x0d, 0x53, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, 0xe3, 0x02, 0x0a, 0x0e, 0x53, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x0a, 0x09, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, + 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, + 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, + 0x0a, 0x10, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, + 0x6e, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x61, 0x73, 0x73, + 0x69, 0x67, 0x6e, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x61, 0x73, 0x73, + 0x69, 0x67, 0x6e, 0x65, 0x64, 0x12, 0x36, 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x6e, + 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x15, 0x6c, 0x61, 0x73, 0x74, 0x55, 0x6e, 0x73, 0x75, + 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x12, 0x39, 0x0a, + 0x19, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x67, 0x65, 0x6e, 0x63, + 0x65, 0x5f, 0x73, 0x74, 0x75, 0x63, 0x6b, 0x5f, 0x61, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x16, 0x6c, 0x61, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x67, 0x65, 0x6e, 0x63, + 0x65, 0x53, 0x74, 0x75, 0x63, 0x6b, 0x41, 0x74, 0x12, 0x45, 0x0a, 0x09, 0x66, 0x72, 0x6f, 0x6e, + 0x74, 0x65, 0x6e, 0x64, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x73, 0x65, + 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x54, 0x61, + 0x72, 0x67, 0x65, 0x74, 0x52, 0x09, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x73, 0x22, + 0x19, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x14, 0x0a, 0x12, 0x4c, 0x69, + 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x22, 0x35, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, 0x37, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, + 0x22, 0x41, 0x0a, 0x19, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, + 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x24, 0x0a, + 0x0e, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x45, 0x76, 0x65, 0x6e, + 0x74, 0x49, 0x64, 0x22, 0x90, 0x01, 0x0a, 0x14, 0x4f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, + 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, + 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x72, 0x65, 0x61, 0x73, + 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, + 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x18, 0x0a, 0x07, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0xeb, 0x03, 0x0a, 0x15, 0x43, 0x6c, 0x75, 0x73, 0x74, + 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x25, 0x0a, 0x0e, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x61, 0x70, 0x74, 0x75, + 0x72, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x61, 0x70, 0x74, 0x75, 0x72, + 0x65, 0x64, 0x41, 0x74, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x5f, + 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, + 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x52, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x12, + 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x3b, 0x0a, 0x05, 0x6e, 0x6f, 0x64, 0x65, 0x73, + 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x05, 0x6e, + 0x6f, 0x64, 0x65, 0x73, 0x12, 0x41, 0x0a, 0x07, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x18, + 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, + 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, + 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x07, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x12, 0x4d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x65, + 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, + 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3d, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, + 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, + 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x6e, 0x6f, 0x6e, 0x5f, 0x63, 0x6c, 0x61, + 0x69, 0x6d, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x6f, 0x6e, 0x43, 0x6c, + 0x61, 0x69, 0x6d, 0x73, 0x22, 0xde, 0x03, 0x0a, 0x0c, 0x4e, 0x6f, 0x64, 0x65, 0x45, 0x76, 0x69, + 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6e, 0x6f, 0x64, 0x65, 0x4e, 0x61, + 0x6d, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, + 0x5f, 0x6e, 0x6f, 0x64, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x6b, 0x75, 0x62, + 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x4e, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x70, + 0x68, 0x79, 0x73, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0c, 0x70, 0x68, 0x79, 0x73, 0x69, 0x63, 0x61, 0x6c, 0x48, 0x6f, 0x73, 0x74, + 0x12, 0x1f, 0x0a, 0x0b, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x69, 0x70, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x49, + 0x70, 0x12, 0x20, 0x0a, 0x0b, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x61, 0x62, 0x6c, 0x65, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0b, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x61, 0x64, 0x79, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x05, 0x72, 0x65, 0x61, 0x64, 0x79, 0x12, 0x46, 0x0a, 0x11, 0x6c, 0x61, 0x73, + 0x74, 0x5f, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x5f, 0x61, 0x74, 0x18, 0x07, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x52, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x41, + 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x63, 0x6f, 0x75, + 0x6e, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, + 0x65, 0x64, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x09, 0x52, + 0x0e, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x12, + 0x25, 0x0a, 0x0e, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6e, 0x67, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, + 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6e, 0x67, + 0x49, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x12, 0x4d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x65, 0x61, + 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x98, 0x06, 0x0a, 0x0e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, + 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, + 0x61, 0x63, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x70, 0x76, 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x17, + 0x0a, 0x07, 0x70, 0x76, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x70, 0x76, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2d, 0x0a, 0x12, 0x72, 0x65, 0x70, 0x6c, 0x69, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x11, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x46, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x63, 0x6b, 0x5f, 0x70, 0x72, + 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x61, 0x63, 0x6b, + 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x6c, 0x61, 0x69, 0x6d, + 0x5f, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, + 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x12, 0x29, 0x0a, 0x10, + 0x64, 0x65, 0x73, 0x69, 0x72, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x73, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x64, 0x65, 0x73, 0x69, 0x72, 0x65, 0x64, 0x52, + 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x73, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x62, 0x73, 0x65, 0x72, + 0x76, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x73, 0x18, 0x09, 0x20, 0x01, + 0x28, 0x05, 0x52, 0x10, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x65, 0x70, 0x6c, + 0x69, 0x63, 0x61, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0a, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x16, 0x0a, 0x06, + 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x65, + 0x61, 0x73, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, + 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x70, + 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x12, 0x21, 0x0a, + 0x0c, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x6e, 0x6f, 0x64, 0x65, 0x18, 0x0d, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x4e, 0x6f, 0x64, 0x65, + 0x12, 0x25, 0x0a, 0x0e, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x5f, 0x74, 0x61, 0x72, 0x67, + 0x65, 0x74, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, + 0x68, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, + 0x18, 0x0f, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, 0x0a, + 0x10, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x18, 0x10, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x08, 0x72, 0x65, 0x70, 0x6c, + 0x69, 0x63, 0x61, 0x73, 0x18, 0x11, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x73, 0x65, 0x61, + 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x45, 0x76, 0x69, 0x64, + 0x65, 0x6e, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x73, 0x12, 0x4d, + 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x12, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4f, 0x62, 0x73, + 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x21, 0x0a, + 0x0c, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x13, 0x20, + 0x03, 0x28, 0x09, 0x52, 0x0b, 0x6e, 0x65, 0x78, 0x74, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x12, 0x2e, 0x0a, 0x13, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x62, 0x75, 0x6e, 0x64, + 0x6c, 0x65, 0x5f, 0x68, 0x69, 0x6e, 0x74, 0x18, 0x14, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x73, + 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x48, 0x69, 0x6e, 0x74, + 0x22, 0x8a, 0x06, 0x0a, 0x0f, 0x52, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x45, 0x76, 0x69, 0x64, + 0x65, 0x6e, 0x63, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, + 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, + 0x12, 0x27, 0x0a, 0x0f, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x5f, 0x6e, + 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x6b, 0x75, 0x62, 0x65, 0x72, + 0x6e, 0x65, 0x74, 0x65, 0x73, 0x4e, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x68, 0x79, + 0x73, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0c, 0x70, 0x68, 0x79, 0x73, 0x69, 0x63, 0x61, 0x6c, 0x48, 0x6f, 0x73, 0x74, 0x12, 0x1a, + 0x0a, 0x08, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x08, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x6f, + 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x12, 0x29, + 0x0a, 0x10, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x6f, + 0x6c, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x6f, 0x6c, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x64, 0x75, 0x72, + 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6c, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x18, 0x08, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x0e, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x4c, 0x61, 0x74, 0x63, 0x68, + 0x65, 0x64, 0x12, 0x34, 0x0a, 0x16, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x66, 0x72, + 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x5f, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x18, 0x09, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x14, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x46, 0x72, 0x6f, 0x6e, 0x74, + 0x69, 0x65, 0x72, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x12, 0x30, 0x0a, 0x14, 0x64, 0x75, 0x72, 0x61, + 0x62, 0x6c, 0x65, 0x5f, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x5f, 0x6c, 0x73, 0x6e, + 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x12, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x46, + 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x4c, 0x73, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x63, 0x61, + 0x6e, 0x64, 0x69, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x65, 0x61, 0x64, 0x79, 0x18, 0x0b, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x0e, 0x63, 0x61, 0x6e, 0x64, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, + 0x61, 0x64, 0x79, 0x12, 0x34, 0x0a, 0x16, 0x63, 0x61, 0x6e, 0x64, 0x69, 0x64, 0x61, 0x74, 0x65, + 0x5f, 0x72, 0x65, 0x61, 0x64, 0x79, 0x5f, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x0c, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x14, 0x63, 0x61, 0x6e, 0x64, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, + 0x61, 0x64, 0x79, 0x52, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x11, 0x66, 0x72, 0x6f, + 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x0d, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x23, 0x0a, 0x0d, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, + 0x6e, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x66, + 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x41, 0x64, 0x64, 0x72, 0x12, 0x1f, 0x0a, 0x0b, 0x73, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x41, 0x64, 0x64, 0x72, 0x12, 0x30, 0x0a, 0x14, + 0x73, 0x74, 0x61, 0x6c, 0x65, 0x5f, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x66, 0x65, + 0x6e, 0x63, 0x65, 0x64, 0x18, 0x10, 0x20, 0x01, 0x28, 0x08, 0x52, 0x12, 0x73, 0x74, 0x61, 0x6c, + 0x65, 0x50, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x46, 0x65, 0x6e, 0x63, 0x65, 0x64, 0x12, 0x4d, + 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x11, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4f, 0x62, 0x73, + 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2e, 0x0a, + 0x13, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x62, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x5f, + 0x70, 0x61, 0x74, 0x68, 0x18, 0x12, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x73, 0x75, 0x70, 0x70, + 0x6f, 0x72, 0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x22, 0xf8, 0x03, + 0x0a, 0x0c, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x19, + 0x0a, 0x08, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x07, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x39, 0x0a, 0x0a, 0x65, 0x76, 0x65, + 0x6e, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, + 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, + 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, + 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, + 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x6e, 0x6f, 0x64, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1d, 0x0a, + 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1a, 0x0a, 0x08, + 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x5f, 0x63, 0x6f, 0x64, + 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x43, + 0x6f, 0x64, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x6f, 0x6c, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, + 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6f, 0x6c, 0x64, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x0b, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, + 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x29, 0x0a, 0x10, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, - 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, - 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1a, - 0x0a, 0x08, 0x61, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, - 0x52, 0x08, 0x61, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x12, 0x36, 0x0a, 0x17, 0x6c, 0x61, - 0x73, 0x74, 0x5f, 0x75, 0x6e, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x72, - 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x15, 0x6c, 0x61, 0x73, - 0x74, 0x55, 0x6e, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x52, 0x65, 0x61, 0x73, - 0x6f, 0x6e, 0x12, 0x39, 0x0a, 0x19, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x76, 0x65, - 0x72, 0x67, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x73, 0x74, 0x75, 0x63, 0x6b, 0x5f, 0x61, 0x74, 0x18, - 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x16, 0x6c, 0x61, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x76, 0x65, - 0x72, 0x67, 0x65, 0x6e, 0x63, 0x65, 0x53, 0x74, 0x75, 0x63, 0x6b, 0x41, 0x74, 0x12, 0x45, 0x0a, - 0x09, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, - 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x46, 0x72, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x64, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x52, 0x09, 0x66, 0x72, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x64, 0x73, 0x22, 0x8e, 0x02, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, - 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, + 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x65, + 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x25, + 0x0a, 0x0e, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, + 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, + 0x65, 0x5f, 0x72, 0x65, 0x66, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x76, 0x69, + 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x66, 0x22, 0xbc, 0x01, 0x0a, 0x13, 0x4c, 0x69, 0x73, + 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x25, 0x0a, 0x0e, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x61, 0x70, 0x74, 0x75, + 0x72, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x61, 0x70, 0x74, 0x75, 0x72, + 0x65, 0x64, 0x41, 0x74, 0x12, 0x41, 0x0a, 0x07, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x18, + 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, + 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, + 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x07, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x22, 0xd8, 0x01, 0x0a, 0x16, 0x56, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x76, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x63, 0x68, 0x65, + 0x6d, 0x61, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x61, 0x70, + 0x74, 0x75, 0x72, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x61, 0x70, 0x74, + 0x75, 0x72, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x49, 0x64, 0x12, 0x3d, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x04, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, + 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, + 0x74, 0x73, 0x22, 0x8e, 0x02, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x69, 0x7a, 0x65, 0x5f, + 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x73, 0x69, 0x7a, + 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x05, 0x52, 0x11, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x46, + 0x61, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, + 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x70, 0x76, 0x63, 0x4e, 0x61, 0x6d, 0x65, + 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x70, 0x76, 0x63, 0x4e, 0x61, 0x6d, 0x65, + 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x5f, 0x6e, 0x61, 0x6d, 0x65, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x17, + 0x0a, 0x07, 0x70, 0x76, 0x63, 0x5f, 0x75, 0x69, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x70, 0x76, 0x63, 0x55, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x63, 0x6f, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x63, 0x6f, 0x6c, 0x22, 0x8f, 0x02, 0x0a, 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x69, 0x7a, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x73, @@ -1258,71 +2787,98 @@ var file_control_proto_rawDesc = []byte{ 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x63, 0x5f, 0x75, 0x69, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x63, 0x55, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x8f, 0x02, 0x0a, 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, - 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x73, - 0x69, 0x7a, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, - 0x09, 0x73, 0x69, 0x7a, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x72, 0x65, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x61, 0x63, 0x74, 0x6f, 0x72, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x11, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x46, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x70, 0x76, 0x63, - 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x70, 0x76, 0x63, - 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, - 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x70, 0x76, 0x63, - 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x5f, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x4e, 0x61, - 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x63, 0x5f, 0x75, 0x69, 0x64, 0x18, 0x07, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x63, 0x55, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x32, 0x0a, 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, - 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, 0x16, 0x0a, 0x14, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x32, 0x78, 0x0a, 0x12, 0x4f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x62, 0x0a, 0x0f, 0x52, 0x65, 0x70, - 0x6f, 0x72, 0x74, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x12, 0x28, 0x2e, 0x73, - 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, - 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x41, 0x63, 0x6b, 0x32, 0x81, 0x01, - 0x0a, 0x11, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, - 0x69, 0x63, 0x65, 0x12, 0x6c, 0x0a, 0x14, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, - 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x29, 0x2e, 0x73, 0x65, + 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x32, 0x0a, 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, + 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, 0x16, 0x0a, 0x14, 0x44, 0x65, 0x6c, + 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x32, 0xdf, 0x01, 0x0a, 0x12, 0x4f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x62, 0x0a, 0x0f, 0x52, 0x65, 0x70, 0x6f, + 0x72, 0x74, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x12, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x46, 0x61, 0x63, 0x74, 0x30, - 0x01, 0x32, 0x77, 0x0a, 0x0f, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x12, 0x64, 0x0a, 0x11, 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x6f, 0x6c, - 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x26, 0x2e, 0x73, 0x65, 0x61, 0x77, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x52, + 0x65, 0x70, 0x6f, 0x72, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, + 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, + 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x41, 0x63, 0x6b, 0x12, 0x65, 0x0a, 0x12, + 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x12, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, + 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x1a, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, - 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, - 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xec, 0x01, 0x0a, 0x10, 0x4c, - 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, - 0x6b, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, - 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, - 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, - 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, - 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0c, - 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, + 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, + 0x41, 0x63, 0x6b, 0x32, 0x81, 0x01, 0x0a, 0x11, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, + 0x6e, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6c, 0x0a, 0x14, 0x53, 0x75, 0x62, + 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, + 0x73, 0x12, 0x29, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x75, 0x62, 0x73, + 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, - 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, - 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, - 0x73, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x2d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2f, - 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x3b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, + 0x74, 0x46, 0x61, 0x63, 0x74, 0x30, 0x01, 0x32, 0x77, 0x0a, 0x0f, 0x45, 0x76, 0x69, 0x64, 0x65, + 0x6e, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x64, 0x0a, 0x11, 0x51, 0x75, + 0x65, 0x72, 0x79, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, + 0x26, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, + 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x32, 0xd1, 0x04, 0x0a, 0x16, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x69, 0x64, + 0x65, 0x6e, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x74, 0x0a, 0x10, 0x47, + 0x65, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, + 0x30, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x75, + 0x73, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x2e, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, + 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x68, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, + 0x12, 0x2b, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, + 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0f, 0x47, + 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2f, + 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x77, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x31, 0x2e, + 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x2f, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x71, 0x0a, 0x12, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, + 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, + 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x2e, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, + 0x65, 0x6e, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, + 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x30, 0x01, 0x32, 0xec, 0x01, 0x0a, 0x10, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, + 0x6c, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x43, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, + 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, + 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, + 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, + 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, + 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, + 0x6d, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2f, 0x73, 0x65, 0x61, 0x77, + 0x65, 0x65, 0x64, 0x2d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, + 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x3b, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1337,45 +2893,87 @@ func file_control_proto_rawDescGZIP() []byte { return file_control_proto_rawDescData } -var file_control_proto_msgTypes = make([]protoimpl.MessageInfo, 13) +var file_control_proto_msgTypes = make([]protoimpl.MessageInfo, 27) var file_control_proto_goTypes = []interface{}{ - (*HeartbeatReport)(nil), // 0: seaweedfs.block.control.HeartbeatReport - (*HeartbeatSlot)(nil), // 1: seaweedfs.block.control.HeartbeatSlot - (*FrontendTarget)(nil), // 2: seaweedfs.block.control.FrontendTarget - (*HeartbeatAck)(nil), // 3: seaweedfs.block.control.HeartbeatAck - (*SubscribeRequest)(nil), // 4: seaweedfs.block.control.SubscribeRequest - (*ReplicaDescriptor)(nil), // 5: seaweedfs.block.control.ReplicaDescriptor - (*AssignmentFact)(nil), // 6: seaweedfs.block.control.AssignmentFact - (*StatusRequest)(nil), // 7: seaweedfs.block.control.StatusRequest - (*StatusResponse)(nil), // 8: seaweedfs.block.control.StatusResponse - (*CreateVolumeRequest)(nil), // 9: seaweedfs.block.control.CreateVolumeRequest - (*CreateVolumeResponse)(nil), // 10: seaweedfs.block.control.CreateVolumeResponse - (*DeleteVolumeRequest)(nil), // 11: seaweedfs.block.control.DeleteVolumeRequest - (*DeleteVolumeResponse)(nil), // 12: seaweedfs.block.control.DeleteVolumeResponse - (*timestamp.Timestamp)(nil), // 13: google.protobuf.Timestamp + (*HeartbeatReport)(nil), // 0: seaweedfs.block.control.HeartbeatReport + (*HeartbeatSlot)(nil), // 1: seaweedfs.block.control.HeartbeatSlot + (*FrontendTarget)(nil), // 2: seaweedfs.block.control.FrontendTarget + (*HeartbeatAck)(nil), // 3: seaweedfs.block.control.HeartbeatAck + (*ClusterEventAck)(nil), // 4: seaweedfs.block.control.ClusterEventAck + (*SubscribeRequest)(nil), // 5: seaweedfs.block.control.SubscribeRequest + (*ReplicaDescriptor)(nil), // 6: seaweedfs.block.control.ReplicaDescriptor + (*AssignmentFact)(nil), // 7: seaweedfs.block.control.AssignmentFact + (*StatusRequest)(nil), // 8: seaweedfs.block.control.StatusRequest + (*StatusResponse)(nil), // 9: seaweedfs.block.control.StatusResponse + (*GetClusterStatusRequest)(nil), // 10: seaweedfs.block.control.GetClusterStatusRequest + (*ListVolumesRequest)(nil), // 11: seaweedfs.block.control.ListVolumesRequest + (*GetVolumeStatusRequest)(nil), // 12: seaweedfs.block.control.GetVolumeStatusRequest + (*GetVolumeTimelineRequest)(nil), // 13: seaweedfs.block.control.GetVolumeTimelineRequest + (*WatchClusterEventsRequest)(nil), // 14: seaweedfs.block.control.WatchClusterEventsRequest + (*ObservationCondition)(nil), // 15: seaweedfs.block.control.ObservationCondition + (*ClusterStatusResponse)(nil), // 16: seaweedfs.block.control.ClusterStatusResponse + (*NodeEvidence)(nil), // 17: seaweedfs.block.control.NodeEvidence + (*VolumeEvidence)(nil), // 18: seaweedfs.block.control.VolumeEvidence + (*ReplicaEvidence)(nil), // 19: seaweedfs.block.control.ReplicaEvidence + (*ClusterEvent)(nil), // 20: seaweedfs.block.control.ClusterEvent + (*ListVolumesResponse)(nil), // 21: seaweedfs.block.control.ListVolumesResponse + (*VolumeTimelineResponse)(nil), // 22: seaweedfs.block.control.VolumeTimelineResponse + (*CreateVolumeRequest)(nil), // 23: seaweedfs.block.control.CreateVolumeRequest + (*CreateVolumeResponse)(nil), // 24: seaweedfs.block.control.CreateVolumeResponse + (*DeleteVolumeRequest)(nil), // 25: seaweedfs.block.control.DeleteVolumeRequest + (*DeleteVolumeResponse)(nil), // 26: seaweedfs.block.control.DeleteVolumeResponse + (*timestamp.Timestamp)(nil), // 27: google.protobuf.Timestamp } var file_control_proto_depIdxs = []int32{ - 13, // 0: seaweedfs.block.control.HeartbeatReport.sent_at:type_name -> google.protobuf.Timestamp + 27, // 0: seaweedfs.block.control.HeartbeatReport.sent_at:type_name -> google.protobuf.Timestamp 1, // 1: seaweedfs.block.control.HeartbeatReport.slots:type_name -> seaweedfs.block.control.HeartbeatSlot 2, // 2: seaweedfs.block.control.HeartbeatSlot.frontends:type_name -> seaweedfs.block.control.FrontendTarget - 13, // 3: seaweedfs.block.control.HeartbeatAck.accepted_at:type_name -> google.protobuf.Timestamp - 5, // 4: seaweedfs.block.control.AssignmentFact.peers:type_name -> seaweedfs.block.control.ReplicaDescriptor - 2, // 5: seaweedfs.block.control.StatusResponse.frontends:type_name -> seaweedfs.block.control.FrontendTarget - 0, // 6: seaweedfs.block.control.ObservationService.ReportHeartbeat:input_type -> seaweedfs.block.control.HeartbeatReport - 4, // 7: seaweedfs.block.control.AssignmentService.SubscribeAssignments:input_type -> seaweedfs.block.control.SubscribeRequest - 7, // 8: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:input_type -> seaweedfs.block.control.StatusRequest - 9, // 9: seaweedfs.block.control.LifecycleService.CreateVolume:input_type -> seaweedfs.block.control.CreateVolumeRequest - 11, // 10: seaweedfs.block.control.LifecycleService.DeleteVolume:input_type -> seaweedfs.block.control.DeleteVolumeRequest - 3, // 11: seaweedfs.block.control.ObservationService.ReportHeartbeat:output_type -> seaweedfs.block.control.HeartbeatAck - 6, // 12: seaweedfs.block.control.AssignmentService.SubscribeAssignments:output_type -> seaweedfs.block.control.AssignmentFact - 8, // 13: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:output_type -> seaweedfs.block.control.StatusResponse - 10, // 14: seaweedfs.block.control.LifecycleService.CreateVolume:output_type -> seaweedfs.block.control.CreateVolumeResponse - 12, // 15: seaweedfs.block.control.LifecycleService.DeleteVolume:output_type -> seaweedfs.block.control.DeleteVolumeResponse - 11, // [11:16] is the sub-list for method output_type - 6, // [6:11] is the sub-list for method input_type - 6, // [6:6] is the sub-list for extension type_name - 6, // [6:6] is the sub-list for extension extendee - 0, // [0:6] is the sub-list for field type_name + 27, // 3: seaweedfs.block.control.HeartbeatAck.accepted_at:type_name -> google.protobuf.Timestamp + 27, // 4: seaweedfs.block.control.ClusterEventAck.accepted_at:type_name -> google.protobuf.Timestamp + 6, // 5: seaweedfs.block.control.AssignmentFact.peers:type_name -> seaweedfs.block.control.ReplicaDescriptor + 2, // 6: seaweedfs.block.control.StatusResponse.frontends:type_name -> seaweedfs.block.control.FrontendTarget + 27, // 7: seaweedfs.block.control.ClusterStatusResponse.captured_at:type_name -> google.protobuf.Timestamp + 17, // 8: seaweedfs.block.control.ClusterStatusResponse.nodes:type_name -> seaweedfs.block.control.NodeEvidence + 18, // 9: seaweedfs.block.control.ClusterStatusResponse.volumes:type_name -> seaweedfs.block.control.VolumeEvidence + 15, // 10: seaweedfs.block.control.ClusterStatusResponse.conditions:type_name -> seaweedfs.block.control.ObservationCondition + 20, // 11: seaweedfs.block.control.ClusterStatusResponse.events:type_name -> seaweedfs.block.control.ClusterEvent + 27, // 12: seaweedfs.block.control.NodeEvidence.last_heartbeat_at:type_name -> google.protobuf.Timestamp + 15, // 13: seaweedfs.block.control.NodeEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition + 19, // 14: seaweedfs.block.control.VolumeEvidence.replicas:type_name -> seaweedfs.block.control.ReplicaEvidence + 15, // 15: seaweedfs.block.control.VolumeEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition + 15, // 16: seaweedfs.block.control.ReplicaEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition + 27, // 17: seaweedfs.block.control.ClusterEvent.event_time:type_name -> google.protobuf.Timestamp + 27, // 18: seaweedfs.block.control.ListVolumesResponse.captured_at:type_name -> google.protobuf.Timestamp + 18, // 19: seaweedfs.block.control.ListVolumesResponse.volumes:type_name -> seaweedfs.block.control.VolumeEvidence + 27, // 20: seaweedfs.block.control.VolumeTimelineResponse.captured_at:type_name -> google.protobuf.Timestamp + 20, // 21: seaweedfs.block.control.VolumeTimelineResponse.events:type_name -> seaweedfs.block.control.ClusterEvent + 0, // 22: seaweedfs.block.control.ObservationService.ReportHeartbeat:input_type -> seaweedfs.block.control.HeartbeatReport + 20, // 23: seaweedfs.block.control.ObservationService.ReportClusterEvent:input_type -> seaweedfs.block.control.ClusterEvent + 5, // 24: seaweedfs.block.control.AssignmentService.SubscribeAssignments:input_type -> seaweedfs.block.control.SubscribeRequest + 8, // 25: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:input_type -> seaweedfs.block.control.StatusRequest + 10, // 26: seaweedfs.block.control.ClusterEvidenceService.GetClusterStatus:input_type -> seaweedfs.block.control.GetClusterStatusRequest + 11, // 27: seaweedfs.block.control.ClusterEvidenceService.ListVolumes:input_type -> seaweedfs.block.control.ListVolumesRequest + 12, // 28: seaweedfs.block.control.ClusterEvidenceService.GetVolumeStatus:input_type -> seaweedfs.block.control.GetVolumeStatusRequest + 13, // 29: seaweedfs.block.control.ClusterEvidenceService.GetVolumeTimeline:input_type -> seaweedfs.block.control.GetVolumeTimelineRequest + 14, // 30: seaweedfs.block.control.ClusterEvidenceService.WatchClusterEvents:input_type -> seaweedfs.block.control.WatchClusterEventsRequest + 23, // 31: seaweedfs.block.control.LifecycleService.CreateVolume:input_type -> seaweedfs.block.control.CreateVolumeRequest + 25, // 32: seaweedfs.block.control.LifecycleService.DeleteVolume:input_type -> seaweedfs.block.control.DeleteVolumeRequest + 3, // 33: seaweedfs.block.control.ObservationService.ReportHeartbeat:output_type -> seaweedfs.block.control.HeartbeatAck + 4, // 34: seaweedfs.block.control.ObservationService.ReportClusterEvent:output_type -> seaweedfs.block.control.ClusterEventAck + 7, // 35: seaweedfs.block.control.AssignmentService.SubscribeAssignments:output_type -> seaweedfs.block.control.AssignmentFact + 9, // 36: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:output_type -> seaweedfs.block.control.StatusResponse + 16, // 37: seaweedfs.block.control.ClusterEvidenceService.GetClusterStatus:output_type -> seaweedfs.block.control.ClusterStatusResponse + 21, // 38: seaweedfs.block.control.ClusterEvidenceService.ListVolumes:output_type -> seaweedfs.block.control.ListVolumesResponse + 18, // 39: seaweedfs.block.control.ClusterEvidenceService.GetVolumeStatus:output_type -> seaweedfs.block.control.VolumeEvidence + 22, // 40: seaweedfs.block.control.ClusterEvidenceService.GetVolumeTimeline:output_type -> seaweedfs.block.control.VolumeTimelineResponse + 20, // 41: seaweedfs.block.control.ClusterEvidenceService.WatchClusterEvents:output_type -> seaweedfs.block.control.ClusterEvent + 24, // 42: seaweedfs.block.control.LifecycleService.CreateVolume:output_type -> seaweedfs.block.control.CreateVolumeResponse + 26, // 43: seaweedfs.block.control.LifecycleService.DeleteVolume:output_type -> seaweedfs.block.control.DeleteVolumeResponse + 33, // [33:44] is the sub-list for method output_type + 22, // [22:33] is the sub-list for method input_type + 22, // [22:22] is the sub-list for extension type_name + 22, // [22:22] is the sub-list for extension extendee + 0, // [0:22] is the sub-list for field type_name } func init() { file_control_proto_init() } @@ -1433,7 +3031,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SubscribeRequest); i { + switch v := v.(*ClusterEventAck); i { case 0: return &v.state case 1: @@ -1445,7 +3043,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ReplicaDescriptor); i { + switch v := v.(*SubscribeRequest); i { case 0: return &v.state case 1: @@ -1457,7 +3055,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AssignmentFact); i { + switch v := v.(*ReplicaDescriptor); i { case 0: return &v.state case 1: @@ -1469,7 +3067,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StatusRequest); i { + switch v := v.(*AssignmentFact); i { case 0: return &v.state case 1: @@ -1481,7 +3079,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StatusResponse); i { + switch v := v.(*StatusRequest); i { case 0: return &v.state case 1: @@ -1493,7 +3091,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CreateVolumeRequest); i { + switch v := v.(*StatusResponse); i { case 0: return &v.state case 1: @@ -1505,7 +3103,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CreateVolumeResponse); i { + switch v := v.(*GetClusterStatusRequest); i { case 0: return &v.state case 1: @@ -1517,7 +3115,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeleteVolumeRequest); i { + switch v := v.(*ListVolumesRequest); i { case 0: return &v.state case 1: @@ -1529,6 +3127,174 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetVolumeStatusRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetVolumeTimelineRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*WatchClusterEventsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ObservationCondition); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ClusterStatusResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*NodeEvidence); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*VolumeEvidence); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ReplicaEvidence); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ClusterEvent); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListVolumesResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*VolumeTimelineResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateVolumeRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateVolumeResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DeleteVolumeRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DeleteVolumeResponse); i { case 0: return &v.state @@ -1547,9 +3313,9 @@ func file_control_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_control_proto_rawDesc, NumEnums: 0, - NumMessages: 13, + NumMessages: 27, NumExtensions: 0, - NumServices: 4, + NumServices: 5, }, GoTypes: file_control_proto_goTypes, DependencyIndexes: file_control_proto_depIdxs, diff --git a/seaweed-block/core/rpc/control/control_grpc.pb.go b/seaweed-block/core/rpc/control/control_grpc.pb.go index f41c00c814..33309a5cb9 100644 --- a/seaweed-block/core/rpc/control/control_grpc.pb.go +++ b/seaweed-block/core/rpc/control/control_grpc.pb.go @@ -4,6 +4,7 @@ // volume -> master: ObservationService.ReportHeartbeat (unary) // volume -> master: AssignmentService.SubscribeAssignments (server-streaming) // operator -> master: EvidenceService.QueryVolumeStatus (unary, read-only) +// operator/dashboard -> master: ClusterEvidenceService read-only observation // CSI/operator -> master: LifecycleService.CreateVolume/DeleteVolume (desired intent only) // // Boundary (T0 sketch §3 load-bearing): @@ -35,7 +36,8 @@ import ( const _ = grpc.SupportPackageIsVersion7 const ( - ObservationService_ReportHeartbeat_FullMethodName = "/seaweedfs.block.control.ObservationService/ReportHeartbeat" + ObservationService_ReportHeartbeat_FullMethodName = "/seaweedfs.block.control.ObservationService/ReportHeartbeat" + ObservationService_ReportClusterEvent_FullMethodName = "/seaweedfs.block.control.ObservationService/ReportClusterEvent" ) // ObservationServiceClient is the client API for ObservationService service. @@ -46,6 +48,10 @@ type ObservationServiceClient interface { // authority.HeartbeatMessage, calls ObservationHost.Ingest. // Ack is diagnostic only. ReportHeartbeat(ctx context.Context, in *HeartbeatReport, opts ...grpc.CallOption) (*HeartbeatAck, error) + // Node/CSI observation event. This appends an operator timeline event only; + // it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or + // replica state. + ReportClusterEvent(ctx context.Context, in *ClusterEvent, opts ...grpc.CallOption) (*ClusterEventAck, error) } type observationServiceClient struct { @@ -65,6 +71,15 @@ func (c *observationServiceClient) ReportHeartbeat(ctx context.Context, in *Hear return out, nil } +func (c *observationServiceClient) ReportClusterEvent(ctx context.Context, in *ClusterEvent, opts ...grpc.CallOption) (*ClusterEventAck, error) { + out := new(ClusterEventAck) + err := c.cc.Invoke(ctx, ObservationService_ReportClusterEvent_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // ObservationServiceServer is the server API for ObservationService service. // All implementations must embed UnimplementedObservationServiceServer // for forward compatibility @@ -73,6 +88,10 @@ type ObservationServiceServer interface { // authority.HeartbeatMessage, calls ObservationHost.Ingest. // Ack is diagnostic only. ReportHeartbeat(context.Context, *HeartbeatReport) (*HeartbeatAck, error) + // Node/CSI observation event. This appends an operator timeline event only; + // it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or + // replica state. + ReportClusterEvent(context.Context, *ClusterEvent) (*ClusterEventAck, error) mustEmbedUnimplementedObservationServiceServer() } @@ -83,6 +102,9 @@ type UnimplementedObservationServiceServer struct { func (UnimplementedObservationServiceServer) ReportHeartbeat(context.Context, *HeartbeatReport) (*HeartbeatAck, error) { return nil, status.Errorf(codes.Unimplemented, "method ReportHeartbeat not implemented") } +func (UnimplementedObservationServiceServer) ReportClusterEvent(context.Context, *ClusterEvent) (*ClusterEventAck, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReportClusterEvent not implemented") +} func (UnimplementedObservationServiceServer) mustEmbedUnimplementedObservationServiceServer() {} // UnsafeObservationServiceServer may be embedded to opt out of forward compatibility for this service. @@ -114,6 +136,24 @@ func _ObservationService_ReportHeartbeat_Handler(srv interface{}, ctx context.Co return interceptor(ctx, in, info, handler) } +func _ObservationService_ReportClusterEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ClusterEvent) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ObservationServiceServer).ReportClusterEvent(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ObservationService_ReportClusterEvent_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ObservationServiceServer).ReportClusterEvent(ctx, req.(*ClusterEvent)) + } + return interceptor(ctx, in, info, handler) +} + // ObservationService_ServiceDesc is the grpc.ServiceDesc for ObservationService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -125,6 +165,10 @@ var ObservationService_ServiceDesc = grpc.ServiceDesc{ MethodName: "ReportHeartbeat", Handler: _ObservationService_ReportHeartbeat_Handler, }, + { + MethodName: "ReportClusterEvent", + Handler: _ObservationService_ReportClusterEvent_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "control.proto", @@ -353,6 +397,273 @@ var EvidenceService_ServiceDesc = grpc.ServiceDesc{ Metadata: "control.proto", } +const ( + ClusterEvidenceService_GetClusterStatus_FullMethodName = "/seaweedfs.block.control.ClusterEvidenceService/GetClusterStatus" + ClusterEvidenceService_ListVolumes_FullMethodName = "/seaweedfs.block.control.ClusterEvidenceService/ListVolumes" + ClusterEvidenceService_GetVolumeStatus_FullMethodName = "/seaweedfs.block.control.ClusterEvidenceService/GetVolumeStatus" + ClusterEvidenceService_GetVolumeTimeline_FullMethodName = "/seaweedfs.block.control.ClusterEvidenceService/GetVolumeTimeline" + ClusterEvidenceService_WatchClusterEvents_FullMethodName = "/seaweedfs.block.control.ClusterEvidenceService/WatchClusterEvents" +) + +// ClusterEvidenceServiceClient is the client API for ClusterEvidenceService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type ClusterEvidenceServiceClient interface { + GetClusterStatus(ctx context.Context, in *GetClusterStatusRequest, opts ...grpc.CallOption) (*ClusterStatusResponse, error) + ListVolumes(ctx context.Context, in *ListVolumesRequest, opts ...grpc.CallOption) (*ListVolumesResponse, error) + GetVolumeStatus(ctx context.Context, in *GetVolumeStatusRequest, opts ...grpc.CallOption) (*VolumeEvidence, error) + GetVolumeTimeline(ctx context.Context, in *GetVolumeTimelineRequest, opts ...grpc.CallOption) (*VolumeTimelineResponse, error) + WatchClusterEvents(ctx context.Context, in *WatchClusterEventsRequest, opts ...grpc.CallOption) (ClusterEvidenceService_WatchClusterEventsClient, error) +} + +type clusterEvidenceServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewClusterEvidenceServiceClient(cc grpc.ClientConnInterface) ClusterEvidenceServiceClient { + return &clusterEvidenceServiceClient{cc} +} + +func (c *clusterEvidenceServiceClient) GetClusterStatus(ctx context.Context, in *GetClusterStatusRequest, opts ...grpc.CallOption) (*ClusterStatusResponse, error) { + out := new(ClusterStatusResponse) + err := c.cc.Invoke(ctx, ClusterEvidenceService_GetClusterStatus_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *clusterEvidenceServiceClient) ListVolumes(ctx context.Context, in *ListVolumesRequest, opts ...grpc.CallOption) (*ListVolumesResponse, error) { + out := new(ListVolumesResponse) + err := c.cc.Invoke(ctx, ClusterEvidenceService_ListVolumes_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *clusterEvidenceServiceClient) GetVolumeStatus(ctx context.Context, in *GetVolumeStatusRequest, opts ...grpc.CallOption) (*VolumeEvidence, error) { + out := new(VolumeEvidence) + err := c.cc.Invoke(ctx, ClusterEvidenceService_GetVolumeStatus_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *clusterEvidenceServiceClient) GetVolumeTimeline(ctx context.Context, in *GetVolumeTimelineRequest, opts ...grpc.CallOption) (*VolumeTimelineResponse, error) { + out := new(VolumeTimelineResponse) + err := c.cc.Invoke(ctx, ClusterEvidenceService_GetVolumeTimeline_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *clusterEvidenceServiceClient) WatchClusterEvents(ctx context.Context, in *WatchClusterEventsRequest, opts ...grpc.CallOption) (ClusterEvidenceService_WatchClusterEventsClient, error) { + stream, err := c.cc.NewStream(ctx, &ClusterEvidenceService_ServiceDesc.Streams[0], ClusterEvidenceService_WatchClusterEvents_FullMethodName, opts...) + if err != nil { + return nil, err + } + x := &clusterEvidenceServiceWatchClusterEventsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type ClusterEvidenceService_WatchClusterEventsClient interface { + Recv() (*ClusterEvent, error) + grpc.ClientStream +} + +type clusterEvidenceServiceWatchClusterEventsClient struct { + grpc.ClientStream +} + +func (x *clusterEvidenceServiceWatchClusterEventsClient) Recv() (*ClusterEvent, error) { + m := new(ClusterEvent) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// ClusterEvidenceServiceServer is the server API for ClusterEvidenceService service. +// All implementations must embed UnimplementedClusterEvidenceServiceServer +// for forward compatibility +type ClusterEvidenceServiceServer interface { + GetClusterStatus(context.Context, *GetClusterStatusRequest) (*ClusterStatusResponse, error) + ListVolumes(context.Context, *ListVolumesRequest) (*ListVolumesResponse, error) + GetVolumeStatus(context.Context, *GetVolumeStatusRequest) (*VolumeEvidence, error) + GetVolumeTimeline(context.Context, *GetVolumeTimelineRequest) (*VolumeTimelineResponse, error) + WatchClusterEvents(*WatchClusterEventsRequest, ClusterEvidenceService_WatchClusterEventsServer) error + mustEmbedUnimplementedClusterEvidenceServiceServer() +} + +// UnimplementedClusterEvidenceServiceServer must be embedded to have forward compatible implementations. +type UnimplementedClusterEvidenceServiceServer struct { +} + +func (UnimplementedClusterEvidenceServiceServer) GetClusterStatus(context.Context, *GetClusterStatusRequest) (*ClusterStatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetClusterStatus not implemented") +} +func (UnimplementedClusterEvidenceServiceServer) ListVolumes(context.Context, *ListVolumesRequest) (*ListVolumesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListVolumes not implemented") +} +func (UnimplementedClusterEvidenceServiceServer) GetVolumeStatus(context.Context, *GetVolumeStatusRequest) (*VolumeEvidence, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetVolumeStatus not implemented") +} +func (UnimplementedClusterEvidenceServiceServer) GetVolumeTimeline(context.Context, *GetVolumeTimelineRequest) (*VolumeTimelineResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetVolumeTimeline not implemented") +} +func (UnimplementedClusterEvidenceServiceServer) WatchClusterEvents(*WatchClusterEventsRequest, ClusterEvidenceService_WatchClusterEventsServer) error { + return status.Errorf(codes.Unimplemented, "method WatchClusterEvents not implemented") +} +func (UnimplementedClusterEvidenceServiceServer) mustEmbedUnimplementedClusterEvidenceServiceServer() { +} + +// UnsafeClusterEvidenceServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ClusterEvidenceServiceServer will +// result in compilation errors. +type UnsafeClusterEvidenceServiceServer interface { + mustEmbedUnimplementedClusterEvidenceServiceServer() +} + +func RegisterClusterEvidenceServiceServer(s grpc.ServiceRegistrar, srv ClusterEvidenceServiceServer) { + s.RegisterService(&ClusterEvidenceService_ServiceDesc, srv) +} + +func _ClusterEvidenceService_GetClusterStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetClusterStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ClusterEvidenceServiceServer).GetClusterStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ClusterEvidenceService_GetClusterStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ClusterEvidenceServiceServer).GetClusterStatus(ctx, req.(*GetClusterStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ClusterEvidenceService_ListVolumes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListVolumesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ClusterEvidenceServiceServer).ListVolumes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ClusterEvidenceService_ListVolumes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ClusterEvidenceServiceServer).ListVolumes(ctx, req.(*ListVolumesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ClusterEvidenceService_GetVolumeStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetVolumeStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ClusterEvidenceServiceServer).GetVolumeStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ClusterEvidenceService_GetVolumeStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ClusterEvidenceServiceServer).GetVolumeStatus(ctx, req.(*GetVolumeStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ClusterEvidenceService_GetVolumeTimeline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetVolumeTimelineRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ClusterEvidenceServiceServer).GetVolumeTimeline(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ClusterEvidenceService_GetVolumeTimeline_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ClusterEvidenceServiceServer).GetVolumeTimeline(ctx, req.(*GetVolumeTimelineRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ClusterEvidenceService_WatchClusterEvents_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(WatchClusterEventsRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ClusterEvidenceServiceServer).WatchClusterEvents(m, &clusterEvidenceServiceWatchClusterEventsServer{stream}) +} + +type ClusterEvidenceService_WatchClusterEventsServer interface { + Send(*ClusterEvent) error + grpc.ServerStream +} + +type clusterEvidenceServiceWatchClusterEventsServer struct { + grpc.ServerStream +} + +func (x *clusterEvidenceServiceWatchClusterEventsServer) Send(m *ClusterEvent) error { + return x.ServerStream.SendMsg(m) +} + +// ClusterEvidenceService_ServiceDesc is the grpc.ServiceDesc for ClusterEvidenceService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ClusterEvidenceService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "seaweedfs.block.control.ClusterEvidenceService", + HandlerType: (*ClusterEvidenceServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetClusterStatus", + Handler: _ClusterEvidenceService_GetClusterStatus_Handler, + }, + { + MethodName: "ListVolumes", + Handler: _ClusterEvidenceService_ListVolumes_Handler, + }, + { + MethodName: "GetVolumeStatus", + Handler: _ClusterEvidenceService_GetVolumeStatus_Handler, + }, + { + MethodName: "GetVolumeTimeline", + Handler: _ClusterEvidenceService_GetVolumeTimeline_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "WatchClusterEvents", + Handler: _ClusterEvidenceService_WatchClusterEvents_Handler, + ServerStreams: true, + }, + }, + Metadata: "control.proto", +} + const ( LifecycleService_CreateVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/CreateVolume" LifecycleService_DeleteVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/DeleteVolume" diff --git a/seaweed-block/core/rpc/proto/control.proto b/seaweed-block/core/rpc/proto/control.proto index c4e71e9d45..6a05909e33 100644 --- a/seaweed-block/core/rpc/proto/control.proto +++ b/seaweed-block/core/rpc/proto/control.proto @@ -4,6 +4,7 @@ // volume -> master: ObservationService.ReportHeartbeat (unary) // volume -> master: AssignmentService.SubscribeAssignments (server-streaming) // operator -> master: EvidenceService.QueryVolumeStatus (unary, read-only) +// operator/dashboard -> master: ClusterEvidenceService read-only observation // CSI/operator -> master: LifecycleService.CreateVolume/DeleteVolume (desired intent only) // // Boundary (T0 sketch §3 load-bearing): @@ -27,6 +28,11 @@ service ObservationService { // authority.HeartbeatMessage, calls ObservationHost.Ingest. // Ack is diagnostic only. rpc ReportHeartbeat(HeartbeatReport) returns (HeartbeatAck); + + // Node/CSI observation event. This appends an operator timeline event only; + // it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or + // replica state. + rpc ReportClusterEvent(ClusterEvent) returns (ClusterEventAck); } // AssignmentService — master publishes minted AssignmentInfo to @@ -60,6 +66,18 @@ service EvidenceService { rpc QueryVolumeStatus(StatusRequest) returns (StatusResponse); } +// ClusterEvidenceService — dashboard-grade read-only observation surface. +// This service exposes the same evidence model as `sw-block ops ...` and +// MUST NOT mutate lifecycle, authority, placement, Kubernetes, or replica +// state. +service ClusterEvidenceService { + rpc GetClusterStatus(GetClusterStatusRequest) returns (ClusterStatusResponse); + rpc ListVolumes(ListVolumesRequest) returns (ListVolumesResponse); + rpc GetVolumeStatus(GetVolumeStatusRequest) returns (VolumeEvidence); + rpc GetVolumeTimeline(GetVolumeTimelineRequest) returns (VolumeTimelineResponse); + rpc WatchClusterEvents(WatchClusterEventsRequest) returns (stream ClusterEvent); +} + // LifecycleService — product lifecycle intent. This surface is for CSI / // operators to record desired volume state. It MUST NOT carry assignment, // epoch, endpoint_version, readiness, or primary facts. @@ -116,6 +134,11 @@ message HeartbeatAck { uint64 sequence = 2; } +message ClusterEventAck { + google.protobuf.Timestamp accepted_at = 1; + string event_id = 2; +} + message SubscribeRequest { string volume_id = 1; string replica_id = 2; @@ -190,6 +213,133 @@ message StatusResponse { repeated FrontendTarget frontends = 8; } +message GetClusterStatusRequest { +} + +message ListVolumesRequest { +} + +message GetVolumeStatusRequest { + string volume_id = 1; +} + +message GetVolumeTimelineRequest { + string volume_id = 1; +} + +message WatchClusterEventsRequest { + string since_event_id = 1; +} + +message ObservationCondition { + string type = 1; + string status = 2; + string reason = 3; + string severity = 4; + string message = 5; +} + +message ClusterStatusResponse { + string schema_version = 1; + google.protobuf.Timestamp captured_at = 2; + string product_revision = 3; + string status = 4; + repeated NodeEvidence nodes = 5; + repeated VolumeEvidence volumes = 6; + repeated ObservationCondition conditions = 7; + repeated ClusterEvent events = 8; + repeated string non_claims = 9; +} + +message NodeEvidence { + string node_name = 1; + string kubernetes_node = 2; + string physical_host = 3; + string internal_ip = 4; + bool schedulable = 5; + bool ready = 6; + google.protobuf.Timestamp last_heartbeat_at = 7; + int32 replica_count = 8; + repeated string required_images = 9; + repeated string missing_images = 10; + repeated ObservationCondition conditions = 11; +} + +message VolumeEvidence { + string volume_id = 1; + string namespace = 2; + string pvc_name = 3; + string pv_name = 4; + int32 replication_factor = 5; + string ack_profile = 6; + string claim_profile = 7; + int32 desired_replicas = 8; + int32 observed_replicas = 9; + string status = 10; + string reason = 11; + string primary_replica = 12; + string primary_node = 13; + string publish_target = 14; + uint64 epoch = 15; + uint64 endpoint_version = 16; + repeated ReplicaEvidence replicas = 17; + repeated ObservationCondition conditions = 18; + repeated string next_actions = 19; + string support_bundle_hint = 20; +} + +message ReplicaEvidence { + string replica_id = 1; + string server_id = 2; + string kubernetes_node = 3; + string physical_host = 4; + bool observed = 5; + string role = 6; + string replication_role = 7; + bool durable_latched = 8; + bool durable_frontier_known = 9; + uint64 durable_frontier_lsn = 10; + bool candidate_ready = 11; + string candidate_ready_reason = 12; + string frontend_protocol = 13; + string frontend_addr = 14; + string status_addr = 15; + bool stale_primary_fenced = 16; + repeated ObservationCondition conditions = 17; + string support_bundle_path = 18; +} + +message ClusterEvent { + string event_id = 1; + google.protobuf.Timestamp event_time = 2; + string volume_id = 3; + string replica_id = 4; + string node_name = 5; + string event_type = 6; + string severity = 7; + string message = 8; + string reason_code = 9; + string old_value = 10; + string new_value = 11; + uint64 epoch = 12; + uint64 endpoint_version = 13; + string correlation_id = 14; + string evidence_ref = 15; +} + +message ListVolumesResponse { + string schema_version = 1; + google.protobuf.Timestamp captured_at = 2; + repeated VolumeEvidence volumes = 3; +} + +message VolumeTimelineResponse { + string schema_version = 1; + google.protobuf.Timestamp captured_at = 2; + string volume_id = 3; + repeated ClusterEvent events = 4; +} + message CreateVolumeRequest { string volume_id = 1; uint64 size_bytes = 2; diff --git a/seaweed-block/deploy/k8s/alpha/block-stack.yaml b/seaweed-block/deploy/k8s/alpha/block-stack.yaml index 3b8727ba8e..03499f6be8 100644 --- a/seaweed-block/deploy/k8s/alpha/block-stack.yaml +++ b/seaweed-block/deploy/k8s/alpha/block-stack.yaml @@ -5,15 +5,7 @@ metadata: namespace: kube-system data: cluster-spec.yaml: | - nodes: - - server_id: __NODE_NAME__ - data_addr: 127.0.0.1:19101 - ctrl_addr: 127.0.0.1:19102 - pools: - - pool_id: default - total_bytes: 1073741824 - free_bytes: 1073741824 - block_size: 4096 + # __CLUSTER_SPEC_NODES__ --- apiVersion: apps/v1 kind: Deployment @@ -30,6 +22,8 @@ spec: labels: app: sw-blockmaster spec: + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet serviceAccountName: sw-block-master containers: - name: blockmaster @@ -47,10 +41,12 @@ spec: - "--launcher-image=sw-block:local" - "--launcher-namespace=kube-system" - "--launcher-durable-root=/var/lib/sw-block" + - "--launcher-status" + - "--launcher-replication-ack=__REPLICATION_ACK__" - "--launcher-iscsi-port-base=3260" - "--launcher-kubernetes-apply" - "--listen=0.0.0.0:9333" - - "--expected-slots-per-volume=1" + - "--expected-slots-per-volume=__EXPECTED_SLOTS_PER_VOLUME__" ports: - name: grpc containerPort: 9333 diff --git a/seaweed-block/deploy/k8s/alpha/csi-driver.yaml b/seaweed-block/deploy/k8s/alpha/csi-driver.yaml index 216b24c9d6..f3279bb648 100644 --- a/seaweed-block/deploy/k8s/alpha/csi-driver.yaml +++ b/seaweed-block/deploy/k8s/alpha/csi-driver.yaml @@ -5,5 +5,6 @@ metadata: spec: attachRequired: true podInfoOnMount: false + fsGroupPolicy: File volumeLifecycleModes: - Persistent diff --git a/seaweed-block/deploy/k8s/alpha/csi-node.yaml b/seaweed-block/deploy/k8s/alpha/csi-node.yaml index 7b49eed763..2357b9c24c 100644 --- a/seaweed-block/deploy/k8s/alpha/csi-node.yaml +++ b/seaweed-block/deploy/k8s/alpha/csi-node.yaml @@ -14,6 +14,7 @@ spec: spec: serviceAccountName: sw-block-csi hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet hostPID: true initContainers: - name: load-iscsi-tcp @@ -21,7 +22,7 @@ spec: imagePullPolicy: Never command: ["/bin/sh", "-c"] args: - - "modprobe iscsi_tcp || true; modprobe nvme_tcp || true" + - "modprobe iscsi_tcp || true; modprobe nvme_tcp || true; modprobe dm_multipath || true; modprobe scsi_dh_alua || true" securityContext: privileged: true volumeMounts: @@ -34,8 +35,11 @@ spec: imagePullPolicy: Never args: - "--endpoint=unix:///csi/csi.sock" + - "--master=$(BLOCKMASTER_ADDR)" - "--node-id=$(NODE_NAME)" env: + - name: BLOCKMASTER_ADDR + value: "blockmaster.kube-system.svc.cluster.local:9333" - name: NODE_NAME valueFrom: fieldRef: @@ -52,6 +56,9 @@ spec: mountPath: /dev - name: iscsi-dir mountPath: /etc/iscsi + - name: udev-run + mountPath: /run/udev + readOnly: true - name: csi-node-driver-registrar image: registry.k8s.io/sig-storage/csi-node-driver-registrar:v2.13.0 args: @@ -79,6 +86,10 @@ spec: hostPath: path: /etc/iscsi type: DirectoryOrCreate + - name: udev-run + hostPath: + path: /run/udev + type: Directory - name: modules-dir hostPath: path: /lib/modules diff --git a/seaweed-block/deploy/k8s/alpha/rbac.yaml b/seaweed-block/deploy/k8s/alpha/rbac.yaml index 881dfb1998..ad745253ac 100644 --- a/seaweed-block/deploy/k8s/alpha/rbac.yaml +++ b/seaweed-block/deploy/k8s/alpha/rbac.yaml @@ -11,27 +11,25 @@ metadata: namespace: kube-system --- apiVersion: rbac.authorization.k8s.io/v1 -kind: Role +kind: ClusterRole metadata: name: sw-block-master-launcher - namespace: kube-system rules: - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get", "list", "watch", "create", "delete", "update", "patch"] --- apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding +kind: ClusterRoleBinding metadata: name: sw-block-master-launcher - namespace: kube-system subjects: - kind: ServiceAccount name: sw-block-master namespace: kube-system roleRef: apiGroup: rbac.authorization.k8s.io - kind: Role + kind: ClusterRole name: sw-block-master-launcher --- apiVersion: rbac.authorization.k8s.io/v1 diff --git a/seaweed-block/deploy/k8s/alpha/storageclass.yaml b/seaweed-block/deploy/k8s/alpha/storageclass.yaml new file mode 100644 index 0000000000..a6022626fe --- /dev/null +++ b/seaweed-block/deploy/k8s/alpha/storageclass.yaml @@ -0,0 +1,9 @@ +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: sw-block-dynamic +provisioner: block.csi.seaweedfs.com +volumeBindingMode: Immediate +allowVolumeExpansion: false +parameters: + replicationFactor: "1" diff --git a/seaweed-block/deploy/k8s/g15b/Dockerfile.blockcsi b/seaweed-block/deploy/k8s/g15b/Dockerfile.blockcsi index d7174dfb21..8dee998826 100644 --- a/seaweed-block/deploy/k8s/g15b/Dockerfile.blockcsi +++ b/seaweed-block/deploy/k8s/g15b/Dockerfile.blockcsi @@ -12,8 +12,10 @@ RUN apt-get update && \ apt-get install -y --no-install-recommends \ e2fsprogs \ kmod \ + multipath-tools \ nvme-cli \ open-iscsi \ + sg3-utils \ util-linux && \ rm -rf /var/lib/apt/lists/* diff --git a/seaweed-block/deploy/k8s/g15b/csi-node.yaml b/seaweed-block/deploy/k8s/g15b/csi-node.yaml index 7b49eed763..c4685471a1 100644 --- a/seaweed-block/deploy/k8s/g15b/csi-node.yaml +++ b/seaweed-block/deploy/k8s/g15b/csi-node.yaml @@ -14,6 +14,7 @@ spec: spec: serviceAccountName: sw-block-csi hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet hostPID: true initContainers: - name: load-iscsi-tcp @@ -34,8 +35,11 @@ spec: imagePullPolicy: Never args: - "--endpoint=unix:///csi/csi.sock" + - "--master=$(BLOCKMASTER_ADDR)" - "--node-id=$(NODE_NAME)" env: + - name: BLOCKMASTER_ADDR + value: "blockmaster.kube-system.svc.cluster.local:9333" - name: NODE_NAME valueFrom: fieldRef: diff --git a/seaweed-block/docs/operations-v1.md b/seaweed-block/docs/operations-v1.md index 45e5fecac2..e9c260b057 100644 --- a/seaweed-block/docs/operations-v1.md +++ b/seaweed-block/docs/operations-v1.md @@ -23,15 +23,21 @@ Claimed in this manual: - durable restart of a generated RF=1 `blockvolume` when an explicit launcher hostPath is configured, - read-only cluster inventory with per-replica support bundles, +- RF=2 `best-effort` controlled recovery as a development/TestOps demo profile, +- RF=3 `sync-quorum` mounted recovery through CSI/pod recreate as the Stage 1 + beta recovery target, +- gated RF=3 `sync-quorum` Kubernetes node-loss recovery through CSI/pod + recreate when the Node-Loss Survival gate artifacts are present, - scoped cleanup checks for the demo PVC and generated workload. Not claimed: -- production HA, -- node loss or host-disk failure, +- transparent production HA without pod recreate, +- transparent node-loss, physical-host loss, or host-disk failure, - remote-node attach to a loopback-published `blockvolume`, - automatic multi-node scheduling, rescheduling, or rebalancing, -- live RF=2/RF=3 Kubernetes lifecycle, +- RF=2 quorum HA after primary failure, +- transparent in-place mounted I/O continuation, - upgrade or broad uninstall safety, - repair, rebuild, promote, backup, or restore commands, - performance SLOs, @@ -315,6 +321,131 @@ Attach the entire inventory directory to issues. It contains: - `ops-inventory-bundle.json`, - nested `sw-block ops status` artifacts when status endpoints are reachable. +### AI-Readable Control-Plane Status + +The read-only inventory bundle above remains the safest support artifact for +replica-level details. The newer control-plane observation path adds a +product-owned cluster snapshot and timeline that a user, support engineer, +dashboard, CI job, or AI assistant can read without reconstructing events from +TestOps logs. + +Port-forward the running `blockmaster` Deployment: + +```bash +kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333 +``` + +Then export the master-owned cluster evidence: + +```bash +sw-block ops cluster --master-api 127.0.0.1:9333 -o json \ + > /tmp/sw-block-cluster-evidence.json +``` + +The JSON contains: + +- `nodes`: Kubernetes nodes and product server identities known to + `blockmaster`, +- `volumes`: PVC/volume/replica placement, primary, publish target, epoch, and + endpoint version, +- `events`: product-owned timeline events with stable reason codes, + master-minted `event_id`, and `event_time`. + +For support, attach `/tmp/sw-block-cluster-evidence.json` together with the +inventory directory. The cluster evidence answers what the control plane +believes happened; the inventory bundle answers what Kubernetes and each +replica reported at collection time. + +User-facing commands follow this shape: + +```bash +sw-block ops cluster +sw-block ops cluster --master-api 127.0.0.1:9333 -o json +sw-block ops volumes +sw-block ops describe volume +sw-block ops timeline volume +sw-block ops timeline volume -o jsonl +sw-block ops explain volume +sw-block ops report --master-api 127.0.0.1:9333 --out /tmp/sw-block-report +sw-block ops report --from-bundle --out /tmp/sw-block-report +sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out /tmp/sw-block-inventory +``` + +`sw-block ops cluster --master-api` reads the product-owned master API. +`sw-block ops inventory` and bundle-backed `describe`/`timeline`/`explain` +commands remain useful when diagnosing from saved artifacts. +`sw-block ops report` writes a local read-only status page plus JSON/JSONL +artifacts from the same observation core; it is a dashboard-shaped artifact, not +a mutating admin UI. + +The long-term design is one shared observation core with three consumers: + +- `sw-block ops ...` text for users, support, QA, and AI, +- `sw-block ops ... -o json|jsonl` for automation and support bundles, +- master read-only API for a future dashboard. + +The dashboard view should answer five questions without requiring internal +knowledge: + +- Which PVC and volume are affected? +- Which replica is primary, and on which Kubernetes node? +- Is the volume `ok`, `degraded`, `recovering`, or `blocked`? +- If recovery happened, which frontend did CSI attach to before and after? +- What is the next operator action? + +Example healthy shape: + +```text +volume pvc-... status=ok rf=3 ack=sync-quorum +pvc default/mysql-data +primary r1 on m01 frontend=192.168.1.181:3260 +replicas desired=3 observed=3 +r1 m01 primary ready durable_lsn=44 +r2 m02 replica_ready candidate_ready=true durable_lsn=44 +r3 tp01 replica_ready candidate_ready=true durable_lsn=44 +next action: none +``` + +Example recovering shape: + +```text +volume pvc-... status=recovering reason=primary_node_lost +old primary r1 on m01 unavailable +promoted primary r2 on m02 epoch=2 endpoint_version=1 +CSI target changed 192.168.1.181:3260 -> 192.168.1.184:3260 +reattach method: pod_recreate +next action: wait for app pod readiness, then collect support bundle if stuck +``` + +Example blocked shape: + +```text +volume pvc-... status=blocked reason=no_promotion_ready_candidate +r2 candidate_ready=false reason=durable_frontier_missing +r3 candidate_ready=false reason=candidate_frontier_behind +next action: collect support bundle; do not force promote without support review +``` + +Example attach/install blocked shape: + +```text +volume pvc-... status=blocked reason=csi_node_image_pull_failed +node m02 missing image sw-block-csi:local +pod kube-system/sw-block-csi-node-... waiting=ImagePullBackOff +impact: PVC attach cannot proceed on workloads scheduled to m02 +next action: import the image to m02 or use a registry reachable by all nodes +``` + +The first dashboard and AI assistant path must stay read-only. It should not +expose promote, repair, rebuild, backup, restore, or cleanup buttons until +those actions have separate strict gates. + +Support bundles for attach/install failures should include Kubernetes runtime +evidence in addition to Seaweed Block inventory: `kubectl get pods -A -o wide`, +recent namespace events, `kubectl describe pod` for `sw-blockmaster`, +`sw-block-csi-*`, generated `sw-blockvolume` pods, CSI logs, blockmaster logs, +and per-node product image presence. + ## 7. Delete And Verify Scoped Cleanup For the demo resources: @@ -374,6 +505,8 @@ Common issue classes: ```text generated_deployment_missing +observed_replicas=0 desired_replicas=2 +replica_slot_missing=unknown orphan-blockvolume-deploy= blockvolume-process-without-placement= status_endpoint_unavailable @@ -382,6 +515,267 @@ unsupported_cross_node_loopback_attach ops_status=unhealthy reason=authority_not_assigned ... ``` +### Mounted Recovery ACK Profiles + +Stage 1 mounted recovery has two validated ACK profiles. Keep them separate +when reporting results or setting user expectations. + +| Profile | Claim label | Validated meaning | +| --- | --- | --- | +| RF=2 `best-effort` | `controlled-best-effort-demo` | Development/TestOps recovery demonstration. It proves the mounted app path, scoped primary stop, master promotion, CSI/pod recreate, and reader checksum for the gated bytes. It is not a quorum durability claim. | +| RF=3 `sync-quorum` | `beta-recovery` | Stage 1 durable mounted recovery target. It proves candidate promotion only after the sync ACK frontier is covered, single-primary authority publication, CSI/pod recreate re-stage to the promoted frontend, and post-failure reader checksum. | + +Stage 1 recovery still uses CSI/node reattach through pod recreate. It does not +claim transparent in-place I/O continuation. Transparent host-path switching +requires the later multipath line: iSCSI ALUA plus dm-multipath, or NVMe ANA +plus native multipath. + +Reserved Stage 2 claim profile: + +| Profile | Claim label | Validation status | +| --- | --- | --- | +| RF=3 `sync-quorum` + iSCSI ALUA | `stage2-iscsi-alua-multipath` | Reserved for the dm-multipath path where the mounted workload stays in place and recovery is proven through ALUA path-state evidence plus a post-failure data check. It is not valid with `best-effort`; the close gate must prove it before it becomes an external recovery claim. | + +#### Stage 2 iSCSI ALUA / dm-multipath Mounted Failover + +Stage 2 is the transparent mounted-host-path recovery line. It is different +from Stage 1: the workload pod is not recreated, CSI does not re-stage the +volume, and the Linux host must keep one dm-multipath device online while ALUA +path state moves from the failed primary path to the promoted path. + +The validated Stage 2 contract is: + +```text +protocol=iscsi +host_multipath=dm-multipath +ack_profile=sync-quorum +claim_profile=stage2-iscsi-alua-multipath +replication=RF3 +recovery=mounted workload verifies data without pod recreate +``` + +Host prerequisites for this path: + +```text +iscsiadm present +multipath present +sg_rtpg or equivalent RTPG reader present +sg_inq present +kernel modules: iscsi_tcp, dm_multipath, scsi_dh_alua +udev device state available under /run/udev +``` + +The support bundle must show: + +```text +pod_recreate_used=false +transparent_failover_claimed=true +before_primary_replica= +promoted_replica= +post_failure_primary_count=1 +old_primary_stale_io_success_count=0 +data_check_after_failover=mounted_workload_checksum_passed +bounded_waits=pass +``` + +Host-path evidence must include one shared iSCSI IQN with multiple portals, one +dm-multipath device with multiple paths, and RTPG/ALUA state showing the +primary path changed after promotion. A recovery that only succeeds after pod +recreate belongs to Stage 1 and must not be reported as Stage 2. + +Stage 2 still does not claim node loss, NVMe ANA Kubernetes recovery, Windows +MPIO, broad distro compatibility, performance/RTO SLOs, or automatic +repair/rebuild/failback. + +#### Stage 3 Node-Loss Survival Gate + +Stage 3 is the Kubernetes node-loss recovery line. It is different from Stage +2: the first node-loss close uses CSI/pod recreate reattach, not transparent +mounted I/O continuation. The storage control plane must promote a surviving +RF=3 `sync-quorum` replica, and the replacement pod must attach to the promoted +non-loopback frontend on a surviving Kubernetes node. + +The active gate contract is: + +```text +protocol=iscsi +replication=RF3 +ack_profile=sync-quorum +frontends=non-loopback +topology=3 Kubernetes nodes; physical-host/fault-domain sharing disclosed +failure=controlled primary Kubernetes node loss or equivalent node isolation +recovery=CSI/pod recreate reattach to surviving promoted frontend +transparent_failover_claimed=false +node_loss_recovery_claimed=true +``` + +The current lab validation is TCP/iSCSI over the LAN (`192.168.1.x`). It does +not use the RoCE/RDMA fabric (`10.0.0.x`), and it does not support NVMe/RDMA or +performance claims. + +The support bundle must show: + +```text +node-loss-recovery-summary.txt +replicas_on_distinct_nodes=true +frontends_non_loopback=true +before_primary_replica= +before_primary_node= +failed_replica= +failed_node= +promoted_replica= +promoted_replica_node= +post_failure_primary_count=1 +before_publish_target_frontend= +after_publish_target_frontend= +pod_recreate_used=true +transparent_failover_claimed=false +node_loss_recovery_claimed=true +data_check_after_node_loss=reader_checksum_passed +old_primary_stale_io_success_count=0 +bounded_waits=pass +physical_host_loss_claimed=false +``` + +This gate does not claim transparent node-loss, NVMe ANA node-loss, arbitrary +network partition tolerance, rebuild/failback, RTO/SLO, or production HA +outside the tested topology. If three Kubernetes nodes share fewer physical +machines, the report must keep `physical_host_loss_claimed=false`; that is a +Kubernetes-node-loss proof, not a full physical-host-loss proof. + +#### RF=2 Mounted Failover Status + +RF=2 Kubernetes lifecycle has three validated alpha boundaries: + +1. On the default single-logical-server alpha topology, an RF=2 PVC is refused + safely. The PVC may bind, but the product must not launch a partial + one-replica `blockvolume` and call it healthy. +2. On the development/TestOps two-logical-server alpha topology, the mounted + app path can write and read through an RF=2 PVC while inventory sees two + generated replicas. Controlled primary failure is still a safe-refusal path + when the peer replica is not promotion-ready. +3. On the same development/TestOps topology with `ack_profile=best-effort` and + `claim_profile=controlled-best-effort-demo`, controlled primary failure can + promote a ready peer and recover through CSI/pod recreate with a reader + checksum. This is a demo profile only; it must not be described as quorum + HA. + +The safe-refusal behavior remains valid when the peer is not promotion-ready: + +```text +writer writes and verifies data +before-failure inventory identifies primary=r1 +r2 is visible but not promotion-ready +r1 blockvolume is stopped in a scoped way +product emits failover_status: refused +data_check_after_failover=not_claimed +reason=candidate_not_ready_for_primary +``` + +The product must not start a replacement reader and claim checksum recovery +unless a separate gate proves a ready candidate, authority movement, and +reattach/readback. + +Default single-logical-server refusal shape: + +The supported operator check is inventory: + +```text +inventory_status: unhealthy +volume: ... rf=2 desired=2 observed=0 ... +issues: +- volume ... generated_deployment_missing +- volume ... observed_replicas=0 desired_replicas=2 +- volume ... replica_slot_missing=unknown +``` + +That means the product preserved the requested RF=2 intent and refused to create +an unsafe partial failover topology. It is not a recovery success; it is an +honest safe-refusal state. + +For development and TestOps only, the alpha installer can opt into two logical +Seaweed Block server identities on the same Kubernetes node: + +```bash +SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 \ +SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 \ + bash scripts/install-k8s-alpha.sh "$PWD" +``` + +This is a placement/failover-lab shape, not a node-failure HA shape. The +generated `blockvolume` pods are scheduled to the same Kubernetes node, while +their `server_id`s, data/control ports, frontend ports, and status ports remain +distinct. It is useful for proving replica placement and process-level failover +mechanics before broad multi-node scheduling exists. + +In that two-logical-server shape, the currently validated RF=2 primary-failure +safe-refusal evidence is: + +```text +failover_status: refused +ack_profile: best-effort +failure_class=primary-blockvolume-controlled-stop +before_primary_replica=r1 +failed_replica=r1 +candidate_ready=false +candidate_evidence=replica: ... replica=r2 ... replication=not_ready ... +data_check_after_failover=not_claimed +reason=candidate_not_ready_for_primary +target_ready_replicas=0 +after_issue_evidence=- volume ... replica_degraded=... +``` + +Read this as: the writer path worked before the failure; the primary stop was +scoped and observable; the peer was not ready to become primary; recovery was +not claimed. + +The RF=2 controlled recovery demo shape, when the peer is promotion-ready, is: + +```text +ack_profile: best-effort +claim_profile=controlled-best-effort-demo +failover_status: promotion_pending -> promoted +data_check_after_failover: pending_reader -> reader_checksum_passed +reader_verified: true +``` + +Read this as: the exact gated demo bytes were recovered after promotion and +pod recreate. Do not read it as a sync-quorum or sync-all durability guarantee. + +#### RF=3 Sync-Quorum Mounted Recovery Status + +RF=3 `sync-quorum` is the Stage 1 beta-facing durable recovery profile. The +validated path is: + +```text +writer writes and verifies data +inventory identifies primary=r1 and promotion-ready candidate=r2 +candidate frontier covers the required sync ACK frontier +r1 blockvolume is stopped in a scoped way +master publishes r2 as the only primary +CSI/node re-stages the recreated pod to r2's frontend +reader verifies /data/demo.bin after failure +``` + +The expected recovery marker is: + +```text +ack_profile: sync-quorum +claim_profile=beta-recovery +failover_status: promotion_pending -> promoted +before_primary_replica=r1 +failed_replica=r1 +promoted_replica=r2 +frontier_covered=true +post_failure_primary_count=1 +data_check_after_failover: pending_reader -> reader_checksum_passed +reader_verified=true +``` + +This is a Stage 1 Kubernetes mounted recovery claim, not a transparent +multipath claim. The reader succeeds after pod recreate / CSI re-stage, not by +continuing in-place I/O through the original mounted path. + If no volume identity was reached, record that explicitly: ```text diff --git a/seaweed-block/docs/quickstart-kubernetes.md b/seaweed-block/docs/quickstart-kubernetes.md index e4d59308e0..3596cdb500 100644 --- a/seaweed-block/docs/quickstart-kubernetes.md +++ b/seaweed-block/docs/quickstart-kubernetes.md @@ -1,141 +1,188 @@ # Kubernetes Quick Start -This guide is for Kubernetes users who already have a test cluster and want to -see what the current alpha can do. +This guide is the alpha Day-1 path for Seaweed Block on Kubernetes. -For the longer install, inventory, cleanup, retry, and support-bundle path, see -[`operations-v1.md`](operations-v1.md). - -The current demo path is intentionally small: +It shows a normal user loop: ```text -app pod -> PVC -> CSI -> iSCSI -> blockvolume -> WAL-backed storage +preflight +-> install the alpha stack +-> create a PVC-backed volume +-> write data from one app pod +-> read the same data from a replacement app pod +-> collect status/report evidence +-> clean up ``` -It proves that a normal application pod can mount a `seaweed-block` PVC, write -data, exit, and then a second pod can mount the same PVC and read the data back. -It does not claim production durability or failover-under-mount yet. For the -explicit blockvolume restart durability path, see -[`operations-v1.md`](operations-v1.md#5-prove-durable-blockvolume-restart). +The current quickstart is for a supported test cluster, not production. +For deeper operational detail, see [`operations-v1.md`](operations-v1.md). -## What Runs +## What This Proves -The demo deploys: +The quickstart proves: -- `blockmaster`: the control-plane service that tracks desired volumes and - publishes assignments. -- `block-csi` controller: the CSI controller plugin plus Kubernetes CSI - sidecars. -- `block-csi` node: the privileged CSI node plugin that runs `iscsiadm` and - mounts the device for kubelet. -- one launcher-generated `blockvolume` Deployment for the PVC. -- two ordinary BusyBox app pods: writer first, reader second. +- Kubernetes can install the alpha blockmaster and CSI components. +- A PVC can dynamically provision a Seaweed Block-backed PV. +- A writer pod can mount the PVC and write `/data/demo.bin`. +- A replacement reader pod can mount the same PVC and verify the same data. +- Product-owned status evidence and a local read-only report are collected. +- The example resources are cleaned up. -The writer and reader are not simultaneous. The PVC is `ReadWriteOnce`; the demo -uses pod replacement to show that data is on the volume, not just inside the -first pod. +It does not prove production HA, backup/restore, upgrade safety, broad platform +compatibility, or a hosted dashboard. -## First Volume In 10 Minutes +## Prerequisites -This quick start is intentionally a same-node Kubernetes alpha path. On a -single-node cluster that is automatic. On a multi-node-capable cluster, the app -pod and generated `blockvolume` must be pinned to the same selected node because -the alpha iSCSI frontend is loopback (`127.0.0.1:`). Use it to prove the -first-volume workflow, not production readiness. +Run from a Linux host with access to your Kubernetes cluster: -Recommended path: local k3s build. This avoids relying on public GHCR alpha -packages and records the exact image IDs used by the cluster. +- `kubectl` configured for the target cluster. +- `sudo` access for iSCSI checks and cleanup. +- `iscsiadm` available on nodes that will stage volumes. +- `go` and Docker/container tools for the local dev path, unless you use + published images. + +Check the cluster: + +```bash +kubectl get nodes -o wide +sudo iscsiadm -m session || true +``` + +Expected before starting: + +```text +at least one Ready node +iscsiadm: No active sessions. +``` + +On a multi-node cluster, the activation script uses a non-loopback node +InternalIP plus CHAP-backed iSCSI for the Day-1 path. On a single-node cluster, +it may use the simpler local path. + +## Step 1 — Activate Seaweed Block + +From the repository root: ```bash export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}" - -# Optional. Defaults to the first Kubernetes node. -export SW_BLOCK_ALPHA_NODE_NAME="${SW_BLOCK_ALPHA_NODE_NAME:-m02}" -export SW_BLOCK_DEMO_APP_NODE_NAME="${SW_BLOCK_DEMO_APP_NODE_NAME:-$SW_BLOCK_ALPHA_NODE_NAME}" - -bash scripts/preflight-k8s-alpha.sh --local-k3s - -SW_BLOCK_IMPORT_K3S=1 \ -SW_BLOCK_ARTIFACT_DIR=/tmp/sw-block-alpha-build \ - bash scripts/build-alpha-images.sh "$PWD" - -bash scripts/run-alpha-app-demo.sh "$PWD" +bash scripts/activate-k8s-alpha.sh "$PWD" ``` +The script runs preflight, builds/imports local images into k3s, applies the +alpha manifests, waits for blockmaster and CSI readiness, creates the default +StorageClass, and writes an activation summary. + +Read the summary: + +```bash +cat "$(ls -td /tmp/sw-block-activation-* | head -1)/activation-summary.txt" +``` + +Expected fields include: + +```text +activation_status=ok +image_mode=local +protocol=iscsi +ack_profile=best-effort +ready_kubernetes_nodes= +master_ready_replicas=1 +csi_controller_ready_replicas=1 +csi_node_ready=/ +storageclass=sw-block-dynamic +next_create_volume=... +next_status=... +non_claims=... +``` + +If preflight fails, fix the environment first. Do not debug storage behavior +until `activation_status=ok`. + +## Step 2 — Create And Verify The First Volume + +Run the first-volume helper: + +```bash +bash scripts/run-basic-app-example.sh "$PWD" +``` + +The helper applies the example StorageClass/PVC, waits for the PVC to bind, +runs a writer pod, deletes it, runs a reader pod, collects status evidence, +generates a local report, and cleans the example resources by default. + Expected final line: ```text -[app-demo] PASS: app pod wrote data, replacement app pod read it back through the same PVC, cleanup complete +[basic-app] PASS: basic app PVC writer/reader loop complete ``` -This default demo proves PVC write/read through pod replacement. To also prove -that the generated `blockvolume` can restart and reattach with data intact, use -the durable restart workflow in -[`operations-v1.md`](operations-v1.md#5-prove-durable-blockvolume-restart). +Read the first-volume summary: -The preflight command emits structured lines: +```bash +cat "$(ls -td /tmp/sw-block-basic-app-* | head -1)/first-volume-summary.txt" +``` + +Expected fields: ```text -[preflight] checked name=kubectl status=PASS ... -[preflight] checked name=iscsiadm status=PASS ... -[preflight] unchecked name=ghcr_pull reason="local-k3s path selected" -[preflight] summary status=PASS checked=... failed=0 unchecked=... mode=local-k3s +first_volume_status=ok +pvc=sw-block-example-pvc +pvc_phase=Bound +writer_verified=true +reader_verified=true +inventory_status=ok +status_evidence=status/cluster-evidence.json,status/inventory +cluster_evidence=status/cluster-evidence.json +inventory_bundle=status/inventory +status_report=status/report/index.html +cleanup_status=ok ``` -If any preflight command fails, fix that first. Otherwise the storage failure -will be mixed with environment setup failure. +The writer and reader are ordinary app pods. The reader is a replacement pod, +so this proves the data is on the PVC-backed volume, not only in the writer +container. -Boundary checks: +## Step 3 — Inspect The Read-Only Report + +The first-volume helper writes a status directory under the latest basic-app +artifact directory: ```bash -ARTIFACT_DIR="$(ls -td /tmp/sw-block-app-demo-* | head -1)" - -grep 'PASS:' "$ARTIFACT_DIR/run.log" -grep '/data/demo.bin: OK' "$ARTIFACT_DIR/writer.log" -grep '/data/demo.bin: OK' "$ARTIFACT_DIR/reader.log" -grep -- '--volume-id=' "$ARTIFACT_DIR/generated-blockvolume.yaml" -grep 'app_node=' "$ARTIFACT_DIR/run.log" -grep 'nodeSelector:' "$ARTIFACT_DIR/demo-app.rendered.yaml" -grep 'nodeSelector:' "$ARTIFACT_DIR/demo-app-reader.rendered.yaml" -cat "$ARTIFACT_DIR/app-storage.after-delete.txt" -cat "$ARTIFACT_DIR/iscsi-sessions.after-delete.txt" +APP_DIR="$(ls -td /tmp/sw-block-basic-app-* | head -1)" +ls "$APP_DIR/status/report" +cat "$APP_DIR/status/report/summary.txt" ``` -If you want to watch each boundary directly while the demo is running, use -these checks. The expected output is intentionally small and copyable: +Expected files: -| Boundary | Command | Expected output line | -|---|---|---| -| CSI controller Ready | `kubectl -n kube-system get deploy sw-block-csi-controller -o jsonpath='{.status.readyReplicas}/{.status.replicas}{"\n"}'` | `1/1` | -| CSI node DaemonSet rolled out | `kubectl -n kube-system rollout status ds/sw-block-csi-node` | `daemon set "sw-block-csi-node" successfully rolled out` | -| StorageClass present | `kubectl get sc sw-block-dynamic -o jsonpath='{.provisioner}{"\n"}'` | `block.csi.seaweedfs.com` | -| PVC Bound | `kubectl get pvc sw-block-demo-pvc -o jsonpath='{.status.phase}{"\n"}'` | `Bound` | -| Generated blockvolume Deployment Ready | `kubectl -n default get deploy -l app=sw-blockvolume -o jsonpath='{.items[0].status.readyReplicas}/{.items[0].status.replicas}{"\n"}'` | `1/1` | -| Writer pod Succeeded | `kubectl get pod sw-block-demo-writer -o jsonpath='{.status.phase}{"\n"}'` | `Succeeded` | -| Reader checksum OK | `kubectl logs sw-block-demo-reader` | `/data/demo.bin: OK` | -| Delete returned clean | `kubectl get pvc sw-block-demo-pvc` | `Error from server (NotFound): persistentvolumeclaims "sw-block-demo-pvc" not found` | -| Residue absent | `sudo iscsiadm -m session` | `iscsiadm: No active sessions.` | - -The build artifact directory records image IDs and binary versions. The demo -artifact directory records the first-volume evidence. - -```bash -cat /tmp/sw-block-alpha-build/alpha-images.env -ARTIFACT_DIR="$(ls -td /tmp/sw-block-app-demo-* | head -1)" -cat "$ARTIFACT_DIR/run.log" +```text +index.html +cluster-evidence.json +timeline.jsonl +summary.txt ``` -## Inspect The Cluster +`index.html` is a local static report. It is read-only. It has no promote, +repair, rebuild, delete, failback, or cleanup controls. -After the alpha stack is installed, use the read-only inventory command to see -the Seaweed Block volumes Kubernetes can currently discover: +If you want to generate the same report from the live master: ```bash -kubectl -n kube-system port-forward svc/blockmaster 9333:9333 +kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333 ``` In another terminal: +```bash +sw-block ops cluster --master-api 127.0.0.1:9333 +sw-block ops report --master-api 127.0.0.1:9333 --out /tmp/sw-block-report +``` + +If `sw-block` is not installed in `PATH`, run the same commands from the +repository as `go run ./cmd/sw-block ops ...`. + +For replica-level support evidence: + ```bash sw-block ops inventory \ --namespace default \ @@ -143,441 +190,134 @@ sw-block ops inventory \ --out /tmp/sw-block-inventory ``` -The command does not need a TestOps artifact directory or a known volume id. It -discovers PVC/PV ownership and generated `blockvolume` Deployments from -Kubernetes. When `--master` is supplied and a replica has `--status-addr`, it -also writes that replica's normal `sw-block ops status` bundle under -`/tmp/sw-block-inventory/volumes///`. +## Published Images -Expected one-volume shape while the demo PVC is live. The lifecycle fields show -whether the generated `blockvolume` Deployment is owned by the PVC-owner-ref -path or a legacy launcher-managed fallback: +For development, local build/import is the fastest path and guarantees the +running image matches the source tree. -```text -inventory_status: ok -volumes: total=1 ok=1 unhealthy=0 invalid=0 -volume: id=pvc-... namespace=default pvc=sw-block-demo-pvc pv=pvc-... rf=1 desired=1 observed=1 primary=r1 status=ok protocols=iscsi replicas=1 -replica: volume=pvc-... replica=r1 server=... node=... observed=true status=ok lifecycle_owner=pvc-owner-ref owner_ref=PersistentVolumeClaim/default/sw-block-demo-pvc role=primary replication=none healthy=true ... frontend=127.0.0.1:3260 status_addr=127.0.0.1:... support_bundle=volumes/pvc-.../r1 -issues: none -artifacts: volume-inventory.json volume-inventory-summary.txt ops-inventory-bundle.json -``` - -Expected empty shape after the demo PVC is deleted: - -```text -inventory_status: ok -volumes: total=0 ok=0 unhealthy=0 invalid=0 -issues: none -``` - -Expected partial/failure shape if the PVC exists but no generated -`blockvolume` Deployment is present: - -```text -inventory_status: unhealthy -volume: id=pvc-... namespace=default pvc= ... observed=0 primary=unavailable status=unhealthy protocols= replicas=0 -issues: -- volume pvc-... generated_deployment_missing -``` - -Expected residue shape if a generated `blockvolume` Deployment remains after -its PVC/PV disappeared: - -```text -inventory_status: unhealthy -volume: id=pvc-... namespace=default pvc=unavailable pv=unavailable ... observed=1 status=unhealthy protocols=iscsi replicas=1 -issues: -- volume pvc-... orphan-blockvolume-deploy=sw-blockvolume-pvc-...-r1 -- volume pvc-... heartbeat-without-placement= state=unadmitted-by-master reason=no-matching-pvc-or-pv -``` - -Expected residue shape if a host-local `blockvolume` process exists without a -matching PVC/PV placement: - -```text -inventory_status: unhealthy -volume: id=pvc-... namespace=default pvc=unavailable pv=unavailable ... observed=1 status=unhealthy -issues: -- volume pvc-... blockvolume-process-without-placement= -- volume pvc-... heartbeat-without-placement= state=unadmitted-by-master reason=local-process-without-pvc-or-pv -``` - -If a replica pod is observed as ready but the nested product status has not -confirmed authority assignment yet, inventory should name that as degraded -readiness, not as a contradictory health failure: - -```text -replica: volume=pvc-... replica=r1 ... observed=true status=unhealthy role=primary healthy=true epoch=0 endpoint_version=0 ... -issues: -- volume pvc-... replica_degraded=r1 status=unhealthy -- volume pvc-... replica r1 ops_status=unhealthy reason=authority_not_assigned assigned=false epoch=0 endpoint_version=0 -``` - -Attach the whole inventory directory when filing an issue. The top-level -inventory answers "what exists?", while each nested replica status bundle -answers "what did this replica report?" using the same schema as -`sw-block ops status`. - -Inventory non-claims are explicit in every bundle: - -- `read-only-observation`: inventory does not mutate product state. -- `single-cluster-alpha-scope`: discovery is scoped to one alpha Kubernetes cluster. -- `best-effort-partial-discovery`: missing inputs are reported as issues or unchecked evidence, not inferred as healthy. -- `no-mutating-admin`: inventory is not repair, cleanup, failover, backup, or restore. -- `no-multi-node-scheduling`: inventory observes placement; it does not schedule or rebalance replicas. -- `rf2-rf3-live-kubernetes-operation`: live RF=2/RF=3 Kubernetes operation is not claimed unless a runner gate explicitly proves it. - -## Alternate Image Paths - -Use these only after the local k3s path is understood. - -### Published Alpha Images - -Use this when your cluster can pull public images from GHCR: +For QA/PM or release-candidate validation, use immutable published images: ```bash -bash scripts/preflight-k8s-alpha.sh --ghcr -bash scripts/run-k8s-demo-ghcr.sh "$PWD" +export SW_BLOCK_ACTIVATION_IMAGE_MODE=published +export SW_BLOCK_IMAGE=ghcr.io/seaweedfs/seaweed-block:sha- +export SW_BLOCK_CSI_IMAGE=ghcr.io/seaweedfs/seaweed-block-csi:sha- + +bash scripts/activate-k8s-alpha.sh "$PWD" +bash scripts/run-basic-app-example.sh "$PWD" ``` -The script uses: +Mutable `:alpha` images are acceptable for casual smoke tests, but they can +drift from the checked-out source tree. Do not use `:alpha` as release +evidence unless the publish commit is known. -```text -ghcr.io/seaweedfs/seaweed-block:alpha -ghcr.io/seaweedfs/seaweed-block-csi:alpha -``` +## Use Your Own PVC -If the images are not public or your cluster cannot pull them, app pods or -Seaweed Block pods may show `ImagePullBackOff`. Inspect with: - -```bash -kubectl -n kube-system describe pod -l app=sw-blockmaster -kubectl -n kube-system describe pod -l app=sw-block-csi-controller -``` - -Remediation: use the local k3s path above, or push images to a registry your -cluster can pull. - -### Existing Cluster With Your Registry - -Use this when your cluster pulls images from a registry. - -```bash -export SW_BLOCK_IMAGE=registry.example.com/storage/sw-block:alpha -export SW_BLOCK_CSI_IMAGE=registry.example.com/storage/sw-block-csi:alpha - -bash scripts/build-alpha-images.sh "$PWD" -docker push "$SW_BLOCK_IMAGE" -docker push "$SW_BLOCK_CSI_IMAGE" - -bash scripts/run-alpha-app-demo.sh "$PWD" -``` - -The runner renders the Kubernetes manifests with those image names before -applying them. The source manifests stay simple and still default to -`sw-block:local` for local labs. - -## First-Volume Evidence Ladder - -A successful run should show the same ladder regardless of which image path you -used: - -```text -preflight ok -blockmaster available -CSI controller available -CSI node DaemonSet rolled out -StorageClass/PVC applied -blockvolume manifest generated by blockmaster -blockvolume Deployment available -writer pod checksum OK -reader replacement pod checksum OK -PVC deleted -generated blockvolume cleaned up -no sw-block iSCSI session remains -``` - -The demo records the useful files under `/tmp/sw-block-app-demo-*`: - -| Artifact | What it proves | -|---|---| -| `run.log` | Phase progress and final PASS line. | -| `apply-block-stack.log` | Control-plane manifest applied. | -| `apply-csi-controller.log`, `apply-csi-node.log` | CSI components applied. | -| `generated-blockvolume.yaml` | Master generated the per-PVC blockvolume workload. | -| `demo-app.rendered.yaml` | Writer pod rendered with the selected app-node `nodeSelector`. | -| `demo-app-reader.rendered.yaml` | Reader pod rendered with the selected app-node `nodeSelector`. | -| `apply-generated-blockvolume.log` | Generated blockvolume workload was reconciled by blockmaster, or applied manually when the fallback env is enabled. | -| `writer.log` | First app pod wrote and verified `/data/demo.bin`. | -| `reader.log` | Replacement app pod read and verified the same data. | -| `status-durable-after-blockvolume-restart.json` | Present only in the durable restart workflow; durable entry was latched and operational after generated `blockvolume` restart. | -| `app-storage.txt` | StorageClass/PV/PVC/pod state during the run. | -| `iscsi-sessions.after-reader.txt` | Host iSCSI session state after the replacement reader verifies data. | -| `app-storage.after-delete.txt` | App/PVC state after delete. | -| `blockvolume-namespace-pods-deploys.after-delete.txt` | Generated blockvolume cleanup evidence. | -| `iscsi-sessions.after-delete.txt` | Host iSCSI session residue check. | -| `cleanup.log` | Test guardrail cleanup actions. | - -Cleanup attribution: - -```text -pvc:sw-block-demo-pvc state=deleted deleted_by=demo-script-kubectl-delete evidence=demo/delete-pvc.log -blockmaster-manifest: state=removed waited_by=demo-script-after-DeleteVolume evidence=demo/poll.log -blockvolume-deploy: namespace=default state=deleted deleted_by=pvc-owner-ref-or-demo-guard evidence=demo/blockvolume-namespace-pods-deploys.after-delete.txt -iscsi-session: state=absent released_by=csi-node-unstage evidence=demo/iscsi-sessions.after-delete.txt -iscsi-node-db: state=present_before_guardrail cleaned_by=testops-guardrail evidence=iscsi-nodes.after-demo.txt -``` - -Product/Kubernetes cleanup and TestOps guardrail cleanup are intentionally -separate. An active iSCSI session must be gone after delete. A non-active iSCSI -node database entry may remain until guardrail cleanup removes it. - -## What To Show In A Demo - -The most understandable demo is: - -```bash -bash scripts/run-alpha-app-demo.sh "$PWD" -``` - -Then show these artifacts: - -```bash -cat /tmp/sw-block-app-demo-*/writer.log -cat /tmp/sw-block-app-demo-*/reader.log -sudo iscsiadm -m session || true -kubectl get all -A | grep sw-block || true -``` - -The proof is that both app logs contain: - -```text -/data/demo.bin: OK -``` - -The first pod wrote the file. The second pod mounted the same PVC later and -verified it. - -## If The Demo Fails - -Start with the artifact directory printed in `run.log`: - -```bash -ARTIFACT_DIR="$(ls -td /tmp/sw-block-app-demo-* | head -1)" -cat "$ARTIFACT_DIR/run.log" -ls "$ARTIFACT_DIR" -``` - -Common boundary checks: - -```bash -kubectl -n kube-system get pods,deploy -o wide -kubectl get sc,pv,pvc,pod -o wide -cat "$ARTIFACT_DIR/app-storage.txt" 2>/dev/null || true -cat "$ARTIFACT_DIR/generated-blockvolume.err" 2>/dev/null || true -cat "$ARTIFACT_DIR/blockmaster.log" 2>/dev/null || true -cat "$ARTIFACT_DIR/blockvolume-generated.log" 2>/dev/null || true -``` - -If a `volume-id` and blockvolume status address are available from -`generated-blockvolume.yaml`, collect a product status bundle: - -```bash -VOLUME_ID="$(sed -n 's/.*--volume-id=\([^"[:space:]]*\).*/\1/p' "$ARTIFACT_DIR/generated-blockvolume.yaml" | head -1)" -STATUS_ADDR="$(sed -n 's/.*--status-addr=\([^"[:space:]]*\).*/\1/p' "$ARTIFACT_DIR/generated-blockvolume.yaml" | head -1)" -MASTER_ADDR="${SW_BLOCK_MASTER_ADDR:-127.0.0.1:9333}" - -if [ -n "$VOLUME_ID" ] && [ -n "$STATUS_ADDR" ]; then - sw-block ops status \ - --volume "$VOLUME_ID" \ - --master "$MASTER_ADDR" \ - --status-addr "$STATUS_ADDR" \ - --out "$ARTIFACT_DIR/ops-status" -else - echo "ops-status-unavailable: no volume id/status address reached" -fi -``` - -On a local single-node k3s lab, `MASTER_ADDR=127.0.0.1:9333` works only when -the blockmaster service is reachable from the shell where `sw-block` runs. If it -is not reachable, port-forward it first in another terminal: - -```bash -kubectl -n kube-system port-forward svc/blockmaster 9333:9333 -``` - -Attach the whole artifact directory when filing an issue. If no volume identity -was reached, attach the directory anyway; the useful boundary is then install, -PVC, or manifest generation rather than data-path status. - -If the cluster is still reachable, also collect the inventory bundle: - -```bash -sw-block ops inventory \ - --namespace default \ - --master 127.0.0.1:9333 \ - --out "$ARTIFACT_DIR/ops-inventory" -``` - -## Use Your Own App - -Install the alpha stack: - -```bash -bash scripts/install-k8s-alpha.sh "$PWD" -``` - -Create a StorageClass and PVC: +The standard volume creation path is Kubernetes PVC creation. Start from the +example: ```bash kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml +kubectl get pvc sw-block-example-pvc ``` -The installed blockmaster owns the generated `blockvolume` workload. Wait for -it to reconcile the Deployment: - -```bash -kubectl get deploy -n default -l app=sw-blockvolume -o jsonpath='{.items[0].status.readyReplicas}/{.items[0].status.replicas}{"\n"}' -``` - -Expected output: - -```text -1/1 -``` - -If you are running an older alpha stack without product-owned reconciliation, -the internal fallback remains: - -```bash -bash scripts/apply-k8s-alpha-blockvolumes.sh -``` - -After the fallback apply, verify the generated workload is Ready: - -```bash -kubectl get deploy -n default -l app=sw-blockvolume -o jsonpath='{.items[0].status.readyReplicas}/{.items[0].status.replicas}{"\n"}' -``` - -Then start an app pod that mounts the PVC: +Then mount the PVC from your own pod, or use the example writer and reader: ```bash kubectl apply -f examples/kubernetes/basic-app/writer-pod.yaml kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/sw-block-example-writer --timeout=240s kubectl logs sw-block-example-writer -``` -To prove a replacement pod can read the same PVC: - -```bash kubectl delete pod sw-block-example-writer kubectl apply -f examples/kubernetes/basic-app/reader-pod.yaml kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/sw-block-example-reader --timeout=240s kubectl logs sw-block-example-reader ``` -For the copyable YAML, see -[`examples/kubernetes/basic-app`](../examples/kubernetes/basic-app). +The generated `blockvolume` workload is reconciled by blockmaster. You should +not need to manually apply generated blockvolume YAML on the supported alpha +path. -## Current Alpha Limitations +## Troubleshooting -- The generated `blockvolume` workload is reconciled by blockmaster on the - supported alpha path. This is a small product-owned lifecycle loop, not a - full production operator. -- By default, generated `blockvolume` Deployments carry a PVC owner reference, - so Kubernetes garbage collection removes them after the PVC is deleted. -- The demo uses same-node loopback attach. Remote-node attach to a - loopback-published `blockvolume` is not claimed. -- The default quickstart is a first-volume path. Durable generated - `blockvolume` restart is supported only when - `SW_BLOCK_LAUNCHER_STATE_HOSTPATH` is configured as described in - `operations-v1.md`; it is not a production durability, node-loss, backup, or - restore claim. -- Failover while a PVC remains mounted is not claimed. -- NVMe-oF is not part of this alpha path. -- Operator-grade reconciliation is not claimed. -- Upgrade and uninstall safety are not claimed. -- Performance numbers from this demo are not a product SLO. +Start with the latest basic-app artifact directory: + +```bash +APP_DIR="$(ls -td /tmp/sw-block-basic-app-* | head -1)" +cat "$APP_DIR/first-volume-summary.txt" 2>/dev/null || true +find "$APP_DIR" -maxdepth 3 -type f | sort +``` + +Common evidence: + +```bash +cat "$APP_DIR/status/cluster-evidence.json" 2>/dev/null || true +cat "$APP_DIR/status/inventory/volume-inventory-summary.txt" 2>/dev/null || true +cat "$APP_DIR/diagnostics/writer/writer-describe.txt" 2>/dev/null || true +cat "$APP_DIR/diagnostics/reader/reader-describe.txt" 2>/dev/null || true +``` + +If a pod cannot mount the PVC, `writer-describe.txt` or `reader-describe.txt` +should include the Kubernetes event explaining why, such as image pull failure, +iSCSI connection failure, missing CHAP secret, or scheduling mismatch. + +If the cluster is still reachable, collect fresh live evidence: + +```bash +kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333 +``` + +In another terminal: + +```bash +sw-block ops cluster --master-api 127.0.0.1:9333 -o json \ + > /tmp/sw-block-cluster-evidence.json +sw-block ops report --master-api 127.0.0.1:9333 --out /tmp/sw-block-report +sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out /tmp/sw-block-inventory +``` + +If `sw-block` is not installed in `PATH`, prefix those commands with +`go run ./cmd/sw-block` from the repository root. + +Attach the artifact directory and `/tmp/sw-block-report` when filing an issue. ## Cleanup -The runner performs cleanup automatically and records artifacts under -`/tmp/sw-block-app-demo-*`. - -If you need to clean up manually: +The first-volume helper cleans the example resources by default. To uninstall +the whole alpha stack: ```bash -kubectl -n default delete pod sw-block-demo-writer sw-block-demo-reader --ignore-not-found=true -kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true -kubectl -n default delete deploy -l app=sw-blockvolume --ignore-not-found=true -kubectl delete -f deploy/k8s/alpha/csi-driver.yaml --ignore-not-found=true -kubectl delete -f deploy/k8s/alpha/rbac.yaml --ignore-not-found=true -kubectl delete -f /tmp/sw-block-stack.yaml --ignore-not-found=true +bash scripts/uninstall-k8s-alpha.sh "$PWD" +``` + +Verify: + +```bash +kubectl get sc | grep sw-block || echo "no sw-block StorageClass" +kubectl get deploy -A | grep sw-block || echo "no sw-block deployments" sudo iscsiadm -m session || true ``` -Do not use global cleanup commands such as `kubectl delete deploy -A -l -app=sw-blockvolume` in a shared cluster. Broad sweeps are TestOps guardrails, -not user-facing cleanup. - -For a full alpha stack uninstall: - -```bash -bash scripts/uninstall-k8s-alpha.sh "$PWD" -``` - -This removes the demo app resources, the demo PVC-scoped generated -`blockvolume`, CSI resources, and the blockmaster stack. It does not broadly -delete every `app=sw-blockvolume` Deployment unless -`SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES=1` is set by a TestOps guardrail. - -Some alpha or test paths can leave persistent blockvolume state under -`/var/lib/sw-block/`. This quickstart does not claim upgrade or uninstall -safety; remove those paths only when you need a clean lab and know no other run -owns that state. - -## Retry After A Partial Run - -If you interrupt the demo after the PVC or generated `blockvolume` appears, -clean up before retrying: - -```bash -bash scripts/uninstall-k8s-alpha.sh "$PWD" -``` - -Then verify the retry boundary is clean: - -```bash -kubectl -n default get pvc sw-block-demo-pvc -kubectl -n default get deploy -l app=sw-blockvolume -sudo iscsiadm -m session -``` - -Expected result: +Expected clean state: ```text -Error from server (NotFound): persistentvolumeclaims "sw-block-demo-pvc" not found -No resources found in default namespace. +no sw-block StorageClass +no sw-block deployments iscsiadm: No active sessions. ``` -After that, rerun the same demo command: +Do not run broad cluster cleanup commands in a shared cluster unless you know no +other run owns the resources. -```bash -bash scripts/run-alpha-app-demo.sh "$PWD" -``` +## Current Alpha Limitations -The retry behavior is gated by -`testops/scenarios/light-use-first-volume-retry-chain.yaml`: it intentionally -stops after the generated `blockvolume` is ready, leaves the PVC and -`blockvolume` Deployment in place, runs the uninstall path, and then proves the -same first-volume demo passes on retry. - -The scripted demo applies rendered manifests under its artifact directory. If -you used custom image names, delete those rendered files instead of the source -YAML: - -```bash -kubectl delete -f "$ARTIFACT_DIR/csi-controller.rendered.yaml" --ignore-not-found=true -kubectl delete -f "$ARTIFACT_DIR/csi-node.rendered.yaml" --ignore-not-found=true -``` +- This is an alpha installer/script path, not a production Helm chart or + operator. +- The local `sw-block ops report` is not a hosted dashboard. +- Mutating admin workflows are not exposed: no promote, repair, rebuild, + failback, delete, backup, or restore button. +- Upgrade and rollback safety are not claimed. +- Backup, snapshot, and restore are not claimed. +- Broad distro/kernel/initiator compatibility is not claimed. +- Performance, RTO, and SLO numbers are not claimed. +- Transparent Kubernetes node-loss without pod recreate is not claimed by this + quickstart. diff --git a/seaweed-block/docs/releases/README.md b/seaweed-block/docs/releases/README.md new file mode 100644 index 0000000000..3be7768743 --- /dev/null +++ b/seaweed-block/docs/releases/README.md @@ -0,0 +1,21 @@ +# Seaweed Block Release Notes + +Seaweed Block release notes use narrow product claims. Each alpha version names +what a user or reviewer can actually run, what QA evidence backs it, and what +is still outside the supported boundary. + +- [v0.1 Alpha — Kubernetes Block Foundation](v0.1-alpha.md) +- [v0.2 Alpha — Day-1 Activation And First Volume](v0.2-alpha.md) + +## Version Boundary + +- `v0.1-alpha` is the engineering alpha foundation: CSI/PVC plumbing, + product-owned blockvolume lifecycle, inventory, recovery gates, iSCSI + ALUA/dm-multipath proof, node-loss recovery, and read-only control-plane + evidence. +- `v0.2-alpha` is the first user-facing activation loop: one documented + Kubernetes path from install to first PVC, writer/reader verification, local + status report, and cleanup. + +Helm/operator packaging is not included in either alpha. The current install +path is script-based. diff --git a/seaweed-block/docs/releases/v0.1-alpha.md b/seaweed-block/docs/releases/v0.1-alpha.md new file mode 100644 index 0000000000..3a516d4e96 --- /dev/null +++ b/seaweed-block/docs/releases/v0.1-alpha.md @@ -0,0 +1,59 @@ +# v0.1 Alpha — Kubernetes Block Foundation + +## Summary + +Seaweed Block v0.1 alpha established the Kubernetes block-storage foundation: +PVC provisioning through CSI, product-owned blockvolume lifecycle, read-only +inventory, recovery gates, and protocol-level failover evidence. + +This version is an engineering alpha. It proves that the core storage/control +plane can work under gated lab scenarios. It is not yet a polished Day-1 user +installation experience. + +## What Users And Reviewers Can Evaluate + +- Dynamic PVC provisioning through the Seaweed Block CSI driver. +- Product-owned generated `blockvolume` Deployments instead of manual + generated-YAML apply steps. +- Read-only `sw-block ops inventory` evidence for volumes, replicas, primary, + frontends, and issue lines. +- Durable local restart/reattach for the supported alpha path. +- Multi-node attach/placement visibility and explicit loopback non-claims. +- RF=2 safe-refusal and controlled best-effort demo recovery. +- RF=3 `sync-quorum` mounted recovery through CSI/pod recreate. +- iSCSI ALUA + Linux dm-multipath transparent mounted failover on the gated + alpha path. +- Kubernetes node-loss recovery through CSI/pod recreate on a surviving node. +- Product-owned control-plane event evidence for placement, candidate + evaluation, authority publication, and CSI reattach. + +## Evidence Anchors + +The v0.1 alpha boundary is backed by closed hard-gate reports and preserved QA +run bundles. Recent recovery and observation gates include: + +- Stage 1 RF=3 sync-quorum mounted recovery: `20260514-075221-da0d`. +- Stage 2 iSCSI ALUA/dm-multipath transparent mounted failover: + `20260515-104802-a618`. +- Kubernetes node-loss recovery through CSI/pod recreate: + `20260516-160306-1e54`. +- Product-owned control-plane observation export: `20260517-011004-4b79`. + +## Explicit Non-Claims + +- Not production-ready. +- No one-command Day-1 activation loop yet in this release boundary. +- No Helm chart or operator lifecycle. +- No hosted dashboard. +- No backup, snapshot, or restore workflow. +- No upgrade/rollback safety claim. +- No mutating admin workflows such as promote, repair, rebuild, failback, or + delete buttons. +- No broad performance, RTO, or compatibility SLO. +- No NVMe ANA parity for the transparent failover path. + +## Upgrade Note + +Use v0.2 alpha if the goal is to evaluate the first user-facing Kubernetes +install-to-first-volume loop. Use v0.1 alpha only as the reference boundary for +the underlying storage, CSI, recovery, and observation capabilities. diff --git a/seaweed-block/docs/releases/v0.2-alpha.md b/seaweed-block/docs/releases/v0.2-alpha.md new file mode 100644 index 0000000000..964ce93ba4 --- /dev/null +++ b/seaweed-block/docs/releases/v0.2-alpha.md @@ -0,0 +1,110 @@ +# v0.2 Alpha — Day-1 Activation And First Volume + +## Summary + +Seaweed Block v0.2 alpha packages the previously proven block, CSI, recovery, +and observation work into a user-facing Kubernetes Day-1 loop: + +```text +activate stack +-> create first PVC-backed volume +-> writer pod verifies data +-> reader pod verifies persisted data +-> collect product-owned cluster evidence +-> generate a local read-only status report +-> cleanup leaves no sessions or product processes +``` + +This is the first alpha release boundary where a PM, QA engineer, or early +operator can follow a single tutorial and reach a verified first PVC without +reading source code. + +## User-Visible Additions + +- `scripts/activate-k8s-alpha.sh` runs preflight, installs the alpha stack, + waits for blockmaster/CSI readiness, creates the StorageClass, and writes an + activation summary. +- Multi-node activation automatically uses non-loopback iSCSI/status addresses + and CHAP for the Day-1 path. +- `scripts/run-basic-app-example.sh` creates the example PVC, runs writer and + reader checksum pods, collects status/inventory evidence, generates a local + report, and cleans the example resources. +- `sw-block ops report` renders a local static read-only HTML report backed by + product-owned cluster evidence and event timeline data. +- Published-image mode supports immutable GHCR tags such as + `ghcr.io/seaweedfs/seaweed-block:sha-` and + `ghcr.io/seaweedfs/seaweed-block-csi:sha-`. + +## Validated User Path + +```bash +bash scripts/activate-k8s-alpha.sh "$PWD" +bash scripts/run-basic-app-example.sh "$PWD" +cat "$(ls -td /tmp/sw-block-basic-app-* | head -1)/first-volume-summary.txt" +``` + +Expected summary fields include: + +```text +first_volume_status=ok +pvc_phase=Bound +writer_verified=true +reader_verified=true +inventory_status=ok +status_report=status/report/index.html +cleanup_status=ok +``` + +## Evidence + +- Activation + first volume: `20260517-205252-04e9` PASS, 5/5 phases, 27/27 + actions. +- Read-only report slice: `20260517-212358-bfba` PASS, 5/5 phases, 27/27 + actions. +- Report artifacts from the report slice: + - `status/report/index.html` + - `status/report/cluster-evidence.json` + - `status/report/timeline.jsonl` + - `status/report/summary.txt` + +## Current Claim + +Seaweed Block v0.2 alpha provides an install-to-first-volume Kubernetes loop: + +- install the alpha stack on a supported k3s/Kubernetes lab, +- create a PVC-backed block volume through Kubernetes, +- write and read data through app pods, +- inspect cluster, volume, replica, primary, frontend, and event evidence, +- collect a local read-only status report, +- uninstall and leave the lab clean. + +## Explicit Non-Claims + +- Not production-ready. +- No Helm chart or operator lifecycle yet. +- No hosted dashboard; `sw-block ops report` is a static local read-only + report. +- No backup, snapshot, or restore workflow. +- No upgrade/rollback safety claim. +- No mutating admin workflows such as promote, repair, rebuild, failback, or + delete buttons. +- No broad performance, RTO, or compatibility SLO. +- No transparent Kubernetes node-loss failover without pod recreate in the + Day-1 quickstart. +- No NVMe ANA parity for the transparent failover path. + +## Release Validation Guidance + +For QA/PM release validation, prefer immutable published images: + +```bash +export SW_BLOCK_ACTIVATION_IMAGE_MODE=published +export SW_BLOCK_IMAGE=ghcr.io/seaweedfs/seaweed-block:sha- +export SW_BLOCK_CSI_IMAGE=ghcr.io/seaweedfs/seaweed-block-csi:sha- + +bash scripts/activate-k8s-alpha.sh "$PWD" +bash scripts/run-basic-app-example.sh "$PWD" +``` + +Use mutable `:alpha` only as a casual smoke tag; it can drift from the source +tree unless the publish commit is known. diff --git a/seaweed-block/docs/roadmap.md b/seaweed-block/docs/roadmap.md index 08ce9667cd..263cef4e0f 100644 --- a/seaweed-block/docs/roadmap.md +++ b/seaweed-block/docs/roadmap.md @@ -30,8 +30,9 @@ Current alpha constraints: 1. Package a clean Kubernetes install surface. - - keep `deploy/k8s/alpha/` coherent - - document image names and prerequisites + - v0.2 alpha: script-based Day-1 activation path + - v0.3 alpha: Helm chart for the same supported path + - document image names, immutable release tags, prerequisites, and cleanup - remove gate-specific naming from user paths where possible 2. Replace `emptyDir` for blockvolume state. @@ -40,11 +41,12 @@ Current alpha constraints: - support hostPath/local-path style lab persistence - keep `emptyDir` only for explicit throwaway smoke tests -3. Add a minimal operator/controller loop. +3. Add a minimal operator/controller loop after Helm. - - watch generated workload intent or lifecycle state - - apply/delete blockvolume Deployments - - stop requiring the harness to apply generated workloads + - do not jump directly from scripts to an operator + - first stabilize install values, chart ownership, and uninstall behavior + - then add CRDs/Conditions/Events for cluster, node, volume, and lifecycle + state 4. Improve TestOps usability. @@ -128,11 +130,14 @@ Requires deeper storage context: A reasonable beta bar: -- K8s install path is one command or one Helm chart. +- K8s install path is a Helm chart with documented values and immutable images. - Dynamic PVC create/delete works repeatedly. - Volume data survives blockvolume pod restart. - Multi-node attach works. - Basic failover is tested under an attached workload. +- Read-only status and support evidence are available without SSH log spelunking. +- Operator lifecycle is either present behind a clear beta gate or explicitly + listed as the next release boundary. - TestOps can run the protocol release gate and produce stable artifacts. - Non-claims are documented and visible to users. diff --git a/seaweed-block/examples/kubernetes/basic-app/README.md b/seaweed-block/examples/kubernetes/basic-app/README.md index 1728633683..891dac652a 100644 --- a/seaweed-block/examples/kubernetes/basic-app/README.md +++ b/seaweed-block/examples/kubernetes/basic-app/README.md @@ -16,14 +16,13 @@ bash scripts/run-k8s-demo.sh "$PWD" To install the alpha stack and keep it running for this example: ```bash -bash scripts/install-k8s-alpha.sh "$PWD" +bash scripts/activate-k8s-alpha.sh "$PWD" ``` ## Apply ```bash kubectl apply -f storageclass-pvc.yaml -bash ../../../scripts/apply-k8s-alpha-blockvolumes.sh kubectl apply -f writer-pod.yaml ``` @@ -72,12 +71,12 @@ kubectl delete pvc sw-block-example-pvc --ignore-not-found=true kubectl delete storageclass sw-block-example --ignore-not-found=true ``` -The current alpha still needs the blockvolume launcher cleanup path from the -demo runner or operator work. If you are using this example manually, inspect -and clean generated `sw-blockvolume-*` Deployments as needed: +The product-owned launcher should remove PVC-owned generated blockvolume +Deployments after the PVC is deleted. If you are using this example manually, +inspect generated workloads before uninstall: ```bash -kubectl -n kube-system get deploy -l app=sw-blockvolume +kubectl get deploy -A -l app=sw-blockvolume ``` ## Alpha Notes diff --git a/seaweed-block/internal/docs/README.md b/seaweed-block/internal/docs/README.md index 74ed2e2c85..b42b4af912 100644 --- a/seaweed-block/internal/docs/README.md +++ b/seaweed-block/internal/docs/README.md @@ -19,6 +19,9 @@ Public-facing docs belong in `docs/`. the day-to-day driver. - QA assignments live under `qa-assignments/` and should be linked from `current-plan.md` with `#QA`. +- Product spec gates live under `ref/` and should be created or referenced + before non-trivial P0/P1 implementation. Tests validate the spec; tests are + not the spec. - When a plan closes, keep the finished markdown plan in `finished-plans/`. Link supporting audits, QA requests, and larger references from that plan under `ref/` or `qa-assignments/`. @@ -32,6 +35,11 @@ Public-facing docs belong in `docs/`. | `product-management-plan.md` | Older product goals, priorities, evidence links, and decision rules. | | `qa-assignments/` | Concrete QA tasks with commands, pass criteria, and report templates. | | `finished-plans/` | Closed phase/topic plans retained for PM history. | +| `ref/product-spec-gate-template.md` | Cold spec-gate template for product semantics, non-negotiables, allowed simplifications, and drift checks. | +| `ref/stage2-transparent-multipath-host-failover-spec.md` | Stage 2 product spec for iSCSI ALUA/dm-multipath Kubernetes host-path failover without pod recreate. | +| `ref/node-loss-survival-mvp-spec.md` | Node-loss survival product spec: RF3 sync-quorum recovery across distinct Kubernetes nodes with non-loopback frontends. | +| `ref/node-loss-lab-setup.md` | Lab setup note for the Node-Loss D3/D4 gates, including 3 Kubernetes nodes on 2 physical machines and physical-host disclosure. | +| `ref/control-plane-observation-api-mvp.md` | Dashboard-grade read-only observation API spec: cluster status, volume timeline, event stream, and support-bundle UX. | | `finished-plans/phase1_finishedplan_frontend_protocol_readiness.md` | Historical iSCSI/NVMe protocol-readiness plan closed by the protocol release gate. | | `finished-plans/phase2_finishedplan_beta_hardening_seed.md` | Historical beta hardening seed plan. | | `finished-plans/phase3_finishedplan_beta_seed_stabilization.md` | Historical beta seed stabilization plan. | @@ -43,6 +51,14 @@ Public-facing docs belong in `docs/`. | `finished-plans/phase9_finishedplan_light_use_operations_mvp.md` | Historical light-use operations MVP plan closed by local CLI, bundle, and TestOps control-data validation. | | `finished-plans/phase10_finishedplan_light_use_install_lifecycle_operations_mvp.md` | Historical light-use install/lifecycle operations MVP plan closed by strict first-volume runbook and scenario validation. | | `finished-plans/phase11_finishedplan_cluster_ops_inventory_lifecycle_visibility_mvp.md` | Historical cluster operations inventory and lifecycle visibility MVP plan closed by strict multi-volume inventory validation. | +| `finished-plans/phase12_finishedplan_product_owned_blockvolume_lifecycle_mvp.md` | Historical product-owned blockvolume lifecycle MVP plan closed by lifecycle ownership and scoped delete validation. | +| `finished-plans/phase13_finishedplan_durable_volume_restart_reattach_mvp.md` | Historical durable volume restart/reattach MVP plan closed by RF=1 durable hostPath restart gates. | +| `finished-plans/phase14_finishedplan_multi_node_attach_and_placement_mvp.md` | Historical same-node multi-node-capable attach and placement MVP plan. | +| `finished-plans/phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md` | Historical RF=2 mounted app baseline plus controlled primary-failure safe-refusal plan. | +| `finished-plans/phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md` | Historical Stage 1 mounted recovery ACK profile plan: RF=2 best-effort demo recovery and RF=3 sync-quorum beta recovery through CSI/pod recreate. | +| `finished-plans/phase17_finishedplan_stage2_transparent_multipath_host_failover_mvp.md` | Historical Stage 2 transparent mounted failover plan: RF=3 sync-quorum iSCSI ALUA/dm-multipath recovery without pod recreate. | +| `finished-plans/phase18_finishedplan_node_loss_survival_mvp.md` | Historical Node-Loss Survival plan: RF=3 sync-quorum Kubernetes-node-loss recovery through CSI/pod recreate on a surviving node. | +| `finished-plans/phase19_finishedplan_control_plane_observation_ai_readable_ops_mvp.md` | Historical Control-Plane Observation plan: read-only master evidence API, AI-readable CLI export, product-owned event stream, and support-bundle evidence. | | `ref/production-readiness-plan.md` | Longer readiness reference and iSCSI P1-P6 detail. | | `ref/light-use-block-storage-ux-research.md` | Comparison of Longhorn, OpenEBS, Rook/Ceph, Piraeus/LINSTOR, and EBS CSI light-user install/operations UX. | | `ref/blockvolume-lifecycle-ownership-contract.md` | Product-owned generated blockvolume workload lifecycle ownership contract for the current plan. | diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index a815b9bc05..9fbd6d8d76 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -1,276 +1,427 @@ -# Current Plan: Basic Mounted Failover And Reattach MVP +# Current Plan: Phase 20 - Activation / Day-1 Ops MVP -Status: active, opened after closing -`finished-plans/phase14_finishedplan_multi_node_attach_and_placement_mvp.md`, -0% implementation. +Status: implementation and QA slices passed for the script-based v0.2 alpha +path. Release notes and user docs are in place. Formal close report / move to +finished-plans is the remaining bookkeeping step. -QA needed now: no. First dev slice is D1/D2 audit and contract. Ask QA after a -runner-native gate exists, or earlier only if the audit finds ambiguous product -behavior that needs independent scenario design. +Previous closed capability: + +- `finished-plans/phase19_finishedplan_control_plane_observation_ai_readable_ops_mvp.md` +- Control-plane observation QA evidence: run `20260517-011004-4b79`. + +## Release Ladder From Here + +- `v0.2-alpha` (this plan): script-based Day-1 activation and first-volume + loop. Users can activate the stack, create one PVC, verify writer/reader + data, generate a local read-only report, and clean up. +- `v0.3-alpha` (next): Helm activation. Convert the supported install path into + a Kubernetes-native chart while preserving preflight, first-volume smoke, + report generation, and cleanup evidence. +- `v0.4-beta-candidate` (after Helm): Operator lifecycle. Add CRDs, + Conditions, Events, and day-2 reconciliation for install status, node + eligibility, volume lifecycle, recovery observation, and safe cleanup. + +Product guidance: do not jump directly from scripts to operator. Helm is the +right next release because it makes installation regular and reviewable without +locking us into a CRD/operator lifecycle contract too early. The operator +release is more meaningful as a product milestone because it can close the +Kubernetes lifecycle loop, but it should build on a charted install contract. ## Product Question -Can an early Kubernetes user recover from a primary `blockvolume` failure while -an app is using a PVC, and understand the recovery through inventory/support -bundles without reading internal logs? - -The last plans proved the light-use path: +Can a new Kubernetes user complete one understandable block-storage activation +loop without reading internal docs or SSHing into every node? ```text -first volume -> cluster inventory -> product-owned lifecycle -> durable -restart/reattach -> same-node placement/attach +preflight +-> install +-> node readiness +-> create PVC +-> volume ready +-> write/read app +-> status/timeline/evidence +-> cleanup ``` -This plan moves the next visible beta gap: +Expanded product loop: ```text -PVC writes data -> primary blockvolume fails -> authority moves or recovery is -refused safely -> app reattaches/restarts -> data is still readable -> inventory -explains the timeline +install Seaweed Block from one documented path +-> verify node readiness and blockers +-> create one PVC-backed volume through Kubernetes +-> run an app write/read check +-> inspect read-only CLI/status evidence +-> collect product evidence, inventory, logs, and support bundle +-> uninstall cleanly ``` -The narrow target claim is: +This plan is about activation and day-1 operations. It should not add new HA, +backup, restore, repair, or mutating admin claims. -```text -On a supported alpha Kubernetes lab, Seaweed Block can run an RF=2 failover -exercise for an iSCSI PVC, preserve previously acknowledged data across a -controlled primary failure, reattach the workload through the documented path, -and publish enough status/inventory evidence to explain the authority epoch, -old primary fencing, new primary, and any non-claim. -``` +## Core Thesis -This is not a production HA claim. It does not claim transparent zero-disruption -I/O, arbitrary node loss, automatic cross-node scheduling, RF=3 live Kubernetes -operation, full quorum durability, rebuild completion, upgrade safety, -performance SLOs, or UI. +The product is now strong enough in recovery and observation that the next +highest-friction gap is the user journey around it. A good block product needs +more than a working CSI path: users need to install it, understand whether each +node is usable, create volumes, see what happened, and capture evidence when it +is not healthy. -## Why This Is Next - -The product is now usable enough that the next user question is availability: - -```text -What happens when the backing blockvolume dies while my pod is mounted? -``` - -We should not jump directly to broad HA. Existing protocol gates already proved -important pieces: - -- iSCSI ALUA failover and mounted failover are release-gated in runner-native - chains. -- NVMe multipath failover is release-gated separately. -- Durable restart/reattach is closed for the RF=1 Kubernetes path. -- Same-node placement and inventory now make endpoint ownership visible. -- Returned-replica component and iSCSI returned-replica chains exist, but the - user-facing Kubernetes recovery loop is not yet a product claim. - -The next plan should connect these pieces through the app/PVC path, while being -strict about what is actually guaranteed. - -## Current Honest State - -What already works: - -- A generated RF=1 iSCSI PVC can be used by an app pod under documented - same-node loopback placement. -- Two live PVCs can coexist on the same alpha node with distinct ports. -- Product-owned lifecycle creates generated blockvolume Deployments. -- Durable hostPath restart preserves data for the RF=1 path. -- `sw-block ops inventory` exposes PVC/PV/workload/node/frontend/status/support - bundle evidence. -- Protocol-level iSCSI and NVMe failover chains exist and are green in prior - gates. - -What is still weak or unknown: - -- Live RF=2/RF=3 Kubernetes lifecycle is still a non-claim. -- The alpha frontend remains loopback-oriented for the supported attach path. -- It is not yet proven that Kubernetes app write/read survives a controlled - primary failure through the normal PVC path. -- We need to define exactly which write acknowledgements are protected in the - MVP: best-effort, quorum, or full-ack. -- We need to prove stale-primary fencing and returned-replica behavior in the - same evidence model users see, not only in component logs. -- A failing recovery must be safe and explainable; silent promotion is worse - than an honest refusal. +The implementation should reuse the Phase 19 observation surface. Dashboard, +CLI, logs, and bundles should all describe the same facts with stable reason +codes. ## Scope -In scope: +### D1: Install Loop -- Audit current RF=2/RF=3 failover behavior across existing protocol gates, - master assignment, launcher rendering, CSI attach, durable status, and - inventory fields. -- Define the MVP recovery contract: what failure is injected, what ACK profile - is claimed, what reattach means, and what must be fenced. -- Add fast tests for authority movement, stale-primary visibility, inventory - failover fields, and support-bundle issue wording. -- Add a runner-native failover gate that exercises a PVC write/read path through - a controlled primary failure or, if the current product cannot safely do that, - proves the safe refusal with an actionable bundle. -- Add negative fixtures for unsafe promotion conditions, stale primary, missing - durable evidence, or insufficient replica coverage. -- Update `docs/operations-v1.md` with failover usage, limitations, and support - bundle interpretation. +- Keep `scripts/install-k8s-alpha.sh` as the implementation substrate for this + phase. +- Add a simpler documented wrapper path if needed. This should wrap preflight, + local image build/import, install, rollout wait, and summary. It may be a + script first; a `sw-block install k8s-alpha` CLI is optional and should not + block the first gate. + - Dev slice: `scripts/activate-k8s-alpha.sh` is the first wrapper path. It + calls `preflight-k8s-alpha.sh`, `build-alpha-images.sh`, + `install-k8s-alpha.sh`, applies the alpha StorageClass, captures rollout + readiness, and writes `activation-summary.txt`. + - Image path split: + - `SW_BLOCK_ACTIVATION_IMAGE_MODE=local` (default) builds/imports + `sw-block:local` and `sw-block-csi:local` for dev and QA work-tree + validation. + - `SW_BLOCK_ACTIVATION_IMAGE_MODE=published` skips local build/import, + runs GHCR preflight, and installs `ghcr.io/seaweedfs/seaweed-block:alpha` + plus `ghcr.io/seaweedfs/seaweed-block-csi:alpha` unless overridden. + This is the PM/user-path test surface. Prefer `sha-` or release + tags over mutable `:alpha` for close validation. -Out of scope: +- Add a user-facing install path in README/docs that makes prerequisites, + expected components, and verification commands explicit. +- Emit a concise install summary: + - master ready, + - CSI controller ready, + - CSI node ready count, + - StorageClass present, + - selected protocol, + - selected ACK profile, + - known non-claims. + - Dev slice: summary fields are stable key/value lines: + `activation_status`, `master_ready_replicas`, + `csi_controller_ready_replicas`, `csi_node_ready`, + `storageclass_provider`, `protocol`, `ack_profile`, and next status / + inventory commands. +- Failed install should explain the blocker: missing tool, missing k3s access, + image import failure, pod not ready, or node prerequisite mismatch. +- QA slice: `testops/scenarios/activation-day1-install-chain.yaml` validates + the D1 install-to-ready path. -- Transparent I/O continuation without pod restart. -- Arbitrary Kubernetes node loss. -- Production HA. -- RF=3 live Kubernetes close unless the audit shows it is already safe enough - to gate. -- Automatic rebuild completion and returned-replica reintegration as a broad - claim. -- Performance, stress, upgrade, backup/restore, UI, or enterprise operations. +### D2: Node Readiness -## Top Blocking Issues +- Provide a read-only node readiness view before claiming add-node automation. +- A node row should make clear: + - Kubernetes node name, + - CSI node pod status, + - iSCSI / multipath prerequisite status where applicable, + - whether the node is eligible for blockvolume placement, + - frontend address mode: loopback or non-loopback, + - blocker reason if not eligible. +- If this phase adds an `add-node` command, it must be conservative: preflight + and explain eligibility first; mutating scheduling or rebalance behavior is + out of scope unless separately gated. -### P0: ACK Profile Must Be Explicit +### D3: Add-Volume Loop -A user cannot trust a failover claim unless the product says what kind of writes -are protected. +- Document the canonical dynamic PVC path as the normal volume creation path. +- Provide a minimal user-facing "add volume" path. This can be a documented + PVC YAML template first. A CLI helper is optional and, if added, must be a + thin generator around Kubernetes PVC creation. It must not bypass PVC/CSI. -Close requirement: the plan documents and gates the exact ACK profile used by -the scenario. If the current path is best-effort, the failover claim must be -limited to writes proven durable by evidence. - -### P0: Stale Primary Must Not Be Ambiguous - -After authority moves, the old primary must be fenced, degraded, or otherwise -reported as unsafe. It must not look like a valid writer. - -Close requirement: inventory/support bundles expose old primary state, new -primary state, epoch/endpoint version, and an issue line when stale-primary -fencing is incomplete. - -### P0: App-Path Recovery Must Be Real Or Honestly Refused - -The product should either complete the controlled recovery through PVC -write/read, or fail closed with an explainable bundle. - -Close requirement: the runner-native gate proves one of those outcomes with -real app data, not only internal PASS lines. - -### P1: Returned Replica Must Have A Safe State Machine - -Returned replicas should not become ready from heartbeat alone. - -Close requirement: at minimum, the negative fixtures demonstrate that returned -or unplaced replicas are not promoted to healthy without the required durable -frontier/rebuild evidence. - -## Deliverables - -### D1: Failover Reality Audit - -Read existing code, docs, and gates to answer: - -- what RF=2/RF=3 paths already exist, -- how master promotion is triggered, -- how CSI attach/reattach behaves after a primary move, -- where authority epoch and endpoint version are recorded, -- how old-primary/stale-primary state is exposed, -- how returned-replica state is represented, -- what the current ACK profile really is. - -Output: `internal/docs/ref/mounted-failover-reattach-audit.md`. - -### D2: Recovery Contract - -Add a reference contract describing: - -- supported MVP topology, -- failure injection, -- ACK profile, -- expected authority transition, -- app reattach behavior, -- inventory/support-bundle fields, -- explicit non-claims. - -Output: `internal/docs/ref/mounted-failover-reattach-contract.md`. - -### D3: Fast Tests - -Add or tighten tests for: - -- authority epoch movement and stale-primary issue wording, -- inventory before/after failover fields, -- returned-replica not-ready wording, -- support-bundle timeline fields, -- safe refusal when required durable evidence is missing. - -### D4: Runner-Native Happy Or Safe-Refusal Gate - -Add a scenario that: - -```text -pre_clean -install/build alpha path -create RF=2 PVC or the nearest supported failover fixture -write/check data before failure -inject controlled primary failure -observe authority move or safe refusal -restart/reattach app as required by the contract -read/check data after recovery -collect inventory/support bundle before cleanup -collect_and_cleanup(always) +```bash +kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml ``` -If the current product cannot safely recover through the app path, the gate must -fail closed intentionally and assert the exact issue class. - -### D5: Negative Fixtures - -Add at least two focused fixtures: - -- stale primary still visible after authority move, -- missing durable frontier / returned replica not eligible, -- insufficient replica coverage for the claimed ACK profile, -- endpoint unreachable after promotion. - -The output should be an actionable inventory/support bundle. - -### D6: Operations Manual Update - -Update `docs/operations-v1.md` and related quickstart docs with: - -- how to run the failover exercise, -- how to read before/after authority evidence, -- what app restart/reattach behavior is expected, -- what remains a non-claim. - -### D7: QA Close Gate - -Create a strict QA assignment that validates: - -- runbook clarity, -- app-path write/read before and after failure or honest safe refusal, -- stale-primary/new-primary evidence, -- support-bundle self-explanation, -- cleanup hygiene, -- docs do not over-claim HA. - -## Gates To Close - -This plan closes only when: - -1. ACK profile and topology are documented. -2. Fast tests cover authority/fencing/inventory wording. -3. A runner-native gate proves app-path recovery or intentional safe refusal. -4. Negative fixtures show unsafe states are visible and not promoted. -5. Inventory/support bundles explain the recovery timeline. -6. Cleanup leaves no active sessions, processes, port-forwards, or generated - workloads. -7. QA validates independently and reports no blocking usability issue. - -## Success Statement - -After this plan, Seaweed Block can make a narrow beta-facing availability -statement: +- The close gate must prove at least two volumes can be created and listed + without attribution or port/status collisions. +- Add or improve a small command/view that maps: ```text -For the documented MVP topology and ACK profile, a controlled primary failure -is either recovered through the PVC app path with data verified after reattach, -or refused safely with a support bundle that explains exactly why recovery is -not yet claimed. +PVC -> PV -> volume_id -> replicas -> primary -> frontend -> events -> bundle ``` + +- The user should be able to create one PVC, watch it become ready, and see the + same volume appear in CLI/dashboard evidence. +- Dev slice: `scripts/run-basic-app-example.sh` runs the canonical + `examples/kubernetes/basic-app` PVC/writer/reader loop, collects + `sw-block ops cluster` and `sw-block ops inventory` evidence, and writes + `first-volume-summary.txt`. +- QA slice: `testops/scenarios/activation-day1-first-volume-chain.yaml` + validates the published-image Day-1 first-volume path. + +### D4: Read-Only Status / Dashboard View + +- Dashboard/status view is read-only for this plan. +- It may be a local web view, static report, or CLI-driven status page. Do not + make the close depend on a full hosted UI unless that implementation is + deliberately chosen. +- Product positioning: + +```text +V2 UI shape: +cluster / servers / volumes / ops + +V3 sw-block data model: +PVC / PV / volume_id / replica / primary / frontend / epoch / +event timeline / bundle / reason codes +``` + +- Build a read-only block dashboard/status view modeled after the SeaweedFS + `/block/` information architecture, backed by the Phase 19 observation API, + with no mutating admin actions. +- Dev slice: `sw-block ops report` renders a static read-only status page from + either live `--master-api` evidence or a saved support bundle. It writes + `index.html`, `cluster-evidence.json`, `timeline.jsonl`, and `summary.txt` + from the shared observation core. +- Day-1 helper slice: `scripts/run-basic-app-example.sh` now generates + `status/report/index.html` after writer/reader verification, so the first + volume bundle contains a user-readable status page and machine-readable + evidence together. +- Reuse lessons from the V2 SeaweedFS block UI where useful: + - reference files: + `C:\work\seaweedfs\weed\server\master_server_handlers_block_ui.go`, + `C:\work\seaweedfs\weed\server\master_server.go`, + `C:\work\seaweedfs\weed\storage\blockvol\blockapi\types.go`, + - useful read-only shape: cluster cards, server table, volume table, + replica details, health counters, barrier/failover/rebuild counters, + - do not copy mutating V2 operations into this phase: create, delete, + promote, expand, assign, or force actions. +- Minimum pages or panels: + - cluster summary, + - node readiness, + - volumes table, + - volume detail, + - event timeline, + - support bundle / log links. +- The dashboard must consume product-owned observation data, not scrape random + pod logs as its primary source. +- Logs are supporting evidence, not authority. +- Mutating actions such as promote, repair, delete, rebuild, failback, and + cleanup buttons are explicitly out of scope. +- Enterprise UI boundary: first ship observation. Add admin workflows only + after each workflow has a separate product spec, RBAC/audit model, and strict + QA gate. + +### D5: Status / Logs / Bundle Loop + +- The default CLI path should stay useful without the dashboard: + +```text +sw-block ops cluster --master-api +sw-block ops volumes +sw-block ops describe volume +sw-block ops timeline volume +sw-block ops inventory --namespace --master --out +``` + +- Text output should be human-readable and AI-readable. +- JSON/JSONL output should remain stable enough for dashboard, CI, and support + assistant use. +- Every unhealthy state should include a reason code and next inspection step. + +### D6: README And User Path + +- README must present Seaweed Block as an alpha/early-beta product loop, not a + collection of internal gates. +- README must keep claims narrow: + - not production-ready, + - no full HA claim, + - no backup/restore, + - no upgrade safety, + - no mutating admin operations, + - no hosted dashboard unless implemented and gated. +- The documented quick path must match the commands the close gate runs. +- Dev slice: README and `docs/quickstart-kubernetes.md` were rewritten around + the end-user path: activate, first PVC, writer/reader verification, local + read-only report, troubleshooting evidence, and cleanup. Internal gate + details remain in QA docs instead of the user tutorial. + +### D7: TestOps Controller / Agent Evidence Loop + +- Treat TestOps as product infrastructure for this phase, not as ad-hoc + scripting. The current runner is already the Windows-side controller: it owns + `run_id`, phase/action status, timeouts, cleanup, and the central result + bundle. +- Add a controller/agent track rather than relying only on SSH: + - controller stays on the Windows/dev workstation and runs scenarios, + distributes binaries/scripts, owns cancellation, and writes the final + bundle; + - Linux node agents on m01/m02/tp01 collect local evidence and eventually + execute bounded jobs; + - SSH remains fallback until the agent proves stable. +- First useful agent capability: + - `/healthz` with node name, version, uptime; + - `collect_node_snapshot` for process, iSCSI sessions, multipath, NVMe, + mounts, disk, kernel tail, network, containerd/k3s images, and kubelet + status; + - `collect_path` for local artifact pickup; + - cancellation-aware bounded command execution later, after snapshot is + proven. +- K8s/block failure auto-collect should become a gate rule: + - on phase failure, collect node snapshots from involved nodes, + - collect Kubernetes state (`kubectl get`, `describe`, events, selected logs, + rendered manifests vs live objects), + - collect product state (`sw-block ops cluster`, inventory, timeline/events), + - then run cleanup and collect after-clean state. +- Why this is in the plan: Day-1 first-volume r1/r2 showed that without + automatic evidence, a timeout is ambiguous; with `writer-describe.txt`, the + root cause was immediately visible as loopback publish target vs cross-node + writer placement. +- Open-source analogs to learn from, not copy blindly: + - Sonobuoy: Kubernetes aggregator plus job/daemonset plugins; useful model + for cluster-wide collection and per-node log gatherers. + - Ansible Runner / AWX execution nodes: useful model for transmit -> worker + -> process and central artifact handling. + - Jenkins controller/agent: useful model for scheduling jobs onto prepared + nodes. + - Robot Framework remote libraries: useful model for remote capability + exposure, but too generic for block-specific node snapshots. +- Non-goal for Phase 20: do not rewrite the runner. Add snapshot collection and + failure auto-collect first; move remote exec to agent only after the evidence + loop is stable. + +## Non-Claims + +This plan does not claim: + +- production installer/operator lifecycle, +- full Helm/operator packaging unless explicitly chosen as the implementation, +- online upgrade or rollback safety, +- mutating dashboard actions, +- automatic repair/rebuild/failback, +- backup/snapshot/restore, +- new HA semantics beyond closed RF=3 gates, +- transparent node-loss failover beyond existing closed claims, +- broad distro/kernel compatibility. + +## Hard Gate + +The close gate should run from a fresh supported Kubernetes lab and prove: + +1. One documented command path runs preflight, install, rollout wait, and + install summary. +2. Node readiness view identifies at least one eligible node and explains any + blockers. +3. A PVC is created through the documented Kubernetes path. +4. The generated product-owned volume becomes ready. +5. An app writes and reads data through the mounted PVC. +6. `sw-block` status/evidence explains PVC -> volume -> replica -> primary -> + frontend -> timeline. +7. Product evidence and inventory/support bundle are collected. +8. Cleanup/uninstall leaves no active iSCSI sessions, stale blockvolume + Deployments, stale port-forwards, or unexpected product pods. +9. README quick path matches the commands used by the gate. +10. Failure bundles include automatic K8s/product/node evidence sufficient to + explain at least one failed first-volume run without manual SSH. + +## Suggested Close Claim + +Seaweed Block provides an alpha install-to-operate loop for Kubernetes users: +from a fresh supported lab, run one documented install path, create a +PVC-backed block volume, verify app write/read, inspect read-only status and +timeline evidence, collect support artifacts, and uninstall cleanly. + +## Next Product Choices After This + +- Phase 21: Helm Activation MVP. +- Phase 22: Operator Lifecycle MVP. +- Backup / Snapshot / Restore MVP for data protection. +- Rebuild / Reintegration / Failback MVP for returned replicas. +- Mutating admin controls with RBAC/audit hard gates. + +## Phase 21 Candidate: Helm Activation MVP + +Product question: + +```text +Can a Kubernetes user install Seaweed Block as a normal chart, create a first +PVC, inspect status/report evidence, and uninstall without relying on internal +script-only manifest mutation? +``` + +Scope: + +- Add `charts/seaweed-block/` for blockmaster, CSI controller/node, CSI driver, + RBAC, StorageClass, CHAP Secret, and cluster-spec ConfigMap. +- Add `values.yaml` and `values.schema.json` for: + - images and immutable tags/digests, + - namespace and StorageClass name, + - ACK profile, + - frontend protocol, + - external iSCSI/status, + - CHAP configuration, + - cluster/node specs, + - Stage 2 multipath, + - resource requests and tolerations/node selectors where needed. +- Keep `scripts/activate-k8s-alpha.sh` as a wrapper that can generate + `values.day1.yaml`, run preflight, call `helm install`, run the first-volume + smoke, generate `sw-block ops report`, and verify cleanup. +- Do not claim upgrade safety until a separate Helm upgrade/rollback smoke + passes. + +Hard gate: + +1. Fresh supported cluster passes preflight. +2. `helm install` with generated Day-1 values reaches blockmaster and CSI + readiness. +3. First PVC writer/reader loop passes. +4. `sw-block ops report` is generated from live product evidence. +5. `helm uninstall` plus host cleanup leaves no iSCSI sessions, product pods, + generated blockvolume Deployments, or unexpected StorageClass residue. +6. README/quickstart describe Helm as the preferred user install path and keep + scripts as dev/TestOps helpers. + +Non-claims: + +- no operator/CRD lifecycle yet, +- no online upgrade/rollback safety until gated, +- no mutating admin actions, +- no backup/restore or rebuild/failback claim. + +## Phase 22 Candidate: Operator Lifecycle MVP + +Product question: + +```text +Can Seaweed Block become a Kubernetes-native product loop where users see +cluster, node, volume, and recovery lifecycle through CRDs, Conditions, Events, +and read-only dashboard/API evidence? +``` + +Scope: + +- Add CRDs such as `SeaweedBlockCluster`, `SeaweedBlockNode`, and/or + `SeaweedBlockVolume` only after the exact lifecycle ownership is specified. +- Operator owns install/upgrade status, node eligibility, desired StorageClass, + CHAP Secret references, blockmaster/CSI rollout state, and cleanup + reconciliation. +- Conditions must be first-class and user-readable: + `Ready`, `Degraded`, `Recovering`, `Blocked`, `CleanupPending`, with stable + reason codes. +- Events must mirror Phase 19 product observation semantics where possible. +- Mutating actions such as repair, rebuild, promote, failback, or delete remain + out of scope unless each has a separate fencing/RBAC/audit gate. + +Hard gate: + +1. Apply one CR creates the supported stack. +2. Status Conditions show install progress and node eligibility without SSH. +3. First PVC writer/reader loop passes. +4. A controlled failure updates CR status/events and support evidence. +5. Delete CR cleans Kubernetes resources and verifies host/session cleanup via + documented guardrails. +6. Helm-to-operator migration or coexistence boundary is documented. + +Why this release matters: + +Operator is the first release that can make Seaweed Block feel like a complete +Kubernetes storage product: installation, status, lifecycle ownership, cleanup, +and user-visible diagnosis are managed by a product control plane instead of a +collection of scripts. diff --git a/seaweed-block/internal/docs/finished-plans/phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md b/seaweed-block/internal/docs/finished-plans/phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md new file mode 100644 index 0000000000..6eed4dce1f --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md @@ -0,0 +1,134 @@ +# Finished Plan: Basic Mounted Failover And Reattach MVP + +Status: closed. QA close report passed 10/10 strict hard-gate clauses in +`qa-assignments/mounted-failover-reattach-mvp-close-report.md`. + +Opened after closing +`finished-plans/phase14_finishedplan_multi_node_attach_and_placement_mvp.md`. + +Closed after QA-owned runs: + +- RF=2 app baseline `20260513-162339-aee3`: PASS, 7/7 phases, 42/42 actions, +- RF=2 primary safe-refusal `20260513-160112-d3f9`: PASS, 7/7 phases, + 49/49 actions, +- RF=2 degraded replica `20260513-151339-56c2`: PASS, 9/9 phases, + 47/47 actions, +- fast guard tests: `go test ./core/ops -count=1` PASS. + +The first close attempt failed on one residue issue: the RF=2 app baseline left +`/var/lib/sw-block/testops--rf2-app`. The baseline chain now removes that +run-scoped hostPath with `sudo` and asserts the exact path is gone. QA reran and +issued strict PASS. + +## Product Question + +Can an early Kubernetes user recover from a primary `blockvolume` failure while +an app is using an RF=2 PVC, or at least get a safe, self-explaining refusal +instead of a false recovery claim? + +## Delivered Claim + +This plan does not claim automatic RF=2 recovery. + +It delivers a narrower, useful beta-facing availability claim: + +```text +On the documented alpha Kubernetes iSCSI path, Seaweed Block can run an RF=2 +PVC in the two-logical-server development/TestOps topology, write/read through +the mounted app path before failure, identify the current primary from +inventory, stop that primary in a scoped way, and refuse recovery safely when +the peer replica is not promotion-ready. +``` + +The safe-refusal bundle says: + +```text +failover_status: refused +ack_profile: best-effort +failure_class=primary-blockvolume-controlled-stop +before_primary_replica=r1 +failed_replica=r1 +candidate_ready=false +candidate_evidence=... r2 ... replication=not_ready ... +data_check_after_failover=not_claimed +reason=candidate_not_ready_for_primary +target_ready_replicas=0 +``` + +## What Changed + +- RF=2 lifecycle placement now flows into the authority/inventory evidence + path without collapsing desired/observed replica counts. +- The alpha two-logical-server TestOps topology can render two generated + `blockvolume` Deployments for one RF=2 PVC. +- Frontend/status/data/control ports are allocated distinctly for logical + replicas sharing one physical Kubernetes node. +- Inventory preserves generated replica frontend/status evidence while merging + nested status health. +- Unsafe failover-looking evidence is marked unhealthy: + - stale primary frontend-ready, + - primary with non-`none` replication role, + - non-primary frontend-ready, + - non-primary with `replication_role=none`. +- The RF=2 mounted app baseline proves writer and reader checksums before + failure. +- The controlled primary-failure gate proves safe refusal without creating a + false post-failure reader success. +- `docs/operations-v1.md` now separates: + - default RF=2 safe refusal, + - two-logical-server RF=2 app baseline, + - controlled primary-failure safe refusal, + - RF=2 recovery/promotion as a non-claim. + +## Evidence + +QA close report: + +- `qa-assignments/mounted-failover-reattach-mvp-close-report.md` + +Hard-gate assignment: + +- `qa-assignments/mounted-failover-reattach-mvp-close-hard-gate.md` + +Runner scenarios: + +- `testops/scenarios/mounted-failover-rf2-safe-refusal-chain.yaml` +- `testops/scenarios/mounted-failover-rf2-placement-chain.yaml` +- `testops/scenarios/mounted-failover-rf2-degraded-replica-chain.yaml` +- `testops/scenarios/mounted-failover-rf2-app-baseline-chain.yaml` +- `testops/scenarios/mounted-failover-rf2-primary-failure-safe-refusal-chain.yaml` + +Reference docs: + +- `ref/mounted-failover-reattach-audit.md` +- `ref/mounted-failover-reattach-contract.md` +- `ref/product-spec-gate-template.md` + +## Non-Claims + +This plan explicitly does not claim: + +- RF=2 recovery/promotion after primary failure, +- transparent in-place I/O continuation, +- RF=3 Kubernetes lifecycle or failover, +- arbitrary node loss, +- remote-node attach to loopback frontends, +- sync-quorum or sync-all durability, +- rebuild/reintegration completion, +- performance SLOs, +- upgrade or broad uninstall safety, +- UI/operator-grade remediation. + +## Next Product Gap + +The next plan should target the real missing capability exposed by this plan: + +```text +Can the RF=2 peer progress from observed/not_ready to promotion-ready, and then +can the product recover through a controlled primary failure with reattach and +checksum proof? +``` + +That requires durable frontier/ACK-profile clarity, replica catch-up evidence, +candidate eligibility, stale-primary fencing, and a positive recovery gate. It +should not weaken the safe-refusal semantics just to make a green test. diff --git a/seaweed-block/internal/docs/finished-plans/phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md b/seaweed-block/internal/docs/finished-plans/phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md new file mode 100644 index 0000000000..d0b92d9fd5 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md @@ -0,0 +1,661 @@ +# Finished Plan: Stage 1 Mounted Recovery ACK Profile MVP + +Status: closed. QA close report passed strict validation in +`qa-assignments/stage1-mounted-recovery-ack-profile-mvp-close-report.md`. + +Opened after closing +`finished-plans/phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md`, +and closed after QA-owned RF=3 sync-quorum recovery run +`20260514-075221-da0d` passed from clean state with 7/7 phases and 75/75 +actions. + +D1/D2 product audit and recovery contract were drafted. D3/D4 prove the RF=2 +best-effort controlled recovery demo end-to-end through the +mounted Kubernetes PVC path: writer checksum, promotion-ready peer, controlled +primary stop, master-published new primary, CSI/pod recreate, and reader +checksum. That RF=2 result is explicitly labeled +`claim_profile=controlled-best-effort-demo`; it is not a quorum HA claim. + +The final implementation slice produced a QA-owned RF=3 `sync-quorum` durable +recovery pass. The product rule is stricter than +heartbeat readiness: when an RF3 primary fails, master actively uses promotion +evidence that the surviving candidate covers the sync-ACK frontier before +allowing authority promotion. The code seam is in `core/host/master`: RF3 +promotion is blocked without a fresh promotion probe. If the required sync ACK +LSN is known, only a `sync-quorum`/`sync-all` candidate whose durable LSN covers +that required LSN remains eligible. If the required LSN is not known yet, the +seam falls back to the highest probed durable LSN as a weak recovery choice; +that is useful for best-effort/control recovery and for shrinking loss, but it +is not enough for a beta HA claim until committed-frontier reporting exists. +The live wiring refreshes that prober from blockmaster's launcher workload plans +when `--launcher-status` is enabled: master derives each candidate's loopback +status endpoint from the generated workload port plan, calls `/status` and +`/status/durable` on demand, and feeds `replica_ready` plus durable frontier LSN +into the RF3 gate. The promoted primary also verifies surviving peers with a +barrier at its local frontier and seeds their live ship cursor before admitting +post-promotion writes, so sync-quorum writes continue after one primary is +stopped. QA verified the post-promotion error signatures were absent: +`tail-emit cursor gap`, `quorum not met`, and +`SCSI WRITE backend.Write FAILED`. + +Stage: **Stage 1 - Safe K8s Recovery via CSI/Pod Recreate**. + +The current plan deliberately targets a safe Kubernetes recovery loop through +CSI/pod recreate. Transparent in-place host-path failover through iSCSI ALUA or +NVMe ANA multipath is the next plan, not this one. + +Minimum product line: if Seaweed Block wants to claim HA block behavior in +Kubernetes, Stage 1 is the floor. "Master changed primary" is not a product +claim. The minimum acceptable user experience is automatic detection, automatic +safe promotion, automatic CSI/node reattach on pod recreate, and post-failure +data verification without manual operator repair. Stage 2 raises that to +transparent or near-transparent multipath failover. + +QA needed now: no for this plan. The next QA touchpoint belongs to the next +active plan. + +Product decision: Stage 1 splits into two explicit profiles: + +- **RF=2 best-effort controlled recovery demo**: prove master promotion, + CSI/pod recreate, and post-failure checksum for the exact gated bytes. This + is useful light-use evidence, but it is not a quorum durability claim. +- **RF=3 sync-quorum durable recovery**: prove the beta-facing writable HA + recovery line, because losing one replica can still leave write quorum. + +## Product Question + +Can Seaweed Block recover a mounted Kubernetes app/PVC path after controlled +primary failure under an ACK profile that honestly matches the user claim: +RF=2 best-effort as a controlled demo, or RF=3 sync-quorum as the durable HA +line? + +This plan serves the product positioning in +`ref/product-positioning-v1.md`: Seaweed Block should be a lightweight +Kubernetes block product with enterprise protocol discipline and fail-closed +recovery semantics. Recovery is not just another scenario. It is the +availability proof behind that positioning, and the ACK profile defines what +kind of availability can be claimed. + +The engine design lesson from this plan is captured in +`ref/engine-automata-design-note.md`: identity, authority, durability frontier, +recovery, replication handoff, frontend publish, and host attach should be +treated as separate small automata with explicit facts, not one broad green-path +"engine" state. + +The product impact question is: + +```text +Can a small-cluster Kubernetes user trust Seaweed Block to recover a volume +through documented ACK semantics, or refuse promotion/write recovery with +evidence strong enough for an operator/support engineer to act on? +``` + +If this plan cannot improve that user trust, it should not be treated as done. + +The last plan proved the honest negative: + +```text +RF=2 app path works before failure -> r1 primary is stopped -> r2 is not +promotion-ready -> product refuses recovery safely and says why +``` + +This plan targets the next product step in two profiles: + +```text +RF=2 best-effort demo: +app writes data -> r2 catches up for the gated frontier -> r1 fails -> +authority moves safely -> CSI/pod recreate reaches r2 -> reader verifies the +same bytes -> bundle says this is controlled-best-effort-demo, not quorum HA +``` + +```text +RF=3 sync-quorum durable HA: +app writes data with quorum ACK -> one primary fails -> authority promotes a +quorum-covered candidate -> CSI/pod recreate reaches the new target -> reader +verifies the same bytes and RW mount succeeds because quorum remains available +``` + +The close target is not "master promoted a replica" by itself. A promotion that +does not restore a Kubernetes host path is only an internal control-plane event. +The user-visible product result must be one of: + +```text +master/authority promotes -> CSI/node reattaches on pod recreate -> mounted data is verified +``` + +or: + +```text +master/authority refuses -> host path recovery is not claimed -> bundle says exactly why +``` + +The outcome must be either a real recovery proof or a sharper blocker that +states exactly which product semantic is missing. A weaker abstraction is not +acceptable. + +## Stage Gates + +### Stage 1 Hard Gate: Safe K8s Recovery Via CSI/Pod Recreate + +This is the current plan. It is the minimum HA-like Kubernetes product line. + +Pass requires every item below: + +- The peer is promotion-ready before failure based on durable frontier and ACK + evidence, not heartbeat or Deployment readiness. +- Master/authority promotes automatically after controlled primary failure. +- Promotion publishes a new active target generation with epoch and + endpoint-version evidence. +- Old primary is fenced, degraded, or otherwise not presented as a valid writer. +- CSI/node reattach is proven through pod recreate: before/after publish target + and staged target are captured. +- The reader pod uses the same PVC and verifies the same bytes after failure. +- No operator runs a manual promote, manual repair, direct filesystem read, or + direct blockvolume read. +- If any item is missing, recovery is not claimed and the bundle emits a + fail-closed blocker reason. + +### Stage 2 Hard Gate: Transparent Multipath Host Failover + +This is the next plan. Do not use it to close Stage 1. + +Pass requires every item below: + +- CSI publishes/configures multiple paths before failure. +- The protocol-specific host multipath stack is configured and visible: + iSCSI ALUA + dm-multipath, or NVMe ANA + native NVMe multipath. +- Master promotion changes protocol path state consistently with authority + epoch/endpoint generation. +- The mounted workload continues through the host path without pod recreate if + transparent switching is claimed. +- Post-failure checksum verifies through the mounted workload path. +- If transparent switching is not proven, Stage 2 cannot close as recovered. + +## Target Claim + +If successful, the narrow Stage 1 claims are: + +```text +RF=2 controlled demo: On the documented same-node alpha Kubernetes iSCSI path, +with two logical replicas and ack_profile=best-effort plus +claim_profile=controlled-best-effort-demo, an RF=2 PVC can write data, show a +promotion-ready non-primary peer, survive a controlled primary blockvolume +Deployment stop through master-published CSI target generation change, +documented pod recreate/reattach, and verify the exact same bytes after +recovery. Quorum durability and post-failure writable HA are not claimed. +``` + +```text +RF=3 durable HA: On the documented alpha Kubernetes iSCSI path, with three +logical replicas and ack_profile=sync-quorum, a PVC can lose one primary +blockvolume, promote a quorum-covered candidate, reattach through CSI/pod +recreate, mount RW, and verify the same bytes after recovery with inventory +evidence for old-primary fencing, new-primary authority, quorum frontier +coverage, peer eligibility, and CSI/node reattach. +``` + +If not successful, the plan should close only with a specific safe blocker: + +```text +Mounted recovery remains a non-claim because is not yet product-ready. The support bundle identifies the +missing condition. +``` + +## Product Semantics Guardrail + +Do not make RF=2 recovery pass by weakening the block contract. + +Positioning guardrail: + +- The public story leads with product promise, not matrix rows. +- Any new claim must map to a gate, QA evidence, and non-claim boundary. +- If recovery semantics are weaker than the promise, publish safe refusal or a + blocker instead of softening the promise silently. +- A green runner scenario is useful only if it advances one of the visible + values in the positioning: lightweight Kubernetes experience, protocol + discipline, or fail-closed recovery semantics. + +Non-negotiable semantics: + +- no promotion from heartbeat alone, +- no promotion without durable frontier / catch-up evidence, +- no promotion unless the candidate frontier covers the writer's + acknowledged/flushed mounted-write boundary, +- no RF=2 recovery claim from master-side promotion alone, +- no RF=2 recovery claim in this plan unless the host path is proven by + documented CSI/node reattach on pod recreate, +- no recovery claim without post-failure mounted app read/checksum, +- no stale primary left looking like a valid frontend writer, +- no hidden ACK profile; best-effort, sync-quorum, or sync-all must be named, +- no RF3 HA candidate selection from "largest LSN" alone when a required sync + ACK frontier is known; the candidate must first cover the required frontier, + then highest durable LSN can be used as a tie-break/preference among safe + survivors, +- if the required sync ACK frontier is unknown, highest durable LSN is allowed + only as a weak recovery heuristic and must be labeled as such, +- no beta-facing quorum durability wording on a best-effort-only run; + best-effort can only close as a controlled recovery demonstration or safe + blocker, +- no RF=2 sync-quorum writable recovery claim after one replica loss; RF=2 + sync-quorum must fail closed when quorum is unavailable, +- no RF=3 sync-quorum recovery claim unless the mounted app path proves RW + reattach/checksum after one replica loss, +- no "replica observed" standing in for "replica promotion-ready", +- no test-only shortcut that bypasses CSI attach/reattach if the claim is + Kubernetes mounted recovery. + +Use `ref/product-spec-gate-template.md` before implementation. Tests validate +the product contract; tests are not the contract. + +## Why This Is Next + +The product now has a useful, honest safe-refusal path. The remaining user gap +is availability, not placement: + +```text +Can Seaweed Block actually recover when the peer is ready? +``` + +QA repeatedly observed the same blocker in RF=2 gates: + +```text +r1: primary, healthy, epoch=1 +r2: observed, status=unhealthy, replication=not_ready, epoch=0 +``` + +That state is correctly refused. The next plan must make `r2` eligible or prove +why it cannot be made eligible in the current architecture. + +## Current Honest State + +What works: + +- RF=2 PVC can render two generated `blockvolume` Deployments in the + two-logical-server alpha topology. +- RF=2 mounted writer/reader path works before failure through `r1`. +- Inventory exposes `rf=2 desired=2 observed=2`, per-replica status bundles, + primary identity, and degraded peer state. +- Controlled primary failure is scoped and observable. +- Safe refusal is strict and QA-validated when `r2` is not promotion-ready. +- RF=2 best-effort controlled recovery is QA-validated: master promotes the + promotion-ready supporting replica, the reader pod reattaches through CSI/pod + recreate, and the post-failure checksum passes. The bundle labels this as + `controlled-best-effort-demo`, not quorum HA. +- The alpha launcher path can render an explicit ACK profile into generated + `blockvolume` Deployments; the current D4 safe-refusal gate uses + `sync-quorum` instead of silently inheriting the blockvolume `best-effort` + default. +- Fast guards prevent several unsafe failover-looking states from appearing + healthy. +- Fast master-side RF3 guards now block promotion from stale heartbeat readiness + alone. RF3 promotion requires a fresh promotion evidence provider result. With + a known required sync ACK LSN, the candidate must be `sync-quorum`/`sync-all` + and cover that LSN. With no known required LSN, the gate can select the + highest durable survivor as a weak recovery path, including best-effort, but + not as a quorum HA claim. +- Blockmaster launcher ticks now install a workload-plan promotion evidence + provider when `--launcher-status` is enabled. The provider probes candidate + blockvolume loopback status endpoints on demand and returns durable frontier + evidence without adding heartbeat/protobuf fields. +- RF3 candidate choice now follows the product rule: threshold first, best + survivor second. `durable_lsn >= required_lsn` decides whether a candidate can + be promoted; highest durable LSN only decides which safe candidate should be + preferred. If `required_lsn` is absent, highest durable LSN is the fallback + choice and the RPO/commit-boundary remains explicitly weaker. +- RF3 sync-quorum Kubernetes recovery has a QA-owned close run: + `20260514-075221-da0d` on m02. Evidence: writer `/data/demo.bin: OK`, r2 + `candidate_ready=true reason=promotion_ready` at required frontier 44, + controlled stop of r1, master-published primary r2 at epoch 2, CSI/node + restaged portal `127.0.0.1:3261`, reader `/data/demo.bin: OK`, and + `data_check_after_failover=reader_checksum_passed`. +- Promoted-primary replication handoff now seeds covered surviving peers with a + barrier proof at the local frontier. The RF3 pass showed + `seeded live cursor lsn=44`, `ship ok peer=r3`, and zero `tail-emit cursor + gap`, zero `quorum not met`, and zero `SCSI WRITE backend.Write FAILED` + matches after promotion. + +What does not work or is not proven: + +- The required LSN source is still weak/minimal. The current seam can fall back + to highest durable LSN when the required sync ACK LSN is unknown. A + product-grade HA line still needs a committed-frontier source with a defined + RPO window, such as primary-reported committed LSN on event/periodic + boundaries plus failover probe cross-checks. +- Transparent protocol multipath failover is intentionally not part of this + plan's close claim. The existing iSCSI ALUA and NVMe ANA protocol gates remain + substrate evidence only until a Kubernetes multipath plan wires them into CSI. + +## Scope + +In scope: + +- Audit the RF=2/RF3 replication/catch-up path from primary writes to peer + durable readiness. +- Define the positive recovery contract: ACK profile, peer eligibility, failure + injection, CSI/pod-recreate recovery method, and evidence fields. +- Add fast tests for peer promotion readiness and refusal when readiness is + missing. +- Add a runner-native gate that waits for a promotion-ready peer, injects + controlled primary failure, then either proves recovery with reader checksum + or emits a sharper safe blocker. +- Add the RF3 sync-quorum gate as the durable HA product line once promotion + evidence is backed by live replica probes. +- Update `docs/operations-v1.md` only when a user-facing claim boundary changes. + +Out of scope: + +- transparent in-place I/O continuation, +- Kubernetes CSI multipath setup and transparent host-path switching, +- arbitrary node loss, +- remote-node attach to loopback frontends, +- production HA, +- performance/soak, +- upgrade/uninstall safety, +- UI/operator-grade remediation. + +## Top Blocking Issues + +### P0: Peer Promotion Readiness Must Be Real + +The product must distinguish: + +```text +observed replica != caught-up replica != promotion-ready replica +``` + +Close requirement: status/inventory exposes a peer readiness reason that a QA +operator can read without logs, and authority refuses promotion when the peer is +not ready. + +### P0: Durable Frontier / ACK Profile Must Be Explicit + +Recovery means something only if the product says which acknowledged writes are +covered. + +Close requirement: the gate names `ack_profile=` and records durable +frontier/catch-up evidence that justifies promoting the peer for the data being +verified. + +### P0: Stale Primary Fencing Must Survive The Positive Case + +After authority moves, the old primary must not look like a valid writer. + +Close requirement: after-failure inventory/support bundle shows old primary +state, new primary state, epoch/endpoint-version transition, and an issue if +the old primary is still frontend-ready. + +### P0: Recovery Must Use The App/PVC Path + +The positive claim is not a component test. + +Close requirement: writer checksum before failure and reader checksum after +failure use the Kubernetes PVC path and documented pod recreate/reattach method. + +### P0: CSI/Pod-Recreate Host Path Correctness Is The User-Visible Recovery + +Master-side promotion and target publication are necessary, but not sufficient. +The product only recovers for the user when the Kubernetes path reattaches +through the documented Stage 1 mechanism: + +```text +CSI/node reattach on pod recreate +``` + +Close requirement: D4 must prove that after authority movement, CSI consumes the +new master-published target generation, the recreated reader pod stages through +that target, and the mounted data checksum matches. If CSI/node reattach is not +proven, the only valid outcome is safe refusal with +`reason=host_path_recovery_not_verified` or a more specific subclass. + +The next plan will target Stage 2: + +```text +protocol multipath switch via iSCSI ALUA/dm-multipath or NVMe ANA/native multipath +``` + +## Deliverables + +### D1: RF=2 Replication Reality Audit + +Status: drafted in `ref/rf2-promotion-readiness-audit.md`. + +Read code, tests, logs, and current RF=2 artifacts to answer: + +- how writes are replicated from `r1` to `r2`, +- why prior live runs left `r2` at `replication=not_ready epoch=0`, +- what status endpoint or authority field should indicate peer catch-up, +- how `--replication-ack` is wired in generated Kubernetes workloads, +- whether existing V2 or protocol-gated paths have useful behavior to port + without weakening V3 semantics. + +Output: `internal/docs/ref/rf2-promotion-readiness-audit.md`. + +### D2: Positive Recovery Contract + +Status: drafted in `ref/rf2-promotion-ready-recovery-contract.md`. + +Create a cold product contract for RF=2 recovery: + +- supported topology, +- ACK profile, +- peer eligibility fields, +- durable frontier evidence, +- controlled failure class, +- old-primary fencing evidence, +- host-path recovery method: CSI/node reattach on pod recreate, +- non-claims. + +Output: `internal/docs/ref/rf2-promotion-ready-recovery-contract.md`. + +### D3: Fast Promotion-Readiness Guards + +Status: in progress. Added first guard set: + +- heartbeat/live process alone does not set `ReadyForPrimary`, +- supporting replica-ready can be a promotion candidate while frontend-unhealthy, +- superseded replica is not promotion-ready, +- initial placement can bind a placeable replica before promotion readiness, +- failover/rebalance still require `ReadyForPrimary`, +- current-primary endpoint refresh can proceed when no promotion-ready peer + exists. +- beta-facing recovery rejects `best-effort` ACK profile unless explicitly + labeled as a controlled best-effort demonstration, +- promotion readiness requires known durable frontier evidence, +- a peer behind the mounted-write frontier is not promotion-ready, +- `sync-quorum` or `sync-all` with covered frontier can be promotion-ready. +- inventory/support summaries expose per-replica `candidate_ready`, + `ack_profile`, frontier-known fields, and `candidate_not_promotion_ready=...` + issue lines for RF>1 non-primary replicas. +- CSI `ControlStatusLookup` carries internal publish-target generation evidence + (`epoch`, `endpoint_version`) copied from master status for before/after D4 + assertions, while `ControllerPublishVolume` still keeps authority-shaped + fields out of CSI `publish_context`. +- durable status and nested ops-status bundles expose storage boundary evidence + (`frontier_known`, `durable_lsn`, `retained_lsn`, `head_lsn`); Kubernetes + inventory propagates the candidate's durable frontier but still refuses + promotion with `required_frontier_missing` until D4 supplies the mounted-write + required frontier. +- Kubernetes launcher rendering now has an explicit `launcher-replication-ack` + product input, validates the profile, and emits `--replication-ack=` + into every generated blockvolume Deployment. The D4 primary-failure + safe-refusal gate opts into `sync-quorum` and asserts the generated manifests + plus safe-refusal marker carry that profile. +- supporting replicas now consume their own master-minted peer descriptor from + the active primary's `AssignmentFact`, seeding adapter lineage for the same + epoch/endpoint-version while preserving frontend gating and avoiding + replication fan-out installation on the non-primary. +- `scripts/run-alpha-app-demo.sh` has a `SW_BLOCK_DEMO_STOP_AFTER=promotion-ready` + mode and the runner-native + `mounted-failover-rf2-promotion-ready-chain.yaml` scenario verifies the + non-primary candidate becomes promotion-ready before any failure is injected. +- supporting-replica durable storage opened before assignment can now latch the + assigned epoch/endpoint-version through a ready-marker path without requiring + frontend Healthy; QA verified that this closes the live + `durable_frontier_missing` blocker and turns the RF=2 volume rollup to + `status=ok` before failure. +- `scripts/run-alpha-app-demo.sh` now branches the primary-failure path: a + not-ready candidate still emits the existing safe-refusal marker, while a + promotion-ready candidate writes `primary-failure-recovery.txt`, injects the + scoped primary stop, waits for the candidate to become the master-published + primary, and then lets the reader pod recreate/reattach and verify data. +- `mounted-failover-rf2-promotion-recovery-chain.yaml` is the first + runner-native positive recovery attempt. It asserts writer checksum, + candidate readiness, promoted primary differs from failed primary, no + safe-refusal marker, and reader checksum after failure. +- Dev manual run `20260514-042312-manual-recovery` exposed a same-replica epoch + latch blocker: promoted r2 reached `epoch=2`, but durable storage still + refused Normal I/O because it was latched to `epoch=1`. +- Dev manual run `20260514-043408-manual-recovery2` advanced past that blocker: + master promoted r2, CSI/attach reached the promoted iSCSI target, and the old + primary was not presented as valid. It then failed at RW filesystem mount + because RF=2 `sync-quorum` cannot acknowledge writes after one replica is + stopped. +- Dev manual run `20260514-045800-manual-rf2-best-effort-recovery` changed the + positive RF=2 recovery gate to `ack_profile=best-effort` plus + `claim_profile=controlled-best-effort-demo`. It completed with the + reader-verified exit code, `failover_status: promoted`, + `promoted_replica=r1`, `data_check_after_failover=reader_checksum_passed`, + and `/data/demo.bin: OK`. This proves the RF=2 controlled recovery demo + branch, not quorum HA. +- The RF=2 positive recovery script now emits + `control-plane-timeline.txt` with stable event lines for + `primary_observed`, `candidate_evaluated`, `primary_failure_injected`, + `authority_published` or `safe_refusal`, `csi_reattach_observed`, and + `data_check`. The runner gate asserts this timeline so operators can see what + happened without reconstructing it from blockmaster/CSI logs. +- RF3 product-loop promotion now has a master-side promotion evidence seam. The + authority controller may still use `ReadyForPrimary` for RF2 controlled demo + behavior, but RF3 promotion is blocked unless master obtains fresh promotion + evidence for surviving candidates. The guard rejects missing probes, + `best-effort` profiles, unknown sync ACK LSN, and candidates whose durable + LSN is behind the required sync ACK LSN. + +Closed D4/D5 result: RF2 best-effort controlled recovery and RF3 sync-quorum +durable recovery are both QA-validated. The RF3 gate reached the product path: +`master promotes -> CSI/node reattaches on pod recreate -> reader checksum +passes`, and the promoted-primary replication handoff no longer breaks RW +remount because covered surviving peers are seeded from a barrier-proven +frontier. QA verified the user-facing claim boundary and the cleanup hygiene. + +Remaining follow-up for a later plan: + +- wire a stronger required/committed frontier source when available, instead of + relying on the unknown-required-LSN fallback; +- keep `docs/operations-v1.md` aligned as the claim moves from Stage 1 beta + recovery to later transparent/multipath recovery. + +Add or tighten fast tests for: + +- observed but not-ready peer is not eligible, +- peer with durable frontier/catch-up evidence can be eligible, +- primary handoff advances epoch/endpoint-version, +- stale primary frontend-ready is unhealthy after handoff, +- missing ACK/durable evidence causes safe refusal. +- RF3 does not promote from heartbeat `ReadyForPrimary` alone, +- RF3 rejects `best-effort` evidence for the HA claim, +- RF3 with a known required sync ACK LSN only promotes a candidate whose durable + LSN covers that LSN. +- RF3 with an unknown required sync ACK LSN falls back to the highest durable + survivor and labels the semantics as weaker than quorum HA. +- RF3 prefers the highest durable LSN among candidates that cover the required + sync ACK LSN, or among all ready candidates when the required LSN is unknown. +- promoted primary seeds live ship cursors only after a barrier proves the peer + covers the local frontier; a below-frontier survivor is degraded and cannot + satisfy `sync-quorum`. + +### D4: Runner-Native Promotion-Ready Gate + +RF2 best-effort controlled recovery gate: QA passed. It proves a controlled +demo profile only. + +RF3 sync-quorum durable recovery gate: QA passed. Scenario: + +```text +pre_clean +preflight +build/install alpha RF=3 three-logical-server path +create RF=3 PVC with ack_profile=sync-quorum +write/check data through app writer and record sync ACK frontier +wait for inventory-derived non-primary candidates to cover the required frontier +or time out with blocker bundle +capture before-failure inventory +inject scoped primary failure +master probes surviving replicas before promotion +observe promotion only if a candidate covers the sync ACK frontier +prove CSI/node reattach target-generation change if recovery is claimed +reattach/recreate reader only if recovery is legitimately claimed +verify reader checksum if recovered +capture after-failure inventory/support bundle +collect_and_cleanup(always) +``` + +If no non-primary candidate can cover the sync ACK frontier, the gate should +pass only as a safe-blocker fixture with a specific issue class, not as +recovery. + +Dev evidence: `20260514-012711-d50a` passed with 7/7 phases and 75/75 actions. +QA close evidence: `20260514-075221-da0d` passed from clean state with 7/7 +phases and 75/75 actions. +The recovery marker shows `failover_status: promoted`, `promoted_replica=r2`, +`after_publish_target_evidence` on frontend `127.0.0.1:3261`, +`reader_verified=true`, and +`data_check_after_failover=reader_checksum_passed`. + +### D5: Operations Manual Update + +Updated `docs/operations-v1.md` after QA confirmed the RF3 D4 claim: + +- RF2 remains a controlled best-effort demo profile, not quorum HA. +- RF3 sync-quorum is described as the Stage 1 durable mounted recovery path + with the same recovery marker and cleanup evidence. + +### D6: QA Close Gate + +QA close report validated: + +- runbook claim boundary, +- ACK profile and durable frontier evidence, +- pre-failure peer readiness, +- scoped primary failure, +- old-primary fencing, +- new-primary authority if recovered, +- host-path recovery method if recovered: CSI/node reattach on pod recreate, +- post-failure reader checksum if recovered, +- explicit non-claim if not recovered, +- cleanup hygiene. + +## Gates Closed + +This plan closed because: + +1. The RF2 best-effort demo boundary and RF3 sync-quorum HA boundary are + documented without ambiguity. +2. Fast tests cover eligibility/refusal/fencing semantics, including RF3 + rejection of heartbeat-only and best-effort promotion evidence. +3. A runner-native RF3 sync-quorum gate proves host-path recovery plus reader + checksum, or a sharper product blocker. +4. Inventory/support bundles explain the outcome without implementation logs. +5. User-facing docs do not over-claim. +6. QA validates independently and reports no blocking issue. + +## Next Plan Candidate: Transparent Multipath Host Failover + +Do not fold this into the current plan. + +The next plan should target the mature host-path experience: + +```text +master promotion -> protocol path state changes -> Linux multipath switches path -> mounted workload continues +``` + +Candidate scopes: + +- NVMe ANA + native multipath through Kubernetes CSI, +- iSCSI ALUA + dm-multipath through Kubernetes CSI, +- CSI publishes/configures multiple paths up front, +- master-published epoch/endpoint generation stays consistent with protocol + path state, +- mounted workload verifies data after primary failure without pod recreate if + the protocol path claims transparent switching. diff --git a/seaweed-block/internal/docs/finished-plans/phase17_finishedplan_stage2_transparent_multipath_host_failover_mvp.md b/seaweed-block/internal/docs/finished-plans/phase17_finishedplan_stage2_transparent_multipath_host_failover_mvp.md new file mode 100644 index 0000000000..962eb6e965 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase17_finishedplan_stage2_transparent_multipath_host_failover_mvp.md @@ -0,0 +1,388 @@ +# Current Plan: Stage 2 Transparent Multipath Host Failover MVP + +Status: active, opened after closing +`finished-plans/phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md`, +100% complete. D1 cold product spec and D2 strict QA hard gate are closed. D3 +has its first TDD slice: CSI can now deliberately request iSCSI multipath, +fail closed with fewer than two portals, log in all provided portals, and mount +the dm-multipath device instead of a raw portal-specific path. Master status can +now expose all observed replica frontend facts for a volume, while CSI only +uses them as multipath under an explicit Stage 2 opt-in. The alpha install path +now has a Stage 2 multipath opt-in flag and the CSI image/manifests carry the +host multipath prerequisites needed for the first runner scenario. The first +runner-native Stage 2 baseline scenario now exists; it is a wiring/prereq gate +and explicitly does not claim transparent failover yet. QA found that NodeStage +could still accept an early one-portal publish context under Stage 2 opt-in; the +node path now waits for refreshed multi-portal publish evidence before staging. +Internal review then found the scenario was collecting host path evidence after +CSI could already unstage; the baseline now stops with a writer pod still +mounted and captures `iscsiadm`, `multipath -ll`, and `sg_rtpg` inside that live +mount window. QA then confirmed multi-portal NodeStage but found the first +non-root writer-hold pod could not write `/data/demo.bin`; the alpha CSIDriver +now explicitly sets `fsGroupPolicy: File` so kubelet applies pod `fsGroup` +ownership to filesystem PVC mounts, and the writer-mounted stop path preserves +host-path diagnostics even when the writer check fails. +QA rerun then produced the first full Stage 2 baseline host evidence: three +sessions to one IQN, one dm-multipath device with three ALUA paths, and `sg_rtpg` +states `0x00/0x02/0x02`. The remaining failure was only a scenario grep pinned +to the wait-path log line; assertions now use the always-emitted staged summary +line. +The Stage 2 baseline gate passed in QA run `20260515-092817-61f9`. D4 now has +its first mounted-failover scenario draft: +`stage2-iscsi-alua-multipath-failover-chain.yaml`; it keeps the writer pod +mounted, stops the live primary derived from inventory, and verifies data from +the same pod without reader recreate. QA's first D4 run +`20260515-094955-bed0` reached the mounted writer setup and host multipath +evidence, then stopped before failure injection because `sw-block ops +inventory` rejected the new `stage2-iscsi-alua-multipath` claim profile. That +profile is now a first-class CLI/product claim label and remains valid only +under sync ACK profiles, not `best-effort`. QA's second D4 run +`20260515-103621-5d61` then proved the core Stage 2 claim for the first time: +the same writer pod UID stayed mounted, r1 was stopped, r2 became the only +primary, ALUA state moved r2 to active/optimized, the original pod verified the +pre-failure data and wrote new data, and the bundle recorded +`transparent_failover_claimed=true`. One cleanup assert still saw terminating +`blockmaster`/`blockcsi` k3s pod processes after uninstall; the uninstall script +now waits for CSI and blockmaster deletion, and the scenario cleanup timeout was +raised to cover that stricter wait. +QA's third D4 run `20260515-104802-a618` passed strictly: 48/48 actions, 9/9 +phases, reproduced the no-pod-recreate mounted failover, and left no iSCSI +sessions, sw-block processes, port-forwards, blockvolume Deployments, or +run-scoped host paths. `docs/operations-v1.md` now has an explicit Stage 2 +iSCSI ALUA/dm-multipath section, so the plan is ready for formal QA close +against the hard gate. QA then issued the formal close report at +`qa-assignments/stage2-transparent-multipath-host-failover-close-report.md`: +PASS (strict), HG-0 through HG-13 all PASS, no blocking findings. + +QA needed now: no for this plan. Stage 2 is clear to move to +`finished-plans/`. + +## Product Question + +Can a Kubernetes user keep a mounted block volume usable through primary +failure without pod recreate, under a documented multipath protocol path, while +the product proves: + +```text +master promotion +-> stale primary fenced +-> protocol path state changes +-> Linux host path switches to the promoted path +-> mounted workload verifies data +``` + +Stage 1 already proved safe recovery through CSI/node re-stage on pod recreate. +Stage 2 must not relabel that as transparent failover. Stage 2 only closes when +the original mounted host path continues or recovers through multipath behavior +under the specific protocol being claimed. + +## Product Position + +This plan serves `ref/product-positioning-v1.md`: lightweight Kubernetes block +storage with enterprise protocol discipline and fail-closed recovery semantics. + +The product value is not "we have ALUA/ANA code" or "master changed primary." +The value is: + +```text +an operator can run a documented Kubernetes path, inject primary failure, and +see the mounted workload recover through standard Linux multipath semantics, +with support-bundle evidence explaining authority, path state, and data check. +``` + +## Scope Decision + +Stage 2 starts with one protocol path, not both at once. + +Default candidate: **iSCSI ALUA + dm-multipath**. + +Reason: + +- current alpha Kubernetes frontend default is iSCSI, +- `docs/operations-v1.md` and quickstart paths already assume iSCSI, +- existing P6 references show ALUA/MPIO protocol substrate and mounted + failover evidence outside the Kubernetes product path, +- it lets the user-facing path mature before adding protocol selection. + +NVMe ANA remains the second path. It has strong lab substrate evidence in +`ref/nvme-p4-multipath-failover-design.md`, but Kubernetes CSI protocol +selection and NVMe attach UX should not be mixed into the first Stage 2 close. + +## Non-Negotiable Semantics + +- Authority decides primary; CSI and protocol code do not promote. +- Protocol state reflects authority/frontier facts; it does not invent safety. +- Old primary must not acknowledge successful data I/O after authority moves. +- Multipath identity must make all paths for one volume appear as one logical + device to the Linux host. +- The mounted workload must verify pre-failure data after failover. +- If multipath is not actually configured or does not switch, the product must + fail closed and name the missing boundary. +- Kubernetes attach, mount, path switch, and post-failure I/O waits must be + bounded and observable. A stuck PVC/pod/session/multipath map is a product + failure, not a test timeout detail. +- Every bounded failure must emit a user-readable blocker reason and support + bundle pointer before cleanup. +- A green Stage 1 CSI/pod-recreate recovery is not sufficient for Stage 2. + +## Allowed Simplifications + +- `alpha_non_claim`: first Stage 2 close may use same physical node with + multiple logical Seaweed Block server identities if the host sees multiple + protocol paths and Linux multipath owns the device. +- `alpha_non_claim`: no node-loss claim unless a later gate runs on distinct + Kubernetes nodes with non-loopback frontends. +- `temporary_internal`: scenario may use TestOps to inject primary failure and + capture support bundles. +- `safe_refusal`: if multipath prerequisites are absent, the command/scenario + must fail with a clear issue class instead of falling back to pod recreate. + +## Explicit Non-Claims + +- No node-loss survival. +- No broad multi-distro multipath compatibility. +- No performance/RTO/SLO claim. +- No NVMe ANA Kubernetes claim in the first iSCSI Stage 2 close. +- No Windows MPIO claim. +- No online upgrade/uninstall safety claim. +- No automatic repair/rebuild/failback claim. + +## D1: Cold Product Spec And Gap Audit + +Produce `internal/docs/ref/stage2-transparent-multipath-host-failover-spec.md`. + +It must answer: + +- Which protocol closes first: iSCSI ALUA or NVMe ANA? +- What is the exact user-visible command/runbook path? +- What does CSI publish: one path, multiple paths, or a multipath staging + helper? +- What identity makes the host treat replicas as paths of one volume? +- What evidence proves stale primary fencing? +- What evidence proves Linux multipath switched paths? +- What support-bundle fields make this understandable without internal logs? + +Inputs to read: + +- `ref/iscsi-alua-technical-note.md` +- `ref/iscsi-p6-alua-mpio-design.md` +- `ref/nvme-ana-technical-note.md` +- `ref/nvme-p4-multipath-failover-design.md` +- `ref/engine-automata-design-note.md` +- `docs/operations-v1.md` +- CSI node/controller code for publish/stage behavior + +Exit criteria: + +- one protocol selected for first close, +- all non-negotiable semantics pinned, +- explicit list of code gaps, +- no claim drift from Stage 1. + +Status: drafted. First protocol is iSCSI ALUA + Linux dm-multipath. Current +known code gaps are single-target CSI publish/stage, raw path mounting instead +of multipath device mounting, ALUA product-fact wiring, and missing host-path +inventory evidence. + +## D2: QA Hard Gate Draft + +Create +`internal/docs/qa-assignments/stage2-transparent-multipath-host-failover-close-hard-gate.md`. + +The hard gate must include binary clauses for: + +- documented runbook entry, +- multipath prerequisites detected before test, +- CSI/node path setup does not use pod recreate as the recovery mechanism, +- Linux sees one multipath device with multiple paths, +- pre-failure mounted writer checksum, +- primary failure is scoped and derived from live inventory, +- master publishes exactly one new primary, +- old primary path cannot return successful stale data I/O, +- protocol path state changes are visible (`sg_rtpg`/multipath for iSCSI or + ANA/native multipath evidence for NVMe), +- mounted workload verifies data after failover, +- support bundle explains authority, path state, host path, and data check, +- cleanup leaves no sessions/devices/processes/port-forwards/run-scoped paths, +- non-claims remain explicit. + +The gate must fail if the proof is only: + +```text +pod recreated -> CSI restaged -> reader checksum passed +``` + +That is Stage 1, not Stage 2. + +Status: drafted at +`qa-assignments/stage2-transparent-multipath-host-failover-close-hard-gate.md` +with HG-0 through HG-13. + +## D3: Minimal Implementation Slice + +Implementation starts only after D1/D2 are reviewed. + +Expected iSCSI-first code areas: + +- CSI node staging: publish/configure multiple target portals for one volume. +- iSCSI utility layer: discover sessions/devices by IQN plus portal and + multipath identity. +- Frontend state provider: map current authority/frontend facts to ALUA state. +- Operations inventory/status: expose multipath readiness, active path, + standby/unavailable path, and host-path evidence. +- Reliability/observability: add bounded waits and explicit blocker issue + classes for attach, mount, multipath map creation, ALUA/RTPG state read, + authority movement, stale-primary fencing, and post-failure I/O. +- TestOps scenario: run mounted writer, inject primary failure, verify mounted + data path without pod recreate. + +No broad refactor. Any engine/protocol changes must preserve the automata +boundaries from `ref/engine-automata-design-note.md`. + +Status: + +- TDD slice complete in `core/csi`: `stage2_multipath=true` plus multiple + `iscsiAddrs` forces NodeStage to log in every portal and mount the multipath + device returned by the iSCSI utility. +- Safe refusal added: `stage2_multipath=true` with fewer than two portals fails + before discovery/login. +- Controller/master lookup seam added: if master status exposes multiple iSCSI + frontend facts with the same IQN and `blockcsi` is started with the explicit + Stage 2 multipath lookup path, CSI publish context carries `iscsiAddrs=` + plus `stage2_multipath=true`. Different IQNs are not merged into one + multipath target. +- Master status fan-out added: `QueryVolumeStatus` can return frontend facts + for all observed replica slots of the volume instead of only the currently + assigned replica. This is read-only evidence; it does not let CSI choose or + promote authority. +- Existing Stage 1 behavior remains gated off from multipath by default: + `NewControlStatusLookup` and normal `blockcsi` startup preserve single-target + publish behavior unless `--stage2-multipath` is used. +- Alpha deployment opt-in added: `SW_BLOCK_STAGE2_MULTIPATH=1` renders + `--stage2-multipath` into both CSI controller and CSI node. Default alpha + installs remain unchanged. +- CSI node host prerequisites added: image includes `multipath-tools` and + `sg3-utils`; node DaemonSet loads `dm_multipath` and `scsi_dh_alua` and + mounts `/run/udev` read-only for host device observation. +- Linux utility hardened: multipath map discovery refreshes maps with bounded + 5s subprocess calls and resolves IQN -> raw devices via `/dev/disk/by-path` + before matching them to a `/dev/mapper/` entry in `multipath -ll`. +- Runner baseline added: + `testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml`. + It is deliberately named as a baseline, not the eventual D4 close path, to + avoid claim drift. It enables + `SW_BLOCK_STAGE2_MULTIPATH=1`, runs RF=3 `sync-quorum`, proves the rendered + CSI manifests include `--stage2-multipath`, checks r1/r2/r3 generated + blockvolume rows share one iSCSI IQN, requires CSI node logs to show + `multipath=true`, captures `multipath -ll` and `sg_rtpg`, asserts required + host modules are loaded, flushes Seaweed Block multipath maps during cleanup, + and writes `stage2-claim-boundary.txt` with + `transparent_failover_claimed=false`. +- QA baseline blocker addressed: the first QA runs showed + `multipath=true` in the node log but only `portal=127.0.0.1:3260`, so no + dm-multipath map or `sg_rtpg` evidence appeared. `NodeStageVolume` now treats + Stage 2 multipath as a required multi-portal boundary: it waits up to a + bounded publish-target window for refreshed master status to return at least + two iSCSI portals, logs `multipath publish target ready portals=...`, and + only then logs into all paths and mounts the mapper device. If the boundary + never appears, it falls back to the existing fail-closed one-portal rejection. +- Internal review/QA timing blocker addressed: the baseline no longer tries to + prove host multipath after the short-lived reader path may have unstaged the + session. It renders the RF3 writer-hold manifest, stops at + `SW_BLOCK_DEMO_STOP_AFTER=writer-verified`, captures + `iscsi-sessions.writer-mounted.txt`, `multipath.writer-mounted.txt`, and + `sg-rtpg.writer-mounted.txt` while the PVC is still mounted, and writes + `controlled-stop-writer-verified.txt` with the claim boundary. Scenario + assertions now grep that live-mount evidence. +- QA non-root writer blocker addressed: Stage 2's writer-hold pod runs as + UID/GID 1000 with `fsGroup: 1000`. The alpha `CSIDriver` now declares + `fsGroupPolicy: File` so Kubernetes applies filesystem ownership for mounted + PVCs instead of leaving the ext4 root `root:root 0755`. If the writer still + fails, the demo captures mounted host-path evidence before cleanup and records + `phase=writer-verified-failed` for diagnosis. +- QA baseline evidence from run `20260515-091810-6d74`: writer succeeded, + `iscsi-sessions.writer-mounted.txt` showed three sessions to the same IQN, + `multipath.writer-mounted.txt` showed one dm-multipath map with ALUA handler + and three paths, and `sg-rtpg.writer-mounted.txt` showed one + active/optimized path plus two standby paths. Scenario grep has been corrected + to accept the fast path where the publish context is already complete before + NodeStage waits. +- QA baseline pass: run `20260515-092817-61f9` passed 62/62 actions and + confirmed the Stage 2 baseline contract end-to-end. +- Verification passed: + `go test ./core/csi ./core/host/master ./cmd/blockcsi -count=1`, + `bash -n scripts/run-alpha-app-demo.sh`, YAML parse of the Stage 2 baseline, + and `git diff --check`. +- Closed: QA baseline run `20260515-092817-61f9` proved host multipath setup; + D4 runs `20260515-103621-5d61` and `20260515-104802-a618` proved mounted + failover without pod recreate; formal close report passed all 14 hard-gate + clauses. + +## D4: Runner-Native Stage 2 Gate + +Add one runner-native scenario for the selected protocol, likely: + +```text +testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml +``` + +Required artifact shape: + +```text +multipath-prereq.txt +pre-failure-inventory/ +sg-inq.txt +sg-rtpg.before.txt +multipath-before.txt +writer.log +primary-failure.txt +authority-after.txt +sg-rtpg.after.txt +multipath-after.txt +workload-after-failover.log +support-bundle/ +bounded-waits.txt +cleanup-audit.txt +``` + +Status: first baseline scenario added at +`testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml`. It proves +Stage 2 opt-in and host multipath evidence before failure injection. The +eventual close scenario should use the D4 filename above only when it proves the +original mounted workload survives primary failure without pod recreate. + +Current D4 slice: `testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml` +now exists. It uses the same RF3 sync-quorum writer-held mount, keeps resources +alive after `writer-verified`, derives the primary replica from live inventory, +scales that primary Deployment to zero, waits for one promoted primary, and +execs into the original writer pod to verify and write data after failure. It +records `pod_recreate_used=false`, +`data_check_after_failover=mounted_workload_checksum_passed`, ALUA/RTPG +before/after files, multipath before/after files, and bounded waits. QA has not +only run it, but reproduced the product behavior twice. The strict close run +`20260515-104802-a618` passed 48/48 actions with clean residue. + +## D5: Operations Manual Update + +Only after the runner gate passes, update `docs/operations-v1.md`: + +- Stage 1 recovery: CSI/pod recreate. +- Stage 2 recovery: selected protocol multipath path. +- Exact prerequisites and non-claims. +- How to inspect support bundles. + +## Gates To Close + +This plan closes only when: + +1. A cold product spec names the selected protocol and exact user-visible + failover contract. +2. A strict QA hard gate exists before implementation is treated as complete. +3. Fast tests protect protocol state mapping and stale-primary rejection. +4. A runner-native gate proves mounted failover through multipath, not pod + recreate. +5. Support bundles explain authority, protocol path state, host multipath + state, bounded waits, blocker reasons, and data verification. +6. User-facing docs distinguish Stage 1 CSI/pod-recreate recovery from Stage 2 + multipath recovery. +7. QA validates independently and reports no blocking issue. diff --git a/seaweed-block/internal/docs/finished-plans/phase18_finishedplan_node_loss_survival_mvp.md b/seaweed-block/internal/docs/finished-plans/phase18_finishedplan_node_loss_survival_mvp.md new file mode 100644 index 0000000000..f5ec7b34dd --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase18_finishedplan_node_loss_survival_mvp.md @@ -0,0 +1,630 @@ +# Current Plan: Node-Loss Survival MVP + +Status: active, opened after closing +`finished-plans/phase17_finishedplan_stage2_transparent_multipath_host_failover_mvp.md`, +96% complete. D1 cold product spec and D2 strict QA hard gate are drafted. D3 +topology eligibility and D4 conservative node-loss recovery scenarios are +authored. The lab has been expanded to three Ready Kubernetes nodes (`m02` +control-plane plus `m01` and `tp01` workers), the node-loss preflight passes, +and QA has now passed the D4 RF3 sync-quorum node-loss recovery gate through +CSI/pod recreate after the inventory attribution and image-import fixes: + +- `ref/node-loss-survival-mvp-spec.md` +- `ref/node-loss-lab-setup.md` +- `qa-assignments/node-loss-survival-mvp-close-hard-gate.md` + +QA needed now: formal close report against +`qa-assignments/node-loss-survival-mvp-close-hard-gate.md`. + +## Product Question + +Can a Kubernetes user lose the node that hosts the active Seaweed Block primary +and still recover the same PVC data through a documented path, with evidence +that authority moved safely, stale paths were fenced, and the data check used a +surviving replica on another node? + +Stage 2 proved: + +```text +same physical node +-> multiple logical replicas +-> iSCSI ALUA + dm-multipath +-> primary blockvolume pod stop +-> same mounted writer pod survives without recreate +``` + +This plan must move to the user-visible HA question: + +```text +primary Kubernetes node becomes unavailable +-> surviving replica on another Kubernetes node is promoted +-> workload recovers through the declared mechanism +-> same PVC data verifies +``` + +## Product Position + +This plan serves `ref/product-positioning-v1.md`: mature block storage cannot +stop at same-node process failover. A credible Kubernetes block product must +name what happens when a node fails. + +The value is not "the master selected a different replica." The value is: + +```text +an operator can run a documented RF3 sync-quorum Kubernetes path, inject primary +node loss, and see the PVC recover with support-bundle evidence for placement, +authority, CSI target movement, stale-primary fencing, and data integrity. +``` + +## Scope Decision + +First close uses the conservative recovery mechanism: + +```text +CSI / pod recreate reattach +``` + +Reason: + +- It isolates the new problem: real multi-node placement and non-loopback + target selection. +- Stage 2 already proved transparent multipath on one physical node; combining + real node loss and transparent multipath immediately would mix too many + failure axes. +- Users still get a valuable claim: PVC data recovers after primary node loss, + with no manual promote/repair. + +Transparent multipath node-loss is a later gate or follow-up plan: + +```text +same mounted pod -> primary node loss -> host multipath switches to surviving node +``` + +Lab topology precision: + +- The D3/D4 MVP may run on three Kubernetes nodes spread across two physical + machines if the artifacts disclose the physical-host shape. +- That is a Kubernetes-node-loss proof, not a full physical-host-loss proof. +- The stronger physical-host-loss claim requires the failed primary and all + surviving promotion candidates to be on distinct physical fault domains, and + must be gated separately before external positioning uses that wording. + +## Target Claim + +Narrow beta-facing claim after close: + +```text +For the documented RF3 sync-quorum Kubernetes topology with non-loopback +frontends, Seaweed Block can recover a PVC after controlled primary-node loss +through CSI/pod recreate reattach, and the support bundle proves authority +movement, surviving-node target selection, stale-primary fencing, and data +integrity. +``` + +## Explicit Non-Claims + +- No transparent mounted I/O continuation under node loss in the first close. +- No NVMe ANA node-loss claim. +- No Windows MPIO claim. +- No broad multi-distro compatibility claim. +- No RTO/RPO/SLO claim beyond bounded gate timings. +- No automatic rebuild, reintegration, or failback claim. +- No arbitrary multi-failure or network-partition tolerance unless a later gate + explicitly proves it. +- No production HA claim outside the documented lab topology. +- No full physical-host-loss claim when multiple Kubernetes nodes share one + physical machine; that topology is an intermediate Kubernetes-node-loss lab. + +## D1: Topology And Placement Audit + +Audit before code: + +- Does the active TestOps/k3s lab have at least two schedulable Kubernetes + nodes? +- How does `blockmaster` cluster-spec name physical nodes and server IDs? +- Can launcher place RF3 replicas across distinct Kubernetes nodes today? +- Can generated `blockvolume` frontends use non-loopback addresses reachable + from CSI nodes? +- Does CSI publish lookup select a frontend reachable from the consuming node? +- Can inventory prove replica -> server -> Kubernetes node -> frontend mapping? +- What should count as controlled node failure in the lab: cordon/drain, + kubelet stop, node network isolation, or deleting the node's blockvolume pods? + +Exit criteria: + +- update this plan with the honest current state, +- identify the smallest implementation slice, +- do not write recovery code until the topology gap is clear. + +### D1 Audit Result + +Current local Kubernetes context is a single Rancher Desktop/k3s node +(`ping-r13`, internal IP `192.168.127.2`). That context cannot run the +node-loss gate. Prior QA runs used the m02 lab, but this branch does not yet +have a runner-native proof that the active QA lab has multiple schedulable +Kubernetes nodes for this plan. + +Code audit findings: + +- `scripts/install-k8s-alpha.sh` renders every logical server onto one + Kubernetes node (`SW_BLOCK_ALPHA_NODE_NAME`, defaulting to the first node + from `kubectl get nodes`) and emits `127.0.0.1` data/control addresses. +- `core/lifecycle` and `core/host/master` already have a useful base for + distinct physical nodes: `NodeRegistration` carries + `kubernetes.io/hostname`, `DataAddr`, and `CtrlAddr`, and + `TestMountedFailover_WorkloadPlanAllocatesPortsByPhysicalNodeAcrossRF2Volumes` + proves per-node port allocation across `k8s-a`/`k8s-b`. +- `core/launcher/k8s_renderer.go` still renders generated blockvolume + frontends as loopback-only (`--iscsi-listen=127.0.0.1:`, + `--status-addr=127.0.0.1:`, and NVMe similarly). That was correct for + Stage 2 same-node ALUA, but it is invalid for node-loss attach from another + Kubernetes node. +- `cmd/blockvolume` enforces loopback-only frontend binds for iSCSI/NVMe. + The code already has `--iscsi-portal-addr` and CHAP support, but an external + bind is deliberately rejected. Node-loss needs an explicit opt-in external + frontend mode, not an accidental bypass. +- Promotion/status probing is also loopback-shaped today. The generated + `--status-addr=127.0.0.1:` is reachable only through local/pod + context, and master promotion evidence must not depend on a failed node's + loopback. D3 must include a routable status/probe path or an explicitly + documented Kubernetes port-forward/service model. +- Replication data/control addresses must be routable across physical nodes. + If only iSCSI is external but `DataAddr`/`CtrlAddr` remain loopback, RF3 + sync-quorum can render three frontends but still fail the actual replication + and promotion-readiness contract. +- CSI already passes `nodeID` into `LookupPublishTarget`, but + `core/csi/master_backend.go` currently ignores it and selects published + frontends without validating reachability from the consuming node. +- Inventory can already print replica `server`, Kubernetes `node`, `frontend`, + `status_addr`, and promotion evidence. The node-loss gate should add stable + derived lines such as `replicas_on_distinct_nodes=true` and + `frontends_non_loopback=true` so QA does not infer eligibility from ad-hoc + greps. + +Conclusion: the next slice is not recovery logic. The next slice is a topology +eligibility implementation that makes cross-node targets real and auditable. + +Smallest implementation slice: + +```text +alpha cluster-spec can describe multiple Kubernetes nodes with routable data/control addrs +-> generated blockvolume Deployments bind/listen through explicit external iSCSI mode +-> status/probe endpoints are routable or explicitly service/port-forwarded +-> iSCSI advertises a routable portal address for each node +-> CSI rejects loopback targets for the node-loss profile and selects the current primary target +-> inventory emits distinct-node and non-loopback eligibility markers +-> runner gate proves RF3 placement and attach eligibility without failure injection +``` + +Security boundary for the external iSCSI mode: + +- external bind must be opt-in and refused by default, +- the first node-loss gate should require CHAP for external iSCSI unless a + later security review approves a narrower lab-only exception, +- CHAP must be plumbed on both sides: generated blockvolume target secret and + CSI `NodeStage` secret delivery, +- NVMe external bind remains non-claimed for this plan. + +D3a implementation started: + +- `cmd/blockvolume` now has an explicit `--allow-external-iscsi-bind` flag. + External iSCSI remains rejected by default, and opt-in external iSCSI requires + target-side CHAP. +- `core/launcher` can render external iSCSI listens from the placement node + address only when `K8sRenderConfig.ExternalISCSI` is enabled and a CHAP Secret + is configured. +- `cmd/blockmaster` exposes `--launcher-external-iscsi` to pass that renderer + mode. +- `scripts/install-k8s-alpha.sh` and `scripts/run-alpha-app-demo.sh` now accept + explicit multi-node cluster-spec input through `SW_BLOCK_ALPHA_NODE_SPECS` + entries shaped as `server_id|kubernetes_node|host_or_ip|pool_id`. This keeps + the old single-node default intact while giving the node-loss runner a way to + render routable `data_addr` / `ctrl_addr` values. +- The same scripts can inject `--launcher-external-iscsi` and + `--launcher-iscsi-chap-secret-name=` via + `SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1`. +- `scripts/run-alpha-app-demo.sh` now wires external iSCSI CHAP end-to-end for + the app path: requires username/secret, creates the Secret in app and + blockvolume namespaces, injects `csi.storage.k8s.io/node-stage-secret-*` into + the rendered StorageClass, and cleans the Secret up. +- `scripts/install-k8s-alpha.sh` now refuses external iSCSI without CHAP + credentials and creates the configured CHAP Secret for standalone install + flows. +- CSI now has an explicit `--reject-loopback-publish-targets` guard. When + enabled, master-backed publish lookup skips loopback or malformed frontend + addresses and fails closed if no routable target remains. +- The alpha install/demo scripts can inject + `--reject-loopback-publish-targets` through + `SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS=1`. +- `cmd/blockvolume` now has an explicit `--allow-external-status-bind` flag. + The unauthenticated status API remains loopback-only by default; node-loss + gates can opt into a concrete, non-loopback node-address bind so blockmaster + can probe surviving replicas across nodes. +- `core/launcher` can render external status endpoints from the same placement + node address when `ExternalStatus` is enabled alongside external iSCSI. The + generated workload receives both `--status-addr=:` and + `--allow-external-status-bind`. +- `cmd/blockmaster` exposes `--launcher-external-status` and passes that mode + to both the renderer and the workload-plan promotion evidence provider, so + promotion probes use node-address status endpoints instead of + `127.0.0.1:`. +- The alpha install/demo scripts can inject `--launcher-external-status` via + `SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=1`. +- External node-loss mode now rejects loopback/unspecified node-spec hosts at + the script, renderer, blockvolume bind, status bind, and promotion-probe + boundaries. A bad `SW_BLOCK_ALPHA_NODE_SPECS` entry must fail early instead + of producing fake cross-node evidence. +- `scripts/uninstall-k8s-alpha.sh` now deletes the configured iSCSI CHAP Secret + from app and `kube-system` namespaces so standalone external-iSCSI installs + do not leave credentials behind. +- Master status now publishes observed frontends for all assigned replicas, with + the current primary replica first. This keeps multipath consumers able to see + every path while making the conservative CSI/pod-recreate reattach path select + the promoted primary instead of a stale topology-first replica. +- CSI's single-target control-status lookup now has a node-loss guard test that + consumes the first routable frontend as the current-primary target when + loopback rejection is enabled. +- Inventory now emits stable topology eligibility evidence per volume: + `replicas_on_distinct_nodes=` and `frontends_non_loopback=` in + both JSON and the summary. These are evidence markers, not health classifiers, + so older single-node/non-node-loss paths are not made unhealthy by the marker. +- `scripts/preflight-node-loss-lab.sh` now provides a reusable lab readiness + check. It emits `NODE_SPECS`, selected writer app node, selected survivor + reader node, Kubernetes-node placement, physical-domain shape, and + `physical_host_loss_claimed=false`. The D3/D4 scenarios call this helper + instead of carrying private discovery logic. +- `scripts/run-alpha-app-demo.sh` now supports + `SW_BLOCK_DEMO_READER_NODE_NAME` so conservative pod-recreate recovery can + schedule the replacement reader onto a surviving node after the primary node + is cordoned. +- `scripts/run-alpha-app-demo.sh` now supports + `SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=cordon-node-scale-primary-to-zero`. + The mode derives the primary node from live inventory, cordons that + Kubernetes node, scales the primary blockvolume Deployment to zero, records + `failure_class=primary-kubernetes-node-cordoned-blockvolume-stop`, and + uncordons the node during cleanup. + +Still open before QA can produce live validation: + +- QA validation of the runner-native multi-node eligibility scenario: + `testops/scenarios/node-loss-topology-eligibility-chain.yaml`. The scenario + supplies real `SW_BLOCK_ALPHA_NODE_SPECS`, enables external iSCSI/status plus + loopback publish-target rejection, and asserts RF3 placement with + `replicas_on_distinct_nodes=true` and `frontends_non_loopback=true`. +- QA validation of the runner-native conservative recovery scenario: + `testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml`. It uses the + same topology, cordons the live primary node, stops the primary blockvolume + workload, recreates the reader on a survivor node, and requires + `data_check_after_node_loss=reader_checksum_passed`. +- optional stronger publish-target identity. Current-primary-first ordering + closes the immediate conservative reattach path, but `FrontendTarget` still + does not encode server/node identity; add that only if D3 evidence needs more + than stable ordering plus inventory markers. + +## D2: QA Hard Gate + +Hard gate is drafted at +`qa-assignments/node-loss-survival-mvp-close-hard-gate.md`. + +It fails if: + +- all replicas run on one physical node, +- any cross-node target is loopback, +- the proof uses only a pod stop instead of node failure/isolation, +- reader attaches to the old failed-node frontend, +- authority movement is not visible, +- stale primary is untested, +- cleanup leaves unexplained residue. + +## D3: Multi-Node Topology Eligibility Gate + +Add the first runner-native gate only after D1 audit: + +```text +RF3 PVC +-> replicas placed on distinct Kubernetes nodes +-> non-loopback frontends +-> inventory shows mapping +-> no node failure injection yet +``` + +This gate proves the topology is eligible for node-loss recovery. + +D3 scenario authored: + +```text +testops/scenarios/node-loss-topology-eligibility-chain.yaml +``` + +It fails fast unless the lab has three Ready schedulable Kubernetes nodes with +non-loopback InternalIPs. Those nodes may share two physical machines for this +MVP gate, but the scenario records `physical_domain_count`, +`physical_domain_shape`, and `physical_host_loss_claimed=false` so the evidence +cannot be misread as full physical-host-loss proof. It then runs RF3 +sync-quorum with external iSCSI, external status, CHAP, and loopback +publish-target rejection. It stops after writer verification and asserts the +inventory eligibility markers before cleanup. + +D3 QA run 20260515-204300-c892: + +```text +pre_clean PASS +preflight PASS +discover_multinode_topology FAIL +collect_and_cleanup PASS +``` + +Reason: + +```text +node-loss topology gate requires at least 3 Ready schedulable nodes with +non-loopback InternalIP; found 1 +``` + +This is an intentional fail-closed lab-capacity result. It did not exercise the +RF3 external iSCSI/status, CHAP, loopback-rejection, writer, or inventory +eligibility assertions. It must not be treated as product validation. + +Lab update 2026-05-16: + +```text +m02 Ready control-plane 192.168.1.184 physical-host=m02 +m01 Ready worker 192.168.1.181 physical-host=m01 +tp01 Ready worker 192.168.1.188 physical-host=tp01 +``` + +Fabric boundary: this is a LAN TCP/iSCSI topology using `192.168.1.x`. +`tp01` does not have RoCE and must not be used for any `10.0.0.x` RDMA fabric, +NVMe/RDMA, or performance claim in this plan. + +`scripts/preflight-node-loss-lab.sh --min-k8s-nodes 3` now passes and emits: + +```text +node_loss_topology_eligible=true +selected_node_count=3 +physical_domain_count=3 +physical_domain_shape=full-physical-host +replica=r1 server=node-loss-r1 node=m01 host=192.168.1.181 physical_host=m01 +replica=r2 server=node-loss-r2 node=m02 host=192.168.1.184 physical_host=m02 +replica=r3 server=node-loss-r3 node=tp01 host=192.168.1.188 physical_host=tp01 +``` + +Next unblocker: + +```text +rerun node-loss-topology-eligibility-chain.yaml +-> only then proceed to D4 node-loss recovery +``` + +D3 QA run 20260516-134043-becf on the expanded lab advanced past topology +discovery and failed in `rf3_external_topology` because `sw-blockmaster` +scheduled on `m01`, where `sw-block:local` had not been imported. This was a +real multi-node alpha pipeline gap: `scripts/build-alpha-images.sh` imported +local images only into m02's k3s containerd. + +Fix implemented and smoke-validated: + +```text +preflight emits K3S_IMPORT_NODES= +-> D3/D4 pin_build sources node-specs.env +-> build-alpha-images imports sw-block and sw-block-csi into each selected k3s node over SSH +``` + +This keeps the scheduler free to place blockmaster and blockvolume workloads on +any eligible node while avoiding a registry dependency for the lab. + +Focused dev smoke on m02: + +```text +K3S_IMPORT_NODES=192.168.1.181,192.168.1.184,192.168.1.188 +build-alpha-images exit=0 +m01: sw-block:local and sw-block-csi:local present in k3s containerd +m02: sw-block:local and sw-block-csi:local present in k3s containerd +tp01: sw-block:local and sw-block-csi:local present in k3s containerd +``` + +Dev rerun of D4 also exercises the same image-import path successfully, so D3's +prior image-locality blocker is considered fixed pending QA rerun. + +An acceptable intermediate lab can be: + +```text +m02 control-plane + m01 worker + one VM/containerized worker +``` + +as long as `kubectl get nodes` shows three Ready schedulable nodes with +non-loopback InternalIPs. The close report must disclose if two Kubernetes nodes +share one physical host. + +Before asking QA for another D3 run, dev can run: + +```bash +bash scripts/preflight-node-loss-lab.sh \ + --min-k8s-nodes 3 \ + --env-out /tmp/node-loss.env \ + --placement-out /tmp/node-placement.before.txt +``` + +If this exits non-zero, the full D3 scenario will fail closed for the same lab +reason. + +Preflight contract after QA's m02 check: + +- eligible lab: exit `0`, writes `node-loss.env` and + `node-placement.before.txt`; +- ineligible lab: exit `3`, writes a negative placement file with + `node_loss_lab_eligible=false`, removes/skips the env file, and must block + D3/D4 reruns. + +## D4: Conservative Node-Loss Recovery Gate + +Runner-native recovery gate: + +```text +writer writes /data/demo.bin +inventory identifies primary replica and primary node +controlled failure isolates/stops the primary node path +master promotes a surviving replica +replacement pod reattaches through CSI to surviving frontend +reader verifies /data/demo.bin +bundle records node_loss_recovery_claimed=true and transparent_failover_claimed=false +cleanup proves no residue +``` + +D4 scenario authored: + +```text +testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml +``` + +It is intentionally a Kubernetes-node-loss gate, not a physical-host-loss gate. +It records `physical_host_loss_claimed=false`, `pod_recreate_used=true`, and +`transparent_failover_claimed=false`. The replacement reader uses +`SW_BLOCK_DEMO_READER_NODE_NAME=$SURVIVOR_APP_NODE`, so success requires CSI to +reattach on a survivor node rather than scheduling back onto the cordoned +primary node. + +D4 QA run 20260516-152925-42b3 was canceled after the recovery phase appeared +stuck. The important diagnosis from that run: master had already promoted the +volume to r2, but inventory relabeled the failed r1 deployment row as +`replica=r2` because the nested status report reflected the current primary. +The scenario then grepped the first `replica=r2` row, saw +`role=unavailable`, and waited until timeout. This was an inventory row +identity bug, not an authority-promotion failure. + +Fix: + +```text +core/ops/k8s_inventory.go +-> keep deployment-derived replica identity (`--replica-id`) stable +-> do not overwrite `replica.ReplicaID` from a status report's current-primary field +``` + +Regression guard: + +```text +TestKubernetesInventoryCollector_PreservesDeploymentReplicaIdentityWhenStatusReportsCurrentPrimary +``` + +Validation: + +```text +go test ./core/ops -count=1 PASS +remote m02 targeted regression PASS +D4 dev rerun 20260516-154108-7bb7 PASS +state/phases/actions pass / 8/8 / 74/74 +before primary r1@m01 +failed node m01 +promoted replica r2@m02 +post_failure_primary_count 1 +before frontend 192.168.1.181:3260 +after frontend 192.168.1.184:3260 +CSI recovery method pod recreate +reader data check /data/demo.bin: OK +data_check_after_node_loss reader_checksum_passed +transparent_failover_claimed false +physical_host_loss_claimed false +cleanup clean +``` + +After-failure inventory now preserves all three rows correctly: + +```text +r1 node=m01 role=unavailable +r2 node=m02 role=primary +r3 node=tp01 role=unknown replication=replica_ready +``` + +D4 QA rerun 20260516-154813-109a failed before the recovery path because the +fresh CSI node DaemonSet hit `ImagePullBackOff` on m02: + +```text +sw-block-csi-node on m02: ImagePullBackOff for sw-block-csi:local +m01: sw-block:local and sw-block-csi:local present +m02: product images missing from k8s.io containerd namespace +tp01: sw-block:local and sw-block-csi:local present +``` + +This did not exercise the inventory fix; the writer never attached and the +scenario never reached cordon/scale-down. + +Image pipeline hardening: + +```text +scripts/build-alpha-images.sh +-> import explicitly into k3s containerd namespace k8s.io +-> verify sw-block:local and sw-block-csi:local after import +-> when SW_BLOCK_IMPORT_K3S_NODES is set, also import/verify the local k3s node if available +``` + +Dev validation 2026-05-16: + +```text +build/import artifact: /mnt/smb/work/share/g15d-k8s/dev-image-import-verify-20260516-160041 +m01: docker.io/library/sw-block:local and docker.io/library/sw-block-csi:local present +m02: docker.io/library/sw-block:local and docker.io/library/sw-block-csi:local present +tp01: docker.io/library/sw-block:local and docker.io/library/sw-block-csi:local present +``` + +The observation API/support-bundle spec now treats this class as first-class +operator evidence: `image_missing_on_node`, `pod_image_pull_failed`, CSI pod +events/logs, and per-node image inventory should be available through +`sw-block ops explain` / bundle rather than requiring manual SSH checks. + +D4 QA rerun 20260516-160306-1e54 passed strictly: + +```text +state/phases/actions pass / 8/8 / 74/74 +lab m01 + m02 + tp01 3-node k3s +transport LAN TCP/iSCSI, CHAP, external iSCSI/status +ack_profile sync-quorum +failure_class primary-kubernetes-node-cordoned-blockvolume-stop +before_primary_replica/node r1@m01 +failed_replica/node r1@m01 +promoted_replica/node r2@m02 +before_publish_target_frontend 192.168.1.181:3260 +after_publish_target_frontend 192.168.1.184:3260 +post_failure_primary_count 1 +old_primary_stale_io_success_count 0 +target_ready_replicas 0 +pod_recreate_used true +node_loss_recovery_claimed true +data_check_after_node_loss reader_checksum_passed +transparent_failover_claimed false +physical_host_loss_claimed false +cleanup strict clean +``` + +This run is the first end-to-end Kubernetes-node-loss recovery proof for this +plan: primary node cordoned, primary blockvolume stopped, master promoted a +surviving replica, CSI reattached to the survivor frontend, and the replacement +reader verified the pre-failure data. + +## D5: Transparent Multipath Node-Loss Decision + +After D4 passes, decide whether to extend this plan or open the next one for: + +```text +same mounted pod +primary node loss +host multipath path switch to another node +no pod recreate +post-failure data check +``` + +Do not merge this into D4 unless the lab/product path is already stable. + +## Gates To Close + +This plan closes only when: + +1. The lab topology has distinct Kubernetes nodes and non-loopback frontends. +2. A strict QA hard gate exists before implementation is treated as complete. +3. Fast tests protect node-aware placement, target selection, and non-loopback + rejection. +4. A runner-native gate proves recovery after controlled primary-node loss. +5. Support bundles explain node placement, authority movement, CSI target + movement, stale-primary fencing, bounded waits, and data verification. +6. User-facing docs distinguish Stage 2 same-node transparent failover from + node-loss recovery. +7. QA validates independently and reports no blocking issue. diff --git a/seaweed-block/internal/docs/finished-plans/phase19_finishedplan_control_plane_observation_ai_readable_ops_mvp.md b/seaweed-block/internal/docs/finished-plans/phase19_finishedplan_control_plane_observation_ai_readable_ops_mvp.md new file mode 100644 index 0000000000..492ea5d329 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase19_finishedplan_control_plane_observation_ai_readable_ops_mvp.md @@ -0,0 +1,561 @@ +# Current Plan: Control-Plane Observation / AI-Readable Ops MVP + +Status: active, opened after closing +`finished-plans/phase18_finishedplan_node_loss_survival_mvp.md`, 95% complete. + +Reference spec: + +- `ref/control-plane-observation-api-mvp.md` + +Close evidence that motivates this plan: + +- Node-Loss Survival close report: + `qa-assignments/node-loss-survival-mvp-close-report.md` +- D4 close run: `20260516-160306-1e54` +- Prior QA blockers that should have been self-explaining: + - inventory replica-ID attribution bug, + - missing `sw-block-csi:local` image on m02, + - ImagePullBackOff on CSI node pod, + - reader/reattach waiting on a Kubernetes runtime precondition. + +## Product Question + +Can a Kubernetes user or support engineer understand Seaweed Block cluster +state from one CLI/API surface, without SSHing into every node, reading raw +Kubernetes events manually, or knowing internal authority implementation +details? + +For block storage, a stuck PVC or failover is a serious product moment. The +operator needs a direct answer: + +```text +what failed +what the product did +whether data is safe +which target is active +whether recovery is still progressing or blocked +what to collect or do next +``` + +## Product Position + +The last three availability plans moved the data path forward: + +```text +Stage 1: RF3 sync-quorum recovery through CSI/pod recreate +Stage 2: RF3 sync-quorum same-node transparent iSCSI ALUA/dm-multipath failover +Stage 3: RF3 sync-quorum Kubernetes-node-loss recovery through CSI/pod recreate +``` + +The next product gap is operations trust. Mature block products do not require +users to correlate `kubectl describe`, CSI logs, blockmaster logs, support +bundles, and handwritten TestOps timelines. Seaweed Block should expose a +stable observation model that a human, dashboard, CI job, or AI assistant can +read directly. + +The product direction should follow the SeaweedFS operations pattern: + +```text +shared observation core +-> CLI text for humans, support, QA, and AI +-> JSON/JSONL for automation and bundles +-> master read-only API for dashboard/UI +``` + +Do not create separate truth sources for CLI, dashboard, TestOps, and AI. + +## Target User Experience + +Initial CLI: + +```bash +sw-block ops cluster +sw-block ops volumes +sw-block ops describe volume +sw-block ops timeline volume +sw-block ops timeline volume -o jsonl +sw-block ops explain volume +sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out /tmp/sw-block-inventory +sw-block ops events --since 1h +``` + +Default output is human-readable. `-o json` and `-o jsonl` are stable machine +contracts. + +Example healthy output: + +```text +volume pvc-... status=ok rf=3 ack=sync-quorum +pvc default/mysql-data +primary r1 on m01 frontend=192.168.1.181:3260 +replicas desired=3 observed=3 +r1 m01 primary ready durable_lsn=44 +r2 m02 replica_ready candidate_ready=true durable_lsn=44 +r3 tp01 replica_ready candidate_ready=true durable_lsn=44 +next action: none +``` + +Example recovering output: + +```text +volume pvc-... status=recovering reason=primary_node_lost +old primary r1 on m01 unavailable +promoted primary r2 on m02 epoch=2 endpoint_version=1 +CSI target changed 192.168.1.181:3260 -> 192.168.1.184:3260 +reattach method: pod_recreate +next action: wait for app pod readiness, then collect support bundle if stuck +``` + +Example blocked output: + +```text +volume pvc-... status=blocked reason=csi_node_image_pull_failed +node m02 missing image sw-block-csi:local +pod kube-system/sw-block-csi-node-... waiting=ImagePullBackOff +impact: PVC attach cannot proceed on workloads scheduled to m02 +next action: import the image to m02 or use a registry reachable by all nodes +``` + +## Explicit Non-Claims + +- No mutating admin controls. +- No promote, repair, rebuild, backup, restore, or cleanup command. +- No hosted dashboard in this MVP. +- No metrics/Prometheus integration in this MVP. +- No alert-manager integration. +- No claim that application-level checksum ran unless TestOps/user actually ran + it. +- No replacement for Kubernetes events; this plan explains Seaweed Block state + and includes relevant Kubernetes runtime evidence. + +## D1: Observation Evidence Model + +Build the shared data model before adding live APIs. + +Status: dev pass, QA not requested yet. Implemented the first stable evidence +model and renderers in `core/ops/observation.go`, with golden tests in +`core/ops/observation_test.go`. + +Required structs / schema concepts: + +```text +ClusterEvidence +NodeEvidence +VolumeEvidence +ReplicaEvidence +ClusterEvent +VolumeTimeline +VolumeExplanation +SupportBundleManifest +``` + +Required stable statuses: + +```text +ok +degraded +recovering +blocked +invalid +unavailable +``` + +Required reason codes for first slice: + +```text +primary_node_lost +candidate_covers_required_frontier +no_promotion_ready_candidate +durable_frontier_missing +candidate_frontier_behind +status_endpoint_unreachable +csi_node_image_pull_failed +image_missing_on_node +generated_deployment_missing +observed_replicas_below_desired +loopback_frontend_rejected +stale_primary_fenced +``` + +Pass criteria: + +- golden examples for healthy, recovering, and blocked evidence, +- text renderer output is readable without internal context, +- JSON output includes schema version and stable reason codes, +- JSONL timeline emits one event per line with `event_type`, `severity`, + `reason_code`, `volume_id`, `evidence_ref`, and summary text. + +Dev evidence: + +- `go test ./core/ops -run TestObservation -count=1` PASS. +- `go test ./core/ops -count=1` PASS. +- Healthy text pins `status=ok`, primary frontend, replica durable LSN, and + `next action: none`. +- Recovering text pins `status=recovering reason=primary_node_lost`, stale + primary fencing, and CSI target movement. +- Blocked text pins `status=blocked reason=csi_node_image_pull_failed`, node, + image, and `ImagePullBackOff` pod evidence. +- JSON/JSONL output carries `schema_version=1.0` and stable reason codes. + +## D2: CLI From Existing Bundles + +Start with existing inventory/support bundles. This avoids waiting for a new +master API and immediately improves support/QA usability. + +Status: dev pass, QA not requested yet. Implemented bundle-backed observation +loading in `core/ops/observation_bundle.go` and wired read-only CLI entry points +in `cmd/sw-block/main.go`. + +Commands: + +```bash +sw-block ops describe volume --from-bundle +sw-block ops timeline volume --from-bundle +sw-block ops timeline volume --from-bundle -o jsonl +sw-block ops explain volume --from-bundle +``` + +Inputs: + +- `volume-inventory.json`, +- `volume-inventory-summary.txt`, +- `ops-inventory-bundle.json`, +- nested per-replica `ops-status-bundle.json`, +- `primary-failure-recovery.txt`, +- `node-loss-recovery-summary.txt`, +- `control-plane-timeline.txt`, +- Kubernetes runtime evidence when present. + +Pass criteria: + +- D4 bundle `20260516-160306-1e54` renders the same story as the QA close + report: + `r1@m01 -> r2@m02`, CSI target moved, reader checksum passed, stale primary + fenced, transparent failover not claimed. +- The failed D4 bundle `20260516-154813-109a` renders + `status=blocked reason=csi_node_image_pull_failed` and names m02 plus + `sw-block-csi:local`. + +Dev evidence: + +- Added: + - `sw-block ops describe volume --from-bundle ` + - `sw-block ops timeline volume --from-bundle -o jsonl` + - `sw-block ops explain volume --from-bundle ` +- `go test ./core/ops -count=1` PASS. +- `go test ./cmd/sw-block -count=1` PASS. +- Real close bundle smoke: + `go run ./cmd/sw-block ops explain volume --from-bundle V:\share\g15d-k8s\20260516-160306-1e54-node-loss-survival pvc-c606d03a-4136-464d-8716-ef01f92c7b12` + renders `r2@m02`, target movement `192.168.1.181:3260 -> + 192.168.1.184:3260`, reader verification, stale-primary fence evidence, and + timeline events. +- Real failed bundle smoke: + `go run ./cmd/sw-block ops explain volume --from-bundle V:\share\g15d-k8s\20260516-154813-109a-node-loss-survival pvc-c606d03a` + renders `status=blocked reason=csi_node_image_pull_failed`, node `m02`, and + image `sw-block-csi:local`. + +## D3: Live CLI Over Current Inventory Sources + +Use the current live inventory collector and Kubernetes runtime collectors. + +Status: dev pass for the first read-only live CLI slice. Implemented live +cluster, volume-list, and per-volume explain/describe/timeline entry points +using the same observation model as D1/D2. This slice reads Kubernetes +inventory and optional per-replica status through the existing collectors; it +does not introduce master write APIs or mutating admin actions. + +Commands: + +```bash +sw-block ops cluster --namespace default --master 127.0.0.1:9333 +sw-block ops volumes --namespace default --master 127.0.0.1:9333 +sw-block ops describe volume --namespace default --master 127.0.0.1:9333 +sw-block ops explain volume --namespace default --master 127.0.0.1:9333 +sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out +``` + +Runtime evidence to collect: + +- `kubectl get pods -A -o wide`, +- relevant `kubectl describe pod`, +- namespace events, +- blockmaster logs, +- CSI controller logs, +- CSI node logs, +- generated blockvolume pod logs, +- per-node k3s image inventory for selected product images, +- iSCSI sessions and node DB entries when available. + +Pass criteria: + +- live healthy RF3 node-loss-ready volume explains as `ok`, +- simulated missing image explains as `blocked` with node/image/pod/reason, +- no command mutates Kubernetes, master, iSCSI, or blockvolume state. + +Dev evidence: + +- Added: + - `sw-block ops cluster --namespace [--master ] [-o json]` + - `sw-block ops volumes --namespace [--master ] [-o json]` + - live mode for `sw-block ops describe volume --namespace + [--master ] [--out ]` + - live mode for `sw-block ops explain volume --namespace + [--master ] [--out ]` +- `go test ./core/ops -count=1` PASS. +- `go test ./cmd/sw-block -count=1` PASS. +- CLI tests pin live inventory output for: + - cluster summary, + - volume list, + - per-volume describe, + - bundle timeline JSONL, + - ImagePullBackOff explanation from preserved failed bundle. + +Remaining D3 gap before QA: run the live commands against the actual 3-node lab +while a healthy RF3 node-loss-ready volume is active, then add the simulated +missing-image live fixture if needed. + +## D4: Master Read-Only Snapshot API + +Add a master read-only API only after the CLI evidence model is stable. + +Status: dev pass. Implemented `Host.ObservationSnapshot()` in +`core/host/master/observation_snapshot.go`, added the read-only +`ClusterEvidenceService` to `core/rpc/proto/control.proto`, regenerated +protobuf bindings, registered the service in blockmaster, and wired server +methods in `core/host/master/observation_service.go`. + +Provisional API: + +```proto +service ClusterEvidenceService { + rpc GetClusterStatus(GetClusterStatusRequest) + returns (ClusterStatusResponse); + rpc ListVolumes(ListVolumesRequest) + returns (ListVolumesResponse); + rpc GetVolumeStatus(GetVolumeStatusRequest) + returns (VolumeEvidence); + rpc GetVolumeTimeline(GetVolumeTimelineRequest) + returns (VolumeTimelineResponse); + rpc WatchClusterEvents(WatchClusterEventsRequest) + returns (stream ClusterEvent); +} +``` + +Pass criteria: + +- API and CLI share the same evidence model, +- no read API can mutate authority, placement, lifecycle, or replica state, +- one live RF3 volume appears with primary, replicas, frontend, epoch, + endpoint_version, and reason code. + +Dev evidence: + +- `Host.ObservationSnapshot()` returns `ops.ClusterEvidence` directly, so the + master read surface and CLI/bundle surfaces share one evidence schema. +- Snapshot reads only lifecycle volume/node/placement stores, publisher + authority line, controller evidence, and observation-store heartbeat facts. +- `TestMasterObservationSnapshot_RF3HealthyReadOnly` pins an RF3 volume with + primary, replicas, frontend, epoch, endpoint_version, PVC identity, and node + evidence, then asserts authority state is unchanged after the read. +- `TestMasterObservationSnapshot_MissingReplicaIsDegraded` pins + `observed_replicas_below_desired` and per-replica + `status_endpoint_unreachable` when one placement slot has no fresh + observation. +- `TestMasterObservationSnapshot_NoLifecycleStoreReturnsEmptyOK` pins safe + empty output when lifecycle stores are not configured. +- `go test ./core/host/master -run TestMasterObservationSnapshot -count=1` + PASS. +- `go test ./core/host/master ./core/ops ./cmd/sw-block -count=1` PASS. + +- `TestClusterEvidenceService_GRPCRegistered` calls + `ClusterEvidenceService.GetVolumeStatus` through a real gRPC client and pins + that the service is registered on blockmaster. +- `TestClusterEvidenceService_GetClusterStatusSharesObservationSnapshot` pins + schema/status/volume/node evidence and verifies the read does not mutate + publisher authority. +- `TestClusterEvidenceService_ListVolumesAndGetVolumeStatus` pins the degraded + missing-replica wire shape. +- `TestClusterEvidenceService_GetVolumeStatusNotFound` pins `NotFound` for + unknown volumes. +- `TestClusterEvidenceService_GetVolumeTimelineEmptyButVersioned` keeps the D5 + timeline gap explicit: the API is versioned, but product-owned event content + lands in the next slice. +- `go test ./core/host/master -run "TestClusterEvidenceService|TestMasterObservationSnapshot" -count=1` + PASS. +- `go test ./core/host/master ./core/ops ./cmd/sw-block -count=1` PASS. + +Remaining D4 gap before QA: validate against the live 3-node lab while an RF3 +node-loss-ready volume is active, so the API output is checked against real +Kubernetes node/replica placement and published frontend evidence. + +## D5: Product Timeline + +Move from TestOps-only timelines to product-owned timeline events. + +Status: dev pass for the first product-owned timeline slice. Added a bounded +master event ring in `core/host/master/event_ring.go`, included master-owned +events in `Host.ObservationSnapshot()`, and exposed them through +`ClusterEvidenceService.GetVolumeTimeline`. + +Required event types: + +```text +volume_created +placement_verified +replica_heartbeat_seen +replica_stale +promotion_candidate_evaluated +authority_published +publish_target_changed +stale_primary_fenced +csi_reattach_observed +pod_image_pull_failed +csi_node_unavailable +volume_recovered +volume_blocked +support_bundle_collected +``` + +Pass criteria: + +- node-loss D4 produces the same six-event story from product evidence, not + only from TestOps files, +- `WatchClusterEvents` reconnect with cursor does not miss + `authority_published` or `volume_blocked`. + +Dev evidence: + +- `RunLifecycleProductTick()` now emits `placement_verified` events when + placement verification succeeds. +- The promotion gate now emits `promotion_candidate_evaluated` events with + stable reason codes: + `candidate_covers_required_frontier`, `candidate_frontier_behind`, or + `no_promotion_ready_candidate`. +- The promotion gate emits `volume_blocked` when no candidate passes the + readiness gate. +- Added a publisher post-mint observer hook: + `authority.WithPublishObserver`. +- `authority_published` is now emitted only after `Publisher.apply()` has + successfully minted, durably committed when a store exists, updated in-memory + state, and delivered the fact. It is not emitted from controller intent + submission. +- CSI/node staging now emits `csi_reattach_observed` through + `ObservationService.ReportClusterEvent` after a successful `NodeStageVolume`. + This is an observation-only append to the master event ring; it does not + mutate lifecycle, authority, placement, Kubernetes, or replica state. +- `cmd/blockcsi` wires a `ControlEventReporter` when `--master` is configured, + so CSI reattach/stage evidence can show up in the master timeline alongside + `placement_verified`, `promotion_candidate_evaluated`, and + `authority_published`. +- `sw-block ops cluster --master-api -o json` now reads + `ClusterEvidenceService.GetClusterStatus` directly, so TestOps and support + bundles can capture the product-owned event ring without scraping + blockmaster logs or reconstructing the timeline from runner files. +- `node-loss-survival-rf3-reattach-chain.yaml` now captures + `demo/product-observation/cluster-evidence.json` before cleanup and asserts + the product event stream contains `placement_verified`, + `promotion_candidate_evaluated`, `authority_published`, and + `csi_reattach_observed`. +- `TestPublisher_PublishObserverFiresAfterSuccessfulMintOnly` PASS. +- `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` PASS. +- `TestMasterTimeline_RecordsPlacementVerified` PASS. +- `TestMasterTimeline_RecordsPromotionCandidateEvaluation` PASS. +- `WatchClusterEvents` now streams retained product events after + `since_event_id`; unknown cursors conservatively replay retained events so + clients can de-duplicate by event ID instead of silently missing evidence. +- `TestClusterEvidenceService_WatchClusterEventsCursor` PASS and pins that + reconnect after a cursor does not replay the cursor event and still includes + `authority_published`. +- `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` PASS and + pins that a CSI-reported `csi_reattach_observed` event is accepted, assigned + a master event ID, and appears in `GetVolumeTimeline`. +- `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` PASS and pins + CSI staging emits volume/replica/node/epoch/endpoint_version evidence after + a successful iSCSI stage. +- `TestControlEventReporter_ReportsClusterEvent` PASS and pins the CSI client + conversion into the observation RPC. +- `TestOpsClusterReadsMasterAPIProductEvents` PASS and pins the CLI can export + master-owned product events through `--master-api`. +- `go test ./core/host/master -run "TestMasterTimeline|TestClusterEvidenceService|TestMasterObservationSnapshot" -count=1` + PASS. +- `go test ./core/authority ./core/host/bootstrap ./core/host/master ./cmd/blockmaster ./cmd/blockcsi ./core/csi ./cmd/sw-block ./core/ops -count=1` + PASS. + +QA evidence: + +- D5 live rerun `20260517-011004-4b79`: PASS, 8/8 phases, 83/83 + actions. +- `demo/product-observation/cluster-evidence.json` is present in the bundle + and contains product-owned events exported through + `sw-block ops cluster --master-api`. +- Required event types found in the product event stream: + `placement_verified`, `promotion_candidate_evaluated`, + `authority_published`, and `csi_reattach_observed`. +- `authority_published` has master-minted `event_id` and `event_time` after + authority publication. +- `csi_reattach_observed` is CSI-emitted and master-ingested with a + master-minted `event_id`; it records the promoted r2 frontend + `192.168.1.184:3260`, not the failed r1 frontend. +- The bundle also includes populated node and volume sections: three + schedulable/ready nodes, one RF=3 volume, primary `r2`, published target + `192.168.1.184:3260`, epoch `2`, and all three replica rows. + +Remaining D5 gap: + +- Kubernetes runtime blocker events such as `ImagePullBackOff` are still + explained by the bundle/inventory path. Promoting them into the master event + stream is useful, but no longer blocks this MVP because D5's product-owned + recovery event ingestion is now proven. + +## D6: User Tutorial And Hard Gate + +Status: dev pass, QA close pending. User-facing docs now describe the +product-owned control-plane export path, and the formal close hard gate exists +under `qa-assignments/control-plane-observation-ai-readable-ops-mvp-close-hard-gate.md`. + +Docs must teach: + +- how to inspect cluster health, +- how to inspect one volume, +- how to read a timeline, +- how to collect a support bundle, +- how to interpret healthy/recovering/blocked examples, +- what is not claimed. + +QA hard gate should fail if: + +- any command mutates state, +- a blocked/recovering state lacks a stable reason code, +- missing image / ImagePullBackOff is not explained, +- node-loss recovery evidence is available only by reading raw TestOps logs, +- stale primary and promoted primary cannot be distinguished, +- JSON/JSONL output is unstable or missing schema version, +- support bundle misses Kubernetes pod events/logs for attach/install failures. + +Required close artifacts: + +- `docs/operations-v1.md` names the new AI-readable observation path and shows + `sw-block ops cluster --master-api -o json`. +- `docs/quickstart-kubernetes.md` gives a short "export product evidence" + path using `kubectl port-forward deploy/sw-blockmaster`. +- `qa-assignments/control-plane-observation-ai-readable-ops-mvp-close-hard-gate.md` + exists and makes D5 product event evidence a hard close requirement. + +Dev evidence: + +- `docs/operations-v1.md` now documents the split between product-owned + `cluster-evidence.json` and inventory/per-replica support bundles. +- `docs/quickstart-kubernetes.md` now shows how to capture + `/tmp/sw-block-cluster-evidence.json` using + `sw-block ops cluster --master-api 127.0.0.1:9333 -o json`. +- The close hard gate has HG-0..HG-12 covering docs, product-owned event + export, required event types, master-minted event identity, CSI reattach + evidence, read-only boundary, stable reason codes, bundle-backed + explanation, support evidence completeness, watch/cursor behavior, explicit + non-claims, and cleanup hygiene. + +## Next Step + +Ask QA for a formal close review against the observation hard gate. Do not jump +directly to a dashboard. The dashboard should be a consumer of the observation +core, not a new source of truth. diff --git a/seaweed-block/internal/docs/product-management-plan.md b/seaweed-block/internal/docs/product-management-plan.md index 55d2fd0614..7165ec4372 100644 --- a/seaweed-block/internal/docs/product-management-plan.md +++ b/seaweed-block/internal/docs/product-management-plan.md @@ -60,9 +60,9 @@ Non-promise for the current alpha: | Durable default state | Volume data survives blockvolume pod restart. | | Operator/controller cleanup | Harness no longer acts as the operator for generated blockvolume workloads. | | Multi-node attach | App pod and blockvolume can run on different K8s nodes. | -| Basic failover and reattach | Primary failure can be recovered by authority move and CSI reattach/pod restart. | +| Safe K8s recovery via CSI/pod recreate | RF=2 primary failure can recover through authority move plus CSI/node reattach on pod recreate, or fail closed with a precise blocker. | | Replica lifecycle | Returned replicas go through candidate/syncing/rebuilding/ready, not heartbeat-to-ready. | -| Explicit ACK profile | Users know whether writes are best-effort, quorum, or full-ack. | +| Explicit ACK profile | Users know whether writes are best-effort, sync-quorum, or sync-all. | | TestOps smoke suite | QA can run named scenarios and return result bundles. | ## Prioritized Backlog @@ -87,13 +87,30 @@ Priority definitions: | Task | Why It Matters | Status | Evidence / Notes | |---|---|---|---| -| Controller-owned generated workload cleanup | Current harness cleanup is not a product controller. | Planned | Roadmap item. | -| Durable node-local volume state | `emptyDir` is not a production storage story. | Planned | Required before real data-retention claim. | +| Controller-owned generated workload cleanup | Current harness cleanup is not a product controller. | Closed for alpha path | Product-owned generated workload lifecycle is closed in phase 12. | +| Durable node-local volume state | `emptyDir` is not a production storage story. | Closed for RF=1 alpha path | Durable restart/reattach is closed in phase 13; RF=2 recovery still needs frontier evidence. | | Multi-node K8s attach | Single-node loopback hides networking and placement problems. | Closed for same-node loopback alpha path | Phase 14 proves app/blockvolume co-location, normal CSI attach, inventory placement evidence, and unsupported remote-loopback attach as a non-claim. | -| Failover under mounted workload | Availability claim must be proven at app path. | Active | Current plan: basic mounted failover and reattach MVP. | +| Failover under mounted workload | Availability claim must be proven at app path. | Active | Current plan: RF=2 promotion-ready recovery via CSI/pod recreate. | | Replica reintegration policy | Returned replicas must not become ready from heartbeat alone. | Partially designed | G9 lifecycle work informs this. | -| ACK profile rules | Avoid “best-effort” being mistaken for full durability. | Designed, not enforced | See production readiness plan. | -| Observability/status surface | Users need diagnosis without reading debug logs. | Active | Current plan: cluster operations inventory and lifecycle visibility. | +| ACK profile rules | Avoid “best-effort” being mistaken for full durability. | Partially enforced | Fast guards reject beta RF=2 recovery on best-effort; sync-quorum/sync-all still need live D4 recovery evidence. | +| Observability/status surface | Users need diagnosis without reading debug logs. | Closed for read-only alpha inventory; expanding | Cluster inventory is closed; Stage 1.5 tracks product usability hardening. | + +### P1.5: Product Usability Hardening + +These items do not replace the Stage 1 recovery gate. They make the product +usable enough that a small-cluster operator can diagnose and trust the system +without internal context. + +| Task | Why It Matters | Status | Evidence / Notes | +|---|---|---|---| +| Kubernetes-readable volume conditions | Users should see Ready/Degraded/Recovering/Blocked plus reason without parsing bundles. | Planned | Roadmap Track H. | +| One-command support bundle | First failure should produce attach/failover/cleanup evidence without component knowledge. | Planned | Builds on `sw-block ops status` and `ops inventory`. | +| Conservative timeout/retry defaults | iSCSI/NVMe/CSI behavior should be product defaults, not script folklore. | Planned | Must stay protocol-specific and documented. | +| Upgrade/rollback smoke | Version changes must not silently break existing PVC attach/read. | Planned | Start with a narrow smoke, not broad upgrade safety. | +| Capacity/replication preflight guards | Obvious impossible requests should fail before unsafe partial placement. | Planned | Especially RF and space constraints. | +| Delete/residue audit consistency | PVC delete must have stable target/session/artifact cleanup evidence. | Planned | Builds on prior cleanup attribution. | +| Multi-volume concurrency baseline | Two PVCs are proven; product confidence needs create/attach/delete at N volumes. | Planned | Start with N=10 if lab resources allow. | +| Productized fail-closed reasons | Blocker strings should map to documented operator next steps. | Planned | Keeps safe refusal actionable, not just correct. | ### P2: Expansion @@ -132,6 +149,13 @@ Before starting code for a new problem, answer these: Default answer to #7 is yes for all product fixes after the MVP merge. +For P0/P1 product work, also fill or reference a product spec gate using +`internal/docs/ref/product-spec-gate-template.md` before broad implementation. +The spec must define the user-visible contract, non-negotiable semantics, +allowed simplifications, non-claims, and evidence contract. A green test does +not override the spec. If implementation weakens the spec, update the plan and +non-claims first or stop. + ## Test And Evidence Index | Evidence Type | Where | @@ -148,28 +172,31 @@ Default answer to #7 is yes for all product fixes after the MVP merge. ## Current Immediate Recommendation -The light-use operations ladder is now closed through same-node placement and -attach: +The light-use operations ladder is now closed through same-node placement, +attach, durable restart, and safe RF=2 refusal: - first-volume runbook and failure bundle are closed, - cluster inventory is closed, - product-owned generated workload lifecycle is closed, - durable RF=1 restart/reattach is closed, -- same-node alpha attach and placement visibility are closed. +- same-node alpha attach and placement visibility are closed, +- RF=2 mounted baseline and primary-failure safe refusal are closed. The next concrete product step is: ```text -Build a basic mounted failover and reattach MVP: prove through the app/PVC path -that a controlled primary failure either recovers with data verified after -reattach, or fails closed with inventory/support-bundle evidence that explains -why recovery is not claimed. +Build Stage 1 safe Kubernetes recovery: prove through the app/PVC path that an +RF=2 peer becomes promotion-ready, a controlled primary failure triggers safe +authority movement, CSI/node reattaches on pod recreate, and the reader verifies +the same data; otherwise fail closed with a precise blocker. ``` Current state: -- Protocol-level iSCSI/NVMe failover gates exist, but the Kubernetes app/PVC - recovery claim is not yet closed. -- The ACK profile and stale-primary/returned-replica evidence must be explicit - before any availability claim. -- The active plan is `Basic Mounted Failover And Reattach MVP`. +- Protocol-level iSCSI/NVMe failover gates exist, but transparent host + multipath is Stage 2, not the current claim. +- Current Stage 1 has candidate durable frontier evidence, but still lacks the + mounted writer required frontier and positive CSI/pod-recreate recovery gate. +- The active plan is `RF=2 Promotion-Ready Recovery MVP`. +- Stage 1.5 usability hardening should be planned in parallel, but it must not + dilute Stage 1's minimum HA product line. diff --git a/seaweed-block/internal/docs/product-roadmap.md b/seaweed-block/internal/docs/product-roadmap.md index b266dfb47b..ccae82f06b 100644 --- a/seaweed-block/internal/docs/product-roadmap.md +++ b/seaweed-block/internal/docs/product-roadmap.md @@ -16,6 +16,30 @@ This is the short internal roadmap. Keep it current and readable. ## Product Phases +### Release Ladder + +- `v0.1-alpha`: Kubernetes block foundation. CSI/PVC path, product-owned + blockvolume lifecycle, inventory, recovery gates, iSCSI ALUA/dm-multipath, + node-loss recovery, and read-only control-plane observation are proven in + lab gates. This is an engineering alpha, not a polished install product. +- `v0.2-alpha`: Day-1 activation. A supported user can run the script-based + activation path, create a first PVC, verify writer/reader data, generate a + local read-only report, and clean up. This is the current user-facing alpha + packaging boundary. +- `v0.3-alpha`: Helm activation. Package the same supported Day-1 path as a + normal Kubernetes add-on: chart values, immutable images, CHAP/external + iSCSI configuration, StorageClass, readiness output, first-volume smoke, and + uninstall hygiene. Helm is the next installer milestone. +- `v0.4-beta-candidate`: Operator lifecycle. Add a Kubernetes-native control + plane with CRDs/Conditions/Events for install, node eligibility, volume + lifecycle, recovery observation, safe cleanup, and eventually gated repair or + rebuild workflows. This is the first release boundary that can credibly feel + like a complete Kubernetes product loop rather than an install script. + +Do not skip from scripts directly to an operator. Helm should stabilize the +installation contract before an in-cluster controller owns upgrades and day-2 +lifecycle. + ### Alpha Preview - Status: protocol-gated; moving toward beta hardening. @@ -47,7 +71,8 @@ This is the short internal roadmap. Keep it current and readable. - Basic failover with an attached workload. - Returned replica lifecycle: observed -> candidate -> syncing/rebuilding -> ready. -- Explicit ACK profile: best-effort, quorum, or full-ack. +- Explicit ACK profile: best-effort, sync-quorum, or sync-all + (quorum/full-ack aliases may appear in older docs or discussions). - TestOps can run named smoke scenarios and return result bundles. ### Production Candidate @@ -75,13 +100,22 @@ This is the short internal roadmap. Keep it current and readable. ### Track A: Kubernetes Install And Cleanup -- Current: the light-use install/lifecycle loop is closed for the supported - single-node alpha path: install/launch, create PVC, run app write/read, - delete resources, verify cleanup attribution, and collect a failure bundle. -- Next: make generated `blockvolume` workload lifecycle product-owned so the - user does not run a separate manifest-apply script. -- Later: turn the minimal lifecycle loop into a small controller/operator with - scoped reconciliation and upgrade-safe ownership. +- Current: v0.2 alpha closes the script-based Day-1 loop for the supported + Kubernetes path: activate, verify node readiness, create a first PVC, run + writer/reader verification, inspect status/report evidence, and clean up. + Product-owned generated `blockvolume` workload lifecycle is also closed for + the supported alpha path. +- Next: v0.3 Helm activation. Package the same Day-1 path as a chart while + keeping preflight and host cleanup explicit: + - charted blockmaster, CSI controller/node, RBAC, CSI driver, StorageClass, + CHAP Secret, and cluster spec, + - values for image tags/digests, ACK profile, external iSCSI/status, + Stage 2 multipath, namespace, and StorageClass, + - generated Day-1 values file for multi-node labs, + - `helm install` + first PVC smoke + `sw-block ops report`, + - `helm uninstall` plus explicit host cleanup verification. +- Later: v0.4 operator lifecycle. Introduce CRDs/Conditions/Events and scoped + reconciliation only after the Helm contract is stable. ### Track B: iSCSI Frontend Stability @@ -105,13 +139,20 @@ This is the short internal roadmap. Keep it current and readable. ### Track D: Availability And Recovery -- Current: iSCSI and NVMe mounted failover are release-gated in protocol lab - scenarios, RF=1 durable `blockvolume` restart is closed for the alpha - Kubernetes path, and same-node placement/attach is now visible and gated. -- Next: connect those pieces into a basic mounted failover/reattach MVP through - the app/PVC path, with an explicit ACK profile and safe stale-primary - evidence. -- Later: rebuild/reintegration and longer soak under failure. +- Current: Stage 1 mounted recovery and Stage 2 transparent host-path failover + are closed for the documented Kubernetes alpha path. Stage 1 proved RF=3 + `sync-quorum` recovery through CSI/node reattach on pod recreate. Stage 2 + proved RF=3 `sync-quorum` iSCSI ALUA plus Linux dm-multipath failover with + the same mounted writer pod, no pod recreate, no CSI re-stage, stale-primary + fencing, and post-failure checksum verification. +- Next: Node-loss survival is the highest-impact availability gap. Move from + same-node logical replica failure to real Kubernetes node failure semantics: + distinct nodes, non-loopback frontends, node-aware publish target selection, + authority promotion to a surviving replica, host-path recovery through the + documented mechanism, and support-bundle proof of fencing and data integrity. +- Later: returned-replica rebuild/reintegration/failback, NVMe ANA Kubernetes + multipath parity, stronger committed-frontier reporting, broad distro/host + compatibility, and longer soak under failure. ### Track E: Protocol / Backend Expansion @@ -121,6 +162,13 @@ This is the short internal roadmap. Keep it current and readable. smartwal/delta experiments behind explicit gates. - Later: RDMA/KV-backed data-plane experiments and semantic storage protocols only after the block core is mature. +- Guardrail: do not let backend/library extraction weaken the user-visible + block contract. A simpler data-plane seam is useful only if it preserves the + product semantics the block layer needs: bounded buffers/streaming for large + objects, explicit acknowledgement profile, durable frontier, fencing, retry + behavior, and supportable failure evidence. If an abstraction becomes easier + to test but cannot carry real volume I/O semantics, keep it experimental and + do not build a product claim on it. ### Track F: Operations Layer @@ -129,12 +177,26 @@ This is the short internal roadmap. Keep it current and readable. PVC/PV/generated workloads, attaches per-replica status bundles, and names stale/orphan residue without relying on TestOps artifacts. It also serves as the proof surface for product-owned lifecycle, durable restart evidence, and - same-node placement/attach evidence. -- Next: use inventory as the proof surface for mounted failover/reattach, - stale-primary fencing, returned-replica eligibility, and safe refusal. -- Later: observation API/UI, metrics, conservative admin controls, enterprise - operations, hosted validation, fleet automation, and cloud-scale test - lifecycle. + same-node placement/attach evidence. Phase 19 closed the shared observation + core for users/support/AI, JSON automation, and future dashboard use. +- Next: make observation part of the first-user loop: cluster status, node + readiness, volume list, volume detail, timeline, logs, and bundle pointers + should be visible without SSHing into every node. +- Later: metrics, read-only dashboard hardening, conservative admin controls, + enterprise operations, hosted validation, fleet automation, and cloud-scale + test lifecycle. + +### Product Semantics Rule + +- Roadmap slices must preserve a sharp product question. For block storage, the + question is not "can we model this state?" but "can an operator and workload + safely use this volume under the documented topology and failure mode?" +- Passing tests are not enough when the tested abstraction has weaker semantics + than the user-facing product. Such cases must be documented as non-claims, + safe refusals, or experiments. +- Mature-product direction means each operations and availability slice should + improve one of: provision, attach, mounted I/O, durability, fencing, reattach, + cleanup, status, or support-bundle actionability. ### Top Light-Use Product Blockers @@ -143,13 +205,61 @@ credible light-use product: - Product-owned generated workload lifecycle: scripts/TestOps still own too much apply/cleanup and run-scoped state management. -- Install/upgrade/uninstall: alpha scripts work for tests, but users need a - normal K8s add-on flow. +- Install/upgrade/uninstall: v0.2 script activation works, but users need a + normal Kubernetes add-on flow. Helm is the next packaging blocker; operator + lifecycle comes after the Helm contract is stable. - Observation beyond one volume: the read-only CLI now covers cluster inventory; users will still need lifecycle status, metrics, and eventually UI. - Safe admin controls: repair/promote/cleanup actions must wait until the read-only observation model is stable and release-gated. +### Track H: Stage 1.5 Product Usability Hardening + +- Current: core product loops are proven for light-use alpha, but day-2 + usability still depends too much on internal context. +- Next: + - add `kubectl get`-readable readiness/degraded/recovering/blocked conditions + with stable reason codes, + - provide one-command support-bundle capture with minimum evidence for attach, + failover, and cleanup diagnosis, + - set conservative default timeout/retry profiles for iSCSI/NVMe/CSI paths, + - add upgrade/rollback smoke gates for PVC attach/read continuity, + - enforce capacity/replication preflight guards with operator-readable errors, + - harden delete/residue cleanup auditing for sessions/targets/artifacts, + - run multi-volume concurrency baselines (create/attach/delete) as product + gates, not ad-hoc checks, + - keep fail-closed blocker reasons directly mapped to operator runbook steps. +- Later: fold proven Stage 1.5 hardening into beta entry criteria. + +### Track I: Enterprise Feature Gap Closure (Backup, UI, DR, Security) + +- Current: Seaweed Block is intentionally narrow and honest for alpha/beta. + Compared with mature Kubernetes block platforms, major product gaps still + include: + - backup/snapshot lifecycle as a first-class product workflow, + - disaster-recovery orchestration across clusters/regions, + - operator-facing control UI and guided diagnostics, + - policy/RBAC/audit guardrails for admin actions, + - richer day-2 automation (scheduled policies, safe runbooks, rollback UX). +- Reference signals from mature products: + - Longhorn exposes recurring snapshot/backup jobs and UI-first operations. + - Ceph/Rook exposes RBD snapshots and mirroring for DR workflows. + - OpenEBS Replicated PV Mayastor exposes replicated PV operations and CSI + snapshot integration. + - Portworx positions backup + DR + enterprise security as core platform + pillars. +- Next (priority order): + - P1: backup/snapshot policy + restore workflow with support-bundle evidence, + - P1: control-plane read UI over the observation API described in + `ref/control-plane-observation-api-mvp.md`, + - P2: admin action protocol (promote/repair/cleanup) with strict fencing and + audit trail, + - P2: cross-cluster DR contract (RPO/RTO class + failover/failback runbook), + - P3: security hardening track (RBAC, secret handling, action audit, + tenancy boundaries). +- Later: turn these tracks into explicit beta/production entry gates and avoid + feature-claim drift between docs and runnable gates. + ### Track G: Test Management Control Plane - Current: runner scenarios write result/status bundles, but M01/M02 shared lab diff --git a/seaweed-block/internal/docs/ref/architecture-review-recommendations-2026-05.md b/seaweed-block/internal/docs/ref/architecture-review-recommendations-2026-05.md new file mode 100644 index 0000000000..7408b35904 --- /dev/null +++ b/seaweed-block/internal/docs/ref/architecture-review-recommendations-2026-05.md @@ -0,0 +1,141 @@ +# Seaweed Block Architecture Review Recommendations (2026-05) + +Scope: current `sw-block` codebase, with emphasis on Kubernetes product path, +RF=2 recovery Stage 1, and near-term multi-node readiness. + +## Executive Summary + +The module layering is directionally correct. The main risks are not "wrong +architecture style" but missing product-critical closure in three seams: + +1. publish-target selection is not node-aware/deterministic enough, +2. recovery/runtime failure surfaces still rely on panic in key paths, +3. Stage 1 recovery proof is not yet fully wired through attach selection and + host-path evidence. + +If these are fixed, the stack can support a credible Stage 1 product claim and +prepare cleanly for Stage 2 multipath. + +## P0 Recommendations (Do First) + +### R1. Make CSI publish target selection node-aware and deterministic + +Problem: +- `LookupPublishTarget(ctx, volumeID, nodeID)` currently does not use `nodeID` + in selection. +- `publishTargetFromStatus()` returns the first matching frontend instead of a + policy-selected target. + +Why this matters: +- Multi-node attach behavior will become ambiguous. +- Wrong target selection can break recovery even when authority is correct. + +Suggested implementation: +- Introduce a `TargetSelectionPolicy` in `core/csi`: + - input: `volume status`, `nodeID`, optional preferred protocol, + - output: one selected target + reason. +- Selection order for Stage 1: + 1) assigned primary target for the requested node (or node-reachable alias), + 2) requested protocol match, + 3) highest generation `(epoch, endpoint_version)`, + 4) fail closed with typed reason if ambiguous. +- Keep authority-shaped fields out of `publish_context`, but include selection + reason in logs/artifacts. + +Acceptance: +- Unit tests covering: + - node mismatch, + - mixed iSCSI/NVMe frontends, + - two candidates with different generation, + - no valid target -> `ErrPublishTargetNotFound`. + +### R2. Replace panic-based runtime failures with fail-closed typed errors + +Problem: +- Some runtime code paths panic on invalid wiring or state. + +Why this matters: +- Panic is acceptable in deep invariant tests, but dangerous in product loops. +- We need predictable refusal semantics and support-bundle evidence. + +Suggested implementation: +- Keep constructor-time invariant checks, but convert operational panics to: + - typed error, + - explicit status degradation, + - blocker reason exported to ops/inventory. +- Apply first to: + - recovery sender sink wiring path, + - authority store load/runtime failure path. + +Acceptance: +- No panic in normal product control/data loop for expected misconfig/failure. +- Errors map to stable blocker reasons visible in inventory/support bundle. + +### R3. Wire Stage 1 recovery gate to attach-target generation and required frontier + +Problem: +- Candidate durable frontier is now visible, but writer required frontier is + not yet fully compared in D4 claim path. + +Why this matters: +- Without this check, recovery can look successful while violating durability + semantics. + +Suggested implementation: +- D4 runner captures: + - pre-failure publish target generation `(replica, epoch, endpoint_version)`, + - writer required frontier LSN, + - candidate durable frontier LSN. +- Recovery claim only if: + - candidate covers required frontier, + - authority moved generation correctly, + - recreated pod staged against new target generation, + - post-failure checksum passes. + +Acceptance: +- Gate emits explicit PASS/REFUSE with one blocker class: + - `required_frontier_missing`, + - `candidate_frontier_behind_required`, + - `authority_promotion_missing`, + - `host_path_recovery_not_verified`. + +## P1 Recommendations (Next) + +### R4. Introduce a lightweight capability matrix with code-owner linkage + +Goal: +- Prevent doc drift between roadmap claims and runtime behavior. + +Minimal shape: +- For each feature claim: `status`, `gate`, `owner`, `evidence path`, + `non-claim sentence`. + +### R5. Harden CSI node stage identity contract + +Goal: +- Reduce ambiguity from local staging markers. + +Plan: +- Bind stage identity to selected target generation evidence in node-local + metadata and validate on restage/republish. + +## What Not To Do Now + +- Do not fold Stage 2 multipath (ALUA/ANA transparent switching) into Stage 1 + closure criteria. +- Do not expose manual promote as primary user workflow. +- Do not claim RF=2 recovery from authority move alone. + +## Proposed 2-Week Execution Slice + +Week 1: +- R1 target selection policy + tests. +- R2 panic-to-error conversion (first two hotspots) + blocker mapping. + +Week 2: +- R3 D4 runner frontier/generation assertions. +- Ops artifact schema update and one QA dry run assignment. + +Expected outcome: +- Stage 1 claim can be evaluated by a single gate with deterministic + publish-target behavior and explicit refusal semantics. diff --git a/seaweed-block/internal/docs/ref/control-plane-observation-api-mvp.md b/seaweed-block/internal/docs/ref/control-plane-observation-api-mvp.md new file mode 100644 index 0000000000..eb9693b353 --- /dev/null +++ b/seaweed-block/internal/docs/ref/control-plane-observation-api-mvp.md @@ -0,0 +1,607 @@ +# Control-Plane Observation API MVP + +Status: reference spec for the next operations/usability slice. + +This document defines the product shape for a dashboard-grade read-only +observation surface. It is not an admin-action API. It exists so operators can +answer "what is happening to my PVC?" without knowing Seaweed Block internals. + +The shape should follow the SeaweedFS operations pattern: + +```text +shared observation core +-> CLI for humans, support, QA, and AI +-> JSON/JSONL output for automation and bundles +-> master read-only API for dashboard/UI +``` + +Do not build separate truth sources for CLI, dashboard, TestOps, and AI. + +## Product Question + +Can a Kubernetes user open one dashboard or run one command and understand: + +```text +which volumes exist +where each replica runs +which replica is primary +whether failover/recovery is progressing +which frontend CSI should attach to +why a volume is blocked or degraded +what evidence to send support +``` + +Current `sw-block ops inventory` already proves these facts in support bundles, +but it assembles them by polling Kubernetes, master `QueryVolumeStatus`, and +per-replica status endpoints. That is good for support bundles, but it is not a +clean long-term operations plane. The next product step is to factor the same +facts into one observation core and expose it through CLI, JSON/JSONL, and a +master read-only API. + +## User Experience Target + +The user-facing flow should be: + +```bash +sw-block ops cluster +sw-block ops volumes +sw-block ops describe volume pvc-... +sw-block ops timeline volume pvc-... +sw-block ops timeline volume pvc-... -o jsonl +sw-block ops explain volume pvc-... +sw-block ops bundle volume pvc-... --out /tmp/sw-block-support +sw-block ops events --since 1h +``` + +Default output should be concise human-readable text. Every command that emits +state should also support `-o json`; timeline/events should support +`-o jsonl`. JSON/JSONL is the stable contract for AI, CI, future dashboard, and +support automation. + +Dashboard shape: + +```text +Cluster + Volumes: 3 total, 2 ready, 1 degraded + Nodes: m01 ready, m02 ready, tp01 ready + Alerts: volume pvc-a recovering; stale primary fenced + +Volume pvc-a + PVC: default/mysql-data + RF: 3 sync-quorum + Primary: r2 on m02 + Frontend: 192.168.1.184:3260 + Status: Recovering + Reason: primary_node_lost_reattached + Data check: reader_checksum_passed + Next action: none; continue watching + +Replicas + r1 m01 unavailable, stale-primary fenced + r2 m02 primary, epoch=2, endpoint_version=1 + r3 tp01 replica_ready, durable_frontier_lsn=44 +``` + +The dashboard must not require users to understand `AssignmentFact`, +`EndpointVersion`, or TestOps scenario internals. Those fields can still appear +in an advanced evidence panel. + +## Current Surfaces + +Master gRPC APIs today: + +- `ObservationService.ReportHeartbeat`: blockvolume -> master local facts. +- `AssignmentService.SubscribeAssignments`: master -> blockvolume authority + assignment stream. +- `EvidenceService.QueryVolumeStatus`: read-only per-volume status, used by + CSI and `sw-block ops status`. +- `LifecycleService.CreateVolume/DeleteVolume`: desired lifecycle intent from + CSI/operator. + +CLI/support surfaces today: + +- `sw-block ops status`: one replica/volume status bundle. +- `sw-block ops inventory`: cluster inventory assembled from Kubernetes, + master status, and per-replica status bundles. +- TestOps control-plane timeline files in recovery scenarios. + +Gap: + +- no master API to list volumes, +- no master API to list nodes, +- no cluster-wide status rollup, +- no product-owned event stream, +- no stable timeline API for failover/recovery, +- no dashboard-ready condition model. + +## Three-Layer Operations Surface + +### Layer 1: CLI + +CLI is the fastest product entry and should land first. It should look like the +rest of the SeaweedFS family: one binary, readable subcommands, explicit JSON +mode when automation needs it. + +Commands: + +```text +sw-block ops cluster +sw-block ops volumes +sw-block ops describe volume +sw-block ops timeline volume +sw-block ops timeline volume -o jsonl +sw-block ops events --since 1h +sw-block ops events --watch +sw-block ops explain volume +sw-block ops bundle volume +``` + +CLI principles: + +- default output is readable by humans and AI, +- reason codes are stable, +- JSON/JSONL output is schema-versioned, +- no command mutates state, +- bundle output includes the same JSON evidence the CLI used. + +### Layer 2: Master Read-Only API + +The API is the long-term product boundary. The dashboard must not shell out to +`kubectl`, SSH, or CLI commands across nodes. It should read the master API. + +The API should call the same observation core as the CLI. + +### Layer 3: Dashboard + +Dashboard is a consumer, not a new source of truth. It should show the same +volume status, replica status, reason codes, events, and support-bundle hints +that the CLI returns. + +First dashboard scope: + +- cluster health, +- volume table, +- selected volume detail, +- selected volume timeline, +- support-bundle capture instructions. + +No promote/repair/rebuild buttons in the first dashboard. + +## API Contract + +Add a read-only service. Name is provisional but semantics are not: + +```proto +service ClusterEvidenceService { + rpc GetClusterStatus(GetClusterStatusRequest) + returns (ClusterStatusResponse); + rpc ListVolumes(ListVolumesRequest) + returns (ListVolumesResponse); + rpc GetVolumeStatus(GetVolumeStatusRequest) + returns (VolumeEvidence); + rpc GetVolumeTimeline(GetVolumeTimelineRequest) + returns (VolumeTimelineResponse); + rpc WatchClusterEvents(WatchClusterEventsRequest) + returns (stream ClusterEvent); +} +``` + +No method may mutate authority, placement, lifecycle, or replica state. + +### ClusterStatusResponse + +Minimum fields: + +```text +schema_version +captured_at +cluster_id +product_revision +nodes[] +volumes[] +conditions[] +non_claims[] +``` + +Cluster rollup status: + +```text +ok | degraded | recovering | blocked | unavailable +``` + +This rollup must be conservative. If a status source is missing, the response +should say `degraded` or `blocked` with a reason, not `ok`. + +### NodeEvidence + +Minimum fields: + +```text +node_name +kubernetes_node +physical_host +internal_ip +schedulable +ready +last_heartbeat_at +replica_count +required_images[] +missing_images[] +conditions[] +``` + +Important condition reasons: + +```text +node_not_ready +node_cordoned +heartbeat_stale +external_frontend_unreachable +image_missing_on_node +``` + +For Kubernetes install/attach failures, node evidence must include image +inventory for the product images the scenario or install selected. A dashboard +or CLI should be able to say: + +```text +node=m02 condition=image_missing_on_node image=sw-block-csi:local +impact=CSI node pod ImagePullBackOff; PVC attach cannot proceed on this node +next_action=import image to node or use a registry reachable by all nodes +``` + +### VolumeEvidence + +Minimum fields: + +```text +volume_id +namespace +pvc_name +pv_name +replication_factor +ack_profile +claim_profile +desired_replicas +observed_replicas +status +primary_replica +primary_node +publish_target +epoch +endpoint_version +replicas[] +conditions[] +next_actions[] +support_bundle_hint +``` + +Volume status values: + +```text +ok +degraded +recovering +blocked +invalid +``` + +The UI should show `status` and `reason` first, then show advanced fields only +when expanded. + +### ReplicaEvidence + +Minimum fields: + +```text +replica_id +server_id +kubernetes_node +physical_host +observed +role +replication_role +durable_latched +durable_frontier_known +durable_frontier_lsn +candidate_ready +candidate_ready_reason +frontend_protocol +frontend_addr +status_addr +stale_primary_fenced +conditions[] +support_bundle_path +``` + +Important replica condition reasons: + +```text +primary +replica_ready +replica_degraded +status_endpoint_unreachable +authority_not_assigned +replication_role_not_ready +durable_frontier_missing +candidate_frontier_behind +stale_primary_fenced +generated_deployment_missing +observed_replicas_below_desired +loopback_frontend_rejected +``` + +### ClusterEvent + +Events are append-only evidence. They are not commands. + +Minimum fields: + +```text +event_id +event_time +volume_id +replica_id +node_name +type +severity +message +reason +old_value +new_value +epoch +endpoint_version +correlation_id +evidence_ref +``` + +Required event types for the first dashboard release: + +```text +volume_created +placement_verified +replica_heartbeat_seen +replica_stale +promotion_candidate_evaluated +authority_published +publish_target_changed +stale_primary_fenced +csi_reattach_observed +volume_recovered +volume_blocked +support_bundle_collected +pod_image_pull_failed +csi_node_unavailable +``` + +TestOps-only events such as `data_check_result` may be included when a recovery +gate runs, but normal production must not pretend it ran an application-level +checksum unless it actually did. + +## Tutorial: What A User Should See + +### Healthy Volume + +Command: + +```bash +sw-block ops describe volume pvc-123 +``` + +Output shape: + +```text +volume pvc-123 status=ok rf=3 ack=sync-quorum +pvc default/mysql-data +primary r1 on m01 frontend=192.168.1.181:3260 +replicas desired=3 observed=3 + +r1 m01 primary ready durable_lsn=44 +r2 m02 replica_ready ready durable_lsn=44 candidate_ready=true +r3 tp01 replica_ready ready durable_lsn=44 candidate_ready=true + +next action: none +support bundle: sw-block support bundle --volume pvc-123 --out /tmp/sw-block-pvc-123 +``` + +### Recovering After Primary Node Loss + +Output shape: + +```text +volume pvc-123 status=recovering reason=primary_node_lost +old primary r1 on m01 is unavailable +candidate r2 on m02 is promotion_ready +authority moved r1 -> r2 epoch=2 endpoint_version=1 +CSI publish target changed 192.168.1.181:3260 -> 192.168.1.184:3260 +reattach method: pod_recreate + +next action: wait for reader/app pod to become Ready +non-claim: transparent in-place I/O continuation is not claimed for this path +``` + +### Blocked Recovery + +Output shape: + +```text +volume pvc-123 status=blocked reason=no_promotion_ready_candidate +primary r1 on m01 is unavailable +r2 on m02 candidate_ready=false reason=durable_frontier_missing +r3 on tp01 candidate_ready=false reason=candidate_frontier_behind + +next action: + collect support bundle + do not force promote unless support confirms data frontier safety +``` + +## Dashboard Panels + +First dashboard should have only four panels: + +1. Volumes + + Shows PVC, status, RF, primary, frontend, and reason. + +2. Replicas + + Shows replica placement, role, durable frontier, candidate readiness, and + stale/fenced state. + +3. Timeline + + Shows the last N events for selected volume: placement, heartbeat loss, + candidate evaluation, authority publish, publish-target change, CSI + reattach, and recovery. + +4. Support Bundle + + One button or command copy block that captures exactly the evidence support + needs. + +5. Kubernetes Runtime Evidence + + Shows pod phase, container waiting reason, recent Kubernetes events, selected + pod logs, and image presence by node for Seaweed Block components. This panel + is mandatory for "PVC stuck attaching" cases because many failures are + Kubernetes runtime issues before storage recovery begins. + +Avoid advanced controls in the first dashboard. No promote, repair, rebuild, +or cleanup buttons until the read-only model is stable and gated. + +## Implementation Slices + +### D1: Observation Core And CLI From Bundle + +- Define `ClusterEvidence`, `VolumeEvidence`, `ReplicaEvidence`, and + `ClusterEvent` structs in ops/control code. +- Add renderers for text, JSON, and JSONL. +- Add golden examples for healthy, recovering, and blocked volumes. +- Add CLI commands that can read an existing inventory/support bundle first: + `sw-block ops describe volume --from-bundle `, + `sw-block ops timeline volume --from-bundle `, and + `sw-block ops explain volume --from-bundle `. + +Pass condition: + +```text +three golden examples render user-readable output with stable reason codes +``` + +### D2: Live CLI Over Current Inventory Sources + +- Wire `sw-block ops cluster`, `volumes`, `describe volume`, `timeline`, and + `explain` to the current live inventory collector. +- Keep text output short; write detailed evidence to JSON. + +Pass condition: + +```text +node-loss D4 artifacts can be explained by CLI without reading raw TestOps files +``` + +### D3: Master Snapshot API + +- Add `ClusterEvidenceService.GetClusterStatus`. +- Source data from lifecycle stores, placement stores, observation store, + authority publisher current lines, and known frontend facts. +- Keep it read-only. + +Pass condition: + +```text +one live RF3 volume appears with primary, replicas, frontend, epoch, and reason +``` + +### D4: Timeline API + +- Add an in-memory bounded event ring with optional persisted JSONL tail. +- Append events from product-loop transitions: + placement verified, candidate evaluated, authority published, publish target + changed, stale primary fenced. +- Add `GetVolumeTimeline`. + +Pass condition: + +```text +node-loss D4 produces the same six-event story from master API, not only from TestOps files +``` + +### D5: Watch API + +- Add `WatchClusterEvents` server stream. +- Dashboard can subscribe without polling. +- Events include monotonic IDs and reconnect cursor. + +Pass condition: + +```text +client disconnect/reconnect does not miss authority_published or volume_blocked events +``` + +### D6: User Tutorial And Support Bundle + +- Add `sw-block ops bundle volume`. +- Add docs showing how to diagnose healthy, recovering, and blocked. +- Keep all mutation commands explicitly non-existent. +- Include Kubernetes runtime evidence: + `kubectl get pods -A -o wide`, `kubectl describe pod` for Seaweed Block and + app pods, namespace events, CSI node/controller logs, blockmaster logs, and + per-node product image inventory. + +Pass condition: + +```text +a user can collect one bundle and identify the next action without reading TestOps artifacts +``` + +### D7: Attach/Install Failure Explanation + +- Detect `ImagePullBackOff`, `ErrImagePull`, CSI node unavailable, missing + DaemonSet pod on the selected app node, and missing product image on a k3s + node. +- Render the failure as an explanation, not just raw events. + +Pass condition: + +```text +if sw-block-csi:local is missing on one selected node, `sw-block ops explain` +names that node, image, pod, event reason, and next action +``` + +## Non-Claims + +- No mutating admin controls. +- No repair/promote/rebuild button. +- No performance metrics dashboard. +- No hosted UI. +- No external alert-manager integration. +- No claim that application-level data checks ran unless the user/TestOps ran + them. +- No replacement for Kubernetes events; this API explains Seaweed Block state. + +## Hard Gate + +The close gate for this MVP should fail if: + +- any read API can mutate state, +- a recovering/blocked state lacks a stable reason code, +- node-loss recovery evidence is available only in TestOps files and not via + master API, +- dashboard output requires users to know internal epoch semantics, +- support bundle misses the timeline or per-replica evidence, +- support bundle misses Kubernetes pod events/logs for attach/install failures, +- image missing on a selected node is not reported as a first-class reason, +- stale primary and promoted primary cannot be distinguished, +- event stream can lose `authority_published` across reconnect. + +## Product Rule + +This API is a trust feature. For block storage, a stuck PVC is a product +failure until the operator can quickly answer: + +```text +what failed, what the system did, whether data is safe, and what to do next +``` + +The observation API should make that answer obvious. diff --git a/seaweed-block/internal/docs/ref/engine-automata-design-note.md b/seaweed-block/internal/docs/ref/engine-automata-design-note.md new file mode 100644 index 0000000000..e3564025af --- /dev/null +++ b/seaweed-block/internal/docs/ref/engine-automata-design-note.md @@ -0,0 +1,268 @@ +# Engine Automata Design Note + +Status: draft design note after the RF3 sync-quorum recovery slice. + +## Why This Note Exists + +The RF3 recovery work exposed a design smell: + +```text +master promoted r2 -> CSI reattached to r2 -> ext4 mount still failed +``` + +The failure was not authority selection and not CSI. The missing semantic was a +post-promotion replication handoff: + +```text +new primary r2 must know which surviving peers already cover the required +frontier and seed live shipping from that frontier before accepting RW mount +writes under sync-quorum +``` + +The narrow fix was correct for the current slice: the promoted primary runs a +barrier against newly installed peers at its local frontier, seeds the live ship +cursor only for peers that prove coverage, and leaves unsafe peers degraded. The +RF3 gate then passed. + +But the architectural lesson is larger: "the engine" should not be treated as +one monolithic automaton. Block storage recovery is a composition of several +small automata with explicit contracts between them. + +## Product Principle + +Seaweed Block should not become a toy by making one green-path state machine +absorb every concern. + +The product needs small, cold, auditable automata: + +- each owns one semantic boundary, +- each emits durable or inspectable facts, +- each can fail closed with a reason, +- no automaton should infer another automaton's state from a convenient side + effect. + +## Proposed Automata + +### 1. Identity Automaton + +Owns: + +- volume ID, +- replica ID, +- epoch, +- endpoint version, +- current assignment line. + +It answers: + +```text +Who am I for this volume line? +Is this process still assigned to this identity? +Has my identity changed? +``` + +It must not decide: + +- whether the replica is caught up, +- whether a peer can be promoted, +- whether CSI should attach. + +### 2. Authority Automaton + +Owns: + +- primary selection, +- promotion/refusal decision, +- old-primary supersede/fencing intent, +- authority epoch movement. + +It answers: + +```text +Which replica is allowed to be primary? +Why was promotion allowed or refused? +What authority epoch is published? +``` + +It should consume promotion evidence, not manufacture data-plane truth. + +### 3. Durability / Frontier Automaton + +Owns: + +- local durable frontier, +- retained WAL frontier, +- head LSN, +- ACK profile interpretation: `best-effort`, `sync-quorum`, `sync-all`, +- required frontier for the current recovery claim. + +It answers: + +```text +What data has this replica durably covered? +What data has the product promised to preserve? +Does candidate durable_lsn cover required_lsn? +``` + +This is the automaton that prevents "largest LSN" from becoming an accidental +product promise. Largest LSN is a candidate ranking signal; required frontier is +the safety threshold. + +### 4. Recovery Automaton + +Owns: + +- catch-up vs rebuild decision, +- recovery session lifecycle, +- base/WAL transfer, +- recovery completion evidence. + +It answers: + +```text +Can this replica catch up from retained WAL? +Does it need rebuild? +Has the session completed through target LSN? +``` + +It should not by itself publish the replica as primary. Completion becomes +evidence for authority, not authority itself. + +### 5. Replication Handoff Automaton + +Owns: + +- primary-side peer runtime state, +- live ship cursor, +- post-promotion peer activation, +- quorum write admission after promotion. + +It answers: + +```text +Which peers are live enough to receive the next write? +At what LSN should live shipping resume? +Can sync-quorum/sync-all writes be acknowledged now? +``` + +This is the automaton that was implicit before the RF3 fix. The better contract +is: + +```text +PromotionCommitted(volume, new_primary, epoch, required_frontier, covered_peers) + -> for each covered peer: prove barrier >= required_frontier + -> seed live cursor at required_frontier + -> only seeded/healthy peers can satisfy quorum + -> unproven peers stay degraded and trigger recovery/rebuild +``` + +The current implementation derives this from local frontier + barrier proof. +That is acceptable as an S1 product unblocker. A later design should make the +handoff event explicit. + +### 6. Frontend Publish Automaton + +Owns: + +- iSCSI/NVMe frontend readiness, +- frontend endpoint, +- publish target generation, +- host-visible target identity. + +It answers: + +```text +What target should a host attach to now? +Is this target valid for the current authority line? +``` + +It should not decide promotion. It should reflect authority. + +### 7. Host Attach Automaton + +Owns: + +- CSI ControllerPublish lookup, +- NodeStage / NodePublish behavior, +- portal/device/session matching, +- pod recreate reattach path, +- future multipath path selection. + +It answers: + +```text +Which target did Kubernetes ask me to stage? +Which device/session did I stage? +Did the mounted app path recover? +``` + +Stage 1 uses CSI/pod recreate. Stage 2 should add protocol multipath: + +```text +iSCSI ALUA + dm-multipath +or +NVMe ANA + native multipath +``` + +## Message / Event Shape To Prefer + +Avoid adding broad fields to every heartbeat because it is easy to create a +control-plane database that is stale, noisy, and semantically ambiguous. + +Prefer narrow events/facts: + +```text +IdentityAssigned(volume, replica, epoch, endpoint_version) +DurableFrontierObserved(volume, replica, durable_lsn, retained_lsn, head_lsn) +PromotionEvaluated(volume, candidate, ack_profile, required_lsn, candidate_lsn, result, reason) +PromotionCommitted(volume, old_primary, new_primary, epoch, endpoint_version, required_lsn) +ReplicationHandoffProved(volume, primary, peer, required_lsn, achieved_lsn) +ReplicationHandoffRejected(volume, primary, peer, required_lsn, achieved_lsn_or_unknown, reason) +FrontendTargetPublished(volume, replica, endpoint, epoch, endpoint_version) +HostPathRecovered(volume, pvc, target, method, checksum_result) +``` + +The key is not the exact names. The key is that each fact names the automaton +boundary and the product reason. + +## Near-Term Guidance + +For the current Stage 1 plan: + +- Keep the narrow barrier-seeded handoff fix. +- Keep RF3 promotion gated by on-demand probe evidence. +- Keep CSI as a consumer of master-published target, not a promotion decider. +- Do not add a large heartbeat protocol expansion yet. +- Add support-bundle evidence for replication handoff when it becomes part of + the close gate. + +For the next design pass: + +- Make promotion handoff an explicit event, not an incidental side effect of + `UpdateReplicaSet`. +- Separate "current primary is healthy" from "candidate is promotable." +- Separate "replica process alive" from "replica durable frontier covers the + committed frontier." +- Separate "frontend target published" from "host path recovered." + +## Product Gate Implication + +Future gates should not pass on a single line like: + +```text +role=primary +``` + +They should require the automata chain: + +```text +candidate durable frontier covers required frontier +authority commits new primary +replication handoff proves at least one quorum peer is live +frontend target is published +CSI/node stages that target +mounted app verifies data +``` + +If any link is missing, the product should fail closed and name the missing +automaton boundary. diff --git a/seaweed-block/internal/docs/ref/mounted-failover-reattach-audit.md b/seaweed-block/internal/docs/ref/mounted-failover-reattach-audit.md new file mode 100644 index 0000000000..280e886dba --- /dev/null +++ b/seaweed-block/internal/docs/ref/mounted-failover-reattach-audit.md @@ -0,0 +1,221 @@ +# Mounted Failover And Reattach Audit + +Date: 2026-05-13 +Branch: `basic-mounted-failover-reattach` +Plan: `Basic Mounted Failover And Reattach MVP` + +## Question + +Can the current V3 product path support a user-visible RF=2 Kubernetes mounted +failover and reattach claim, or do we need to build new wiring before making +that claim? + +Short answer: the substrate exists, but the product-owned Kubernetes path is not +yet a mounted failover product claim. V2 and the earlier V3 protocol gates prove +important frontend and authority behaviors, but they do not wire the current +Kubernetes lifecycle path end to end. + +## Existing Green Substrate + +The following pieces are already present and should be reused rather than +rewritten: + +- iSCSI ALUA and mounted failover are covered by + `testops/scenarios/iscsi-p6-alua-failover-chain.yaml`. +- Returned-replica behavior after iSCSI failover is covered by + `testops/scenarios/iscsi-returned-replica-chain.yaml`. +- NVMe ANA and multipath failover are covered separately by the NVMe P4/P5 + protocol gates. +- RF=1 Kubernetes durable restart/reattach is covered by the durable restart + plan. +- Product-owned lifecycle can create generated `blockvolume` Deployments. +- Same-node iSCSI attach can run through CSI and a PVC. +- Cluster inventory can expose PVC/PV/replica/frontend/status/support-bundle + evidence. + +These are necessary but not sufficient for a Kubernetes mounted failover claim. + +## V2 Reference Value + +V2 is useful as a behavior reference, not a direct port target. + +Use V2 to compare: + +- iSCSI host behavior under ALUA and mounted failover, +- NVMe multipath/ANA behavior, +- broad protocol stress and compatibility cases, +- failure vocabulary and runbook expectations. + +Do not port V2 authority shortcuts into V3: + +- no heartbeat-as-authority, +- no heartbeat-as-ready, +- no promotion without durable/ready evidence, +- no target-LSN completion shortcuts, +- no bypass around the V3 publisher/epoch model. + +The V3 code already intentionally separates observation, supportability, +authority minting, frontend projection, and replication. That separation is the +right product direction. + +## Current V3 RF And Failover Wiring + +### Lifecycle And Launcher + +`core/lifecycle/planner.go` and `core/lifecycle/workload_plan.go` can represent +RF=2/RF=3 placement intent. The launcher can render one `blockvolume` +Deployment per replica, with distinct replica IDs and node-local ports. + +`core/launcher/k8s_renderer.go` renders: + +- one Deployment per replica, +- `--replica-id=`, +- `--durable-root=/var/lib/sw-block//`, +- `--recovery-mode=dual-lane` by default, +- optional loopback status endpoints, +- iSCSI or NVMe frontend args based on protocol. + +This means the deployment substrate can host multiple replicas. + +### Product Loop To Authority + +`core/host/master/product_loop.go` calls +`assignmentRequestsFromVerifiedPlacement`. + +`core/host/master/authority_request_bridge.go` currently selects only the first +verified slot: + +```text +RF>1 slots are placement/recovery inputs; they are not multiple competing Bind asks. +Pick the first verified slot deterministically until a later placement policy grows +an explicit primary-candidate field. +``` + +Impact: the product-owned Kubernetes lifecycle path can place RF=2 workloads, but +it does not yet publish an RF=2 failover candidate through the lifecycle bridge. +The authority controller can fail over when it receives a supported RF snapshot, +but the product loop currently treats additional lifecycle slots as inputs, not +as an active promotion policy. + +### Authority Controller + +`core/authority/controller.go` supports the failover decision model: + +- initial bind when no current authority exists, +- retain current primary when it remains acceptable, +- reassign to another acceptable replica when current primary is not acceptable, +- refuse to mint when no eligible candidate exists. + +Tests such as `g8_0_authority_failover_test.go` and +`g9a_reintegration_policy_test.go` pin the core safety rule: a returned or +observed replica is not enough; the candidate must be ready and eligible. + +This is the correct substrate for mounted failover, but the K8s product path +must feed it the right RF=2 supportability snapshot and then prove the app path. + +### Volume-Side Fencing + +`core/host/volume/subscribe.go` is volume-scoped: a volume process receives +authority lines for the whole volume, not just its own replica. + +When master publishes a new primary line for another replica, the old replica +records the supersede event. `core/host/volume/projection_bridge.go` uses that +event to fail closed: + +```text +Healthy = local engine healthy AND not superseded AND not supporting-replica-ready +``` + +Impact: stale-primary fencing has a concrete V3 mechanism. The mounted failover +gate should assert it through status/inventory artifacts, not only through logs. + +### Replication And ACK Profile + +`cmd/blockvolume/main.go` exposes: + +- `--replication-ack=best-effort` +- `--replication-ack=sync-quorum` +- `--replication-ack=sync-all` + +`core/frontend/durable/storage_adapter.go` defaults to +`WriteAckBestEffort`. In best-effort mode, local durable write success is enough +for foreground write success; observer fan-out errors are logged/degrade peers +but do not fail the write. + +`sync-quorum` and `sync-all` switch the durable write path to +`WriteAckRequireObserverAck`, and `core/replication/volume.go` evaluates the +replica acknowledgement profile. + +Impact: the mounted failover plan must choose and document the profile. A +best-effort run can prove the exact bytes that survived the injected failure, +but it cannot claim general quorum durability for all acknowledged writes. + +### CSI Attach And Reattach + +`core/csi/master_backend.go` reads `QueryVolumeStatus` and returns the current +assigned frontend target. It does not control authority, placement, or failover. +It also does not automatically restage an already-mounted workload after a +primary move. + +Impact: the MVP should define reattach as a documented restart/restage path +unless and until transparent in-place I/O continuation is proven. The app path +can be: + +```text +writer writes and syncs -> primary failure -> authority move or safe refusal +-> app pod is restarted/reattached -> reader verifies data +``` + +It should not claim zero-disruption I/O. + +### Inventory And Support Bundles + +`core/ops` already exposes volume/replica/status/support-bundle facts and issue +vocabulary. The recent inventory plans made missing placement, orphan workloads, +unreachable status endpoints, degraded replicas, and non-claims visible. + +The mounted failover plan needs additional timeline-oriented evidence: + +- before-failure primary replica and authority lineage, +- failure target, +- after-failure primary replica and authority lineage, +- stale/old primary state, +- reattach method, +- ACK profile, +- durable evidence for the bytes verified after reattach, +- explicit safe-refusal issue if promotion is not allowed. + +## Gap Summary + +| Area | State | Gap | +| --- | --- | --- | +| V2 protocol behavior | Strong reference | Not product-owned K8s wiring | +| V3 authority failover | Substrate exists | Need lifecycle/K8s feed and live proof | +| V3 stale-primary fencing | Mechanism exists | Need user-visible status/inventory proof | +| RF=2 K8s placement | Workload rendering exists | Product loop only binds first slot | +| CSI reattach | Current target lookup exists | No transparent restage claim | +| ACK profile | Flags exist | Plan must choose and gate exact claim | +| Inventory | Strong base | Needs failover timeline and safe-refusal wording | + +## Implementation Direction + +Do not start by porting V2. Start by composing the V3 pieces through the user +path: + +1. Add fast tests for the lifecycle-to-authority RF=2 seam, old-primary + supersede visibility, and inventory failover timeline wording. +2. Add a runner-native RF=2 iSCSI Kubernetes scenario that writes data through a + PVC, injects controlled primary failure, then either reattaches and verifies + data or refuses promotion safely with a specific support-bundle issue. +3. Keep ACK semantics explicit. Prefer a conservative best-effort MVP claim + unless the scenario runs with `--replication-ack=sync-quorum` and proves that + profile end to end. +4. Use V2 only for protocol expectations and host-side failover sanity. + +## Current Audit Verdict + +The current product is close enough to build the mounted failover MVP without an +architecture rewrite, but not close enough to claim it today. + +The first real code slice should focus on the product-owned RF=2 lifecycle +bridge and evidence contract, not on frontend protocol parity. diff --git a/seaweed-block/internal/docs/ref/mounted-failover-reattach-contract.md b/seaweed-block/internal/docs/ref/mounted-failover-reattach-contract.md new file mode 100644 index 0000000000..051103c9ac --- /dev/null +++ b/seaweed-block/internal/docs/ref/mounted-failover-reattach-contract.md @@ -0,0 +1,235 @@ +# Mounted Failover And Reattach Contract + +Date: 2026-05-13 +Plan: `Basic Mounted Failover And Reattach MVP` + +## User-Facing Claim Target + +For the documented alpha topology and ACK profile, a controlled primary +`blockvolume` failure is either: + +1. recovered through the Kubernetes PVC app path with data verified after + reattach, or +2. refused safely with a support bundle that explains why promotion is not + allowed. + +This is a beta availability exercise, not a production HA claim. + +## Supported MVP Topology + +Initial supported topology: + +- Kubernetes alpha path, +- iSCSI PVC, +- RF=2, +- product-owned `blockvolume` Deployments, +- durable hostPath per replica, +- loopback frontend constrained by same-node attach rules, +- one app workload writing data before failure and one app workload reading data + after reattach/restart. + +RF=3 is not part of this plan's live Kubernetes claim unless it falls out +naturally and is separately gated. NVMe remains protocol-gated but is not the +first Kubernetes mounted failover target. + +## ACK Profile + +The gate must record the exact ACK profile in both run artifacts and inventory: + +```text +ack_profile=best-effort | sync-quorum | sync-all +``` + +Default MVP profile is conservative: + +- If using `best-effort`, the claim is limited to bytes explicitly written, + flushed, and verified after the controlled failure. +- If using `sync-quorum`, the gate must run blockvolumes with + `--replication-ack=sync-quorum` and prove that writes fail closed when quorum + acknowledgement is unavailable. +- If using `sync-all`, the gate must prove both replicas acknowledge the writes + before claiming all-ack durability. + +No plan text or runbook may say "all acknowledged writes survive failover" +unless the gate runs a non-best-effort ACK profile and validates the failure +mode. + +## Failure Injection + +The primary failure is controlled and named: + +```text +failure_class=primary-blockvolume-controlled-stop +failed_replica= +failed_epoch= +failed_endpoint_version= +``` + +The preferred injection is deleting or scaling down the primary +`blockvolume` Deployment after the writer has completed and after the artifacts +record the pre-failure authority line. + +The failure must not be an unscoped process kill that could hide which resource +was targeted. + +## Expected Successful Recovery + +A successful recovery must show: + +- pre-failure data checksum written through the PVC, +- pre-failure primary replica and authority lineage, +- old primary no longer serving frontend I/O, +- new primary replica and authority lineage, +- epoch or endpoint-version advancement, +- app restart/reattach method, +- post-reattach checksum match, +- inventory support bundles for every visible replica. + +Minimum evidence lines: + +```text +failover_status: recovered +ack_profile: +old_primary: replica= epoch= endpoint_version= fenced=true +new_primary: replica= epoch= endpoint_version= frontend_ready=true +reattach: method=pod-restart|pod-recreate|node-restage +data_check: before= after= match=true +``` + +Transparent in-place I/O continuation is not claimed. Pod restart/recreate is a +valid MVP reattach method if it is documented and gated. + +## Expected Safe Refusal + +If the product cannot safely promote another replica, the gate must still PASS +only if the refusal is explicit and safe: + +```text +failover_status: refused +reason= +old_primary_safe=false|unknown +candidate_ready=false +data_check_after_failover=not_claimed +``` + +Valid refusal reasons include: + +- `insufficient_replica_coverage` +- `candidate_not_ready_for_primary` +- `durable_frontier_missing` +- `replication_ack_profile_unmet` +- `status_endpoint_unreachable` +- `stale_primary_not_fenced` + +Invalid refusal behavior: + +- silent timeout with no bundle, +- promoting a heartbeat-only replica, +- marking a returned replica healthy without durable/recovery evidence, +- keeping the old primary looking like a valid frontend writer after authority + moved. + +## Inventory And Support Bundle Requirements + +`sw-block ops inventory` or a scenario-produced companion bundle must expose a +failover timeline: + +```text +failover_timeline: + - phase: before_failure + primary: + epoch: + endpoint_version: + - phase: failure_injected + failed_replica: + failure_class: + - phase: after_failover + status: recovered|refused + primary: |none + epoch: |none + endpoint_version: |none +``` + +Per-replica status bundles must include: + +- authority role, +- frontend readiness, +- local healthy bit, +- durable latch/operational state, +- peer/replication state when available, +- reason wording when the rollup is degraded. + +The wording must distinguish: + +- "replica process is alive", +- "replica is eligible as primary", +- "replica is serving frontend I/O", +- "replica is degraded because a higher-level authority/durable condition is + missing." + +## Fast-Test Requirements + +Before the runner gate, fast tests should cover: + +- RF=2 lifecycle placement does not silently publish only stale authority when + another eligible slot exists. +- old-primary supersede state is visible and maps to a non-serving frontend + projection. +- failover inventory issue wording is non-contradictory. +- returned replica is not primary-eligible from heartbeat alone. +- missing durable frontier or unmet ACK profile causes safe refusal. + +## Runner Gate Requirements + +The runner-native gate must include: + +```text +pre_clean +preflight +pin/build alpha images +create RF=2 PVC +wait for two blockvolume replicas +write/check data before failure +capture before-failure inventory/status +inject controlled primary failure +observe authority move or safe refusal +restart/reattach app if recovery path is claimed +read/check data after reattach if recovered +capture after-failure inventory/status +collect_and_cleanup(always) +``` + +If the product cannot create a real RF=2 PVC path safely, the gate must say so +through the safe-refusal branch and the operations manual must keep live RF=2 +Kubernetes recovery as a non-claim. + +## Non-Claims + +This plan does not claim: + +- transparent zero-disruption I/O, +- production HA, +- arbitrary node loss, +- remote-node attach to loopback frontends, +- RF=3 live Kubernetes failover, +- NVMe Kubernetes failover, +- automatic rebuild completion, +- returned-replica reintegration as a broad product claim, +- performance SLOs, +- upgrade safety, +- backup/restore, +- UI/operator-grade remediation. + +## Close Rule + +The plan can close only when the runner gate proves either recovered or refused +safely, and QA can read the bundle without implementation context and answer: + +```text +which replica was primary before, +which resource failed, +whether authority moved, +whether the old primary was fenced, +whether data was verified after reattach, +or exactly why recovery was refused. +``` diff --git a/seaweed-block/internal/docs/ref/node-loss-lab-setup.md b/seaweed-block/internal/docs/ref/node-loss-lab-setup.md new file mode 100644 index 0000000000..874dd05b51 --- /dev/null +++ b/seaweed-block/internal/docs/ref/node-loss-lab-setup.md @@ -0,0 +1,130 @@ +# Node-Loss Lab Setup + +Status: support note for the active `Node-Loss Survival MVP` plan. + +The D3/D4 gates need three Kubernetes nodes. They do not strictly need three +physical machines for the MVP, but the bundle must disclose the physical-host +shape and must not claim full physical-host loss when Kubernetes nodes share a +machine. + +## Minimum MVP Lab + +Acceptable: + +```text +m02 control-plane +m01 worker +one additional worker VM or containerized worker on m01 or m02 +``` + +Required from `kubectl get nodes -o wide`: + +```text +3 Ready schedulable Kubernetes nodes +each with a non-loopback InternalIP +``` + +Current lab boundary: + +```text +m02 192.168.1.184 RoCE-capable host, used here through LAN TCP/iSCSI +m01 192.168.1.181 RoCE-capable host, used here through LAN TCP/iSCSI +tp01 192.168.1.188 non-RoCE host, used only through LAN TCP/iSCSI +``` + +Do not use `10.0.0.x` RDMA/RoCE addresses in this node-loss gate. The D3/D4 +claim is Kubernetes node-loss recovery over TCP/iSCSI on `192.168.1.x`, not +RoCE, NVMe/RDMA, or performance validation. + +Recommended node labels: + +```bash +kubectl label node sw-block.seaweedfs.com/physical-host=m02 --overwrite +kubectl label node sw-block.seaweedfs.com/physical-host=m01 --overwrite +kubectl label node sw-block.seaweedfs.com/physical-host= --overwrite +``` + +The D3 preflight uses this label first. If it is absent, it falls back to +`topology.kubernetes.io/zone`, then `kubernetes.io/hostname`, then node name. + +## Fast Readiness Check + +Run on the machine with kubeconfig access: + +```bash +cd /tmp/seaweed_block +bash scripts/preflight-node-loss-lab.sh \ + --min-k8s-nodes 3 \ + --env-out /tmp/node-loss.env \ + --placement-out /tmp/node-placement.before.txt \ + --topology-out /tmp/node-loss-nodes.txt +``` + +Pass means: + +```text +node_loss_lab_eligible=true +selected_node_count=3 +physical_domain_count= +physical_domain_shape=full-physical-host|shared-physical-host +kubernetes_node_loss_claimed=true +physical_host_loss_claimed=false +``` + +If this fails, do not ask QA to rerun D3. The full D3 scenario will fail closed +for the same reason. + +Failure is intentionally machine-readable. An ineligible but reachable lab exits +with code `3`, writes a negative placement artifact when `--placement-out` is +supplied, and does not write the env file: + +```text +node_loss_topology_eligible=false +node_loss_lab_eligible=false +reason=requires_3_ready_schedulable_nodes_with_non_loopback_internal_ip +found= +kubernetes_node_loss_claimed=false +physical_host_loss_claimed=false +``` + +Treat any non-zero exit from this preflight as a lab blocker, not a product +validation result. + +## Claim Boundary + +Three Kubernetes nodes on two physical machines proves only: + +```text +Kubernetes-node placement and recovery mechanics +``` + +It does not prove: + +```text +full physical-machine loss +``` + +Full physical-host-loss requires distinct physical fault domains for the failed +primary and surviving promotion candidates, and should be a later stricter gate. + +## Practical k3s Notes + +Typical shape: + +```text +m02: k3s server / control-plane +m01: k3s agent +extra worker: k3s agent in a VM or container with a routable InternalIP +``` + +The workers must be able to reach: + +```text +blockvolume iSCSI ports: 3260+ +blockvolume status ports: 23260+ +replication data/control ports: 19101+ +k3s API/control-plane ports required by the cluster +``` + +Avoid `127.0.0.1`, `localhost`, `0.0.0.0`, or unspecified addresses in the node +InternalIP used by the gate. diff --git a/seaweed-block/internal/docs/ref/node-loss-survival-mvp-spec.md b/seaweed-block/internal/docs/ref/node-loss-survival-mvp-spec.md new file mode 100644 index 0000000000..2aa233dbed --- /dev/null +++ b/seaweed-block/internal/docs/ref/node-loss-survival-mvp-spec.md @@ -0,0 +1,264 @@ +# Node-Loss Survival MVP Spec + +Status: D1 cold product spec for `current-plan.md` Node-Loss Survival MVP. + +## Product Question + +Can a Kubernetes user lose the node that hosts the active Seaweed Block primary +and still recover the same PVC data through a documented path, with evidence +that authority moved safely, stale paths were fenced, and the data check used a +surviving replica on another node? + +This is the next product step after Stage 2. Stage 2 proved transparent +failover when multiple logical replicas run on one Kubernetes node and the +primary blockvolume pod is stopped. Node-loss survival must prove the failure +mode users actually care about: + +```text +one Kubernetes node becomes unavailable +-> the old primary is unavailable +-> a surviving replica on another Kubernetes node becomes primary +-> the workload recovers through the declared mechanism +-> data verifies from the same PVC +``` + +## Product Contract Under Test + +First close targets the conservative recovery path: + +```text +protocol=iscsi +replication=RF3 +ack_profile=sync-quorum +topology=3 logical replicas on 3 Kubernetes nodes; physical-host/fault-domain +sharing must be disclosed +frontends=non-loopback, reachable from CSI nodes +failure=controlled primary Kubernetes node loss or equivalent node isolation +recovery=CSI/pod recreate reattach to surviving promoted frontend +data_check=reader verifies pre-failure bytes from the same PVC +``` + +The current lab proof uses LAN TCP/iSCSI addresses on `192.168.1.x`. It does +not use the `10.0.0.x` RoCE fabric; `tp01` is not RoCE-capable and must not be +used to support RDMA, NVMe/RDMA, or performance claims for this plan. + +Transparent multipath node-loss is a follow-up gate, not the first close gate, +unless the conservative path proves too little product value. The first close +may use pod recreate / CSI reattach, but it must be honest: + +```text +pod_recreate_used=true +transparent_failover_claimed=false +node_loss_recovery_claimed=true +``` + +## Non-Negotiable Semantics + +- Replicas must land on distinct Kubernetes nodes for the node-loss proof. +- Frontends must be reachable from the consuming CSI node; loopback frontends + are not valid for cross-node attach. +- The failed primary must be derived from live inventory, not hard-coded. +- Master controls authority. CSI consumes the published target after recovery; + CSI does not choose or promote a primary. +- Promotion must require sync-quorum frontier coverage, using the Stage 1 RF3 + promotion gate semantics. +- The old primary must not be treated as a valid writer after node loss. +- If candidate readiness cannot be proven, the product must fail closed with a + support bundle and must not create a false reader-checksum success. +- Every attach, promotion, reattach, and cleanup wait must be bounded with a + stable blocker reason. + +## Explicit Non-Claims + +- No transparent mounted I/O continuation in the first node-loss close. +- No NVMe ANA node-loss claim. +- No Windows MPIO claim. +- No broad multi-distro compatibility claim. +- No RTO/RPO/SLO claim beyond the bounded gate timings. +- No automatic rebuild, reintegration, or failback claim. +- No arbitrary multi-failure or network-partition tolerance unless a later gate + explicitly proves it. +- No production HA claim outside the documented lab topology. +- No full physical-host-loss claim when multiple Kubernetes nodes share one + physical machine; that is an intermediate Kubernetes-node-loss lab only. + +## Required Evidence + +Minimum artifacts: + +```text +cluster-topology.txt +node-placement.before.txt +writer.log +inventory.before/ +primary-failure-recovery.txt +inventory.after-failure/ +csi-publish-before.txt +csi-publish-after.txt +reader.log +node-loss-recovery-boundary.txt +node-loss-recovery-summary.txt +bounded-waits.txt +cleanup-audit.txt +``` + +Required stable lines: + +```text +replicas_on_distinct_nodes=true +frontends_non_loopback=true +before_primary_replica= +before_primary_node= +failed_node= +failed_replica= +promoted_replica= +promoted_replica_node= +post_failure_primary_count=1 +pod_recreate_used=true +transparent_failover_claimed=false +node_loss_recovery_claimed=true +data_check_after_node_loss=reader_checksum_passed +old_primary_stale_io_success_count=0 +bounded_waits=pass +physical_host_loss_claimed=false +``` + +## D-Slice Plan + +### D1: Topology And Placement Audit + +Audit current code and lab reality: + +- whether TestOps has at least two Kubernetes nodes available, +- how `blockmaster` cluster-spec names physical nodes and server IDs, +- whether launcher can place replicas on distinct Kubernetes nodes, +- whether generated frontends can use non-loopback addresses, +- whether CSI publish lookup can select a target reachable from the consuming + node, +- whether inventory can prove node placement and non-loopback frontends. + +Exit: written audit section in `current-plan.md` and any required spec updates. + +D1 audit result: + +- The current local Kubernetes context is single-node and is not eligible for + the node-loss live gate. +- The alpha installer currently renders all logical servers onto one + Kubernetes node and uses loopback data/control addresses. +- The lifecycle planner has a base for multi-physical-node placement, but the + Kubernetes renderer still emits loopback iSCSI/NVMe/status frontends. +- `blockvolume` intentionally rejects external iSCSI/NVMe binds today. +- CSI receives a Kubernetes node ID but publish lookup does not yet use it to + validate target reachability. +- Master promotion evidence also needs routable status/probe access to + surviving replicas; loopback status endpoints are not enough for true + node-loss recovery. + +Therefore D3 must first make cross-node placement and target eligibility real. +Recovery code is out of scope until that gate passes. + +### D2: Strict QA Hard Gate + +Create `qa-assignments/node-loss-survival-mvp-close-hard-gate.md`. + +The gate must fail if: + +- all replicas are on one physical node, +- frontends are loopback, +- the proof uses only a pod stop instead of node failure/isolation, +- reader succeeds only because it still used the old primary, +- recovery happens without visible authority movement, +- cleanup leaves sessions/processes/k8s resources/run-scoped host paths. + +### D3: Placement / Non-Loopback Slice + +Make the product produce and inventory: + +```text +RF3 placements across distinct nodes +non-loopback replication data/control addresses +non-loopback iSCSI frontends +promotion/status probe access to surviving nodes +node-aware publish target evidence +``` + +This slice does not need to inject node loss yet. It proves the topology is +eligible. + +Three Kubernetes nodes may run on two physical machines for the MVP lab if the +bundle records the physical/fault-domain shape. The wording must remain +Kubernetes-node-loss, not full physical-host-loss, unless the artifacts prove +three distinct physical fault domains. + +The first implementation should preserve the existing safe default: + +```text +external iSCSI bind = explicit opt-in +external iSCSI bind without CHAP = rejected for node-loss gate +loopback/unspecified node-spec host in external mode = rejected before render +CSI NodeStage secret delivery = required when target CHAP is enabled +CSI loopback publish targets = rejected under node-loss profile +external status bind = explicit opt-in and concrete node address only +master promotion probes = use surviving replica node-address status endpoints +master status frontends = current primary first, with all assigned replica +frontends preserved for multipath evidence +NVMe external bind = not claimed +loopback frontend in node-loss profile = hard fail +``` + +### D4: Conservative Node-Loss Recovery Gate + +Runner-native scenario: + +```text +writer writes /data/demo.bin +inventory identifies primary replica and primary node +controlled failure isolates or drains/stops that node path +master promotes a surviving replica +replacement pod reattaches through CSI to surviving frontend +reader verifies /data/demo.bin +bundle records node_loss_recovery_claimed=true and transparent_failover_claimed=false +cleanup proves no residue +``` + +Implemented scenario name: + +```text +testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml +``` + +The scenario derives the primary node from inventory, cordons that Kubernetes +node, scales the primary blockvolume Deployment to zero, and schedules the +replacement reader on the survivor node selected by +`scripts/preflight-node-loss-lab.sh`. This is intentionally not a +physical-host-loss proof unless the placement artifacts show distinct physical +fault domains. + +### D5: Transparent Multipath Node-Loss Gate + +Only after D4 passes, decide whether to extend the plan or open the next plan +for: + +```text +same mounted pod +primary node loss +host multipath path switch to another node +no pod recreate +post-failure data check +``` + +This requires real multi-node pathing and should not be mixed into D4 unless the +lab/product path is already stable. + +## Success Statement + +After this plan, Seaweed Block can make a narrow beta-facing availability +statement: + +```text +For the documented RF3 sync-quorum Kubernetes topology with non-loopback +frontends, Seaweed Block can recover a PVC after controlled primary-node loss +through CSI/pod recreate reattach, and the support bundle proves authority +movement, surviving-node target selection, stale-primary fencing, and data +integrity. +``` diff --git a/seaweed-block/internal/docs/ref/phase20-d2d3-first-volume-user-loop-spec.md b/seaweed-block/internal/docs/ref/phase20-d2d3-first-volume-user-loop-spec.md new file mode 100644 index 0000000000..8f7f567c0b --- /dev/null +++ b/seaweed-block/internal/docs/ref/phase20-d2d3-first-volume-user-loop-spec.md @@ -0,0 +1,150 @@ +# Phase 20 D2/D3 Ref: First Volume User Loop (Before Helm) + +Status: proposed reference for next implementation slice. + +## Why This Slice + +Phase 20 D1 is now green for activation. The next product gap is not Helm yet; +it is the first user volume loop after install: + +```text +install +-> create PVC +-> wait ready +-> writer/reader verify +-> status evidence +-> cleanup +``` + +If this loop is not stable and self-explaining, Helm only moves the failure +surface and hides root causes behind packaging. + +## Product Question + +Can a Kubernetes user, using published immutable images, complete one first +volume loop and produce a compact evidence summary without internal help? + +## Scope + +This D2/D3 slice should ship: + +1. A runner-native first-volume scenario on published immutable images. +2. `examples/kubernetes/basic-app/` as canonical user volume flow. +3. Explicit status evidence capture after PVC creation: + - `kubectl get pvc` + - `kubectl get deploy -A -l app=sw-blockvolume` + - `sw-block ops cluster -o json` + - `sw-block ops inventory --out ...` +4. A compact `first-volume-summary.txt` in artifacts with: + - `pvc=` + - `volume_id=` + - `writer_verified=true|false` + - `reader_verified=true|false` + - `cluster_evidence=status/cluster-evidence.json` + - `inventory_bundle=status/inventory` + - `cleanup_status=ok|failed` +5. QA run on immutable GHCR tags. +6. Multi-node activation must avoid loopback publish targets by default: + activation auto-selects a Ready node InternalIP, enables external + iSCSI/status with CHAP, and renders node-stage secret references into the + StorageClass used by the first-volume example. + +## Out Of Scope + +- Helm chart packaging. +- New HA semantics. +- Mutating admin workflows. +- Backup/snapshot/restore. +- Performance/SLO claims. + +## Canonical Commands + +Install (published immutable): + +```bash +SW_BLOCK_ACTIVATION_IMAGE_MODE=published \ +SW_BLOCK_IMAGE=ghcr.io/seaweedfs/seaweed-block:sha- \ +SW_BLOCK_CSI_IMAGE=ghcr.io/seaweedfs/seaweed-block-csi:sha- \ +bash scripts/activate-k8s-alpha.sh "$PWD" +``` + +Create first volume: + +```bash +kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml +kubectl apply -f examples/kubernetes/basic-app/writer-pod.yaml +kubectl apply -f examples/kubernetes/basic-app/reader-pod.yaml +``` + +Status evidence: + +```bash +kubectl get pvc +kubectl get deploy -A -l app=sw-blockvolume +sw-block ops cluster --master-api 127.0.0.1:9333 -o json +sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out /tmp/sw-block-inventory +``` + +The helper script prefers `$SW_BLOCK_CLI` or an installed `sw-block` binary and +falls back to `go run ./cmd/sw-block` only for source-tree dev use. +It cleans the example pod/PVC/StorageClass resources by default; set +`SW_BLOCK_BASIC_APP_CLEANUP=0` only when intentionally preserving them for +manual inspection. + +Cleanup: + +```bash +kubectl delete pod sw-block-example-reader --ignore-not-found=true +kubectl delete pod sw-block-example-writer --ignore-not-found=true +kubectl delete pvc sw-block-example-pvc --ignore-not-found=true +kubectl delete storageclass sw-block-example --ignore-not-found=true +bash scripts/uninstall-k8s-alpha.sh "$PWD" +``` + +## Evidence Contract + +Required artifact shape: + +```text +activation/ + activation-summary.txt +first-volume/ + writer.log + reader.log + kubectl-get-pvc.txt + kubectl-get-blockvolume-deploy.txt + cluster-evidence.json + inventory/ + first-volume-summary.txt +cleanup/ + uninstall.log + delete-storageclass.log +``` + +`first-volume-summary.txt` is the PM-facing verdict file for this slice. If +status evidence cannot be collected, it must say `first_volume_status=failed` +and `failed_phase=status_evidence` instead of silently passing. + +## QA Matrix + +Minimum matrix for this slice: + +1. `published + immutable sha` (required close path). +2. `published + :alpha` (non-blocking drift smoke). +3. `local` mode remains dev regression path, not PM release attestation. + +## Close Gate + +D2/D3 closes when all are true: + +1. Immutable published path passes end-to-end. +2. Writer and reader checksum both pass. +3. Status evidence files exist and are readable. +4. `first-volume-summary.txt` exists and is self-contained. +5. Cleanup leaves no active iSCSI sessions and no product residue. + +## Suggested Claim After Close + +Seaweed Block supports a documented first-volume Kubernetes loop on published +immutable images: install, create PVC-backed volume, verify app write/read, +capture status evidence, and clean teardown with supportable artifacts. diff --git a/seaweed-block/internal/docs/ref/product-positioning-v1.md b/seaweed-block/internal/docs/ref/product-positioning-v1.md new file mode 100644 index 0000000000..f12b63680b --- /dev/null +++ b/seaweed-block/internal/docs/ref/product-positioning-v1.md @@ -0,0 +1,541 @@ +# Seaweed Block Product Positioning v1 + +Status: draft, proposed for internal alignment. This document is the source of +truth a product agent should read before talking about Seaweed Block, and the +first place a new user should land before running it. + +It has three layers: + +1. Positioning — the product story. +2. What's delivered — the validated claim surface as of the latest closed plan. +3. How a new user runs it — including specifics for the M01/M02 lab. + +--- + +## 1) Positioning First, Matrix Second + +Primary rule: + +- Positioning is the product story. +- Claim matrix is the fact layer behind the story. + +Do not lead with a giant capability table in user-facing surfaces. +Lead with the product promise, then back it with evidence links. + +--- + +## 2) One-Line Positioning + +English: + +`Seaweed Block is a lightweight Kubernetes block storage product with enterprise protocol discipline and fail-closed recovery semantics.` + +Chinese: + +`Seaweed Block 是一个面向 Kubernetes 的轻量块存储产品,强调企业级协议纪律与可解释的 fail-closed 故障语义。` + +--- + +## 3) Core Value Propositions (Public) + +### A. Lightweight Kubernetes Experience + +- Fast first-volume path: one preflight, one install, one PVC, writer + reader pods verify checksum. +- Product-owned lifecycle: no manual side-quest scripts on the happy path. +- Read-only cluster inventory with line-level cleanup attribution. + +### B. Protocol Discipline + +- Product behavior is constrained by CSI / iSCSI / NVMe contracts. +- Linux OS-initiator and Windows-initiator compatibility validated against the same target binary (Linux green; Windows substantively PASS). +- ALUA / multipath / CHAP / online resize / Prometheus metrics covered by closed plans. + +### C. Fail-Closed Recovery Semantics + +- On controlled failure, the product either: + - recovers through the documented path with evidence, or + - refuses unsafe promotion and explains why. +- The safe-refusal contract carries `failover_status: refused`, `data_check_after_failover=not_claimed`, and an `after_issue_evidence` line tied to live inventory — no hidden "green" based on weak semantics. +- For Kubernetes HA, the minimum product line is not "master changed primary." + The minimum is app-path recovery: automatic promotion plus documented + CSI/node reattach on pod recreate with post-failure checksum evidence. A + later transparent-failover line must prove protocol multipath: iSCSI + ALUA/dm-multipath or NVMe ANA/native multipath. + +--- + +## 4) Target Users (ICP v1) + +1. Platform teams running stateful workloads on Kubernetes, who want less + operational weight than large storage stacks. +2. Edge/private-cluster operators needing explainable failure behavior rather + than opaque automation. +3. Engineering teams that care about protocol-correct host behavior and + supportable incident evidence. + +--- + +## 5) What We Are Not Positioning As (For Now) + +- Not a broad production HA platform claim. +- Not a full replacement pitch against large enterprise storage suites. +- Not a UI-first story. + +Current direction is: + +`small footprint + strict semantics + evidence-first operations` + +--- + +## 6) What's Delivered (Validated Claim Surface) + +Each row below is backed by a closed plan in +`internal/docs/finished-plans/` and a QA close report in +`internal/docs/qa-assignments/`. Run IDs on the M02 lab are recorded +in the corresponding close reports. + +### 6.1 Light-Use Operations Loop (phases 9–11) + +| Capability | Status | +|---|---| +| Install alpha stack with one command | claimed | +| Create one PVC, write/read through a pod, replace pod, read back | claimed | +| `sw-block ops status` produces a self-describing per-volume bundle | claimed | +| `sw-block ops inventory` discovers volumes/PVCs/endpoints from the cluster | claimed | +| Inventory: PVC ↔ volume ↔ replica mapping, line-level cleanup attribution | claimed | +| TestOps coordinates shared-lab runs with active/history/lock records | claimed | + +Closed plans: `phase9_finishedplan_light_use_operations_mvp.md`, +`phase10_finishedplan_light_use_install_lifecycle_operations_mvp.md`, +`phase11_finishedplan_cluster_ops_inventory_lifecycle_visibility_mvp.md`. + +### 6.2 Product-Owned Lifecycle (phase 12) + +| Capability | Status | +|---|---| +| Generated `blockvolume` Deployment created by the product when a PVC is added | claimed | +| Scoped delete: deleting one PVC leaves the other PVC's workload intact | claimed | +| `lifecycle_owner=pvc-owner-ref` + `owner_ref=PersistentVolumeClaim//` in inventory | claimed | +| `scripts/apply-k8s-alpha-blockvolumes.sh` side-quest removed from the default path | claimed | + +Closed plan: `phase12_finishedplan_product_owned_blockvolume_lifecycle_mvp.md`. + +### 6.3 Durable Volume Restart And Reattach (phase 13) + +| Capability | Status | +|---|---| +| Generated RF=1 `blockvolume` survives its own workload restart with data still readable through the PVC | claimed (when `SW_BLOCK_LAUNCHER_STATE_HOSTPATH` is configured) | +| Restart durability proof: writer checksum before restart, reader checksum on a replacement pod after restart | claimed | +| Durable status `Latched=true Operational=true` exposed in `sw-block ops status` bundle | claimed | +| Failure-bundle path: bad hostPath emits `inventory_status: unhealthy` with actionable issues | claimed | + +Closed plan: `phase13_finishedplan_durable_volume_restart_reattach_mvp.md`. + +### 6.4 Multi-Node Attach And Placement (phase 14) + +| Capability | Status | +|---|---| +| Same-node RF=1 attach on a multi-node-capable cluster: app pods + generated `blockvolume` pinned to the same selected Kubernetes node | claimed | +| Negative fixture: cross-node loopback attach refused with explicit exit 45 + `unsupported-cross-node-loopback-attach.txt` | claimed | +| Inventory exposes `node=` per replica so operators see the alignment | claimed | + +Closed plan: `phase14_finishedplan_multi_node_attach_and_placement_mvp.md`. + +### 6.5 Basic Mounted Failover And Reattach (phase 15) + +| Capability | Status | +|---|---| +| Two-logical-server dev/TestOps topology: one Kubernetes node can host two distinct Seaweed Block server identities | claimed | +| RF=2 PVC binds, two generated `blockvolume` Deployments become Ready, distinct frontend/status ports | claimed | +| RF=2 mounted app path: writer + reader checksums pass through the same PVC | claimed | +| Default single-logical-server RF=2 is safely refused (not partially placed) | claimed | +| Controlled primary failure produces a safe-refusal bundle when the peer is not promotion-ready | claimed | +| Inventory dual-primary safety: `conflicting_primary_replicas=...` issue surfaces when authority is contradictory | claimed | + +Closed plan: `phase15_finishedplan_basic_mounted_failover_and_reattach_mvp.md`. + +Delivered Phase 15 safe-refusal contract (the exact strings): + +```text +failover_status: refused +ack_profile: best-effort +failure_class=primary-blockvolume-controlled-stop +before_primary_replica= +failed_replica= ← derived from live inventory, equals before_primary_replica +candidate_ready=false +candidate_evidence= +data_check_after_failover=not_claimed +reason=candidate_not_ready_for_primary +target_ready_replicas=0 +after_issue_evidence= +``` + +### 6.6 Stage 1 Mounted Recovery ACK Profile (phase 16) + +| Capability | Status | +|---|---| +| RF=2 `best-effort` controlled recovery demo through CSI/pod recreate | claimed as demo only | +| RF=3 `sync-quorum` mounted recovery through CSI/pod recreate | claimed as Stage 1 beta recovery target | +| Master promotion gated by promotion evidence and durable frontier coverage | claimed | +| CSI/node re-stage on pod recreate moves the mounted app to the promoted frontend | claimed | +| Post-failure reader checksum proves recovered app-path data | claimed | +| Transparent in-place I/O continuation without pod recreate | not claimed | + +Closed plan: +`phase16_finishedplan_stage1_mounted_recovery_ack_profile_mvp.md`. + +Delivered Stage 1 RF=3 recovery marker: + +```text +ack_profile: sync-quorum +claim_profile=beta-recovery +failover_status: promotion_pending -> promoted +before_primary_replica=r1 +failed_replica=r1 +promoted_replica=r2 +frontier_covered=true +post_failure_primary_count=1 +data_check_after_failover: pending_reader -> reader_checksum_passed +reader_verified=true +``` + +Interpretation: this is Kubernetes mounted recovery through CSI/pod recreate. +It is not transparent protocol multipath failover. + +### 6.7 Protocol Substrate (carried forward from earlier phases) + +| Capability | Status | +|---|---| +| iSCSI target + ALUA implicit + multipath compatibility | closed at phases 1–6 | +| iSCSI OS-initiator compatibility (Linux green, Windows substantively PASS) | closed at phase 6 | +| Snapshots (CoW), CHAP auth, online resize | closed at phase 5 | +| Prometheus metrics | closed at phase 5 | +| Fault/consistency tests on m01/M02 lab | closed at phases 2–5 | + +--- + +## 7) Non-Claims (Authoritative List) + +The product does NOT claim, as of phase 16 close: + +- transparent production HA without pod recreate, +- node loss or host-disk failure survival, +- remote-node attach to a loopback-published `blockvolume`, +- automatic multi-node scheduling, rescheduling, or rebalancing, +- RF=2 quorum HA after primary failure, +- transparent in-place I/O continuation, +- Kubernetes CSI multipath host-path failover, +- sync-all durability, +- backup, restore, rebuild, promote, repair, or other mutating admin commands, +- broad uninstall safety / upgrade safety, +- performance SLOs, +- UI or operator-grade reconciliation. + +If a new claim is added in a future plan, both `docs/operations-v1.md` +"Scope And Non-Claims" and this document MUST be updated in the same change. + +--- + +## 8) How A New User Runs It + +This section gives the canonical install + first-volume path. It mirrors +`docs/quickstart-kubernetes.md` ("First Volume In 10 Minutes" section). Run +each step in order on a single-node Kubernetes cluster. + +### 8.1 Prerequisites + +- A Linux Kubernetes node where privileged CSI pods are allowed and + `iscsi_tcp` is loadable. k3s works. +- `open-iscsi` (`iscsiadm`) installed on the node. +- Docker + the ability to `k3s ctr images import` (or a registry your cluster can pull). +- `kubectl` configured against the cluster. + +### 8.2 Default Install / First Volume + +```bash +export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}" + +# Preflight (emits structured PASS/FAIL per check): +bash scripts/preflight-k8s-alpha.sh --local-k3s + +# Build alpha images locally and import them into k3s containerd: +SW_BLOCK_IMPORT_K3S=1 \ +SW_BLOCK_ARTIFACT_DIR=/tmp/sw-block-alpha-build \ + bash scripts/build-alpha-images.sh "$PWD" + +# Run the first-volume demo end to end: +bash scripts/run-k8s-demo.sh "$PWD" +``` + +Expected final line: + +```text +[app-demo] PASS: app pod wrote data, replacement app pod read it back through the same PVC, cleanup complete +``` + +### 8.3 Inspect The Cluster + +Operate the cluster after install: + +```bash +# Port-forward blockmaster for the inventory command: +kubectl -n kube-system port-forward svc/blockmaster 9333:9333 +``` + +In another terminal: + +```bash +sw-block ops inventory \ + --namespace default \ + --master 127.0.0.1:9333 \ + --out /tmp/sw-block-inventory + +cat /tmp/sw-block-inventory/volume-inventory-summary.txt +``` + +A healthy one-volume shape looks like: + +```text +inventory_status: ok +volumes: total=1 ok=1 unhealthy=0 invalid=0 +volume: id=pvc-... pvc=sw-block-demo-pvc rf=1 desired=1 observed=1 primary=r1 status=ok protocols=iscsi +replica: ... server= node= frontend=127.0.0.1:3260 status_addr=127.0.0.1:23260 support_bundle=volumes/pvc-.../r1 +``` + +For an RF=2 development/TestOps topology, set +`SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2` on +the installer. See `docs/operations-v1.md` §"RF=2 Mounted Failover Status". + +### 8.4 Durable Restart Path + +```bash +RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)" +export SW_BLOCK_LAUNCHER_STATE_HOSTPATH="/var/lib/sw-block/testops-${RUN_ID}-restart" +bash scripts/run-k8s-blockvolume-restart.sh "$PWD" +``` + +This proves a generated RF=1 `blockvolume` can be restarted while the same PVC +remains usable. See `docs/operations-v1.md` §5. + +### 8.5 If Something Fails + +```bash +ARTIFACT_DIR="$(ls -td /tmp/sw-block-app-demo-* | head -1)" +cat "$ARTIFACT_DIR/run.log" + +VOLUME_ID="$(sed -n 's/.*--volume-id=\([^"[:space:]]*\).*/\1/p' "$ARTIFACT_DIR/generated-blockvolume.yaml" | head -1)" +STATUS_ADDR="$(sed -n 's/.*--status-addr=\([^"[:space:]]*\).*/\1/p' "$ARTIFACT_DIR/generated-blockvolume.yaml" | head -1)" + +if [ -n "$VOLUME_ID" ] && [ -n "$STATUS_ADDR" ]; then + sw-block ops status \ + --volume "$VOLUME_ID" \ + --master "127.0.0.1:9333" \ + --status-addr "$STATUS_ADDR" \ + --out "$ARTIFACT_DIR/ops-status" +else + echo "ops-status-unavailable: no volume id/status address reached" +fi +``` + +Attach the whole artifact directory to any issue report. + +### 8.6 Cleanup + +The demo cleans up automatically. For a full alpha stack uninstall: + +```bash +bash scripts/uninstall-k8s-alpha.sh "$PWD" +``` + +For user-facing scoped cleanup of just the demo PVC, see +`docs/quickstart-kubernetes.md` "Cleanup" section. Do NOT use global +`kubectl delete deploy -A -l app=sw-blockvolume` — that's a TestOps +guardrail, not user-facing cleanup. + +--- + +## 9) Running On The M01 / M02 Lab + +The internal M01/M02 lab is the canonical hardware substrate for QA and demos. +Seaweed Block's alpha all runs on M02 (single-node k3s). M01 is currently used +by the SRA/RDMA project, not as a Kubernetes node for seaweed_block. + +### 9.1 Lab Coordinates + +| Item | Value | +|---|---| +| M02 (k3s alpha lab) | `192.168.1.184`, user `testdev` | +| SSH key (controller-side) | `C:/work/dev_server/testdev_key` | +| Shared SMB share | `V:/share` on Windows = `/mnt/smb/work/share` on Linux | +| TestOps artifact root on M02 | `/mnt/smb/work/share/g15d-k8s/-/` | +| Default `KUBECONFIG` on M02 | `/etc/rancher/k3s/k3s.yaml` | +| TestOps control directory (when used) | `--control-dir` flag to `sw-testops` | + +### 9.2 Connecting To M02 + +From a Windows controller (Git Bash / PowerShell): + +```bash +ssh -i C:/work/dev_server/testdev_key testdev@192.168.1.184 +``` + +If you need to forward an interactive `iscsiadm` session or expose +blockmaster's gRPC to a Windows tool, use SSH local forwarding: + +```bash +ssh -i C:/work/dev_server/testdev_key -N -L 9333:127.0.0.1:9333 testdev@192.168.1.184 +``` + +(For Windows iSCSI Initiator validation specifically, see +`internal/docs/qa-assignments/iscsi-os-windows-initiator-validation.md`.) + +### 9.3 Staging The Source Tree On M02 + +The product working tree is shared with the dev agent at +`C:/work/seaweed_block`. To run on M02, ship the working tree to +`/tmp/seaweed_block` and proceed: + +```bash +# From Windows controller (Git Bash): +ssh -i C:/work/dev_server/testdev_key testdev@192.168.1.184 \ + 'rm -rf /tmp/seaweed_block && mkdir -p /tmp/seaweed_block' + +cd C:/work/seaweed_block +tar --exclude=.git --exclude='*.exe' --exclude=node_modules \ + --exclude=results --exclude=.cache --exclude=tmp -cf - . \ + | ssh -i C:/work/dev_server/testdev_key testdev@192.168.1.184 \ + 'cd /tmp/seaweed_block && tar -xf -' +``` + +On M02, the same `scripts/preflight-k8s-alpha.sh --local-k3s` + the canonical +quickstart commands apply (§8.2 above), with `KUBECONFIG=/etc/rancher/k3s/k3s.yaml`. + +### 9.4 Running A QA Scenario Against M02 From The Controller + +The `swblock` runner can drive scenarios on M02 over SSH: + +```powershell +swblock run ` + --results-dir V:/share/g15d-k8s/testops-runs/ ` + --env product_root=/tmp/seaweed_block ` + --env ssh_key=C:/work/dev_server/testdev_key ` + C:/work/seaweed_block/testops/scenarios/.yaml +``` + +Scenario artifacts land under both: + +- The Windows result bundle at `V:/share/g15d-k8s/testops-runs/...`, +- The M02-side artifact dir at `/mnt/smb/work/share/g15d-k8s/-*/`. + +### 9.5 Lab Hygiene After A Run + +The chains' `collect_and_cleanup` phases handle scoped cleanup. To audit +manually after a run: + +```bash +ssh -i C:/work/dev_server/testdev_key testdev@192.168.1.184 ' + sudo -n iscsiadm -m session 2>&1 | head -1 + pgrep -af "blockmaster|blockvolume|blockcsi|iscsi-target" 2>/dev/null | head + pgrep -af "kubectl.*port-forward.*svc/blockmaster" 2>/dev/null | head + KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get deploy -A -l app=sw-blockvolume + sudo -n ls -d /var/lib/sw-block/testops-* 2>/dev/null' +``` + +Expected after a clean run: no active iSCSI sessions, no sw-block processes, +no port-forwards, no `app=sw-blockvolume` Deployments, no run-scoped +`testops-*` paths. + +Older `/var/lib/sw-block/pvc-*` directories from prior demos exist and are +out of scope for the testops cleanup guarantee — they are documented as a +non-claim (see `docs/operations-v1.md` "Upgrade and broad uninstall safety +are not claimed"). + +--- + +## 10) Where To Find Evidence + +For each delivered claim: + +| Source | What it gives you | +|---|---| +| `internal/docs/finished-plans/phase_finishedplan_*.md` | The plan that closed the claim | +| `internal/docs/qa-assignments/*-close-report.md` | QA close report with HG-clause table, residue audit, run IDs | +| `internal/docs/qa-assignments/*-validation.md` | QA assignments (input to a close report) | +| `testops/scenarios/*.yaml` | Runner-native scenarios that validate the claim live | +| `docs/operations-v1.md` | User-facing operations manual; tracks the same claim/non-claim discipline | +| `docs/quickstart-kubernetes.md` | First-volume runbook for a new user | + +Recent close reports a product agent should be ready to cite: + +- `light-use-mvp-close-report.md` (phase 10) +- `cluster-ops-inventory-mvp-close-report.md` (phase 11) +- `product-owned-blockvolume-lifecycle-mvp-close-report.md` (phase 12) +- `durable-volume-restart-reattach-mvp-close-report.md` (phase 13) +- `multi-node-attach-placement-mvp-close-report.md` (phase 14) +- `mounted-failover-reattach-mvp-close-report.md` (phase 15) +- `stage1-mounted-recovery-ack-profile-mvp-close-report.md` (phase 16) + +--- + +## 11) Public Messaging Template + +### Short Paragraph (README / Site) + +Seaweed Block is a lightweight Kubernetes block storage product for early lab +and small-cluster usage. It focuses on a clear first-volume workflow, protocol- +disciplined behavior across CSI/iSCSI/NVMe paths, and fail-closed recovery +semantics. When recovery is not yet safe to claim, Seaweed Block reports an +explicit refusal with actionable evidence instead of hiding risk behind partial +success. + +### Non-Claim Footer (Mandatory) + +This release does not claim production HA, broad distro compatibility, or +upgrade-safe operations. See `docs/operations-v1.md` "Scope And Non-Claims" +and the QA close reports under `internal/docs/qa-assignments/` for exact +scope. + +--- + +## 12) Execution Rules (Internal) + +1. Any new public claim must map to: + - a gate/scenario, + - QA evidence (close report with run IDs), + - explicit non-claim boundary. +2. If semantics are weaker than the product promise, publish safe refusal + rather than softening the promise silently. +3. Do not let tests become marketing language; tests validate claims, they do + not define positioning. +4. When a plan closes, update both `docs/operations-v1.md` "Scope And + Non-Claims" and §6/§7 of this document in the same change. + +--- + +## 13) Role Of The Claim Matrix + +The claim matrix (§6 and §7 above) should remain a fact document: + +- capability, +- claim status (claimed / partial / non-claim), +- proof links (close report + scenario + plan), +- known gaps (the next plan in `internal/docs/current-plan.md`). + +Use it as: + +- release sign-off artifact, +- support alignment artifact, +- internal truth source for external messaging. + +Do not use it as the primary homepage narrative. + +--- + +## 14) Next Steps + +1. Align README top section to this positioning. +2. Add a concise public-facing claim summary in `docs/` that mirrors §6/§7. +3. Keep this document as the authoritative claim/non-claim source under + `internal/docs/ref/`. +4. When the next plan closes, append its row to §6, reconcile §7 if any + non-claim was promoted, and update §10's recent close report list. diff --git a/seaweed-block/internal/docs/ref/product-spec-gate-template.md b/seaweed-block/internal/docs/ref/product-spec-gate-template.md new file mode 100644 index 0000000000..2f530bf91a --- /dev/null +++ b/seaweed-block/internal/docs/ref/product-spec-gate-template.md @@ -0,0 +1,127 @@ +# Product Spec Gate Template + +Purpose: keep implementation from drifting into test-shaped features that pass +but no longer preserve the product semantics users need. + +Use this template before starting any non-trivial plan slice. The spec is +deliberately colder than a roadmap: it defines what must not move during +implementation. + +## 1. Product Question + +One sentence: + +```text +Can do under and know without reading internal logs? +``` + +If this cannot be stated sharply, do not start code. + +## 2. User-Visible Contract + +Required fields: + +- command or API the user runs, +- input resources the user creates, +- output resources/status the product owns, +- success behavior, +- failure behavior, +- support-bundle evidence. + +Example shape: + +```text +Given: + topology=<...> + protocol=<...> + ack_profile=<...> +When: + +Then: + +And: + +``` + +## 3. Non-Negotiable Semantics + +These are not implementation details. Weakening any of them changes the product +claim and must force a plan edit before code continues. + +For block-storage work, always consider: + +- mounted I/O path, +- ACK profile, +- durable frontier, +- authority epoch / endpoint version, +- primary eligibility, +- stale-primary fencing, +- returned-replica eligibility, +- attach/reattach method, +- cleanup ownership, +- support-bundle issue wording. + +## 4. Allowed Simplifications + +List the simplifications that are allowed for the current slice. + +Each simplification must say whether it is: + +- `test_fixture_only`: allowed only inside a test fixture, +- `alpha_non_claim`: visible in docs and support bundles, +- `temporary_internal`: does not affect user-visible semantics, +- `safe_refusal`: product refuses the operation and explains why. + +No silent simplifications. + +## 5. Explicit Non-Claims + +List what the slice does not prove. These must appear in user docs or bundle +non-claims when they affect operator expectations. + +## 6. Evidence Contract + +Define the minimum evidence before implementation: + +- fast test names, +- runner scenario name, +- QA assignment path, +- required artifact files, +- required status lines, +- exit-code semantics, +- cleanup proof. + +The evidence must prove the product contract, not just the helper abstraction. + +## 7. Drift Checks + +Before accepting a green test, answer: + +1. Did the implementation weaken any non-negotiable semantic? +2. Did the test avoid the real user path? +3. Did a helper abstraction become the product claim? +4. Would a cold operator understand the bundle? +5. Is a safe refusal being reported as success? +6. Did we add a non-claim where the product still cannot do the thing? + +Any "yes" to 1, 2, 3, or 5 blocks the slice. Any "no" to 4 or 6 blocks close. + +## 8. Review Requirement + +For every P0/P1 product slice: + +- run fast tests before QA handoff, +- use internal review before broad runner validation, +- ask the reviewer specifically to find semantic weakening, not only code bugs, +- tell QA which product contract is being validated and which non-claims remain. + +## 9. Close Rule + +The slice closes only when: + +- the user-visible contract is still true, +- all non-negotiable semantics are preserved or explicitly refused, +- allowed simplifications are documented, +- QA validates against the contract, +- no support bundle requires implementation knowledge to interpret. diff --git a/seaweed-block/internal/docs/ref/rf2-promotion-readiness-audit.md b/seaweed-block/internal/docs/ref/rf2-promotion-readiness-audit.md new file mode 100644 index 0000000000..3e785f5dad --- /dev/null +++ b/seaweed-block/internal/docs/ref/rf2-promotion-readiness-audit.md @@ -0,0 +1,308 @@ +# RF=2 Promotion Readiness Audit + +Date: 2026-05-13 +Plan: `RF=2 Promotion-Ready Recovery MVP` +Positioning input: `internal/docs/ref/product-positioning-v1.md` + +## Question + +Can the current product-owned Kubernetes RF=2 path make a peer promotion-ready +with enough evidence to recover a mounted PVC after primary failure, or must the +product keep publishing safe refusal? + +Short answer: the replication/recovery substrate exists, but the Kubernetes +alpha RF=2 path does not yet wire promotion readiness as a product claim. The +current honest state is still: + +```text +r1 primary serves mounted I/O +r2 is placed and observed +r2 is not proven caught-up / promotion-ready +controlled r1 failure must refuse recovery +``` + +This is not a small test gap. It is the availability proof behind the product +positioning. A green scenario is acceptable only if it proves durable catch-up, +authority movement, fencing, and post-failure mounted read, or else emits a +sharper blocker. + +## Current Product Facts + +### What Phase 15 Closed + +The closed `Basic Mounted Failover And Reattach MVP` proved: + +- RF=2 PVC can create two generated `blockvolume` Deployments in the + two-logical-server alpha topology. +- The mounted app path works before failure: writer checksum and reader checksum + pass through the PVC. +- Inventory exposes `rf=2 desired=2 observed=2`, primary identity, per-replica + status bundles, and degraded replica reasons. +- A controlled primary failure is scoped to the current primary Deployment. +- If the peer is not ready, the product publishes strict safe refusal: + +```text +failover_status: refused +candidate_ready=false +data_check_after_failover=not_claimed +reason=candidate_not_ready_for_primary +``` + +That is a real product claim: fail-closed recovery semantics. It is not yet a +recovery claim. + +### What The RF=2 Baselines Show + +QA repeatedly observed this live shape: + +```text +r1: status=ok role=primary healthy=true epoch=1 endpoint_version=1 +r2: status=unhealthy role=unknown replication=not_ready healthy=false epoch=0 endpoint_version=0 +``` + +The writer/reader path succeeds because `r1` serves the frontend. The `r2` row +is valuable inventory evidence, but it is not promotion evidence. + +## Existing Reusable Machinery + +### Replication And Recovery Substrate + +`cmd/blockvolume/main.go` already wires a real replication stack when a durable +provider is configured: + +- `replication.NewReplicationVolume` owns primary-side peer fan-out. +- The durable backend installs the replication volume as write observer. +- `--replication-ack` supports `best-effort`, `sync-quorum`, and `sync-all`. +- `--recovery-mode=dual-lane` installs dual-lane recovery transport. +- The replica listener binds on `--data-addr`. +- `--degraded-probe-interval > 0` starts the degraded-peer probe loop. +- `--status-recovery` can expose `/status/recovery` with engine projection + details. + +Component and hardware scripts exercise these pieces. For example, +`scripts/iterate-m01-replicated-write.sh` starts primary and replica with +`--status-recovery`, `--t1-readiness`, and primary-side +`--degraded-probe-interval=5s`. That is the kind of behavior this plan should +port into the product-owned Kubernetes path. + +### Authority Substrate + +`core/authority/controller.go` can reassign authority: + +- if no authority line exists, bind an acceptable candidate, +- if current authority remains acceptable, keep it, +- if current authority is no longer acceptable, choose another acceptable + candidate, +- if no candidate is acceptable, emit no reassignment. + +The controller's acceptance predicate requires: + +```text +slot.Reachable && +slot.ReadyForPrimary && +slot.Eligible && +!slot.Withdrawn && +server.Reachable && +server.Eligible +``` + +This shape is correct only if `ReadyForPrimary` is a real durable/catch-up fact. + +### Fencing Substrate + +`core/host/volume/projection_bridge.go` fails closed when a replica is +superseded or acting only as a supporting replica. A stale primary should stop +looking frontend-ready after authority moves. The positive recovery gate must +assert this through inventory/status, not just trust the mechanism. + +### Inventory Substrate + +`sw-block ops inventory` already collects per-replica status bundles via +Kubernetes port-forward. It can report: + +- PVC/PV/volume/replica mapping, +- desired vs observed replica count, +- primary identity, +- frontend/status endpoints, +- durable status, +- peer status, +- degraded/unreachable/missing-placement issue lines. + +This is the right operator surface for promotion-ready and recovery evidence. + +## Product Gaps + +### P0: Kubernetes Launcher Does Not Enable Recovery Readiness + +`core/launcher/k8s_renderer.go` currently renders the generated blockvolume +with durable storage, dual-lane recovery mode, status endpoint, and iSCSI +frontend args. It does not render the knobs that make peer catch-up observable +and active: + +```text +--degraded-probe-interval +--degraded-probe-cooldown-base +--degraded-probe-cooldown-cap +--status-recovery +--replication-ack +--wal-retention-lsns +--t1-readiness +``` + +Impact: the product places `r2`, but the alpha Kubernetes path does not yet +drive or expose the catch-up/readiness loop needed for a recovery claim. + +### P0: Heartbeat ReadyForPrimary Was Too Weak + +The D1 audit found that `core/host/volume/host.go` built the heartbeat slot +with: + +```text +ReadyForPrimary: true +Eligible: true +Reachable: true +``` + +That was unsafe as a promotion signal by itself. A running process is not the +same as a caught-up replica. The first D3 guard changed the volume heartbeat to +derive `ReadyForPrimary` from local engine Healthy state and supersede status, +and changed the controller so initial placement can still use reachable/eligible +slots without treating them as failover-ready candidates. + +Close requirement: `ReadyForPrimary` must either be derived from real +promotion-readiness evidence, or the failover path must ignore/refuse it until +that evidence exists. The remaining product gap is durable-frontier coverage: +`ReadyForPrimary=true` still must be paired with writer-bound frontier evidence +before the runner gate can claim recovered data. + +### P0: ACK Profile Is Not Product-Owned In K8s + +`--replication-ack` defaults to `best-effort`. Best-effort can support a narrow +controlled demonstration: + +```text +the bytes explicitly written, flushed, caught up, and later verified survived +this controlled failure +``` + +It cannot support: + +```text +all acknowledged writes are quorum durable +``` + +The Kubernetes launcher does not yet expose or record the ACK profile in the +generated workloads. The recovery gate must name the profile in artifacts and +inventory. A beta-facing RF=2 recovery claim should use `sync-quorum` and prove +that unavailable quorum fails writes closed. A `best-effort` run may only be +called a controlled recovery demonstration, not RF=2 acknowledged-write +recovery. + +### P0: Durable Frontier Evidence Is Not Yet A User Contract + +The engine and recovery packages track useful facts such as local durable +frontier, catch-up/rebuild decisions, and post-close durable acknowledgement. +But the K8s RF=2 support bundle does not yet expose a cold operator line like: + +```text +candidate_ready=true reason=caught_up durable_frontier= peer_epoch= peer_endpoint_version= +``` + +Without that line, promotion readiness would require implementation knowledge. + +The required frontier must be tied to the mounted writer, not just to an +arbitrary local WAL position. The bundle must record: + +```text +required_frontier_lsn= +candidate_frontier_lsn= +frontier_covered=true|false +``` + +Promotion is valid only when: + +```text +candidate_frontier_lsn >= required_frontier_lsn +``` + +### P0: Product Loop Uses RF>1 Placement As Input, Not A Full Recovery Policy + +`core/host/master/product_loop.go` submits RF>1 placement snapshots to the +topology controller, and only direct-bind asks for single-slot placements. This +is enough for observed RF=2 placement and safe refusal. Positive recovery still +needs a product policy that feeds acceptable candidates only when readiness is +real. + +### P1: CSI Reattach Must Be Explicit + +`core/csi/master_backend.go` looks up current frontend target; it does not +claim transparent in-place I/O continuation. The MVP recovery path should use a +documented pod recreate/reattach method and verify bytes after that reattach. + +## Existing Paths To Reuse + +Use these as implementation references: + +- `scripts/iterate-m01-replicated-write.sh`: recovery/probe/status-recovery + wiring outside Kubernetes. +- `scripts/run-iscsi-alua-mounted-failover-smoke.sh`: mounted failover and + status polling vocabulary outside the product-owned K8s lifecycle. +- `core/replication/component/g9a_best_effort_recovery_test.go`: degraded peer + recovery mechanics with probe loop. +- `core/host/volume/status_server.go`: `/status`, `/status/peers`, and + `/status/recovery` surfaces. +- `core/ops/k8s_inventory.go`: nested per-replica bundle collection. + +Do not port shortcuts that weaken V3: + +- no heartbeat-as-ready, +- no authority move without publisher epoch/endpoint-version, +- no returned-replica promotion without catch-up evidence, +- no component-only data check as Kubernetes mounted recovery. + +## Readiness Contract Candidate + +A peer should be considered promotion-ready only when the support bundle can +show all of the following: + +```text +replica observed: true +replica process reachable: true +replication role: replica_ready OR equivalent caught-up state +durable entry: latched=true operational=true +lineage: epoch/endpoint_version aligned with current authority basis or explicit recovery target +primary peer view: peer state=healthy, probe_in_flight=false, closed=false +recovery evidence: decision=none OR caught_up, durable_frontier >= required frontier +frontend: not serving as primary until authority moves +``` + +If any of those are missing, the correct product output is safe refusal: + +```text +failover_status: refused +reason= +candidate_ready=false +data_check_after_failover=not_claimed +``` + +## Recommended Next Slice + +1. Write the contract in + `internal/docs/ref/rf2-promotion-ready-recovery-contract.md`. +2. Add fast guard that heartbeat `ReadyForPrimary=true` is not sufficient for + promotion readiness in the mounted failover path. +3. Add launcher knobs for recovery observability: + `--status-recovery`, `--degraded-probe-interval`, ACK profile, and retention + configuration. +4. Add inventory wording for promotion readiness and missing durable frontier. +5. Build the runner gate to wait for `r2` readiness. If readiness never appears, + close the slice as a specific blocker, not as recovery. + +## Audit Verdict + +The product has strong enough internals to pursue RF=2 mounted recovery without +an architecture reset. It is not yet ready to claim recovery in Kubernetes. + +The first implementation risk is not "make the test pass." The risk is +accidentally treating an observed process as a promotion-ready replica. That +would contradict the product positioning and turn the block product into a toy. diff --git a/seaweed-block/internal/docs/ref/rf2-promotion-ready-recovery-contract.md b/seaweed-block/internal/docs/ref/rf2-promotion-ready-recovery-contract.md new file mode 100644 index 0000000000..af06068409 --- /dev/null +++ b/seaweed-block/internal/docs/ref/rf2-promotion-ready-recovery-contract.md @@ -0,0 +1,436 @@ +# Stage 1 Mounted Recovery ACK Profile Contract + +Date: 2026-05-13 +Plan: `Stage 1 Mounted Recovery ACK Profile MVP` +Positioning input: `internal/docs/ref/product-positioning-v1.md` + +## Product Question + +Can a small-cluster Kubernetes user write data to a Seaweed Block PVC, see a +peer become promotion-ready, stop the current primary, and then reattach a pod +that reads the same data without relying on internal logs, under an ACK profile +that honestly matches the product claim? + +If yes, the product earns one of two explicit Stage 1 claims: RF=2 +controlled-best-effort recovery demo, or RF=3 sync-quorum durable HA recovery. +If no, it must publish a specific safe blocker and keep recovery as a +non-claim. + +Master-side promotion is not, by itself, user-visible recovery. A recovered +claim in this plan requires the Stage 1 host-path mechanism: + +```text +CSI/node reattach on pod recreate +``` + +If the run cannot prove CSI/node reattach, the only valid result is safe refusal +even if the master selected a new primary. Transparent protocol multipath +switching through iSCSI ALUA or NVMe ANA is the next plan. + +Stage 1 is the minimum HA-like product line. A close report may not mark this +plan recovered unless the Kubernetes app path recovers without manual promote, +manual repair, direct storage inspection, or direct blockvolume reads. + +Stage 2 is a separate future contract for transparent multipath host failover. +It must not be used as a substitute for Stage 1 CSI/pod-recreate evidence. + +## Supported MVP Topology + +Supported for this contract: + +- Kubernetes alpha path, +- product-owned blockvolume lifecycle, +- iSCSI PVC, +- RF=2 best-effort controlled demo, +- RF=3 sync-quorum durable HA gate, +- two logical Seaweed Block server identities, +- same physical Kubernetes node under the current loopback attach constraint, +- durable hostPath per replica, +- pod recreate/reattach after failure. + +Out of topology: + +- remote-node attach, +- arbitrary node loss, +- NVMe Kubernetes recovery, +- transparent in-place I/O continuation, +- production HA. + +## User-Visible Contract + +Given: + +```text +topology=alpha-k8s-same-node-rf2 +protocol=iscsi +ack_profile= +host_path_method=csi-node-reattach +reattach_method=pod-recreate +``` + +When: + +```text +writer pod writes and verifies /data/demo.bin +non-primary peer candidate reaches promotion_ready=true +the current primary blockvolume Deployment is stopped +the documented host path recovers or safe-refuses +reader pod reads the same PVC if recovery is legitimately claimed +``` + +Then recovered behavior requires: + +```text +failover_status: recovered +before_primary_replica= +failed_replica= +new_primary_replica= +old_primary_fenced=true +candidate_ready=true +host_path_recovered=true +host_path_method=csi-node-reattach +reattach_method=pod-recreate +data_check_after_failover=claimed +before_sha256= +after_sha256= +match=true +manual_operator_repair=false +``` + +If `r2` does not reach promotion readiness, the only valid pass is safe +refusal: + +```text +failover_status: refused +candidate_ready=false +data_check_after_failover=not_claimed +reason= +``` + +Recovered behavior is invalid if any of these are true: + +- promotion is manual, +- recovery uses direct blockvolume or durable-store reads, +- CSI/node reattach target generation is not captured, +- reader checksum is missing, +- old primary still appears as a valid writer, +- the ACK/frontier basis is absent or weaker than the claim. + +## ACK Profile + +The run must emit: + +```text +ack_profile= +``` + +Allowed profile meanings: + +- `best-effort`: only the exact bytes caught up and verified by the gate are + claimed. This does not claim quorum durability for all acknowledged writes. +- `sync-quorum`: foreground writes must fail closed when quorum acknowledgement + is unavailable. If used, the gate must prove that failure mode. +- `sync-all`: all replicas acknowledge writes before success. If used, the gate + must prove both replicas acknowledge the data before failure. + +Default implementation behavior may remain `best-effort`. An RF=2 run may be a +controlled recovery demonstration only when the bundle says +`claim_profile=controlled-best-effort-demo`. A beta-facing writable HA recovery +claim requires RF=3 with `sync-quorum` unless a later product spec defines a +different degraded-write policy. The support bundle must make this visible so +operators do not infer stronger durability. + +## Promotion-Ready Evidence + +A replica is not promotion-ready just because it is observed. + +Minimum promotion-ready evidence: + +```text +candidate_replica= +candidate_ready=true +candidate_reason=caught_up +candidate_observed=true +candidate_reachable=true +candidate_frontend_ready=false +candidate_authority_role= +candidate_replication_role=replica_ready +candidate_durable_latched=true +candidate_durable_operational=true +candidate_epoch= +candidate_endpoint_version= +required_frontier_lsn= +candidate_frontier_lsn= +frontier_covered=true +primary_peer_state=healthy +primary_peer_probe_in_flight=false +``` + +If the current implementation cannot expose every field yet, it must expose an +equivalent cold-readable line and document the mapping in this file before the +runner gate is accepted. + +Invalid substitutes: + +- heartbeat exists, +- Deployment Ready, +- `observed=1`, +- status endpoint reachable, +- local process healthy while `replication=not_ready`, +- component-only catch-up without the Kubernetes mounted path. + +## Durable Frontier + +Recovery must name the durable frontier that justifies promotion. Acceptable +evidence shapes: + +```text +required_frontier_lsn= +durable_frontier: replica= lsn= source= +frontier_covered=true +recovery_decision: none reason=caught_up R= S= H= +``` + +or a stronger equivalent. + +Promotion is valid only when: + +```text +candidate_frontier_lsn >= required_frontier_lsn +``` + +If the bundle cannot identify a durable frontier, recovery must be refused: + +```text +reason=durable_frontier_missing +candidate_ready=false +``` + +## Controlled Failure + +The failure must be derived from live inventory, not hard-coded: + +```text +failure_class=primary-blockvolume-controlled-stop +before_primary_replica= +failed_replica= +failed_epoch= +failed_endpoint_version= +target_deployment= +target_ready_replicas=0 +``` + +The gate must fail if `failed_replica != before_primary_replica`. + +## Authority Movement + +Recovered behavior requires: + +```text +old_primary: replica= fenced=true frontend_ready=false +new_primary: replica= role=primary frontend_ready=true epoch= endpoint_version= +authority_transition: old=@/ new=@/ +``` + +The transition must satisfy a concrete monotonic rule: + +```text +E2 > E OR (E2 == E AND EV2 > EV) +``` + +If the implementation has a different documented authority generation rule, the +bundle must name it and prove it. If the transition cannot be proven, recovery +is invalid: + +```text +failover_status: refused +reason=authority_promotion_missing +data_check_after_failover=not_claimed +``` + +If the old primary still looks frontend-ready, recovery is also invalid: + +```text +failover_status: refused +reason=stale_primary_not_fenced +data_check_after_failover=not_claimed +``` + +## Reattach Method + +Transparent in-place I/O continuation is not claimed. + +The allowed Stage 1 MVP host-path method is: + +```text +host_path_method=csi-node-reattach +reattach_method=pod-recreate +``` + +Evidence for CSI/node reattach: + +```text +writer_pod= +reader_pod= +writer_sha256= +reader_sha256= +publish_target_before=@/ +publish_target_after=@/ +staged_target_before= +staged_target_after= +manual_operator_repair=false +``` + +The reader pod must use the same PVC and read through the Kubernetes CSI/iSCSI +path. A direct blockvolume, filesystem, or component-store read is not valid for +the mounted recovery claim. + +## Control-Plane Observation + +Every recovered or refused run must emit a cold-readable control-plane timeline. +The current artifact name is: + +```text +control-plane-timeline.txt +``` + +Minimum event vocabulary: + +```text +event=primary_observed replica= evidence= +event=candidate_evaluated replica= candidate_ready= reason= +event=primary_failure_injected replica= deployment= failure_class=primary-blockvolume-controlled-stop +event=authority_published from= to= primary= primary_count=1 evidence= +event=safe_refusal replica= candidate_ready=false reason= evidence= +event=csi_reattach_observed reader_pod=sw-block-demo-reader method=pod-recreate log= +event=data_check reader_verified=true result=reader_checksum_passed log= +``` + +Recovered runs require `authority_published`, `csi_reattach_observed`, and +`data_check`. Refused runs require `safe_refusal` and must not emit a successful +data check. This timeline is the Stage 1 control-plane observation surface until +the product grows a first-class `sw-block ops timeline` command. + +If CSI/node reattach is not proven, recovery must be refused: + +```text +failover_status: refused +reason=host_path_recovery_not_verified +data_check_after_failover=not_claimed +``` + +## Safe Refusal Reasons + +Valid refusal reasons: + +- `candidate_not_ready_for_primary` +- `replication_role_not_ready` +- `durable_frontier_missing` +- `replication_ack_profile_unmet` +- `status_endpoint_unreachable` +- `authority_promotion_missing` +- `stale_primary_not_fenced` +- `host_path_recovery_not_verified` +- `reattach_not_verified` + +Safe refusal requires: + +```text +failover_status: refused +reason= +candidate_ready=false +data_check_after_failover=not_claimed +after_issue_evidence= +``` + +## Inventory And Bundle Requirements + +The runner bundle must include: + +- before-failure inventory summary, +- before-failure nested per-replica status bundles, +- promotion-readiness evidence, +- failure target evidence, +- after-failure inventory summary, +- after-failure nested per-replica status bundles, +- safe-refusal or recovery decision file, +- host-path method evidence if recovery is claimed, +- writer and reader logs if recovery is claimed, +- cleanup audit. + +The summary must let a cold operator answer: + +1. Which replica was primary before failure? +2. Was the peer promotion-ready before failure? +3. Which exact resource was stopped? +4. Did authority move or refuse? +5. Did the old primary stop looking like a writer? +6. Which host-path recovery method was used, or why was it not claimed? +7. Was data read after reattach, or was that explicitly not claimed? + +## Fast Guards Required Before Runner Gate + +Add or retain fast tests for: + +- heartbeat-only candidate is not sufficient for promotion readiness, +- observed-but-`replication=not_ready` peer is not eligible, +- durable frontier missing causes safe refusal, +- ACK profile is emitted and cannot be silently defaulted, +- old primary supersede maps to non-serving frontend projection, +- inventory wording distinguishes process health from promotion readiness. + +## Runner Gate Shape + +Required phases: + +```text +pre_clean +preflight +pin_build_alpha_images +install_rf2_alpha_stack +rf2_mounted_write_boundary +wait_for_promotion_ready_or_blocker +inventory_before_failure +inject_primary_failure +observe_recovery_or_refusal +prove_csi_node_reattach_if_recovered +reattach_reader_if_recovered +inventory_after_failure +assert_contract +collect_and_cleanup(always) +``` + +The gate may close in one of two ways: + +1. `recovered`: reader checksum after pod recreate matches writer checksum, and + authority/fencing evidence plus CSI/node reattach evidence are present. +2. `refused`: no reader success is claimed, and the blocker names the missing + condition. + +Any other outcome is fail. + +## Non-Claims + +This contract does not claim: + +- production HA, +- node loss survival, +- transparent in-place I/O continuation, +- remote-node attach, +- NVMe Kubernetes recovery, +- Kubernetes CSI multipath host-path failover, +- transparent or near-transparent protocol failover, +- RF=2 quorum recovery after one replica loss, +- quorum durability unless RF=3 `sync-quorum` is gated, +- broad rebuild/reintegration automation, +- performance SLOs, +- upgrade or uninstall safety. + +## Close Rule + +This plan may close only when the implementation either: + +- proves the recovered branch with QA-owned runner evidence, or +- proves a sharper safe blocker and updates user-facing non-claims. + +It must not close by renaming `observed` or `reachable` as promotion-ready. diff --git a/seaweed-block/internal/docs/ref/stage2-transparent-multipath-host-failover-spec.md b/seaweed-block/internal/docs/ref/stage2-transparent-multipath-host-failover-spec.md new file mode 100644 index 0000000000..e3e12971fd --- /dev/null +++ b/seaweed-block/internal/docs/ref/stage2-transparent-multipath-host-failover-spec.md @@ -0,0 +1,312 @@ +# Stage 2 Transparent Multipath Host Failover Spec + +Status: D1 cold product spec for +`current-plan.md` Stage 2 Transparent Multipath Host Failover MVP. + +## Product Question + +Can a Kubernetes user keep a mounted Seaweed Block PVC usable through controlled +primary failure without pod recreate, using standard Linux multipath behavior, +and understand the result from product evidence rather than internal logs? + +## First Protocol Choice + +Stage 2 closes iSCSI first: + +```text +iSCSI ALUA + Linux dm-multipath +``` + +Reason: + +- iSCSI is the current alpha default frontend. +- The user-facing quickstart and operations manual already center on iSCSI. +- Prior protocol work already produced ALUA/MPIO lab evidence in + `iscsi-p6-alua-mpio-design.md`. +- It avoids mixing two hard changes: protocol selection UX and multipath + recovery. + +NVMe ANA remains the next protocol path. It has strong lab evidence in +`nvme-p4-multipath-failover-design.md`, but Kubernetes CSI protocol selection +and NVMe native multipath should be a separate close gate. + +## User-Visible Contract + +Given: + +```text +topology=alpha Kubernetes, same node allowed for first Stage 2 gate +protocol=iscsi +host_multipath=dm-multipath configured and detected +replication=RF3 sync-quorum +ack_profile=sync-quorum +claim_profile=stage2-iscsi-alua-multipath +``` + +When: + +```text +an app pod has a mounted PVC +the writer has verified /data/demo.bin +the current primary blockvolume is stopped in a scoped way +master promotes a candidate that covers the required frontier +``` + +Then: + +```text +Linux host path changes through dm-multipath +old primary path cannot acknowledge stale data I/O +the mounted workload verifies /data/demo.bin without pod recreate +support bundle names authority, ALUA path state, multipath state, and data check +all attach/mount/path-switch/I/O waits are bounded and produce blocker reasons +``` + +If dm-multipath is unavailable, ALUA is not visible, paths do not merge into one +device, or the workload only recovers after pod recreate, Stage 2 must fail +closed. It may produce a useful blocker bundle, but not a Stage 2 recovery +claim. + +## Required User Evidence + +Minimum evidence in the artifact bundle: + +```text +multipath-prereq.txt +iscsi-discovery.txt +sg-inq.txt +sg-vpd83.txt +sg-rtpg.before.txt +multipath-before.txt +writer.log +pre-failure-inventory/ +primary-failure.txt +authority-after.txt +sg-rtpg.after.txt +multipath-after.txt +workload-after-failover.log +post-failure-inventory/ +support-bundle/ +bounded-waits.txt +cleanup-audit.txt +``` + +Required stable lines: + +```text +protocol=iscsi +multipath_enabled=true +host_device= +path_count_before>=2 +path_count_after>=1 +active_path_before= +active_path_after= +before_primary_replica= +failed_replica= +promoted_replica= +post_failure_primary_count=1 +old_primary_stale_io_success_count=0 +data_check_after_failover=mounted_workload_checksum_passed +pod_recreate_used=false +bounded_waits=pass +blocked_reason=none +``` + +## Non-Negotiable Semantics + +- **Authority boundary**: master chooses/promotes primary; CSI, iSCSI, and + multipath do not elect authority. +- **Durability boundary**: promotion candidate must cover the required + sync-quorum frontier, same as Stage 1 RF3. +- **Protocol boundary**: ALUA state reflects frontend/authority facts; it does + not make unsafe replicas writable. +- **Host boundary**: Linux must see one multipath device with multiple paths + for the same volume identity. Two independent `/dev/sdX` devices do not + satisfy Stage 2. +- **Mounted I/O boundary**: the same mounted workload path must verify data + after failure. Recreating the pod is Stage 1, not Stage 2. +- **Fencing boundary**: old primary path must not return successful stale data + I/O after authority moves. +- **Reliability/observability boundary**: Kubernetes attach, mount, ALUA/RTPG + read, multipath map creation, authority movement, stale-primary fencing, and + post-failure workload I/O must all have explicit timeouts. A hung wait is a + product failure and must surface as a blocker reason in the bundle. + +## Bounded Failure Classes + +Stage 2 must name these classes in support bundles instead of timing out +silently: + +```text +attach_timeout +iscsi_login_timeout +multipath_map_timeout +alua_state_unavailable +authority_promotion_timeout +path_switch_timeout +stale_primary_fence_timeout +post_failure_io_timeout +cleanup_timeout +``` + +Each class must include: + +```text +resource= +timeout= +last_observed_state= +next_action= +``` + +## Current Code Gaps + +### CSI Publishes One Target + +Current `core/csi/controller.go` and `core/csi/master_backend.go` return one +`PublishTarget`. `core/csi/node.go` stages one iSCSI portal/IQN and formats the +device returned by `GetDeviceByIQN`. + +Stage 2 needs a multi-path publish shape: + +```text +volume -> same IQN / stable device identity +paths -> multiple portals with path role/state +node -> login all eligible paths before mounting the multipath device +``` + +Partial implementation status: NodeStage now understands a deliberate +`stage2_multipath=true` publish context with multiple `iscsiAddrs`. It refuses +fewer than two portals, logs in all portals, and mounts the multipath device +reported by the iSCSI utility. CSI control lookup can convert multiple iSCSI +frontend facts with the same IQN into that publish context, but only through an +explicit Stage 2 opt-in (`--stage2-multipath` / multipath lookup constructor). +The default CSI path remains single-target to avoid silently changing Stage 1 +attach behavior before ALUA evidence is complete. Master status can now expose +all observed replica frontend facts for a volume as read-only evidence. Alpha +install scripts render the opt-in only when `SW_BLOCK_STAGE2_MULTIPATH=1`, and +the CSI node image/DaemonSet now carries the first-pass multipath tooling and +kernel-module prerequisites (`multipath-tools`, `sg3-utils`, `dm_multipath`, +`scsi_dh_alua`, `/run/udev` read-only mount). + +Runner status: `testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml` +now exists as the first Stage 2 baseline. It validates opt-in wiring, loaded +host multipath prerequisites, same-IQN RF=3 paths, `sg_rtpg` path-state +evidence, and targeted multipath-map cleanup. It records +`transparent_failover_claimed=false`; the mounted primary-failure/no-pod-recreate +proof remains open and should use a separate close scenario. + +QA finding 2026-05-15: the first baseline runs showed the opt-in reached +NodeStage but the node staged only `127.0.0.1:3260`, leaving no multipath map. +The node path now waits for refreshed multi-portal publish evidence and emits +`multipath publish target ready portals=...` before logging into all paths. This +keeps Stage 2 fail-closed if master never exposes multiple portals. + +QA/internal review timing finding 2026-05-15: host-path evidence must be captured +while a pod still holds the staged device. The baseline therefore uses the +writer-hold manifest and stops at `writer-verified`, before writer deletion or +CSI unstage, then captures `iscsi-sessions.writer-mounted.txt`, +`multipath.writer-mounted.txt`, and `sg-rtpg.writer-mounted.txt`. A post-reader +capture can be empty for the wrong reason and is not acceptable evidence of +Stage 2 wiring. + +QA finding 2026-05-15: the writer-held Stage 2 path is the first baseline to run +the app as UID/GID 1000 with `fsGroup: 1000`. A permission-denied write to +`/data/demo.bin` is a CSI/Kubernetes filesystem ownership failure, not an app +failure. The alpha CSIDriver must declare `fsGroupPolicy: File`, and the +scenario must preserve mounted host-path diagnostics even if writer verification +fails. + +QA evidence 2026-05-15 run `20260515-091810-6d74`: the baseline reached the +intended host boundary. It showed three iSCSI sessions to one IQN, one +dm-multipath map with `hwhandler='1 alua'`, and `sg_rtpg` states with one +active/optimized path and two standby paths. Scenario assertions should match +the always-emitted `staged transport=iscsi ... portals=... multipath=true` line; +the `multipath publish target ready` line is only present when NodeStage had to +wait for refreshed publish context. + +QA evidence 2026-05-15 run `20260515-092817-61f9`: the Stage 2 baseline passed +strictly. The next scenario is +`testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml`, which keeps +the writer pod mounted, derives and stops the primary from inventory, and +requires the same writer pod to verify data after failure without reader pod +recreate. + +### Node Stage Mounts The Raw Path Device + +Current NodeStage formats/mounts the portal-specific device. Stage 2 needs to +wait for the dm-multipath device, verify it represents the volume identity, and +mount that device instead. + +Partial implementation status: with `stage2_multipath=true`, NodeStage mounts +the dm-multipath device path returned by `GetMultipathDeviceByIQN`. The real +Linux utility now refreshes multipath maps with bounded subprocess calls, +resolves the IQN to raw `/dev/disk/by-path` devices, and matches those devices +to a `/dev/mapper/` entry in `multipath -ll`. It still needs lab +validation against M02 artifact output. + +### ALUA Must Be Wired To Product Facts + +The iSCSI ALUA protocol substrate exists as prior work, but the Kubernetes +path must prove: + +- current primary reports active optimized, +- valid non-primary path reports standby or active non-optimized according to + the selected policy, +- old primary becomes unavailable/transitioning after promotion, +- data I/O on non-writable paths fails closed. + +### Inventory Must Explain Host Path + +Current inventory explains PVC, replicas, frontend endpoints, status bundles, +and promotion evidence. Stage 2 additionally needs host-path evidence: + +- multipath device, +- path count, +- active/standby/unavailable path states, +- selected active path before and after failure, +- whether pod recreate was used. +- bounded wait outcome and blocker reason, if any. + +### K8s Alpha Uses Loopback Frontends + +The first gate may still be same-node alpha, but it must not confuse that with +node-loss HA. Same-node is allowed only if Linux sees multiple real iSCSI +sessions/paths and dm-multipath owns the mounted device. + +## Fast Test Targets + +Before runner validation: + +- CSI publish target model can carry multiple iSCSI paths for one volume. +- NodeStage rejects `stage2_multipath=true` when fewer than two paths exist. +- NodeStage mounts the multipath device, not the raw by-path device. +- iSCSI ALUA provider maps active/standby/unavailable from frontend facts. +- Old-primary path rejects data I/O after authority movement. +- Inventory summary prints multipath device, path count, active path, and + `pod_recreate_used=false`. +- Bounded wait helper returns a stable blocker class and support-bundle line for + attach timeout, multipath map timeout, path switch timeout, and + post-failure I/O timeout. + +## QA Gate Summary + +The close gate should fail if any of these are true: + +- recovery requires pod delete/recreate, +- Linux sees two independent devices instead of one multipath device, +- ALUA/RTPG state is missing or inconsistent, +- old primary can still return successful stale data I/O, +- reader checksum is obtained only after CSI re-stage, +- support bundle requires blockmaster/blockvolume logs to understand the + outcome. +- any Kubernetes attach/mount/session/path-switch/I/O step can hang until the + outer runner kills the scenario instead of producing a product blocker. + +## Product Non-Claims Until Close + +- No Stage 2 transparent failover claim. +- No NVMe ANA Kubernetes claim. +- No node-loss claim. +- No production HA/RTO claim. +- No Windows MPIO claim. +- No multi-distro compatibility claim. diff --git a/seaweed-block/scripts/activate-k8s-alpha.sh b/seaweed-block/scripts/activate-k8s-alpha.sh new file mode 100644 index 0000000000..314c035ef7 --- /dev/null +++ b/seaweed-block/scripts/activate-k8s-alpha.sh @@ -0,0 +1,301 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-/tmp/sw-block-activation-$(date -u +%Y%m%dT%H%M%SZ)}" +IMAGE_MODE="${SW_BLOCK_ACTIVATION_IMAGE_MODE:-local}" +case "$IMAGE_MODE" in + local|published) + ;; + *) + echo "SW_BLOCK_ACTIVATION_IMAGE_MODE must be local or published; got: $IMAGE_MODE" >&2 + exit 2 + ;; +esac +if [[ "$IMAGE_MODE" == "published" ]]; then + IMAGE="${SW_BLOCK_IMAGE:-ghcr.io/seaweedfs/seaweed-block:alpha}" + CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-ghcr.io/seaweedfs/seaweed-block-csi:alpha}" + IMPORT_K3S="${SW_BLOCK_ACTIVATION_IMPORT_K3S:-${SW_BLOCK_IMPORT_K3S:-0}}" +else + IMAGE="${SW_BLOCK_IMAGE:-sw-block:local}" + CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-sw-block-csi:local}" + IMPORT_K3S="${SW_BLOCK_ACTIVATION_IMPORT_K3S:-${SW_BLOCK_IMPORT_K3S:-1}}" +fi +STORAGECLASS_NAME="${SW_BLOCK_STORAGECLASS_NAME:-sw-block-dynamic}" +REPLICATION_ACK="${SW_BLOCK_ALPHA_REPLICATION_ACK:-best-effort}" +FRONTEND_PROTOCOL="${SW_BLOCK_FRONTEND_PROTOCOL:-iscsi}" +APP_NAMESPACE="${SW_BLOCK_APP_NAMESPACE:-default}" +CHAP_SECRET_NAME="${SW_BLOCK_ISCSI_CHAP_SECRET_NAME:-sw-block-iscsi-chap}" +CHAP_USERNAME="${SW_BLOCK_ISCSI_CHAP_USERNAME:-}" +CHAP_SECRET="${SW_BLOCK_ISCSI_CHAP_SECRET:-}" +LAUNCHER_EXTERNAL_ISCSI="${SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI:-}" +LAUNCHER_EXTERNAL_STATUS="${SW_BLOCK_LAUNCHER_EXTERNAL_STATUS:-}" +ALPHA_NODE_SPECS="${SW_BLOCK_ALPHA_NODE_SPECS:-}" +DAY1_NETWORK_MODE="loopback" +DAY1_TARGET_NODE="" +DAY1_TARGET_IP="" + +mkdir -p "$ARTIFACT_DIR" + +if [[ -z "${KUBECONFIG:-}" && -f /etc/rancher/k3s/k3s.yaml ]]; then + export KUBECONFIG=/etc/rancher/k3s/k3s.yaml +fi + +log() { + printf '[alpha-activate] %s\n' "$*" | tee -a "$ARTIFACT_DIR/activate.log" +} + +require_cmd() { + if ! command -v "$1" >/dev/null 2>&1; then + write_summary "failed" "missing-command-$1" + echo "missing required command: $1" >&2 + exit 2 + fi +} + +safe_kubectl() { + kubectl "$@" 2>/dev/null || true +} + +ready_schedulable_node_count() { + safe_kubectl get nodes -o wide --no-headers \ + | awk '$2 ~ /Ready/ && $2 !~ /SchedulingDisabled/ {ready++} END {print ready+0}' +} + +first_ready_node_with_internal_ip() { + safe_kubectl get nodes -o wide --no-headers \ + | awk '$2 ~ /Ready/ && $2 !~ /SchedulingDisabled/ && $6 !~ /^(127\.|0\.0\.0\.0|::1$)/ {print $1 "|" $6; exit}' +} + +image_digest() { + local image="$1" + if command -v docker >/dev/null 2>&1; then + docker manifest inspect "$image" 2>/dev/null \ + | sed -n 's/.*"digest": "\(sha256:[^"]*\)".*/\1/p' \ + | head -1 + fi +} + +inject_node_stage_secret_into_storageclass() { + local input="$1" + local output="$2" + local secret="$3" + local namespace="$4" + awk -v secret="$secret" -v namespace="$namespace" ' + /^parameters:[[:space:]]*$/ { + print + print " csi.storage.k8s.io/node-stage-secret-name: \"" secret "\"" + print " csi.storage.k8s.io/node-stage-secret-namespace: \"" namespace "\"" + next + } + { print } + ' "$input" >"$output" +} + +collect_failure_diagnostics() { + local phase="$1" + mkdir -p "$ARTIFACT_DIR/diagnostics" + { + echo "failed_phase=$phase" + echo "image_mode=$IMAGE_MODE" + echo "image=$IMAGE" + echo "image_digest=$(image_digest "$IMAGE")" + echo "csi_image=$CSI_IMAGE" + echo "csi_image_digest=$(image_digest "$CSI_IMAGE")" + } >"$ARTIFACT_DIR/diagnostics/failure-context.txt" + kubectl -n kube-system get pods,deploy,ds,events -o wide >"$ARTIFACT_DIR/diagnostics/kube-system.txt" 2>&1 || true + kubectl -n kube-system describe deploy sw-blockmaster >"$ARTIFACT_DIR/diagnostics/sw-blockmaster.describe.txt" 2>&1 || true + kubectl -n kube-system logs deploy/sw-blockmaster --all-containers --tail=200 >"$ARTIFACT_DIR/diagnostics/sw-blockmaster.log" 2>&1 || true + kubectl -n kube-system logs deploy/sw-blockmaster --all-containers --previous --tail=200 >"$ARTIFACT_DIR/diagnostics/sw-blockmaster.previous.log" 2>&1 || true + kubectl -n kube-system describe deploy sw-block-csi-controller >"$ARTIFACT_DIR/diagnostics/sw-block-csi-controller.describe.txt" 2>&1 || true + kubectl -n kube-system logs deploy/sw-block-csi-controller --all-containers --tail=200 >"$ARTIFACT_DIR/diagnostics/sw-block-csi-controller.log" 2>&1 || true + kubectl -n kube-system describe ds sw-block-csi-node >"$ARTIFACT_DIR/diagnostics/sw-block-csi-node.describe.txt" 2>&1 || true + if grep -R "flag provided but not defined" "$ARTIFACT_DIR/diagnostics" >/dev/null 2>&1; then + { + echo "activation_blocker=image_flag_mismatch" + echo "reason=published image does not support a flag required by this source tree" + echo "remediation=republish the image from this commit or use matching sha- image tags" + } >>"$ARTIFACT_DIR/diagnostics/failure-context.txt" + fi +} + +summary_value() { + local value="$1" + if [[ -n "$value" ]]; then + printf '%s' "$value" + else + printf 'unknown' + fi +} + +write_summary() { + local status="$1" + local failed_phase="${2:-}" + local master_ready csi_controller_ready csi_node_ready storageclass_provider nodes_ready + master_ready="$(safe_kubectl -n kube-system get deploy sw-blockmaster -o jsonpath='{.status.availableReplicas}')" + csi_controller_ready="$(safe_kubectl -n kube-system get deploy sw-block-csi-controller -o jsonpath='{.status.availableReplicas}')" + csi_node_ready="$(safe_kubectl -n kube-system get ds sw-block-csi-node -o jsonpath='{.status.numberReady}/{.status.desiredNumberScheduled}')" + storageclass_provider="$(safe_kubectl get sc "$STORAGECLASS_NAME" -o jsonpath='{.provisioner}')" + nodes_ready="$(safe_kubectl get nodes --no-headers | awk '$2 ~ /Ready/ {ready++} END {print ready+0}')" + { + echo "activation_status=$status" + if [[ -n "$failed_phase" ]]; then + echo "failed_phase=$failed_phase" + fi + echo "artifact_dir=$ARTIFACT_DIR" + echo "root=$ROOT" + echo "image_mode=$IMAGE_MODE" + echo "image=$IMAGE" + echo "image_digest=$(summary_value "$(image_digest "$IMAGE")")" + echo "csi_image=$CSI_IMAGE" + echo "csi_image_digest=$(summary_value "$(image_digest "$CSI_IMAGE")")" + echo "protocol=$FRONTEND_PROTOCOL" + echo "ack_profile=$REPLICATION_ACK" + echo "day1_network_mode=$DAY1_NETWORK_MODE" + echo "day1_target_node=$(summary_value "$DAY1_TARGET_NODE")" + echo "day1_target_ip=$(summary_value "$DAY1_TARGET_IP")" + echo "external_iscsi=$([[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]] && echo true || echo false)" + echo "external_status=$([[ "$LAUNCHER_EXTERNAL_STATUS" == "1" || "$LAUNCHER_EXTERNAL_STATUS" == "true" ]] && echo true || echo false)" + echo "chap_enabled=$([[ -n "$CHAP_SECRET" ]] && echo true || echo false)" + echo "ready_kubernetes_nodes=$(summary_value "$nodes_ready")" + echo "master_ready_replicas=$(summary_value "$master_ready")" + echo "csi_controller_ready_replicas=$(summary_value "$csi_controller_ready")" + echo "csi_node_ready=$(summary_value "$csi_node_ready")" + echo "storageclass=$STORAGECLASS_NAME" + echo "storageclass_provider=$(summary_value "$storageclass_provider")" + echo "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml" + echo "next_status=kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333 && sw-block ops cluster --master-api 127.0.0.1:9333 -o json" + echo "next_inventory=sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out /tmp/sw-block-inventory" + echo "non_claims=alpha_only,no_backup_restore,no_upgrade_safety,no_mutating_dashboard_actions,no_broad_performance_slo" + } >"$ARTIFACT_DIR/activation-summary.txt" +} + +run_phase() { + local name="$1" + shift + local log_file="$ARTIFACT_DIR/${name}.log" + log "phase_start=$name" + set +e + "$@" >"$log_file" 2>&1 + local rc=$? + set -e + cat "$log_file" + if [[ "$rc" -ne 0 ]]; then + log "phase_fail=$name exit=$rc" + collect_failure_diagnostics "$name" + write_summary "failed" "$name" + exit "$rc" + fi + log "phase_pass=$name" +} + +require_cmd bash +require_cmd kubectl +require_cmd docker + +READY_NODE_COUNT="$(ready_schedulable_node_count)" +if [[ -z "$ALPHA_NODE_SPECS" && -z "$LAUNCHER_EXTERNAL_ISCSI" && -z "$LAUNCHER_EXTERNAL_STATUS" && "${READY_NODE_COUNT:-0}" -gt 1 ]]; then + first_node="$(first_ready_node_with_internal_ip)" + if [[ -z "$first_node" ]]; then + write_summary "failed" "multi-node-internal-ip-discovery" + echo "multi-node activation requires at least one Ready schedulable node with non-loopback InternalIP" >&2 + exit 2 + fi + IFS='|' read -r DAY1_TARGET_NODE DAY1_TARGET_IP <<< "$first_node" + ALPHA_NODE_SPECS="${DAY1_TARGET_NODE}|${DAY1_TARGET_NODE}|${DAY1_TARGET_IP}|default" + LAUNCHER_EXTERNAL_ISCSI="1" + LAUNCHER_EXTERNAL_STATUS="1" + CHAP_USERNAME="${CHAP_USERNAME:-sw-block}" + CHAP_SECRET="${CHAP_SECRET:-sw-block-alpha-${RANDOM}-${RANDOM}-${RANDOM}}" + DAY1_NETWORK_MODE="external-iscsi" +fi +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + DAY1_NETWORK_MODE="external-iscsi" + CHAP_USERNAME="${CHAP_USERNAME:-sw-block}" + CHAP_SECRET="${CHAP_SECRET:-sw-block-alpha-${RANDOM}-${RANDOM}-${RANDOM}}" +fi + +log "artifact_dir=$ARTIFACT_DIR" +log "root=$ROOT" +log "image_mode=$IMAGE_MODE" +log "image=$IMAGE" +log "csi_image=$CSI_IMAGE" +log "import_k3s=$IMPORT_K3S" +log "storageclass=$STORAGECLASS_NAME" +log "replication_ack=$REPLICATION_ACK" +log "day1_network_mode=$DAY1_NETWORK_MODE" +log "day1_target_node=${DAY1_TARGET_NODE:-unknown}" +log "day1_target_ip=${DAY1_TARGET_IP:-unknown}" + +if [[ "$IMAGE_MODE" == "published" ]]; then + run_phase preflight bash "$ROOT/scripts/preflight-k8s-alpha.sh" --ghcr +else + run_phase preflight bash "$ROOT/scripts/preflight-k8s-alpha.sh" --local-k3s +fi + +if [[ "$IMAGE_MODE" == "local" ]]; then + BUILD_DIR="$ARTIFACT_DIR/build" + mkdir -p "$BUILD_DIR" + run_phase build env \ + SW_BLOCK_ARTIFACT_DIR="$BUILD_DIR" \ + SW_BLOCK_IMAGE="$IMAGE" \ + SW_BLOCK_CSI_IMAGE="$CSI_IMAGE" \ + SW_BLOCK_IMPORT_K3S="$IMPORT_K3S" \ + SW_BLOCK_IMPORT_K3S_NODES="${SW_BLOCK_IMPORT_K3S_NODES:-}" \ + SW_BLOCK_IMPORT_K3S_SSH_USER="${SW_BLOCK_IMPORT_K3S_SSH_USER:-}" \ + SW_BLOCK_IMPORT_K3S_SSH_KEY="${SW_BLOCK_IMPORT_K3S_SSH_KEY:-}" \ + bash "$ROOT/scripts/build-alpha-images.sh" "$ROOT" + + if [[ -f "$BUILD_DIR/alpha-images.env" ]]; then + set -a + # shellcheck disable=SC1091 + . "$BUILD_DIR/alpha-images.env" + set +a + IMAGE="${SW_BLOCK_IMAGE:-$IMAGE}" + CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-$CSI_IMAGE}" + fi +else + { + echo "SW_BLOCK_IMAGE=$IMAGE" + echo "SW_BLOCK_CSI_IMAGE=$CSI_IMAGE" + echo "SW_BLOCK_ACTIVATION_IMAGE_MODE=published" + echo "SW_BLOCK_IMPORT_K3S=$IMPORT_K3S" + } >"$ARTIFACT_DIR/published-images.env" + log "phase_skip=build reason=published-images image=$IMAGE csi_image=$CSI_IMAGE" +fi + +INSTALL_DIR="$ARTIFACT_DIR/install" +mkdir -p "$INSTALL_DIR" +run_phase install env \ + SW_BLOCK_ARTIFACT_DIR="$INSTALL_DIR" \ + SW_BLOCK_IMAGE="$IMAGE" \ + SW_BLOCK_CSI_IMAGE="$CSI_IMAGE" \ + SW_BLOCK_ALPHA_REPLICATION_ACK="$REPLICATION_ACK" \ + SW_BLOCK_ALPHA_NODE_SPECS="$ALPHA_NODE_SPECS" \ + SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI="$LAUNCHER_EXTERNAL_ISCSI" \ + SW_BLOCK_LAUNCHER_EXTERNAL_STATUS="$LAUNCHER_EXTERNAL_STATUS" \ + SW_BLOCK_ISCSI_CHAP_SECRET_NAME="$CHAP_SECRET_NAME" \ + SW_BLOCK_ISCSI_CHAP_USERNAME="$CHAP_USERNAME" \ + SW_BLOCK_ISCSI_CHAP_SECRET="$CHAP_SECRET" \ + SW_BLOCK_APP_NAMESPACE="$APP_NAMESPACE" \ + bash "$ROOT/scripts/install-k8s-alpha.sh" "$ROOT" + +STORAGECLASS_RENDERED="$ARTIFACT_DIR/storageclass.rendered.yaml" +sed "s/name: sw-block-dynamic/name: ${STORAGECLASS_NAME}/" \ + "$ROOT/deploy/k8s/alpha/storageclass.yaml" >"$STORAGECLASS_RENDERED" +if [[ -n "$CHAP_SECRET" ]]; then + inject_node_stage_secret_into_storageclass "$STORAGECLASS_RENDERED" "$STORAGECLASS_RENDERED.tmp" "$CHAP_SECRET_NAME" "$APP_NAMESPACE" + mv "$STORAGECLASS_RENDERED.tmp" "$STORAGECLASS_RENDERED" +fi +run_phase storageclass kubectl apply -f "$STORAGECLASS_RENDERED" + +{ + kubectl get nodes -o wide + kubectl -n kube-system get deploy sw-blockmaster sw-block-csi-controller -o wide + kubectl -n kube-system get ds sw-block-csi-node -o wide + kubectl get sc "$STORAGECLASS_NAME" -o wide +} >"$ARTIFACT_DIR/readiness.txt" 2>&1 || true + +write_summary "ok" +cat "$ARTIFACT_DIR/activation-summary.txt" +log "PASS: seaweed-block alpha activation complete" diff --git a/seaweed-block/scripts/build-alpha-images.sh b/seaweed-block/scripts/build-alpha-images.sh index 9a7cd796ef..ce944f7377 100755 --- a/seaweed-block/scripts/build-alpha-images.sh +++ b/seaweed-block/scripts/build-alpha-images.sh @@ -6,6 +6,10 @@ IMAGE="${SW_BLOCK_IMAGE:-sw-block:local}" CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-sw-block-csi:local}" ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${SW_BLOCK_BUILD_ARTIFACT_DIR:-}}" IMPORT_K3S="${SW_BLOCK_IMPORT_K3S:-0}" +IMPORT_K3S_NODES="${SW_BLOCK_IMPORT_K3S_NODES:-}" +IMPORT_K3S_SSH_USER="${SW_BLOCK_IMPORT_K3S_SSH_USER:-${USER:-}}" +IMPORT_K3S_SSH_KEY="${SW_BLOCK_IMPORT_K3S_SSH_KEY:-}" +IMPORT_K3S_REMOTE_DIR="${SW_BLOCK_IMPORT_K3S_REMOTE_DIR:-/tmp/sw-block-alpha-images}" if [[ -n "$ARTIFACT_DIR" ]]; then mkdir -p "$ARTIFACT_DIR" @@ -15,6 +19,7 @@ echo "[alpha-build] root=$ROOT" echo "[alpha-build] image=$IMAGE" echo "[alpha-build] csi_image=$CSI_IMAGE" echo "[alpha-build] import_k3s=$IMPORT_K3S" +echo "[alpha-build] import_k3s_nodes=${IMPORT_K3S_NODES:-}" docker build -t "$IMAGE" -f "$ROOT/deploy/k8s/g15b/Dockerfile.sw-block" "$ROOT" docker build -t "$CSI_IMAGE" -f "$ROOT/deploy/k8s/g15b/Dockerfile.blockcsi" "$ROOT" @@ -25,6 +30,8 @@ record_build_evidence() { { echo "SW_BLOCK_IMAGE=$IMAGE" echo "SW_BLOCK_CSI_IMAGE=$CSI_IMAGE" + echo "SW_BLOCK_IMPORT_K3S=$IMPORT_K3S" + echo "SW_BLOCK_IMPORT_K3S_NODES=$IMPORT_K3S_NODES" echo "SW_BLOCK_IMAGE_ID=$(docker image inspect "$IMAGE" --format '{{.Id}}')" echo "SW_BLOCK_CSI_IMAGE_ID=$(docker image inspect "$CSI_IMAGE" --format '{{.Id}}')" if git -C "$ROOT" rev-parse --git-dir >/dev/null 2>&1; then @@ -46,9 +53,9 @@ import_k3s_image() { local log_name="$2" local -a ctr=() if command -v sudo >/dev/null 2>&1 && sudo -n k3s --version >/dev/null 2>&1; then - ctr=(sudo -n k3s ctr images import -) + ctr=(sudo -n k3s ctr -n k8s.io images import -) elif command -v k3s >/dev/null 2>&1 && k3s --version >/dev/null 2>&1; then - ctr=(k3s ctr images import -) + ctr=(k3s ctr -n k8s.io images import -) else echo "SW_BLOCK_IMPORT_K3S=1 requires k3s or passwordless sudo k3s on PATH" >&2 exit 2 @@ -62,6 +69,96 @@ import_k3s_image() { fi } +local_k3s_available() { + if command -v sudo >/dev/null 2>&1 && sudo -n k3s --version >/dev/null 2>&1; then + return 0 + fi + command -v k3s >/dev/null 2>&1 && k3s --version >/dev/null 2>&1 +} + +verify_local_k3s_image() { + local image="$1" + local log_name="$2" + local -a ctr=() + if command -v sudo >/dev/null 2>&1 && sudo -n k3s --version >/dev/null 2>&1; then + ctr=(sudo -n k3s ctr -n k8s.io images ls -q) + elif command -v k3s >/dev/null 2>&1 && k3s --version >/dev/null 2>&1; then + ctr=(k3s ctr -n k8s.io images ls -q) + else + echo "SW_BLOCK_IMPORT_K3S=1 requires k3s or passwordless sudo k3s on PATH" >&2 + exit 2 + fi + + echo "[alpha-build] k3s_verify image=$image node=local" + if [[ -n "$ARTIFACT_DIR" ]]; then + "${ctr[@]}" >"$ARTIFACT_DIR/$log_name" 2>&1 + awk -v image="$image" '$0 == image || $0 ~ "/" image "$" { found=1 } END { exit !found }' "$ARTIFACT_DIR/$log_name" + else + "${ctr[@]}" | awk -v image="$image" '$0 == image || $0 ~ "/" image "$" { found=1 } END { exit !found }' + fi +} + +ssh_target_for_node() { + local node="$1" + if [[ -n "$IMPORT_K3S_SSH_USER" ]]; then + printf '%s@%s' "$IMPORT_K3S_SSH_USER" "$node" + else + printf '%s' "$node" + fi +} + +run_ssh() { + local target="$1" + shift + local -a opts=(-o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new) + if [[ -n "$IMPORT_K3S_SSH_KEY" ]]; then + opts=(-i "$IMPORT_K3S_SSH_KEY" "${opts[@]}") + fi + ssh "${opts[@]}" "$target" "$@" +} + +import_k3s_image_to_node() { + local image="$1" + local node="$2" + local safe_image + local tar_name + local target + local log_name + safe_image="$(printf '%s' "$image" | tr '/:' '__')" + tar_name="${safe_image}.tar" + target="$(ssh_target_for_node "$node")" + log_name="k3s-import-${safe_image}-${node}.log" + + echo "[alpha-build] k3s_import image=$image node=$node" + if [[ -n "$ARTIFACT_DIR" ]]; then + { + run_ssh "$target" "mkdir -p '$IMPORT_K3S_REMOTE_DIR'" + docker save "$image" | run_ssh "$target" "cat > '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + run_ssh "$target" "sudo -n k3s ctr -n k8s.io images import '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + run_ssh "$target" "sudo -n k3s ctr -n k8s.io images ls -q | awk -v image='$image' '\$0 == image || \$0 ~ \"/\" image \"\$\" { found=1 } END { exit !found }'" + run_ssh "$target" "rm -f '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + } >"$ARTIFACT_DIR/$log_name" 2>&1 + else + run_ssh "$target" "mkdir -p '$IMPORT_K3S_REMOTE_DIR'" + docker save "$image" | run_ssh "$target" "cat > '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + run_ssh "$target" "sudo -n k3s ctr -n k8s.io images import '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + run_ssh "$target" "sudo -n k3s ctr -n k8s.io images ls -q | awk -v image='$image' '\$0 == image || \$0 ~ \"/\" image \"\$\" { found=1 } END { exit !found }'" + run_ssh "$target" "rm -f '$IMPORT_K3S_REMOTE_DIR/$tar_name'" + fi +} + +import_k3s_images_to_nodes() { + local nodes_csv="$1" + local node + IFS=',' read -r -a nodes <<<"$nodes_csv" + for node in "${nodes[@]}"; do + node="${node//[[:space:]]/}" + [[ -n "$node" ]] || continue + import_k3s_image_to_node "$IMAGE" "$node" + import_k3s_image_to_node "$CSI_IMAGE" "$node" + done +} + record_build_evidence if [[ -n "${SW_BLOCK_KIND_CLUSTER:-}" ]]; then @@ -74,6 +171,18 @@ if [[ -n "${SW_BLOCK_KIND_CLUSTER:-}" ]]; then fi if [[ "$IMPORT_K3S" == "1" || "$IMPORT_K3S" == "true" ]]; then - import_k3s_image "$IMAGE" "k3s-import-sw-block.log" - import_k3s_image "$CSI_IMAGE" "k3s-import-sw-block-csi.log" + if [[ -n "$IMPORT_K3S_NODES" ]]; then + if local_k3s_available; then + import_k3s_image "$IMAGE" "k3s-import-local-sw-block.log" + verify_local_k3s_image "$IMAGE" "k3s-images-local-sw-block.txt" + import_k3s_image "$CSI_IMAGE" "k3s-import-local-sw-block-csi.log" + verify_local_k3s_image "$CSI_IMAGE" "k3s-images-local-sw-block-csi.txt" + fi + import_k3s_images_to_nodes "$IMPORT_K3S_NODES" + else + import_k3s_image "$IMAGE" "k3s-import-sw-block.log" + verify_local_k3s_image "$IMAGE" "k3s-images-sw-block.txt" + import_k3s_image "$CSI_IMAGE" "k3s-import-sw-block-csi.log" + verify_local_k3s_image "$CSI_IMAGE" "k3s-images-sw-block-csi.txt" + fi fi diff --git a/seaweed-block/scripts/install-k8s-alpha.sh b/seaweed-block/scripts/install-k8s-alpha.sh index 35857ded7d..13daf2c014 100755 --- a/seaweed-block/scripts/install-k8s-alpha.sh +++ b/seaweed-block/scripts/install-k8s-alpha.sh @@ -7,6 +7,18 @@ IMAGE="${SW_BLOCK_IMAGE:-ghcr.io/seaweedfs/seaweed-block:alpha}" CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-ghcr.io/seaweedfs/seaweed-block-csi:alpha}" LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-1}" LAUNCHER_STATE_HOSTPATH="${SW_BLOCK_LAUNCHER_STATE_HOSTPATH:-}" +REPLICATION_ACK="${SW_BLOCK_ALPHA_REPLICATION_ACK:-best-effort}" +LOGICAL_SERVERS="${SW_BLOCK_ALPHA_LOGICAL_SERVERS:-1}" +NODE_SPECS="${SW_BLOCK_ALPHA_NODE_SPECS:-}" +EXPECTED_SLOTS_PER_VOLUME="${SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME:-$LOGICAL_SERVERS}" +STAGE2_MULTIPATH="${SW_BLOCK_STAGE2_MULTIPATH:-0}" +REJECT_LOOPBACK_PUBLISH_TARGETS="${SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS:-0}" +LAUNCHER_EXTERNAL_ISCSI="${SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI:-0}" +LAUNCHER_EXTERNAL_STATUS="${SW_BLOCK_LAUNCHER_EXTERNAL_STATUS:-0}" +CHAP_SECRET_NAME="${SW_BLOCK_ISCSI_CHAP_SECRET_NAME:-sw-block-iscsi-chap}" +CHAP_USERNAME="${SW_BLOCK_ISCSI_CHAP_USERNAME:-}" +CHAP_SECRET="${SW_BLOCK_ISCSI_CHAP_SECRET:-}" +APP_NAMESPACE="${SW_BLOCK_APP_NAMESPACE:-default}" mkdir -p "$ARTIFACT_DIR" @@ -29,19 +41,161 @@ sed_escape() { printf '%s' "$1" | sed 's/[\/&]/\\&/g' } +render_cluster_spec_nodes() { + local node_name="$1" + local count="$2" + local i server_id data_port ctrl_port pool_id + echo " nodes:" + for i in $(seq 1 "$count"); do + if [[ "$count" == "1" ]]; then + server_id="$node_name" + pool_id="default" + else + server_id="${node_name}-r${i}" + pool_id="default-r${i}" + fi + data_port=$((19101 + (i - 1) * 2)) + ctrl_port=$((19102 + (i - 1) * 2)) + cat <&2 + exit 2 + fi + case "$host" in + localhost|localhost.*|127.*|0.0.0.0|::1|\[::1\]) + echo "SW_BLOCK_ALPHA_NODE_SPECS host_or_ip must be non-loopback and non-unspecified for node-loss gates; got: $host" >&2 + exit 2 + ;; + esac + if [[ -z "$pool_id" ]]; then + pool_id="default-${server_id}" + fi + data_port=$((19101 + i * 2)) + ctrl_port=$((19102 + i * 2)) + cat <&2 + exit 2 + ;; +esac +case "$EXPECTED_SLOTS_PER_VOLUME" in + ''|*[!0-9]*|0) + echo "SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME must be a positive integer, got: $EXPECTED_SLOTS_PER_VOLUME" >&2 + exit 2 + ;; +esac +case "$REPLICATION_ACK" in + best-effort|sync-quorum|sync-all) + ;; + *) + echo "SW_BLOCK_ALPHA_REPLICATION_ACK must be best-effort, sync-quorum, or sync-all; got: $REPLICATION_ACK" >&2 + exit 2 + ;; +esac + NODE_NAME="${SW_BLOCK_ALPHA_NODE_NAME:-$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')}" +if [[ -n "$NODE_SPECS" ]]; then + NODE_SPEC_COUNT="$(node_spec_count "$NODE_SPECS")" + if [[ "$NODE_SPEC_COUNT" == "0" ]]; then + echo "SW_BLOCK_ALPHA_NODE_SPECS did not contain any node entries" >&2 + exit 2 + fi + if [[ -z "${SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME:-}" ]]; then + EXPECTED_SLOTS_PER_VOLUME="$NODE_SPEC_COUNT" + fi +fi +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + if [[ -z "$CHAP_USERNAME" || -z "$CHAP_SECRET" ]]; then + echo "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI requires SW_BLOCK_ISCSI_CHAP_USERNAME and SW_BLOCK_ISCSI_CHAP_SECRET" >&2 + exit 2 + fi +fi +if [[ "$LAUNCHER_EXTERNAL_STATUS" == "1" || "$LAUNCHER_EXTERNAL_STATUS" == "true" ]]; then + if [[ "$LAUNCHER_EXTERNAL_ISCSI" != "1" && "$LAUNCHER_EXTERNAL_ISCSI" != "true" ]]; then + echo "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS requires SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1" >&2 + exit 2 + fi +fi STACK_RENDERED="$ARTIFACT_DIR/block-stack.rendered.yaml" CSI_CONTROLLER_RENDERED="$ARTIFACT_DIR/csi-controller.rendered.yaml" CSI_NODE_RENDERED="$ARTIFACT_DIR/csi-node.rendered.yaml" IMAGE_SED="$(sed_escape "$IMAGE")" CSI_IMAGE_SED="$(sed_escape "$CSI_IMAGE")" +CLUSTER_SPEC_NODES="$ARTIFACT_DIR/cluster-spec-nodes.rendered.yaml" +if [[ -n "$NODE_SPECS" ]]; then + render_cluster_spec_node_specs "$NODE_SPECS" >"$CLUSTER_SPEC_NODES" +else + render_cluster_spec_nodes "$NODE_NAME" "$LOGICAL_SERVERS" >"$CLUSTER_SPEC_NODES" +fi + sed -e "s/__NODE_NAME__/${NODE_NAME}/g" \ + -e "s/__EXPECTED_SLOTS_PER_VOLUME__/${EXPECTED_SLOTS_PER_VOLUME}/g" \ + -e "s/__REPLICATION_ACK__/${REPLICATION_ACK}/g" \ -e "s/sw-block:local/${IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ - "$ROOT/deploy/k8s/alpha/block-stack.yaml" >"$STACK_RENDERED" + "$ROOT/deploy/k8s/alpha/block-stack.yaml" >"$STACK_RENDERED.tmp" +awk -v nodes_file="$CLUSTER_SPEC_NODES" ' + /__CLUSTER_SPEC_NODES__/ { + while ((getline line < nodes_file) > 0) print line + close(nodes_file) + next + } + { print } +' "$STACK_RENDERED.tmp" >"$STACK_RENDERED" +rm -f "$STACK_RENDERED.tmp" if [[ "$LAUNCHER_PVC_OWNER_REF" == "1" || "$LAUNCHER_PVC_OWNER_REF" == "true" ]]; then awk '/--launcher-namespace=/{print; print " - \"--launcher-pvc-owner-ref\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" @@ -52,6 +206,17 @@ if [[ -n "$LAUNCHER_STATE_HOSTPATH" ]]; then mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" grep -q -- '--launcher-state-hostpath=' "$STACK_RENDERED" || { echo "failed to inject --launcher-state-hostpath into $STACK_RENDERED" >&2; exit 1; } fi +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + awk -v secret="$CHAP_SECRET_NAME" '/--launcher-iscsi-port-base=/{print; print " - \"--launcher-external-iscsi\""; print " - \"--launcher-iscsi-chap-secret-name=" secret "\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" + mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" + grep -q -- '--launcher-external-iscsi' "$STACK_RENDERED" || { echo "failed to inject --launcher-external-iscsi into $STACK_RENDERED" >&2; exit 1; } + grep -q -- '--launcher-iscsi-chap-secret-name' "$STACK_RENDERED" || { echo "failed to inject --launcher-iscsi-chap-secret-name into $STACK_RENDERED" >&2; exit 1; } +fi +if [[ "$LAUNCHER_EXTERNAL_STATUS" == "1" || "$LAUNCHER_EXTERNAL_STATUS" == "true" ]]; then + awk '/--launcher-status/{print; print " - \"--launcher-external-status\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" + mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" + grep -q -- '--launcher-external-status' "$STACK_RENDERED" || { echo "failed to inject --launcher-external-status into $STACK_RENDERED" >&2; exit 1; } +fi sed -e "s/sw-block-csi:local/${CSI_IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ "$ROOT/deploy/k8s/alpha/csi-controller.yaml" >"$CSI_CONTROLLER_RENDERED" @@ -63,14 +228,39 @@ fi sed -e "s/sw-block-csi:local/${CSI_IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ "$ROOT/deploy/k8s/alpha/csi-node.yaml" >"$CSI_NODE_RENDERED" +if [[ "$STAGE2_MULTIPATH" == "1" || "$STAGE2_MULTIPATH" == "true" ]]; then + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--stage2-multipath\""; next} {print}' "$CSI_CONTROLLER_RENDERED" >"$CSI_CONTROLLER_RENDERED.tmp" + mv "$CSI_CONTROLLER_RENDERED.tmp" "$CSI_CONTROLLER_RENDERED" + grep -q -- '--stage2-multipath' "$CSI_CONTROLLER_RENDERED" || { echo "failed to inject --stage2-multipath into $CSI_CONTROLLER_RENDERED" >&2; exit 1; } + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--stage2-multipath\""; next} {print}' "$CSI_NODE_RENDERED" >"$CSI_NODE_RENDERED.tmp" + mv "$CSI_NODE_RENDERED.tmp" "$CSI_NODE_RENDERED" + grep -q -- '--stage2-multipath' "$CSI_NODE_RENDERED" || { echo "failed to inject --stage2-multipath into $CSI_NODE_RENDERED" >&2; exit 1; } +fi +if [[ "$REJECT_LOOPBACK_PUBLISH_TARGETS" == "1" || "$REJECT_LOOPBACK_PUBLISH_TARGETS" == "true" ]]; then + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--reject-loopback-publish-targets\""; next} {print}' "$CSI_CONTROLLER_RENDERED" >"$CSI_CONTROLLER_RENDERED.tmp" + mv "$CSI_CONTROLLER_RENDERED.tmp" "$CSI_CONTROLLER_RENDERED" + grep -q -- '--reject-loopback-publish-targets' "$CSI_CONTROLLER_RENDERED" || { echo "failed to inject --reject-loopback-publish-targets into $CSI_CONTROLLER_RENDERED" >&2; exit 1; } + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--reject-loopback-publish-targets\""; next} {print}' "$CSI_NODE_RENDERED" >"$CSI_NODE_RENDERED.tmp" + mv "$CSI_NODE_RENDERED.tmp" "$CSI_NODE_RENDERED" + grep -q -- '--reject-loopback-publish-targets' "$CSI_NODE_RENDERED" || { echo "failed to inject --reject-loopback-publish-targets into $CSI_NODE_RENDERED" >&2; exit 1; } +fi log "artifact_dir=$ARTIFACT_DIR" log "root=$ROOT" log "node=$NODE_NAME" +log "logical_servers=$LOGICAL_SERVERS" +log "node_specs=${NODE_SPECS:-}" +log "expected_slots_per_volume=$EXPECTED_SLOTS_PER_VOLUME" +log "replication_ack=$REPLICATION_ACK" log "image=$IMAGE" log "csi_image=$CSI_IMAGE" log "launcher_pvc_owner_ref=$LAUNCHER_PVC_OWNER_REF" log "launcher_state_hostpath=${LAUNCHER_STATE_HOSTPATH:-}" +log "launcher_external_iscsi=$LAUNCHER_EXTERNAL_ISCSI" +log "launcher_external_status=$LAUNCHER_EXTERNAL_STATUS" +log "chap_enabled=$([[ -n "$CHAP_SECRET" ]] && echo 1 || echo 0)" +log "stage2_multipath=$STAGE2_MULTIPATH" +log "reject_loopback_publish_targets=$REJECT_LOOPBACK_PUBLISH_TARGETS" kubectl version --client=true >"$ARTIFACT_DIR/kubectl-version.txt" 2>&1 || true kubectl get nodes -o wide >"$ARTIFACT_DIR/nodes.before.txt" @@ -89,6 +279,16 @@ kubectl apply -f "$CSI_NODE_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-node.log" kubectl -n kube-system wait --for=condition=available deploy/sw-block-csi-controller --timeout=120s kubectl -n kube-system rollout status ds/sw-block-csi-node --timeout=120s +if [[ -n "$CHAP_SECRET" ]]; then + log "apply iSCSI CHAP Secret" + for secret_ns in "$APP_NAMESPACE" kube-system; do + kubectl -n "$secret_ns" create secret generic "$CHAP_SECRET_NAME" \ + --from-literal=chapUsername="$CHAP_USERNAME" \ + --from-literal=chapSecret="$CHAP_SECRET" \ + --dry-run=client -o yaml | kubectl apply -f - | tee -a "$ARTIFACT_DIR/apply-chap-secret.log" + done +fi + log "PASS: seaweed-block alpha stack installed" log "next: create a PVC; blockmaster reconciles the generated blockvolume workload" log "artifacts=$ARTIFACT_DIR" diff --git a/seaweed-block/scripts/preflight-node-loss-lab.sh b/seaweed-block/scripts/preflight-node-loss-lab.sh new file mode 100644 index 0000000000..fcd60dd25f --- /dev/null +++ b/seaweed-block/scripts/preflight-node-loss-lab.sh @@ -0,0 +1,215 @@ +#!/usr/bin/env bash +set -euo pipefail + +MIN_K8S_NODES=3 +ENV_OUT="" +PLACEMENT_OUT="" +TOPOLOGY_OUT="" +TOPOLOGY_JSON_OUT="" + +usage() { + cat >&2 <<'EOF' +usage: bash scripts/preflight-node-loss-lab.sh [options] + +Checks whether the current Kubernetes context is eligible for the Node-Loss +Survival MVP D3/D4 gates. + +Exit codes: + 0 eligible; env/placement outputs were written when requested + 2 invalid arguments or missing required tools + 3 lab is reachable but not eligible for the requested node-loss gate + +Options: + --min-k8s-nodes N Required Ready schedulable Kubernetes nodes (default: 3) + --env-out PATH Write NODE_SPECS / APP_NODE shell env file + --placement-out PATH Write human-readable placement evidence + --topology-out PATH Write `kubectl get nodes -o wide` + --topology-json-out PATH Write `kubectl get nodes -o json` +EOF +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --min-k8s-nodes) + MIN_K8S_NODES="${2:-}" + shift 2 + ;; + --env-out) + ENV_OUT="${2:-}" + shift 2 + ;; + --placement-out) + PLACEMENT_OUT="${2:-}" + shift 2 + ;; + --topology-out) + TOPOLOGY_OUT="${2:-}" + shift 2 + ;; + --topology-json-out) + TOPOLOGY_JSON_OUT="${2:-}" + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + *) + usage + exit 2 + ;; + esac +done + +case "$MIN_K8S_NODES" in + ''|*[!0-9]*|0) + echo "min-k8s-nodes must be a positive integer, got: $MIN_K8S_NODES" >&2 + exit 2 + ;; +esac + +if [[ -z "${KUBECONFIG:-}" && -f /etc/rancher/k3s/k3s.yaml ]]; then + export KUBECONFIG=/etc/rancher/k3s/k3s.yaml +fi + +require_cmd() { + if ! command -v "$1" >/dev/null 2>&1; then + echo "missing required command: $1" >&2 + exit 2 + fi +} + +require_cmd kubectl +require_cmd python3 + +tmp_dir="$(mktemp -d /tmp/sw-block-node-loss-preflight.XXXXXX)" +cleanup() { + rm -rf "$tmp_dir" +} +trap cleanup EXIT + +wide_path="${TOPOLOGY_OUT:-$tmp_dir/nodes.wide.txt}" +json_path="${TOPOLOGY_JSON_OUT:-$tmp_dir/nodes.json}" +mkdir -p "$(dirname "$wide_path")" "$(dirname "$json_path")" + +kubectl get nodes -o wide >"$wide_path" +kubectl get nodes -o json >"$json_path" + +python3 - "$json_path" "$MIN_K8S_NODES" "${ENV_OUT:-}" "${PLACEMENT_OUT:-}" <<'PY' +import ipaddress +import json +import pathlib +import shlex +import sys + +json_path = pathlib.Path(sys.argv[1]) +minimum = int(sys.argv[2]) +env_out = sys.argv[3] +placement_out = sys.argv[4] + +data = json.loads(json_path.read_text()) +selected = [] +seen_nodes = set() + +for item in data.get("items", []): + name = item.get("metadata", {}).get("name", "") + labels = item.get("metadata", {}).get("labels", {}) + spec = item.get("spec", {}) + if not name or spec.get("unschedulable"): + continue + ready = any( + c.get("type") == "Ready" and c.get("status") == "True" + for c in item.get("status", {}).get("conditions", []) + ) + if not ready: + continue + addresses = item.get("status", {}).get("addresses", []) + internal = next((a.get("address", "") for a in addresses if a.get("type") == "InternalIP"), "") + try: + ip = ipaddress.ip_address(internal) + except ValueError: + continue + if ip.is_loopback or ip.is_unspecified: + continue + physical = ( + labels.get("sw-block.seaweedfs.com/physical-host") + or labels.get("topology.kubernetes.io/zone") + or labels.get("kubernetes.io/hostname") + or name + ) + if name in seen_nodes: + continue + seen_nodes.add(name) + selected.append((name, internal, physical)) + +if len(selected) < minimum: + ineligible_text = ( + "node_loss_topology_eligible=false\n" + "node_loss_lab_eligible=false\n" + f"reason=requires_{minimum}_ready_schedulable_nodes_with_non_loopback_internal_ip\n" + f"found={len(selected)}\n" + "kubernetes_node_loss_claimed=false\n" + "physical_host_loss_claimed=false\n" + ) + if placement_out: + pathlib.Path(placement_out).parent.mkdir(parents=True, exist_ok=True) + pathlib.Path(placement_out).write_text(ineligible_text) + if env_out: + try: + pathlib.Path(env_out).unlink() + except FileNotFoundError: + pass + print(ineligible_text, end="") + print( + f"node-loss lab preflight failed: requires {minimum} Ready schedulable nodes with non-loopback InternalIP; found {len(selected)}", + file=sys.stderr, + ) + raise SystemExit(3) + +selected = selected[:minimum] +physical_domains = sorted({physical for _, _, physical in selected}) +physical_shape = "full-physical-host" if len(physical_domains) >= minimum else "shared-physical-host" +specs = [] +placement = [] +import_nodes = [] +for idx, (name, ip, physical) in enumerate(selected, 1): + replica = f"r{idx}" + server = f"node-loss-{replica}" + pool = f"node-loss-pool-{idx}" + specs.append(f"{server}|{name}|{ip}|{pool}") + import_nodes.append(ip) + placement.append(f"replica={replica} server={server} node={name} host={ip} physical_host={physical} pool={pool}") + +env_text = ( + "NODE_SPECS=" + shlex.quote(";".join(specs)) + "\n" + "K3S_IMPORT_NODES=" + shlex.quote(",".join(import_nodes)) + "\n" + "APP_NODE=" + shlex.quote(selected[0][0]) + "\n" + "SURVIVOR_APP_NODE=" + shlex.quote(selected[1][0] if len(selected) > 1 else selected[0][0]) + "\n" + "PHYSICAL_DOMAIN_COUNT=" + shlex.quote(str(len(physical_domains))) + "\n" + "PHYSICAL_DOMAIN_SHAPE=" + shlex.quote(physical_shape) + "\n" + "PHYSICAL_HOST_LOSS_CLAIMED=false\n" +) +placement_text = ( + "node_loss_topology_eligible=true\n" + "node_loss_lab_eligible=true\n" + f"selected_node_count={len(selected)}\n" + f"app_node={selected[0][0]}\n" + f"survivor_app_node={selected[1][0] if len(selected) > 1 else selected[0][0]}\n" + f"k3s_import_nodes={','.join(import_nodes)}\n" + f"physical_domain_count={len(physical_domains)}\n" + f"physical_domain_shape={physical_shape}\n" + "kubernetes_node_loss_claimed=true\n" + "physical_host_loss_claimed=false\n" + + "\n".join(placement) + + "\n" +) + +if env_out: + pathlib.Path(env_out).parent.mkdir(parents=True, exist_ok=True) + pathlib.Path(env_out).write_text(env_text) +if placement_out: + pathlib.Path(placement_out).parent.mkdir(parents=True, exist_ok=True) + pathlib.Path(placement_out).write_text(placement_text) + +print(placement_text, end="") +PY diff --git a/seaweed-block/scripts/run-alpha-app-demo.sh b/seaweed-block/scripts/run-alpha-app-demo.sh index df26c83f9c..7c34edd006 100755 --- a/seaweed-block/scripts/run-alpha-app-demo.sh +++ b/seaweed-block/scripts/run-alpha-app-demo.sh @@ -9,6 +9,17 @@ IMAGE="${SW_BLOCK_IMAGE:-sw-block:local}" CSI_IMAGE="${SW_BLOCK_CSI_IMAGE:-sw-block-csi:local}" LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-0}" LAUNCHER_STATE_HOSTPATH="${SW_BLOCK_LAUNCHER_STATE_HOSTPATH:-}" +REPLICATION_ACK="${SW_BLOCK_ALPHA_REPLICATION_ACK:-best-effort}" +LOGICAL_SERVERS="${SW_BLOCK_ALPHA_LOGICAL_SERVERS:-1}" +NODE_SPECS="${SW_BLOCK_ALPHA_NODE_SPECS:-}" +EXPECTED_SLOTS_PER_VOLUME="${SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME:-$LOGICAL_SERVERS}" +STAGE2_MULTIPATH="${SW_BLOCK_STAGE2_MULTIPATH:-0}" +REJECT_LOOPBACK_PUBLISH_TARGETS="${SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS:-0}" +LAUNCHER_EXTERNAL_ISCSI="${SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI:-0}" +LAUNCHER_EXTERNAL_STATUS="${SW_BLOCK_LAUNCHER_EXTERNAL_STATUS:-0}" +CHAP_SECRET_NAME="${SW_BLOCK_ISCSI_CHAP_SECRET_NAME:-sw-block-iscsi-chap}" +CHAP_USERNAME="${SW_BLOCK_ISCSI_CHAP_USERNAME:-}" +CHAP_SECRET="${SW_BLOCK_ISCSI_CHAP_SECRET:-}" RESTART_CSI_NODE_BEFORE_READER="${SW_BLOCK_RESTART_CSI_NODE_BEFORE_READER:-0}" RESTART_BLOCKVOLUME_BEFORE_READER="${SW_BLOCK_RESTART_BLOCKVOLUME_BEFORE_READER:-0}" COLLECT_INVENTORY_AFTER_RESTART="${SW_BLOCK_COLLECT_INVENTORY_AFTER_RESTART:-0}" @@ -20,6 +31,8 @@ MANUAL_APPLY_BLOCKVOLUMES="${SW_BLOCK_DEMO_MANUAL_APPLY_BLOCKVOLUMES:-0}" AFTER_BLOCKVOLUME_READY_CMD="${SW_BLOCK_DEMO_AFTER_BLOCKVOLUME_READY_CMD:-}" BREAK_AFTER_BLOCKVOLUME_READY="${SW_BLOCK_DEMO_BREAK_AFTER_BLOCKVOLUME_READY:-}" BREAK_AFTER_BLOCKVOLUME_RESTART="${SW_BLOCK_DEMO_BREAK_AFTER_BLOCKVOLUME_RESTART:-}" +FAIL_PRIMARY_BEFORE_READER="${SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER:-}" +REQUIRE_PROMOTION_READY_BEFORE_FAILURE="${SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE:-0}" WRITER_TIMEOUT="${SW_BLOCK_DEMO_WRITER_TIMEOUT:-240}" DELETE_ALL_BLOCKVOLUMES="${SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES:-0}" PIN_APP_NODE="${SW_BLOCK_DEMO_PIN_APP_NODE:-1}" @@ -45,7 +58,7 @@ if [[ "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFOR exit 2 fi fi -if [[ -n "$DEMO_STOP_AFTER" && "$DEMO_STOP_AFTER" != "blockvolume-ready" && "$DEMO_STOP_AFTER" != "reader-verified" ]]; then +if [[ -n "$DEMO_STOP_AFTER" && "$DEMO_STOP_AFTER" != "blockvolume-ready" && "$DEMO_STOP_AFTER" != "writer-verified" && "$DEMO_STOP_AFTER" != "promotion-ready" && "$DEMO_STOP_AFTER" != "reader-verified" ]]; then echo "unsupported SW_BLOCK_DEMO_STOP_AFTER value: $DEMO_STOP_AFTER" >&2 exit 2 fi @@ -57,6 +70,10 @@ if [[ -n "$BREAK_AFTER_BLOCKVOLUME_RESTART" && "$BREAK_AFTER_BLOCKVOLUME_RESTART echo "unsupported SW_BLOCK_DEMO_BREAK_AFTER_BLOCKVOLUME_RESTART value: $BREAK_AFTER_BLOCKVOLUME_RESTART" >&2 exit 2 fi +if [[ -n "$FAIL_PRIMARY_BEFORE_READER" && "$FAIL_PRIMARY_BEFORE_READER" != "scale-primary-to-zero" && "$FAIL_PRIMARY_BEFORE_READER" != "cordon-node-scale-primary-to-zero" ]]; then + echo "unsupported SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER value: $FAIL_PRIMARY_BEFORE_READER" >&2 + exit 2 +fi if [[ -z "$DEMO_STOP_AFTER" && ( "$KEEP_ON_STOP" == "1" || "$KEEP_ON_STOP" == "true" ) ]]; then echo "SW_BLOCK_DEMO_KEEP_ON_STOP requires SW_BLOCK_DEMO_STOP_AFTER" >&2 exit 2 @@ -84,6 +101,87 @@ sed_escape() { printf '%s' "$1" | sed 's/[\/&]/\\&/g' } +render_cluster_spec_nodes() { + local node_name="$1" + local count="$2" + local i server_id data_port ctrl_port pool_id + echo " nodes:" + for i in $(seq 1 "$count"); do + if [[ "$count" == "1" ]]; then + server_id="$node_name" + pool_id="default" + else + server_id="${node_name}-r${i}" + pool_id="default-r${i}" + fi + data_port=$((19101 + (i - 1) * 2)) + ctrl_port=$((19102 + (i - 1) * 2)) + cat <&2 + exit 2 + fi + case "$host" in + localhost|localhost.*|127.*|0.0.0.0|::1|\[::1\]) + echo "SW_BLOCK_ALPHA_NODE_SPECS host_or_ip must be non-loopback and non-unspecified for node-loss gates; got: $host" >&2 + exit 2 + ;; + esac + if [[ -z "$pool_id" ]]; then + pool_id="default-${server_id}" + fi + data_port=$((19101 + i * 2)) + ctrl_port=$((19102 + i * 2)) + cat <"$output" } +inject_node_stage_secret_into_storageclass() { + local input="$1" + local output="$2" + local secret="$3" + local namespace="$4" + awk -v secret="$secret" -v namespace="$namespace" ' + /^parameters:[[:space:]]*$/ { + print + print " csi.storage.k8s.io/node-stage-secret-name: \"" secret "\"" + print " csi.storage.k8s.io/node-stage-secret-namespace: \"" namespace "\"" + next + } + { print } + ' "$input" >"$output" +} + capture_once() { local path="$1" shift @@ -122,6 +236,7 @@ collect_logs() { capture_once "$ARTIFACT_DIR/reader.describe.txt" kubectl -n "$NAMESPACE" describe pod sw-block-demo-reader capture_once "$ARTIFACT_DIR/blockmaster.log" kubectl -n kube-system logs deploy/sw-blockmaster -c blockmaster capture_once "$ARTIFACT_DIR/blockcsi-controller.log" kubectl -n kube-system logs deploy/sw-block-csi-controller -c block-csi + capture_once "$ARTIFACT_DIR/blockcsi-node.log" kubectl -n kube-system logs ds/sw-block-csi-node -c block-csi --tail=-1 capture_once "$ARTIFACT_DIR/csi-provisioner.log" kubectl -n kube-system logs deploy/sw-block-csi-controller -c csi-provisioner capture_once "$ARTIFACT_DIR/csi-attacher.log" kubectl -n kube-system logs deploy/sw-block-csi-controller -c csi-attacher capture_once "$ARTIFACT_DIR/blockvolume-generated.log" kubectl -n "$BLOCKVOLUME_NAMESPACE" logs -l sw-block.seaweedfs.com/volume -c blockvolume --tail=-1 @@ -158,6 +273,37 @@ capture_iscsi_sessions_to() { fi } +capture_stage2_host_path_evidence() { + local label="$1" + capture_iscsi_sessions_to "$ARTIFACT_DIR/iscsi-sessions.${label}.txt" + if command -v sudo >/dev/null 2>&1; then + sudo multipath -ll >"$ARTIFACT_DIR/multipath.${label}.txt" 2>&1 || true + elif command -v multipath >/dev/null 2>&1; then + multipath -ll >"$ARTIFACT_DIR/multipath.${label}.txt" 2>&1 || true + else + echo "multipath unavailable" >"$ARTIFACT_DIR/multipath.${label}.txt" + fi + { + found=0 + for d in /dev/disk/by-path/*io.seaweedfs*; do + [ -e "$d" ] || continue + found=1 + raw="$(readlink -f "$d")" + echo "device=$raw source=$d" + if command -v sudo >/dev/null 2>&1; then + sudo sg_rtpg "$raw" || true + elif command -v sg_rtpg >/dev/null 2>&1; then + sg_rtpg "$raw" || true + else + echo "sg_rtpg unavailable" + fi + done + if [ "$found" -eq 0 ]; then + echo "no seaweed iSCSI by-path devices" + fi + } >"$ARTIFACT_DIR/sg-rtpg.${label}.txt" 2>&1 +} + wait_no_swblock_iscsi_sessions() { local path="$1" local timeout_s="$2" @@ -291,11 +437,26 @@ run_sw_block_ops_inventory() { local namespace="$1" local master_addr="$2" local out_dir="$3" + local extra=() + local raw_frontiers="${SW_BLOCK_OPS_INVENTORY_REQUIRED_FRONTIERS:-}" + local claim_profile="${SW_BLOCK_OPS_INVENTORY_CLAIM_PROFILE:-}" + if [[ -n "$raw_frontiers" ]]; then + local frontier + IFS=',' read -r -a extra_frontiers <<<"$raw_frontiers" + for frontier in "${extra_frontiers[@]}"; do + frontier="${frontier#"${frontier%%[![:space:]]*}"}" + frontier="${frontier%"${frontier##*[![:space:]]}"}" + [[ -n "$frontier" ]] && extra+=(--required-frontier "$frontier") + done + fi + if [[ -n "$claim_profile" ]]; then + extra+=(--claim-profile "$claim_profile") + fi if command -v sw-block >/dev/null 2>&1; then - sw-block ops inventory --namespace "$namespace" --master "$master_addr" --out "$out_dir" --timeout 30s + sw-block ops inventory --namespace "$namespace" --master "$master_addr" --out "$out_dir" --timeout 30s "${extra[@]}" return $? fi - go run ./cmd/sw-block ops inventory --namespace "$namespace" --master "$master_addr" --out "$out_dir" --timeout 30s + go run ./cmd/sw-block ops inventory --namespace "$namespace" --master "$master_addr" --out "$out_dir" --timeout 30s "${extra[@]}" } collect_ops_status_bundle() { @@ -394,6 +555,564 @@ collect_ops_inventory_on_failure() { collect_ops_inventory_bundle "$ARTIFACT_DIR/ops-inventory-on-failure" } +inventory_primary_replica() { + local summary="$1" + awk ' + /^replica: / && / role=primary / { + for (i = 1; i <= NF; i++) { + if ($i ~ /^replica=/) { + sub(/^replica=/, "", $i) + print $i + exit + } + } + } + ' "$summary" +} + +inventory_non_primary_not_ready_evidence() { + local summary="$1" + local primary="$2" + awk -v primary="$primary" ' + /^replica: / { + replica = "" + for (i = 1; i <= NF; i++) { + if ($i ~ /^replica=/) { + replica = $i + sub(/^replica=/, "", replica) + } + } + if (replica != "" && replica != primary && ($0 ~ /status=unhealthy/ || $0 ~ /replication=not_ready/ || $0 ~ / role=unknown /)) { + print + exit + } + } + ' "$summary" +} + +inventory_non_primary_promotion_evidence() { + local summary="$1" + local primary="$2" + awk -v primary="$primary" ' + /^promotion: / { + replica = "" + for (i = 1; i <= NF; i++) { + if ($i ~ /^replica=/) { + replica = $i + sub(/^replica=/, "", replica) + } + } + if (replica != "" && replica != primary) { + print + exit + } + } + ' "$summary" +} + +promotion_evidence_field() { + local line="$1" + local key="$2" + awk -v key="$key" ' + { + for (i = 1; i <= NF; i++) { + if ($i ~ "^" key "=") { + sub("^" key "=", "", $i) + print $i + exit + } + } + } + ' <<<"$line" +} + +inventory_actionable_issue_evidence() { + local summary="$1" + grep -E 'replica_degraded=|ops_status=unhealthy|status_endpoint_' "$summary" 2>/dev/null | head -n 1 || true +} + +write_control_plane_timeline_event() { + local timeline="$1" + local event="$2" + shift 2 + { + printf 'event=%s' "$event" + local field + for field in "$@"; do + printf ' %s' "$field" + done + printf '\n' + } >>"$timeline" +} + +marker_field() { + local marker="$1" + local key="$2" + sed -n "s/^${key}=//p" "$marker" 2>/dev/null | tail -n 1 +} + +marker_colon_field() { + local marker="$1" + local key="$2" + sed -n "s/^${key}: //p" "$marker" 2>/dev/null | tail -n 1 +} + +write_node_loss_recovery_summary() { + local marker="$1" + local out="$2" + local failover_status + local ack_profile + local before_primary_replica + local before_primary_node + local failed_replica + local failed_node + local promoted_replica + local promoted_replica_node + local before_frontend + local after_frontend + local reader_verified + local data_check + local stale_success + local pod_recreate + local transparent_claim + local physical_host_claim + + failover_status="$(marker_colon_field "$marker" "failover_status")" + ack_profile="$(marker_colon_field "$marker" "ack_profile")" + before_primary_replica="$(marker_field "$marker" "before_primary_replica")" + before_primary_node="$(marker_field "$marker" "before_primary_node")" + failed_replica="$(marker_field "$marker" "failed_replica")" + failed_node="$(marker_field "$marker" "failed_node")" + promoted_replica="$(marker_field "$marker" "promoted_replica")" + promoted_replica_node="$(marker_field "$marker" "promoted_replica_node")" + before_frontend="$(marker_field "$marker" "before_publish_target_frontend")" + after_frontend="$(marker_field "$marker" "after_publish_target_frontend")" + reader_verified="$(marker_field "$marker" "reader_verified")" + data_check="$(marker_field "$marker" "data_check_after_node_loss")" + stale_success="$(marker_field "$marker" "old_primary_stale_io_success_count")" + pod_recreate="$(marker_field "$marker" "pod_recreate_used")" + transparent_claim="$(marker_field "$marker" "transparent_failover_claimed")" + physical_host_claim="$(marker_field "$marker" "physical_host_loss_claimed")" + + { + echo "node_loss_recovery_summary_version=1" + echo "result=${failover_status:-unavailable}" + echo "ack_profile=${ack_profile:-unavailable}" + echo "before_primary=${before_primary_replica:-unavailable}@${before_primary_node:-unavailable}" + echo "failed=${failed_replica:-unavailable}@${failed_node:-unavailable}" + echo "promoted=${promoted_replica:-unavailable}@${promoted_replica_node:-unavailable}" + echo "before_frontend=${before_frontend:-unavailable}" + echo "after_frontend=${after_frontend:-unavailable}" + echo "pod_recreate_used=${pod_recreate:-unavailable}" + echo "reader_verified=${reader_verified:-false}" + echo "data_check_after_node_loss=${data_check:-unavailable}" + echo "old_primary_stale_io_success_count=${stale_success:-unavailable}" + echo "transparent_failover_claimed=${transparent_claim:-false}" + echo "physical_host_loss_claimed=${physical_host_claim:-false}" + echo "source_marker=${marker}" + } >"$out" +} + +inventory_replica_line() { + local summary="$1" + local replica="$2" + awk -v replica="$replica" ' + /^replica: / { + for (i = 1; i <= NF; i++) { + if ($i == "replica=" replica) { + print + exit + } + } + } + ' "$summary" +} + +inventory_primary_required_frontier_arg() { + local summary="$1" + local inventory_dir="$2" + python3 - "$summary" "$inventory_dir" <<'PY' +import json +import pathlib +import re +import sys + +summary_path = pathlib.Path(sys.argv[1]) +inventory_dir = pathlib.Path(sys.argv[2]) +try: + summary = summary_path.read_text(encoding="utf-8", errors="replace") +except FileNotFoundError: + sys.exit(0) + +primary_line = None +for line in summary.splitlines(): + if line.startswith("replica: ") and " role=primary " in line: + primary_line = line + break +if not primary_line: + sys.exit(0) + +volume = re.search(r"\bvolume=([^ ]+)", primary_line) +replica = re.search(r"\breplica=([^ ]+)", primary_line) +if not volume or not replica: + sys.exit(0) +volume_id = volume.group(1) +replica_id = replica.group(1) +report_path = inventory_dir / "volumes" / volume_id / replica_id / "volume-status-report.json" +try: + report = json.loads(report_path.read_text(encoding="utf-8")) +except Exception: + sys.exit(0) + +for durable in report.get("durable") or []: + if durable.get("replica_id") != replica_id: + continue + if durable.get("frontier_known") is not True: + continue + lsn = durable.get("durable_lsn") + if isinstance(lsn, int) and lsn >= 0: + print(f"{volume_id}={lsn}") + sys.exit(0) +PY +} + +wait_promotion_ready_before_reader() { + local out_dir="$ARTIFACT_DIR/ops-inventory-promotion-ready" + local summary="$out_dir/volume-inventory-summary.txt" + local marker="$ARTIFACT_DIR/promotion-ready.txt" + local primary + local required_frontier_arg + local candidate_promotion_evidence + local promotion_candidate_ready + local promotion_reason + + log "collect inventory before promotion-ready wait" + collect_ops_inventory_bundle "$out_dir" || true + required_frontier_arg="$(inventory_primary_required_frontier_arg "$summary" "$out_dir")" + if [[ -z "$required_frontier_arg" ]]; then + echo "required_frontier_missing: unable to derive primary durable frontier from mounted writer path" >"$ARTIFACT_DIR/mounted-writer-required-frontier.txt" + echo "unable to derive required frontier from mounted writer path" >&2 + cat "$summary" >&2 || true + exit 1 + fi + echo "$required_frontier_arg" >"$ARTIFACT_DIR/mounted-writer-required-frontier.txt" + log "mounted writer required frontier: $required_frontier_arg" + + for _ in $(seq 1 90); do + SW_BLOCK_OPS_INVENTORY_REQUIRED_FRONTIERS="$required_frontier_arg" collect_ops_inventory_bundle "$out_dir" || true + primary="$(inventory_primary_replica "$summary")" + if [[ -n "$primary" ]]; then + candidate_promotion_evidence="$(inventory_non_primary_promotion_evidence "$summary" "$primary")" + promotion_candidate_ready="$(promotion_evidence_field "$candidate_promotion_evidence" "candidate_ready")" + promotion_reason="$(promotion_evidence_field "$candidate_promotion_evidence" "reason")" + if [[ "$promotion_candidate_ready" == "true" ]]; then + log "controlled stop after promotion-ready" + { + echo "promotion_ready_status: ready" + echo "ack_profile: ${REPLICATION_ACK}" + echo "required_frontier=${required_frontier_arg}" + echo "primary_replica=${primary}" + echo "candidate_promotion_evidence=${candidate_promotion_evidence}" + echo "candidate_ready=true" + echo "reason=${promotion_reason:-promotion_ready}" + echo "inventory=${out_dir}" + echo "data_check_after_failover=not_claimed" + } >"$marker" + exit 47 + fi + fi + sleep 2 + done + + { + echo "promotion_ready_status: timeout" + echo "ack_profile: ${REPLICATION_ACK}" + echo "required_frontier=${required_frontier_arg}" + echo "primary_replica=${primary:-unavailable}" + echo "candidate_promotion_evidence=${candidate_promotion_evidence:-unavailable}" + echo "candidate_ready=${promotion_candidate_ready:-false}" + echo "reason=${promotion_reason:-promotion_ready_timeout}" + echo "inventory=${out_dir}" + echo "data_check_after_failover=not_claimed" + } >"$marker" + echo "non-primary candidate did not become promotion-ready" >&2 + cat "$summary" >&2 || true + exit 1 +} + +fail_primary_before_reader() { + local before_dir="$ARTIFACT_DIR/ops-inventory-before-primary-failure" + local after_dir="$ARTIFACT_DIR/ops-inventory-after-primary-failure" + local before_summary="$before_dir/volume-inventory-summary.txt" + local after_summary="$after_dir/volume-inventory-summary.txt" + local marker="$ARTIFACT_DIR/primary-failure-safe-refusal.txt" + local recovery_marker="$ARTIFACT_DIR/primary-failure-recovery.txt" + local timeline="$ARTIFACT_DIR/control-plane-timeline.txt" + local primary + local primary_count + local after_primary_count + local before_primary_line + local candidate_evidence + local candidate_promotion_evidence + local candidate_replica + local promotion_candidate_ready + local promotion_reason + local after_issue_evidence + local after_primary + local failed_after_line + local promoted_line + local promoted_node + local deploy + local ready + local required_frontier_arg + local failure_class="primary-blockvolume-controlled-stop" + local node_loss_mode=0 + local before_primary_node="" + local before_primary_frontend="" + local promoted_frontend="" + + if [[ "$FAIL_PRIMARY_BEFORE_READER" == "cordon-node-scale-primary-to-zero" ]]; then + failure_class="primary-kubernetes-node-cordoned-blockvolume-stop" + node_loss_mode=1 + fi + + log "collect inventory before primary failure" + collect_ops_inventory_bundle "$before_dir" || true + required_frontier_arg="$(inventory_primary_required_frontier_arg "$before_summary" "$before_dir")" + if [[ -n "$required_frontier_arg" ]]; then + echo "$required_frontier_arg" >"$ARTIFACT_DIR/mounted-writer-required-frontier.txt" + log "mounted writer required frontier: $required_frontier_arg" + SW_BLOCK_OPS_INVENTORY_REQUIRED_FRONTIERS="$required_frontier_arg" collect_ops_inventory_bundle "$before_dir" || true + else + echo "required_frontier_missing: unable to derive primary durable frontier from mounted writer path" >"$ARTIFACT_DIR/mounted-writer-required-frontier.txt" + log "mounted writer required frontier unavailable" + fi + primary_count="$(grep -c '^replica: .* role=primary ' "$before_summary" 2>/dev/null || true)" + if [[ "$primary_count" != "1" ]]; then + echo "expected exactly one primary before failure, found ${primary_count}" >&2 + cat "$before_summary" >&2 || true + exit 1 + fi + primary="$(inventory_primary_replica "$before_summary")" + before_primary_line="$(inventory_replica_line "$before_summary" "$primary" 2>/dev/null || true)" + before_primary_node="$(promotion_evidence_field "$before_primary_line" "node")" + before_primary_frontend="$(promotion_evidence_field "$before_primary_line" "frontend")" + if [[ "$node_loss_mode" == "1" && ( -z "$before_primary_node" || "$before_primary_node" == "unavailable" ) ]]; then + echo "node-loss failure mode requires primary replica node evidence" >&2 + cat "$before_summary" >&2 || true + exit 1 + fi + if [[ "$node_loss_mode" == "1" && "$READER_NODE_NAME" == "$before_primary_node" ]]; then + echo "node-loss failure mode requires SW_BLOCK_DEMO_READER_NODE_NAME to target a survivor node; reader_node=${READER_NODE_NAME} primary_node=${before_primary_node}" >&2 + cat "$before_summary" >&2 || true + exit 1 + fi + candidate_evidence="$(inventory_non_primary_not_ready_evidence "$before_summary" "$primary")" + candidate_promotion_evidence="$(inventory_non_primary_promotion_evidence "$before_summary" "$primary")" + if [[ -z "$candidate_promotion_evidence" ]]; then + echo "no non-primary promotion-readiness evidence before failure" >&2 + cat "$before_summary" >&2 || true + exit 1 + fi + promotion_candidate_ready="$(promotion_evidence_field "$candidate_promotion_evidence" "candidate_ready")" + promotion_reason="$(promotion_evidence_field "$candidate_promotion_evidence" "reason")" + candidate_replica="$(promotion_evidence_field "$candidate_promotion_evidence" "replica")" + if [[ "$promotion_candidate_ready" != "true" && ( "$REQUIRE_PROMOTION_READY_BEFORE_FAILURE" == "1" || "$REQUIRE_PROMOTION_READY_BEFORE_FAILURE" == "true" ) ]]; then + log "wait for promotion-ready candidate before primary failure" + for _ in $(seq 1 120); do + if [[ -n "$required_frontier_arg" ]]; then + SW_BLOCK_OPS_INVENTORY_REQUIRED_FRONTIERS="$required_frontier_arg" collect_ops_inventory_bundle "$before_dir" || true + else + collect_ops_inventory_bundle "$before_dir" || true + fi + candidate_promotion_evidence="$(inventory_non_primary_promotion_evidence "$before_summary" "$primary")" + promotion_candidate_ready="$(promotion_evidence_field "$candidate_promotion_evidence" "candidate_ready")" + promotion_reason="$(promotion_evidence_field "$candidate_promotion_evidence" "reason")" + candidate_replica="$(promotion_evidence_field "$candidate_promotion_evidence" "replica")" + if [[ "$promotion_candidate_ready" == "true" ]]; then + break + fi + sleep 2 + done + fi + if [[ "$promotion_candidate_ready" != "true" && -z "$candidate_evidence" ]]; then + echo "no non-primary not-ready candidate evidence before failure" >&2 + cat "$before_summary" >&2 || true + exit 1 + fi + deploy="$(kubectl -n "$BLOCKVOLUME_NAMESPACE" get deploy -l "app=sw-blockvolume,sw-block.seaweedfs.com/replica=${primary}" -o name | head -n 1)" + if [[ -z "$deploy" ]]; then + echo "primary blockvolume Deployment not found for replica ${primary}" >&2 + exit 1 + fi + rm -f "$timeline" + write_control_plane_timeline_event "$timeline" "primary_observed" "replica=${primary}" "evidence=${before_primary_line:-unavailable}" "inventory=${before_dir}" + write_control_plane_timeline_event "$timeline" "candidate_evaluated" "replica=${candidate_replica:-unavailable}" "candidate_ready=${promotion_candidate_ready:-false}" "reason=${promotion_reason:-unavailable}" "evidence=${candidate_promotion_evidence:-${candidate_evidence:-unavailable}}" + + if [[ "$node_loss_mode" == "1" ]]; then + echo "$before_primary_node" >"$ARTIFACT_DIR/cordoned-primary-node.txt" + fi + + if [[ "$promotion_candidate_ready" == "true" ]]; then + { + echo "failover_status: promotion_pending" + echo "ack_profile: ${REPLICATION_ACK}" + echo "failure_class=${failure_class}" + echo "before_primary_replica=${primary}" + echo "before_primary_node=${before_primary_node:-unavailable}" + echo "promotion_candidate_replica=${candidate_replica}" + echo "failed_replica=${primary}" + echo "failed_node=${before_primary_node:-unavailable}" + echo "required_frontier=${required_frontier_arg:-unavailable}" + echo "candidate_ready=true" + echo "candidate_promotion_evidence=${candidate_promotion_evidence}" + echo "before_publish_target_evidence=${before_primary_line}" + echo "before_publish_target_frontend=${before_primary_frontend:-unavailable}" + echo "data_check_after_failover=pending_reader" + if [[ "$node_loss_mode" == "1" ]]; then + echo "kubernetes_node_loss_claimed=true" + echo "physical_host_loss_claimed=false" + echo "transparent_failover_claimed=false" + echo "pod_recreate_used=pending" + echo "node_loss_recovery_claimed=pending" + echo "data_check_after_node_loss=pending_reader" + fi + echo "control_plane_timeline=$timeline" + echo "before_inventory=${before_dir}" + echo "after_inventory=${after_dir}" + echo "target_deployment=${deploy}" + } >"$recovery_marker" + + if [[ "$node_loss_mode" == "1" ]]; then + log "controlled node-loss failure: cordon ${before_primary_node}" + kubectl cordon "$before_primary_node" | tee "$ARTIFACT_DIR/cordon-primary-node.log" + fi + log "controlled primary failure: scale ${deploy} to zero" + write_control_plane_timeline_event "$timeline" "primary_failure_injected" "replica=${primary}" "node=${before_primary_node:-unavailable}" "deployment=${deploy}" "failure_class=${failure_class}" + kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o yaml >"$ARTIFACT_DIR/primary-deployment.before-failure.yaml" 2>&1 || true + kubectl -n "$BLOCKVOLUME_NAMESPACE" scale "$deploy" --replicas=0 | tee "$ARTIFACT_DIR/scale-primary-zero.log" + for _ in $(seq 1 60); do + ready="$(kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true)" + if [[ -z "$ready" || "$ready" == "0" ]]; then + break + fi + sleep 1 + done + kubectl -n "$BLOCKVOLUME_NAMESPACE" get deploy -l app=sw-blockvolume -o wide >"$ARTIFACT_DIR/blockvolume-pods.after-primary-failure.txt" 2>&1 || true + ready="$(kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true)" + echo "target_ready_replicas=${ready:-0}" >>"$recovery_marker" + echo "old_primary_stale_io_success_count=0" >>"$recovery_marker" + echo "stale_primary_fence_evidence=target_ready_replicas=${ready:-0}" >>"$recovery_marker" + + log "wait for promoted primary ${candidate_replica} after controlled failure" + for _ in $(seq 1 120); do + if [[ -n "$required_frontier_arg" ]]; then + SW_BLOCK_OPS_INVENTORY_REQUIRED_FRONTIERS="$required_frontier_arg" collect_ops_inventory_bundle "$after_dir" || true + else + collect_ops_inventory_bundle "$after_dir" || true + fi + after_primary="$(inventory_primary_replica "$after_summary" 2>/dev/null || true)" + after_primary_count="$(grep -c '^replica: .* role=primary ' "$after_summary" 2>/dev/null || true)" + promoted_line="$(inventory_replica_line "$after_summary" "$candidate_replica" 2>/dev/null || true)" + promoted_node="$(promotion_evidence_field "$promoted_line" "node")" + promoted_frontend="$(promotion_evidence_field "$promoted_line" "frontend")" + failed_after_line="$(inventory_replica_line "$after_summary" "$primary" 2>/dev/null || true)" + frontend_ready_issue_count="$(grep -c 'frontend_primary_ready=true' "$after_summary" 2>/dev/null || true)" + if [[ "$after_primary" == "$candidate_replica" && "$after_primary_count" == "1" && "$promoted_line" == *" role=primary "* && -n "$failed_after_line" && "$failed_after_line" != *" role=primary "* && "$frontend_ready_issue_count" == "0" ]]; then + { + echo "failover_status: promoted" + echo "post_failure_primary_count=${after_primary_count}" + echo "frontend_primary_ready_issue_count=${frontend_ready_issue_count}" + echo "after_primary_replica=${after_primary}" + echo "promoted_replica=${candidate_replica}" + echo "promoted_replica_node=${promoted_node:-unavailable}" + echo "promoted_replica_evidence=${promoted_line}" + echo "failed_replica_after_evidence=${failed_after_line}" + echo "after_publish_target_evidence=${promoted_line}" + echo "after_publish_target_frontend=${promoted_frontend:-unavailable}" + } >>"$recovery_marker" + write_control_plane_timeline_event "$timeline" "authority_published" "from=${primary}" "to=${candidate_replica}" "primary=${after_primary}" "primary_count=${after_primary_count}" "evidence=${promoted_line}" + return 0 + fi + sleep 2 + done + + { + echo "failover_status: promotion_timeout" + echo "post_failure_primary_count=${after_primary_count:-0}" + echo "frontend_primary_ready_issue_count=${frontend_ready_issue_count:-0}" + echo "after_primary_replica=${after_primary:-unavailable}" + echo "reason=promotion_not_observed" + } >>"$recovery_marker" + write_control_plane_timeline_event "$timeline" "promotion_timeout" "candidate=${candidate_replica:-unavailable}" "after_primary=${after_primary:-unavailable}" "primary_count=${after_primary_count:-0}" "reason=promotion_not_observed" + echo "promotion-ready candidate did not become primary after controlled failure" >&2 + cat "$after_summary" >&2 || true + exit 1 + fi + + { + echo "failover_status: refused" + echo "ack_profile: ${REPLICATION_ACK}" + echo "failure_class=${failure_class}" + echo "before_primary_replica=${primary}" + echo "before_primary_node=${before_primary_node:-unavailable}" + echo "failed_replica=${primary}" + echo "failed_node=${before_primary_node:-unavailable}" + echo "old_primary_safe=unknown" + echo "required_frontier=${required_frontier_arg:-unavailable}" + echo "candidate_ready=${promotion_candidate_ready:-false}" + echo "candidate_evidence=${candidate_evidence}" + echo "candidate_promotion_evidence=${candidate_promotion_evidence}" + echo "data_check_after_failover=not_claimed" + if [[ "$node_loss_mode" == "1" ]]; then + echo "kubernetes_node_loss_claimed=true" + echo "physical_host_loss_claimed=false" + echo "transparent_failover_claimed=false" + echo "pod_recreate_used=false" + echo "node_loss_recovery_claimed=false" + echo "data_check_after_node_loss=not_claimed" + fi + echo "reason=${promotion_reason:-candidate_not_ready_for_primary}" + echo "control_plane_timeline=$timeline" + echo "before_inventory=${before_dir}" + echo "after_inventory=${after_dir}" + echo "target_deployment=${deploy}" + } >"$marker" + + if [[ "$node_loss_mode" == "1" ]]; then + log "controlled node-loss failure: cordon ${before_primary_node}" + kubectl cordon "$before_primary_node" | tee "$ARTIFACT_DIR/cordon-primary-node.log" + fi + log "controlled primary failure: scale ${deploy} to zero" + write_control_plane_timeline_event "$timeline" "primary_failure_injected" "replica=${primary}" "node=${before_primary_node:-unavailable}" "deployment=${deploy}" "failure_class=${failure_class}" + kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o yaml >"$ARTIFACT_DIR/primary-deployment.before-failure.yaml" 2>&1 || true + kubectl -n "$BLOCKVOLUME_NAMESPACE" scale "$deploy" --replicas=0 | tee "$ARTIFACT_DIR/scale-primary-zero.log" + for _ in $(seq 1 60); do + ready="$(kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true)" + if [[ -z "$ready" || "$ready" == "0" ]]; then + break + fi + sleep 1 + done + kubectl -n "$BLOCKVOLUME_NAMESPACE" get deploy -l app=sw-blockvolume -o wide >"$ARTIFACT_DIR/blockvolume-pods.after-primary-failure.txt" 2>&1 || true + ready="$(kubectl -n "$BLOCKVOLUME_NAMESPACE" get "$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true)" + echo "target_ready_replicas=${ready:-0}" >>"$marker" + echo "old_primary_stale_io_success_count=0" >>"$marker" + echo "stale_primary_fence_evidence=target_ready_replicas=${ready:-0}" >>"$marker" + + log "collect inventory after primary failure" + collect_ops_inventory_bundle "$after_dir" || true + after_issue_evidence="$(inventory_actionable_issue_evidence "$after_summary")" + if [[ -z "$after_issue_evidence" ]]; then + echo "after-failure inventory did not include an actionable degradation issue" >&2 + cat "$after_summary" >&2 || true + exit 1 + fi + echo "after_issue_evidence=${after_issue_evidence}" >>"$marker" + write_control_plane_timeline_event "$timeline" "safe_refusal" "replica=${candidate_replica:-unavailable}" "candidate_ready=${promotion_candidate_ready:-false}" "reason=${promotion_reason:-candidate_not_ready_for_primary}" "evidence=${after_issue_evidence}" + exit 46 +} + record_ops_status_unavailable() { local reason="$1" mkdir -p "$ARTIFACT_DIR" @@ -499,7 +1218,15 @@ cleanup() { kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1 kubectl delete -f "$ROOT/deploy/k8s/alpha/rbac.yaml" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1 kubectl delete -f "$STACK_RENDERED" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1 - if [[ "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" ]]; then + if [[ -s "$ARTIFACT_DIR/cordoned-primary-node.txt" ]]; then + primary_node="$(cat "$ARTIFACT_DIR/cordoned-primary-node.txt" 2>/dev/null || true)" + if [[ -n "$primary_node" ]]; then + kubectl uncordon "$primary_node" >>"$ARTIFACT_DIR/cleanup.log" 2>&1 || true + fi + fi + kubectl -n "$NAMESPACE" delete secret "$CHAP_SECRET_NAME" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1 + kubectl -n "$BLOCKVOLUME_NAMESPACE" delete secret "$CHAP_SECRET_NAME" --ignore-not-found=true >>"$ARTIFACT_DIR/cleanup.log" 2>&1 + if [[ "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" || -n "$FAIL_PRIMARY_BEFORE_READER" || "$DEMO_STOP_AFTER" == "promotion-ready" ]]; then case "$LAUNCHER_STATE_HOSTPATH" in /var/lib/sw-block/testops-*) if command -v sudo >/dev/null 2>&1; then @@ -552,8 +1279,52 @@ wait_pod_log_contains() { require_cmd kubectl +case "$LOGICAL_SERVERS" in + ''|*[!0-9]*|0) + echo "SW_BLOCK_ALPHA_LOGICAL_SERVERS must be a positive integer, got: $LOGICAL_SERVERS" >&2 + exit 2 + ;; +esac +case "$EXPECTED_SLOTS_PER_VOLUME" in + ''|*[!0-9]*|0) + echo "SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME must be a positive integer, got: $EXPECTED_SLOTS_PER_VOLUME" >&2 + exit 2 + ;; +esac +case "$REPLICATION_ACK" in + best-effort|sync-quorum|sync-all) + ;; + *) + echo "SW_BLOCK_ALPHA_REPLICATION_ACK must be best-effort, sync-quorum, or sync-all; got: $REPLICATION_ACK" >&2 + exit 2 + ;; +esac + NODE_NAME="${SW_BLOCK_ALPHA_NODE_NAME:-$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')}" +if [[ -n "$NODE_SPECS" ]]; then + NODE_SPEC_COUNT="$(node_spec_count "$NODE_SPECS")" + if [[ "$NODE_SPEC_COUNT" == "0" ]]; then + echo "SW_BLOCK_ALPHA_NODE_SPECS did not contain any node entries" >&2 + exit 2 + fi + if [[ -z "${SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME:-}" ]]; then + EXPECTED_SLOTS_PER_VOLUME="$NODE_SPEC_COUNT" + fi +fi +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + if [[ -z "$CHAP_USERNAME" || -z "$CHAP_SECRET" ]]; then + echo "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI requires SW_BLOCK_ISCSI_CHAP_USERNAME and SW_BLOCK_ISCSI_CHAP_SECRET" >&2 + exit 2 + fi +fi +if [[ "$LAUNCHER_EXTERNAL_STATUS" == "1" || "$LAUNCHER_EXTERNAL_STATUS" == "true" ]]; then + if [[ "$LAUNCHER_EXTERNAL_ISCSI" != "1" && "$LAUNCHER_EXTERNAL_ISCSI" != "true" ]]; then + echo "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS requires SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1" >&2 + exit 2 + fi +fi APP_NODE_NAME="${SW_BLOCK_DEMO_APP_NODE_NAME:-$NODE_NAME}" +READER_NODE_NAME="${SW_BLOCK_DEMO_READER_NODE_NAME:-$APP_NODE_NAME}" STACK_RENDERED="$ARTIFACT_DIR/block-stack.rendered.yaml" CSI_CONTROLLER_RENDERED="$ARTIFACT_DIR/csi-controller.rendered.yaml" CSI_NODE_RENDERED="$ARTIFACT_DIR/csi-node.rendered.yaml" @@ -561,10 +1332,28 @@ DEMO_APP_RENDERED="$ARTIFACT_DIR/demo-app.rendered.yaml" READER_RENDERED="$ARTIFACT_DIR/demo-app-reader.rendered.yaml" IMAGE_SED="$(sed_escape "$IMAGE")" CSI_IMAGE_SED="$(sed_escape "$CSI_IMAGE")" +CLUSTER_SPEC_NODES="$ARTIFACT_DIR/cluster-spec-nodes.rendered.yaml" +if [[ -n "$NODE_SPECS" ]]; then + render_cluster_spec_node_specs "$NODE_SPECS" >"$CLUSTER_SPEC_NODES" +else + render_cluster_spec_nodes "$NODE_NAME" "$LOGICAL_SERVERS" >"$CLUSTER_SPEC_NODES" +fi + sed -e "s/__NODE_NAME__/${NODE_NAME}/g" \ + -e "s/__EXPECTED_SLOTS_PER_VOLUME__/${EXPECTED_SLOTS_PER_VOLUME}/g" \ + -e "s/__REPLICATION_ACK__/${REPLICATION_ACK}/g" \ -e "s/sw-block:local/${IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ - "$ROOT/deploy/k8s/alpha/block-stack.yaml" >"$STACK_RENDERED" + "$ROOT/deploy/k8s/alpha/block-stack.yaml" >"$STACK_RENDERED.tmp" +awk -v nodes_file="$CLUSTER_SPEC_NODES" ' + /__CLUSTER_SPEC_NODES__/ { + while ((getline line < nodes_file) > 0) print line + close(nodes_file) + next + } + { print } +' "$STACK_RENDERED.tmp" >"$STACK_RENDERED" +rm -f "$STACK_RENDERED.tmp" if [[ "$BLOCKVOLUME_NAMESPACE" != "kube-system" ]]; then awk '/--launcher-namespace=/{print; print " - \"--launcher-pvc-owner-ref\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" @@ -575,11 +1364,26 @@ if [[ -n "$LAUNCHER_STATE_HOSTPATH" ]]; then mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" grep -q -- '--launcher-state-hostpath=' "$STACK_RENDERED" || { echo "failed to inject --launcher-state-hostpath into $STACK_RENDERED" >&2; exit 1; } fi +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + awk -v secret="$CHAP_SECRET_NAME" '/--launcher-iscsi-port-base=/{print; print " - \"--launcher-external-iscsi\""; print " - \"--launcher-iscsi-chap-secret-name=" secret "\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" + mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" + grep -q -- '--launcher-external-iscsi' "$STACK_RENDERED" || { echo "failed to inject --launcher-external-iscsi into $STACK_RENDERED" >&2; exit 1; } + grep -q -- '--launcher-iscsi-chap-secret-name' "$STACK_RENDERED" || { echo "failed to inject --launcher-iscsi-chap-secret-name into $STACK_RENDERED" >&2; exit 1; } +fi if [[ "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" || "$COLLECT_OPS_STATUS" == "1" || "$COLLECT_OPS_STATUS" == "true" || -n "$DEMO_STOP_AFTER" ]]; then awk '/--launcher-durable-root=/{print; print " - \"--launcher-status\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" grep -q -- '--launcher-status' "$STACK_RENDERED" || { echo "failed to inject --launcher-status into $STACK_RENDERED" >&2; exit 1; } fi +if [[ "$LAUNCHER_EXTERNAL_STATUS" == "1" || "$LAUNCHER_EXTERNAL_STATUS" == "true" ]]; then + grep -q -- '--launcher-status' "$STACK_RENDERED" || { + awk '/--launcher-durable-root=/{print; print " - \"--launcher-status\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" + mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" + } + awk '/--launcher-status/{print; print " - \"--launcher-external-status\""; next} {print}' "$STACK_RENDERED" >"$STACK_RENDERED.tmp" + mv "$STACK_RENDERED.tmp" "$STACK_RENDERED" + grep -q -- '--launcher-external-status' "$STACK_RENDERED" || { echo "failed to inject --launcher-external-status into $STACK_RENDERED" >&2; exit 1; } +fi sed -e "s/sw-block-csi:local/${CSI_IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ "$ROOT/deploy/k8s/alpha/csi-controller.yaml" >"$CSI_CONTROLLER_RENDERED" @@ -591,20 +1395,50 @@ fi sed -e "s/sw-block-csi:local/${CSI_IMAGE_SED}/g" \ -e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \ "$ROOT/deploy/k8s/alpha/csi-node.yaml" >"$CSI_NODE_RENDERED" +if [[ "$STAGE2_MULTIPATH" == "1" || "$STAGE2_MULTIPATH" == "true" ]]; then + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--stage2-multipath\""; next} {print}' "$CSI_CONTROLLER_RENDERED" >"$CSI_CONTROLLER_RENDERED.tmp" + mv "$CSI_CONTROLLER_RENDERED.tmp" "$CSI_CONTROLLER_RENDERED" + grep -q -- '--stage2-multipath' "$CSI_CONTROLLER_RENDERED" || { echo "failed to inject --stage2-multipath into $CSI_CONTROLLER_RENDERED" >&2; exit 1; } + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--stage2-multipath\""; next} {print}' "$CSI_NODE_RENDERED" >"$CSI_NODE_RENDERED.tmp" + mv "$CSI_NODE_RENDERED.tmp" "$CSI_NODE_RENDERED" + grep -q -- '--stage2-multipath' "$CSI_NODE_RENDERED" || { echo "failed to inject --stage2-multipath into $CSI_NODE_RENDERED" >&2; exit 1; } +fi +if [[ "$REJECT_LOOPBACK_PUBLISH_TARGETS" == "1" || "$REJECT_LOOPBACK_PUBLISH_TARGETS" == "true" ]]; then + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--reject-loopback-publish-targets\""; next} {print}' "$CSI_CONTROLLER_RENDERED" >"$CSI_CONTROLLER_RENDERED.tmp" + mv "$CSI_CONTROLLER_RENDERED.tmp" "$CSI_CONTROLLER_RENDERED" + grep -q -- '--reject-loopback-publish-targets' "$CSI_CONTROLLER_RENDERED" || { echo "failed to inject --reject-loopback-publish-targets into $CSI_CONTROLLER_RENDERED" >&2; exit 1; } + awk '/--node-id=\$\(NODE_NAME\)/{print; print " - \"--reject-loopback-publish-targets\""; next} {print}' "$CSI_NODE_RENDERED" >"$CSI_NODE_RENDERED.tmp" + mv "$CSI_NODE_RENDERED.tmp" "$CSI_NODE_RENDERED" + grep -q -- '--reject-loopback-publish-targets' "$CSI_NODE_RENDERED" || { echo "failed to inject --reject-loopback-publish-targets into $CSI_NODE_RENDERED" >&2; exit 1; } +fi render_pods_with_node_selector "$DEMO_APP_MANIFEST" "$DEMO_APP_RENDERED" "$APP_NODE_NAME" -render_pods_with_node_selector "$ROOT/deploy/k8s/alpha/demo-app-reader-pod.yaml" "$READER_RENDERED" "$APP_NODE_NAME" +render_pods_with_node_selector "$ROOT/deploy/k8s/alpha/demo-app-reader-pod.yaml" "$READER_RENDERED" "$READER_NODE_NAME" +if [[ "$LAUNCHER_EXTERNAL_ISCSI" == "1" || "$LAUNCHER_EXTERNAL_ISCSI" == "true" ]]; then + inject_node_stage_secret_into_storageclass "$DEMO_APP_RENDERED" "$DEMO_APP_RENDERED.tmp" "$CHAP_SECRET_NAME" "$NAMESPACE" + mv "$DEMO_APP_RENDERED.tmp" "$DEMO_APP_RENDERED" +fi log "artifact_dir=$ARTIFACT_DIR" log "root=$ROOT" log "namespace=$NAMESPACE" log "node=$NODE_NAME" log "app_node=$APP_NODE_NAME" +log "reader_node=$READER_NODE_NAME" log "pin_app_node=$PIN_APP_NODE" +log "logical_servers=$LOGICAL_SERVERS" +log "node_specs=${NODE_SPECS:-}" +log "expected_slots_per_volume=$EXPECTED_SLOTS_PER_VOLUME" +log "replication_ack=$REPLICATION_ACK" log "image=$IMAGE" log "csi_image=$CSI_IMAGE" log "blockvolume_namespace=$BLOCKVOLUME_NAMESPACE" log "launcher_pvc_owner_ref=$LAUNCHER_PVC_OWNER_REF" log "launcher_state_hostpath=${LAUNCHER_STATE_HOSTPATH:-}" +log "launcher_external_iscsi=$LAUNCHER_EXTERNAL_ISCSI" +log "launcher_external_status=$LAUNCHER_EXTERNAL_STATUS" +log "chap_enabled=$([[ -n "$CHAP_SECRET" ]] && echo 1 || echo 0)" +log "stage2_multipath=$STAGE2_MULTIPATH" +log "reject_loopback_publish_targets=$REJECT_LOOPBACK_PUBLISH_TARGETS" log "restart_csi_node_before_reader=$RESTART_CSI_NODE_BEFORE_READER" log "restart_blockvolume_before_reader=$RESTART_BLOCKVOLUME_BEFORE_READER" log "collect_inventory_after_restart=$COLLECT_INVENTORY_AFTER_RESTART" @@ -616,6 +1450,7 @@ log "manual_apply_blockvolumes=$MANUAL_APPLY_BLOCKVOLUMES" log "after_blockvolume_ready_cmd=${AFTER_BLOCKVOLUME_READY_CMD:-}" log "break_after_blockvolume_ready=${BREAK_AFTER_BLOCKVOLUME_READY:-}" log "break_after_blockvolume_restart=${BREAK_AFTER_BLOCKVOLUME_RESTART:-}" +log "fail_primary_before_reader=${FAIL_PRIMARY_BEFORE_READER:-}" log "writer_timeout=$WRITER_TIMEOUT" log "demo_app_manifest=$DEMO_APP_MANIFEST" kubectl version --client=true >"$ARTIFACT_DIR/kubectl-version.txt" 2>&1 || true @@ -657,6 +1492,16 @@ kubectl apply -f "$CSI_NODE_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-node.log" kubectl -n kube-system wait --for=condition=available deploy/sw-block-csi-controller --timeout=120s kubectl -n kube-system rollout status ds/sw-block-csi-node --timeout=120s +if [[ -n "$CHAP_SECRET" ]]; then + log "apply iSCSI CHAP Secret" + for secret_ns in "$NAMESPACE" "$BLOCKVOLUME_NAMESPACE"; do + kubectl -n "$secret_ns" create secret generic "$CHAP_SECRET_NAME" \ + --from-literal=chapUsername="$CHAP_USERNAME" \ + --from-literal=chapSecret="$CHAP_SECRET" \ + --dry-run=client -o yaml | kubectl apply -f - | tee -a "$ARTIFACT_DIR/apply-chap-secret.log" + done +fi + log "apply demo app PVC and writer pod" kubectl apply -f "$DEMO_APP_RENDERED" | tee "$ARTIFACT_DIR/apply-demo-app.log" @@ -713,14 +1558,59 @@ if [[ "$DEMO_STOP_AFTER" == "blockvolume-ready" ]]; then fi log "wait for app writer completion" -if [[ "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" ]]; then - wait_pod_log_contains sw-block-demo-writer "[app-writer] wrote and verified /data/demo.bin" "$WRITER_TIMEOUT" +WRITER_WAIT_FAILED=0 +if [[ "$DEMO_STOP_AFTER" == "writer-verified" || "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" ]]; then + if ! wait_pod_log_contains sw-block-demo-writer "[app-writer] wrote and verified /data/demo.bin" "$WRITER_TIMEOUT"; then + WRITER_WAIT_FAILED=1 + fi else - wait_pod_succeeded sw-block-demo-writer "$WRITER_TIMEOUT" + if ! wait_pod_succeeded sw-block-demo-writer "$WRITER_TIMEOUT"; then + WRITER_WAIT_FAILED=1 + fi fi kubectl -n "$NAMESPACE" logs sw-block-demo-writer | tee "$ARTIFACT_DIR/writer.log" kubectl -n "$NAMESPACE" describe pod sw-block-demo-writer >"$ARTIFACT_DIR/writer.describe.before-delete.txt" 2>&1 || true +if [[ "$DEMO_STOP_AFTER" == "writer-verified" ]]; then + if [[ "$WRITER_WAIT_FAILED" == "1" ]]; then + log "controlled stop after writer verification failed; capture mounted host path evidence before cleanup" + else + log "controlled stop after writer verified while PVC is still mounted" + fi + kubectl -n kube-system logs -l app=sw-block-csi-node -c block-csi --tail=-1 >"$ARTIFACT_DIR/blockcsi-node.log" 2>&1 || true + capture_stage2_host_path_evidence "writer-mounted" + collect_ops_inventory_bundle "$ARTIFACT_DIR/ops-inventory-writer-verified" || true + { + if [[ "$WRITER_WAIT_FAILED" == "1" ]]; then + echo "phase=writer-verified-failed" + echo "writer_verified=false" + echo "writer_log=$ARTIFACT_DIR/writer.log" + else + echo "phase=writer-verified" + echo "writer_verified=true" + fi + echo "host_path_evidence=multipath.writer-mounted.txt,sg-rtpg.writer-mounted.txt,iscsi-sessions.writer-mounted.txt" + echo "ops_inventory_dir=$ARTIFACT_DIR/ops-inventory-writer-verified" + } >"$ARTIFACT_DIR/controlled-stop-writer-verified.txt" + if [[ "$WRITER_WAIT_FAILED" == "1" ]]; then + exit 1 + fi + if [[ "$KEEP_ON_STOP" == "1" || "$KEEP_ON_STOP" == "true" ]]; then + log "keeping resources after writer verified" + { + echo "resources-kept: true" + echo "cleanup-required: bash scripts/uninstall-k8s-alpha.sh \"$ROOT\"" + } >>"$ARTIFACT_DIR/controlled-stop-writer-verified.txt" + collect_logs + trap - EXIT + fi + exit 44 +fi + +if [[ "$WRITER_WAIT_FAILED" == "1" ]]; then + exit 1 +fi + if [[ "$RESTART_CSI_NODE_BEFORE_READER" == "1" || "$RESTART_CSI_NODE_BEFORE_READER" == "true" ]]; then log "restart CSI node DaemonSet before replacing the app pod" kubectl -n kube-system rollout restart ds/sw-block-csi-node | tee "$ARTIFACT_DIR/restart-csi-node.log" @@ -785,12 +1675,24 @@ restart_blockvolume_deployment() { log "delete writer pod but keep PVC" kubectl -n "$NAMESPACE" delete pod sw-block-demo-writer --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-writer.log" +if [[ "$DEMO_STOP_AFTER" == "promotion-ready" ]]; then + log "wait for writer unstage before promotion-ready check" + wait_no_swblock_iscsi_sessions "$ARTIFACT_DIR/iscsi-sessions.before-promotion-ready.txt" 120 + wait_promotion_ready_before_reader +fi + if [[ "$RESTART_BLOCKVOLUME_BEFORE_READER" == "1" || "$RESTART_BLOCKVOLUME_BEFORE_READER" == "true" ]]; then log "wait for writer unstage before blockvolume restart" wait_no_swblock_iscsi_sessions "$ARTIFACT_DIR/iscsi-sessions.before-blockvolume-restart.txt" 120 restart_blockvolume_deployment fi +if [[ -n "$FAIL_PRIMARY_BEFORE_READER" ]]; then + log "wait for writer unstage before primary failure" + wait_no_swblock_iscsi_sessions "$ARTIFACT_DIR/iscsi-sessions.before-primary-failure.txt" 120 + fail_primary_before_reader +fi + log "start reader pod on the same PVC" kubectl apply -f "$READER_RENDERED" | tee "$ARTIFACT_DIR/apply-reader.log" wait_pod_succeeded sw-block-demo-reader 240 @@ -801,11 +1703,40 @@ kubectl -n kube-system logs -l app=sw-block-csi-node -c block-csi --tail=-1 >"$A log "reader verified data written by previous app pod" +if [[ -f "$ARTIFACT_DIR/primary-failure-recovery.txt" ]]; then + { + echo "reader_verified=true" + echo "data_check_after_failover=reader_checksum_passed" + if [[ "$FAIL_PRIMARY_BEFORE_READER" == "cordon-node-scale-primary-to-zero" ]]; then + echo "pod_recreate_used=true" + echo "node_loss_recovery_claimed=true" + echo "data_check_after_node_loss=reader_checksum_passed" + echo "transparent_failover_claimed=false" + fi + echo "reader_log=$ARTIFACT_DIR/reader.log" + } >>"$ARTIFACT_DIR/primary-failure-recovery.txt" + if [[ "$FAIL_PRIMARY_BEFORE_READER" == "cordon-node-scale-primary-to-zero" ]]; then + cp "$ARTIFACT_DIR/primary-failure-recovery.txt" "$ARTIFACT_DIR/node-loss-recovery-boundary.txt" + write_node_loss_recovery_summary "$ARTIFACT_DIR/primary-failure-recovery.txt" "$ARTIFACT_DIR/node-loss-recovery-summary.txt" + fi + write_control_plane_timeline_event "$ARTIFACT_DIR/control-plane-timeline.txt" "csi_reattach_observed" "reader_pod=sw-block-demo-reader" "method=pod-recreate" "log=$ARTIFACT_DIR/blockcsi-node.log" + write_control_plane_timeline_event "$ARTIFACT_DIR/control-plane-timeline.txt" "data_check" "reader_verified=true" "result=reader_checksum_passed" "log=$ARTIFACT_DIR/reader.log" +fi + if [[ "$DEMO_STOP_AFTER" == "reader-verified" ]]; then log "controlled stop after reader verified" collect_ops_inventory_bundle "$ARTIFACT_DIR/ops-inventory-reader-verified" || true echo "phase=reader-verified" >"$ARTIFACT_DIR/controlled-stop-reader-verified.txt" echo "ops_inventory_dir=$ARTIFACT_DIR/ops-inventory-reader-verified" >>"$ARTIFACT_DIR/controlled-stop-reader-verified.txt" + if [[ "$KEEP_ON_STOP" == "1" || "$KEEP_ON_STOP" == "true" ]]; then + log "keeping resources after reader verified" + { + echo "resources-kept: true" + echo "cleanup-required: bash scripts/uninstall-k8s-alpha.sh \"$ROOT\"" + } >>"$ARTIFACT_DIR/controlled-stop-reader-verified.txt" + collect_logs + trap - EXIT + fi exit 44 fi diff --git a/seaweed-block/scripts/run-basic-app-example.sh b/seaweed-block/scripts/run-basic-app-example.sh new file mode 100644 index 0000000000..f34f1d3583 --- /dev/null +++ b/seaweed-block/scripts/run-basic-app-example.sh @@ -0,0 +1,286 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-/tmp/sw-block-basic-app-$(date -u +%Y%m%dT%H%M%SZ)}" +NAMESPACE="${SW_BLOCK_APP_NAMESPACE:-default}" +MASTER_PORT="${SW_BLOCK_MASTER_PORT_FORWARD_PORT:-}" +CLEANUP_REQUESTED="${SW_BLOCK_BASIC_APP_CLEANUP:-1}" +PVC_NAME="sw-block-example-pvc" +WRITER_POD="sw-block-example-writer" +READER_POD="sw-block-example-reader" +EXAMPLE_DIR="$ROOT/examples/kubernetes/basic-app" +CHAP_SECRET_NAME="${SW_BLOCK_ISCSI_CHAP_SECRET_NAME:-sw-block-iscsi-chap}" +FIRST_VOLUME_STATUS="ok" +FAILED_PHASE="" +CLEANUP_STATUS="external_to_script" +if [[ "$CLEANUP_REQUESTED" == "1" || "$CLEANUP_REQUESTED" == "true" ]]; then + CLEANUP_STATUS="pending" +fi +PVC_PHASE_SNAPSHOT="" +PV_NAME_SNAPSHOT="" +VOLUME_ID_SNAPSHOT="" + +mkdir -p "$ARTIFACT_DIR" + +if [[ -z "${KUBECONFIG:-}" && -f /etc/rancher/k3s/k3s.yaml ]]; then + export KUBECONFIG=/etc/rancher/k3s/k3s.yaml +fi + +log() { + printf '[basic-app] %s\n' "$*" | tee -a "$ARTIFACT_DIR/run.log" +} + +require_cmd() { + if ! command -v "$1" >/dev/null 2>&1; then + echo "missing required command: $1" >&2 + exit 2 + fi +} + +safe_capture() { + local out="$1" + shift + "$@" >"$out" 2>&1 || true +} + +inject_node_stage_secret_into_storageclass() { + local input="$1" + local output="$2" + local secret="$3" + local namespace="$4" + awk -v secret="$secret" -v namespace="$namespace" ' + /^parameters:[[:space:]]*$/ { + print + print " csi.storage.k8s.io/node-stage-secret-name: \"" secret "\"" + print " csi.storage.k8s.io/node-stage-secret-namespace: \"" namespace "\"" + next + } + { print } + ' "$input" >"$output" +} + +render_example_manifest() { + local input="$EXAMPLE_DIR/storageclass-pvc.yaml" + local output="$ARTIFACT_DIR/storageclass-pvc.rendered.yaml" + if kubectl -n "$NAMESPACE" get secret "$CHAP_SECRET_NAME" >/dev/null 2>&1; then + inject_node_stage_secret_into_storageclass "$input" "$output" "$CHAP_SECRET_NAME" "$NAMESPACE" + log "node_stage_secret=$CHAP_SECRET_NAME namespace=$NAMESPACE" + else + cp "$input" "$output" + log "node_stage_secret=none" + fi + EXAMPLE_MANIFEST="$output" +} + +capture_failure_diagnostics() { + local phase="$1" + local out="$ARTIFACT_DIR/diagnostics/$phase" + mkdir -p "$out" + safe_capture "$out/pods.txt" kubectl -n "$NAMESPACE" get pods -o wide + safe_capture "$out/pvc.txt" kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o wide + safe_capture "$out/blockvolume-deployments.txt" kubectl -n "$NAMESPACE" get deploy -l app=sw-blockvolume -o wide + safe_capture "$out/writer-describe.txt" kubectl -n "$NAMESPACE" describe pod "$WRITER_POD" + safe_capture "$out/reader-describe.txt" kubectl -n "$NAMESPACE" describe pod "$READER_POD" + safe_capture "$out/events.txt" kubectl -n "$NAMESPACE" get events --sort-by=.lastTimestamp +} + +sw_block_cmd() { + if [[ -n "${SW_BLOCK_CLI:-}" ]]; then + "$SW_BLOCK_CLI" "$@" + elif command -v sw-block >/dev/null 2>&1; then + sw-block "$@" + else + go run ./cmd/sw-block "$@" + fi +} + +find_free_port() { + if command -v python3 >/dev/null 2>&1; then + python3 - <<'PY' +import socket +s = socket.socket() +s.bind(("127.0.0.1", 0)) +print(s.getsockname()[1]) +s.close() +PY + return + fi + for port in $(seq 29333 29433); do + if ! (echo >"/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1; then + echo "$port" + return + fi + done + echo "9333" +} + +wait_for_port() { + local port="$1" + for _ in $(seq 1 30); do + if (echo >"/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1; then + return 0 + fi + sleep 1 + done + return 1 +} + +stop_port_forward() { + if [[ -n "${PF_PID:-}" ]]; then + kill "$PF_PID" >/dev/null 2>&1 || true + wait "$PF_PID" >/dev/null 2>&1 || true + fi +} + +collect_status_evidence() { + local out="$ARTIFACT_DIR/status" + local rc=0 + mkdir -p "$out" + kubectl -n kube-system port-forward deploy/sw-blockmaster "${MASTER_PORT}:9333" >"$out/blockmaster-port-forward.log" 2>&1 & + PF_PID=$! + trap stop_port_forward RETURN + if ! wait_for_port "$MASTER_PORT"; then + echo "status evidence failed: blockmaster port-forward did not become ready" >"$out/status-evidence-error.txt" + rc=1 + fi + if [[ "$rc" -eq 0 ]] && ! sw_block_cmd ops cluster --master-api "127.0.0.1:${MASTER_PORT}" --timeout 30s -o json >"$out/cluster-evidence.json" 2>"$out/cluster-evidence.stderr.txt"; then + rc=1 + fi + if [[ "$rc" -eq 0 ]] && ! sw_block_cmd ops inventory --namespace "$NAMESPACE" --master "127.0.0.1:${MASTER_PORT}" --out "$out/inventory" --timeout 30s >"$out/inventory.stdout.txt" 2>"$out/inventory.stderr.txt"; then + rc=1 + fi + if [[ "$rc" -eq 0 ]] && ! sw_block_cmd ops report --from-bundle "$ARTIFACT_DIR" --out "$out/report" >"$out/report.stdout.txt" 2>"$out/report.stderr.txt"; then + rc=1 + fi + if [[ ! -s "$out/cluster-evidence.json" || ! -s "$out/inventory/volume-inventory-summary.txt" ]]; then + rc=1 + fi + if [[ ! -s "$out/report/index.html" || ! -s "$out/report/cluster-evidence.json" ]]; then + rc=1 + fi + stop_port_forward + unset PF_PID + trap - RETURN + return "$rc" +} + +cleanup_basic_app() { + local rc=0 + kubectl -n "$NAMESPACE" delete pod "$READER_POD" "$WRITER_POD" --ignore-not-found=true --wait=true --timeout=120s || rc=1 + kubectl -n "$NAMESPACE" delete pvc "$PVC_NAME" --ignore-not-found=true --wait=true --timeout=120s || rc=1 + kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s || rc=1 + return "$rc" +} + +snapshot_volume_state() { + PVC_PHASE_SNAPSHOT="$(kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o jsonpath='{.status.phase}' 2>/dev/null || true)" + PV_NAME_SNAPSHOT="$(kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true)" + VOLUME_ID_SNAPSHOT="$PV_NAME_SNAPSHOT" +} + +write_summary() { + local pvc_phase pv_name volume_id writer_ok reader_ok inventory_status + pvc_phase="$PVC_PHASE_SNAPSHOT" + pv_name="$PV_NAME_SNAPSHOT" + volume_id="$VOLUME_ID_SNAPSHOT" + if [[ -z "$pvc_phase" || -z "$pv_name" ]]; then + pvc_phase="$(kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o jsonpath='{.status.phase}' 2>/dev/null || true)" + pv_name="$(kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true)" + volume_id="$pv_name" + fi + writer_ok="false" + reader_ok="false" + grep -q '/data/demo.bin: OK' "$ARTIFACT_DIR/writer.log" 2>/dev/null && writer_ok="true" + grep -q '/data/demo.bin: OK' "$ARTIFACT_DIR/reader.log" 2>/dev/null && reader_ok="true" + inventory_status="$(sed -n 's/^inventory_status: //p' "$ARTIFACT_DIR/status/inventory/volume-inventory-summary.txt" 2>/dev/null | head -1)" + { + echo "first_volume_status=$FIRST_VOLUME_STATUS" + if [[ -n "$FAILED_PHASE" ]]; then + echo "failed_phase=$FAILED_PHASE" + fi + echo "namespace=$NAMESPACE" + echo "pvc=$PVC_NAME" + echo "pvc_phase=${pvc_phase:-unknown}" + echo "pv=${pv_name:-unknown}" + echo "volume_id=${volume_id:-unknown}" + echo "writer_verified=$writer_ok" + echo "reader_verified=$reader_ok" + echo "inventory_status=${inventory_status:-unknown}" + echo "status_evidence=status/cluster-evidence.json,status/inventory" + echo "cluster_evidence=status/cluster-evidence.json" + echo "inventory_bundle=status/inventory" + echo "status_report=status/report/index.html" + echo "cleanup_status=$CLEANUP_STATUS" + } >"$ARTIFACT_DIR/first-volume-summary.txt" +} + +require_cmd kubectl +if [[ "$NAMESPACE" != "default" ]]; then + echo "SW_BLOCK_APP_NAMESPACE=$NAMESPACE is not supported by the static basic-app manifests; use default" >&2 + exit 2 +fi +if [[ -z "${SW_BLOCK_CLI:-}" ]] && ! command -v sw-block >/dev/null 2>&1; then + require_cmd go +fi +if [[ -z "$MASTER_PORT" ]]; then + MASTER_PORT="$(find_free_port)" +fi + +log "artifact_dir=$ARTIFACT_DIR" +log "namespace=$NAMESPACE" +log "master_port=$MASTER_PORT" +render_example_manifest +log "apply StorageClass and PVC" +kubectl apply -f "$EXAMPLE_MANIFEST" | tee "$ARTIFACT_DIR/apply-storageclass-pvc.log" +kubectl -n "$NAMESPACE" wait --for=jsonpath='{.status.phase}'=Bound "pvc/${PVC_NAME}" --timeout=180s | tee "$ARTIFACT_DIR/wait-pvc-bound.log" + +safe_capture "$ARTIFACT_DIR/pvc.after-bound.txt" kubectl -n "$NAMESPACE" get pvc "$PVC_NAME" -o wide +safe_capture "$ARTIFACT_DIR/blockvolume-deployments.after-bound.txt" kubectl get deploy -A -l app=sw-blockvolume -o wide + +log "run writer pod" +kubectl apply -f "$EXAMPLE_DIR/writer-pod.yaml" | tee "$ARTIFACT_DIR/apply-writer.log" +if ! kubectl -n "$NAMESPACE" wait --for=jsonpath='{.status.phase}'=Succeeded "pod/${WRITER_POD}" --timeout=240s | tee "$ARTIFACT_DIR/wait-writer.log"; then + capture_failure_diagnostics "writer" + exit 1 +fi +kubectl -n "$NAMESPACE" logs "$WRITER_POD" >"$ARTIFACT_DIR/writer.log" +grep -q '/data/demo.bin: OK' "$ARTIFACT_DIR/writer.log" + +log "replace writer with reader pod" +kubectl -n "$NAMESPACE" delete pod "$WRITER_POD" --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-writer.log" +kubectl apply -f "$EXAMPLE_DIR/reader-pod.yaml" | tee "$ARTIFACT_DIR/apply-reader.log" +if ! kubectl -n "$NAMESPACE" wait --for=jsonpath='{.status.phase}'=Succeeded "pod/${READER_POD}" --timeout=240s | tee "$ARTIFACT_DIR/wait-reader.log"; then + capture_failure_diagnostics "reader" + exit 1 +fi +kubectl -n "$NAMESPACE" logs "$READER_POD" >"$ARTIFACT_DIR/reader.log" +grep -q '/data/demo.bin: OK' "$ARTIFACT_DIR/reader.log" + +log "collect status evidence" +if ! collect_status_evidence; then + FIRST_VOLUME_STATUS="failed" + FAILED_PHASE="status_evidence" +fi +snapshot_volume_state + +if [[ "$CLEANUP_REQUESTED" == "1" || "$CLEANUP_REQUESTED" == "true" ]]; then + log "cleanup basic app resources" + if cleanup_basic_app; then + CLEANUP_STATUS="ok" + else + CLEANUP_STATUS="failed" + FIRST_VOLUME_STATUS="failed" + if [[ -z "$FAILED_PHASE" ]]; then + FAILED_PHASE="cleanup" + fi + fi +fi +write_summary + +cat "$ARTIFACT_DIR/first-volume-summary.txt" +if [[ "$FIRST_VOLUME_STATUS" != "ok" ]]; then + log "FAIL: basic app PVC writer/reader loop incomplete" + exit 1 +fi +log "PASS: basic app PVC writer/reader loop complete" diff --git a/seaweed-block/scripts/uninstall-k8s-alpha.sh b/seaweed-block/scripts/uninstall-k8s-alpha.sh index 9314b224b5..ad1bab5aa4 100755 --- a/seaweed-block/scripts/uninstall-k8s-alpha.sh +++ b/seaweed-block/scripts/uninstall-k8s-alpha.sh @@ -5,6 +5,8 @@ ROOT="${1:-$(pwd)}" ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-/tmp/sw-block-uninstall-$(date -u +%Y%m%dT%H%M%SZ)}" NAMESPACE="${SW_BLOCK_APP_NAMESPACE:-default}" DELETE_ALL_BLOCKVOLUMES="${SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES:-0}" +CHAP_SECRET_NAME="${SW_BLOCK_ISCSI_CHAP_SECRET_NAME:-sw-block-iscsi-chap}" +STORAGECLASS_NAME="${SW_BLOCK_STORAGECLASS_NAME:-sw-block-dynamic}" mkdir -p "$ARTIFACT_DIR" @@ -28,6 +30,8 @@ require_cmd kubectl log "artifact_dir=$ARTIFACT_DIR" log "namespace=$NAMESPACE" log "delete_all_blockvolumes=$DELETE_ALL_BLOCKVOLUMES" +log "chap_secret_name=$CHAP_SECRET_NAME" +log "storageclass_name=$STORAGECLASS_NAME" DEMO_PVC_UID="$(kubectl -n "$NAMESPACE" get pvc sw-block-demo-pvc -o jsonpath='{.metadata.uid}' 2>/dev/null || true)" @@ -58,13 +62,29 @@ else fi log "delete CSI components" -kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-node.yaml" --ignore-not-found=true | tee "$ARTIFACT_DIR/delete-csi-node.log" -kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-controller.yaml" --ignore-not-found=true | tee "$ARTIFACT_DIR/delete-csi-controller.log" -kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" --ignore-not-found=true | tee "$ARTIFACT_DIR/delete-csidriver.log" -kubectl delete -f "$ROOT/deploy/k8s/alpha/rbac.yaml" --ignore-not-found=true | tee "$ARTIFACT_DIR/delete-rbac.log" +kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-node.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csi-node.log" +kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-controller.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csi-controller.log" +kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csidriver.log" +kubectl delete -f "$ROOT/deploy/k8s/alpha/rbac.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-rbac.log" + +log "delete alpha StorageClass" +if kubectl get storageclass "$STORAGECLASS_NAME" >/dev/null 2>&1; then + kubectl delete storageclass "$STORAGECLASS_NAME" --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-storageclass.log" +else + echo "storageclasses.storage.k8s.io \"$STORAGECLASS_NAME\" not found" | tee "$ARTIFACT_DIR/delete-storageclass.log" +fi + +log "delete iSCSI CHAP Secret" +for secret_ns in "$NAMESPACE" kube-system; do + kubectl -n "$secret_ns" delete secret "$CHAP_SECRET_NAME" --ignore-not-found=true --wait=true --timeout=120s | tee -a "$ARTIFACT_DIR/delete-chap-secret.log" +done log "delete blockmaster stack" -kubectl delete -f "$ROOT/deploy/k8s/alpha/block-stack.yaml" --ignore-not-found=true | tee "$ARTIFACT_DIR/delete-block-stack.log" +{ + kubectl -n kube-system delete deploy/sw-blockmaster --ignore-not-found=true --wait=true --timeout=120s + kubectl -n kube-system delete svc/blockmaster --ignore-not-found=true --wait=true --timeout=120s + kubectl -n kube-system delete configmap/sw-block-cluster-spec --ignore-not-found=true --wait=true --timeout=120s +} | tee "$ARTIFACT_DIR/delete-block-stack.log" kubectl -n kube-system get pods,deploy -o wide >"$ARTIFACT_DIR/kube-system.after-delete.txt" 2>&1 || true kubectl -n "$NAMESPACE" get pods,deploy,pvc,pv -o wide >"$ARTIFACT_DIR/app-namespace.after-delete.txt" 2>&1 || true diff --git a/seaweed-block/testops/scenarios/activation-day1-first-volume-chain.yaml b/seaweed-block/testops/scenarios/activation-day1-first-volume-chain.yaml new file mode 100644 index 0000000000..7ac31fcd4a --- /dev/null +++ b/seaweed-block/testops/scenarios/activation-day1-first-volume-chain.yaml @@ -0,0 +1,151 @@ +# Runner-native Phase 20 D2/D3 first-volume chain. +# +# Goal: +# Prove the user-facing post-activation loop: +# activate -> create PVC -> writer checksum -> reader checksum -> +# status/inventory evidence -> cleanup. + +name: activation-day1-first-volume-chain +timeout: 24m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-28a99ce4f644" + sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-28a99ce4f644" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/activation /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/cleanup" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: activate_alpha_stack + actions: + - action: exec + node: m02 + timeout: 12m + cmd: "cd {{ product_root }} && bash scripts/activate-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/activation" + env.SW_BLOCK_ACTIVATION_IMAGE_MODE: "published" + env.SW_BLOCK_IMAGE: "{{ sw_block_image }}" + env.SW_BLOCK_CSI_IMAGE: "{{ sw_block_csi_image }}" + + - name: first_volume_user_loop + actions: + - action: exec + node: m02 + timeout: 10m + cmd: "cd {{ product_root }} && bash scripts/run-basic-app-example.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app" + env.SW_BLOCK_BASIC_APP_CLEANUP: "1" + + - name: first_volume_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/first-volume-summary.txt" + pattern: "^first_volume_status=ok$" + save_as: first_volume_ok_count + - action: assert_greater + actual: "{{ first_volume_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/first-volume-summary.txt" + pattern: "^pvc=sw-block-example-pvc$" + save_as: pvc_count + - action: assert_greater + actual: "{{ pvc_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/first-volume-summary.txt" + pattern: "^writer_verified=true$" + save_as: writer_verified_count + - action: assert_greater + actual: "{{ writer_verified_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/first-volume-summary.txt" + pattern: "^reader_verified=true$" + save_as: reader_verified_count + - action: assert_greater + actual: "{{ reader_verified_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/writer.log" + pattern: "/data/demo.bin: OK" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/reader.log" + pattern: "/data/demo.bin: OK" + save_as: reader_checksum_count + - action: assert_greater + actual: "{{ reader_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/first-volume-summary.txt" + pattern: "^cleanup_status=ok$" + save_as: basic_cleanup_count + - action: assert_greater + actual: "{{ basic_cleanup_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/status/cluster-evidence.json" + pattern: "\"volumes\"" + save_as: cluster_volumes_count + - action: assert_greater + actual: "{{ cluster_volumes_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/basic-app/status/inventory/volume-inventory-summary.txt" + pattern: "pvc=sw-block-example-pvc" + save_as: inventory_pvc_count + - action: assert_greater + actual: "{{ inventory_pvc_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s; cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-first-volume/cleanup" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " diff --git a/seaweed-block/testops/scenarios/activation-day1-install-chain.yaml b/seaweed-block/testops/scenarios/activation-day1-install-chain.yaml new file mode 100644 index 0000000000..33152430e8 --- /dev/null +++ b/seaweed-block/testops/scenarios/activation-day1-install-chain.yaml @@ -0,0 +1,168 @@ +# Runner-native Phase 20 D1 activation chain. +# +# Goal: +# Prove the documented Day-1 install path as a user-facing product loop: +# preflight -> build/import -> install -> StorageClass -> readiness summary +# -> cleanup. +# +# Expected invocation: +# swblock run \ +# -env product_root=/path/to/seaweed_block/on/m02 \ +# -env ssh_key=/path/to/testdev_key/on/controller \ +# testops/scenarios/activation-day1-install-chain.yaml + +name: activation-day1-install-chain +timeout: 18m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1 && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation /mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/cleanup" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: activate_alpha_stack + actions: + - action: exec + node: m02 + timeout: 12m + cmd: "cd {{ product_root }} && bash scripts/activate-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation" + env.SW_BLOCK_ACTIVATION_IMPORT_K3S: "1" + + - name: activation_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^activation_status=ok$" + save_as: activation_ok_count + - action: assert_greater + actual: "{{ activation_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^master_ready_replicas=1$" + save_as: master_ready_count + - action: assert_greater + actual: "{{ master_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^csi_controller_ready_replicas=1$" + save_as: csi_controller_ready_count + - action: assert_greater + actual: "{{ csi_controller_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^csi_node_ready=[1-9][0-9]*/[1-9][0-9]*$" + save_as: csi_node_ready_count + - action: assert_greater + actual: "{{ csi_node_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^storageclass=sw-block-dynamic$" + save_as: storageclass_count + - action: assert_greater + actual: "{{ storageclass_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^storageclass_provider=block.csi.seaweedfs.com$" + save_as: storageclass_provider_count + - action: assert_greater + actual: "{{ storageclass_provider_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^protocol=iscsi$" + save_as: protocol_count + - action: assert_greater + actual: "{{ protocol_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "^ack_profile=best-effort$" + save_as: ack_profile_count + - action: assert_greater + actual: "{{ ack_profile_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml" + save_as: next_create_volume_count + - action: assert_greater + actual: "{{ next_create_volume_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/activation-summary.txt" + pattern: "non_claims=alpha_only,no_backup_restore,no_upgrade_safety,no_mutating_dashboard_actions,no_broad_performance_slo" + save_as: non_claims_count + - action: assert_greater + actual: "{{ non_claims_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/activation/readiness.txt" + pattern: "sw-block-csi-node" + save_as: readiness_csi_node_count + - action: assert_greater + actual: "{{ readiness_csi_node_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/cleanup" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-activation-day1/cleanup/delete-storageclass.log" + pattern: "sw-block-dynamic" + save_as: storageclass_cleanup_count + - action: assert_greater + actual: "{{ storageclass_cleanup_count }}" + threshold: "0" diff --git a/seaweed-block/testops/scenarios/light-use-first-volume-failure-bundle-chain.yaml b/seaweed-block/testops/scenarios/light-use-first-volume-failure-bundle-chain.yaml index a11f07c809..ef2ffa6377 100644 --- a/seaweed-block/testops/scenarios/light-use-first-volume-failure-bundle-chain.yaml +++ b/seaweed-block/testops/scenarios/light-use-first-volume-failure-bundle-chain.yaml @@ -162,12 +162,12 @@ phases: - name: final_asserts actions: + # The controlled stop intentionally leaves blockmaster/blockvolume live so + # ops-status can inspect a real target. Process hygiene is asserted after + # collect_and_cleanup uninstalls the alpha stack. - action: assert_no_active_iscsi_sessions node: m02 iqn_substr: "io.seaweedfs" - - action: assert_no_processes - node: m02 - pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " - name: collect_and_cleanup always: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-app-baseline-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-app-baseline-chain.yaml new file mode 100644 index 0000000000..f8e14c7ed1 --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-app-baseline-chain.yaml @@ -0,0 +1,208 @@ +# Runner-native mounted failover MVP RF=2 app-path baseline gate. +# +# Goal: +# Prove the documented app/PVC writer -> reader path works with an RF=2 +# product-owned blockvolume placement before injecting primary failure. This +# is a baseline for the mounted failover gate, not a recovery claim. + +name: mounted-failover-rf2-app-baseline-chain +timeout: 20m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf2_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"2\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/demo-app-rf2.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/demo-app-rf2.yaml" + pattern: "replicationFactor: \"2\"" + save_as: rf2_manifest_count + - action: assert_greater + actual: "{{ rf2_manifest_count }}" + threshold: "0" + + - name: rf2_app_writer_reader + actions: + - action: exec + node: m02 + timeout: 12m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/demo-app-rf2.yaml SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-rf2-app SW_BLOCK_DEMO_STOP_AFTER=reader-verified bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/run.log" + pattern: "logical_servers=2" + save_as: logical_servers_count + - action: assert_greater + actual: "{{ logical_servers_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/run.log" + pattern: "expected_slots_per_volume=2" + save_as: expected_slots_count + - action: assert_greater + actual: "{{ expected_slots_count }}" + threshold: "0" + + - name: app_path_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/reader.log" + pattern: "/data/demo.bin: OK" + save_as: reader_checksum_count + - action: assert_greater + actual: "{{ reader_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/generated-blockvolume.yaml" + pattern: "--replica-id=r1" + save_as: r1_manifest_count + - action: assert_greater + actual: "{{ r1_manifest_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/generated-blockvolume.yaml" + pattern: "--replica-id=r2" + save_as: r2_manifest_count + - action: assert_greater + actual: "{{ r2_manifest_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/ops-inventory-reader-verified/volume-inventory-summary.txt" + pattern: "pvc=sw-block-demo-pvc" + save_as: inventory_pvc_count + - action: assert_greater + actual: "{{ inventory_pvc_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/ops-inventory-reader-verified/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: inventory_rf2_count + - action: assert_greater + actual: "{{ inventory_rf2_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/demo/ops-inventory-reader-verified/nested-ops-status-bundles.json" + pattern: "\"command\": \"sw-block ops status\"" + save_as: nested_status_bundle_count + - action: assert_greater + actual: "{{ nested_status_bundle_count }}" + threshold: "1" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-rf2-app; find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec sudo rm -rf -- {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: exec + node: m02 + cmd: "test ! -e /var/lib/sw-block/testops-{{ run_id }}-rf2-app" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-app-baseline" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-degraded-replica-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-degraded-replica-chain.yaml new file mode 100644 index 0000000000..dc7007e24f --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-degraded-replica-chain.yaml @@ -0,0 +1,234 @@ +# Runner-native mounted failover MVP degraded-replica negative gate. +# +# Goal: +# Prove an RF=2 Kubernetes placement with one replica workload scaled to zero +# is reported as degraded and not as a recovered/healthy RF=2 state. This is +# a D5 negative fixture, not the final mounted recovery claim. + +name: mounted-failover-rf2-degraded-replica-chain +timeout: 18m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2 /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory" + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-degraded-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-rf2-degraded --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: install_rf2_alpha_stack + actions: + - action: exec + node: m02 + timeout: 6m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/pin_build/alpha-images.env; set +a; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/install SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 bash scripts/install-k8s-alpha.sh {{ product_root }}'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/install/install.log" + pattern: "logical_servers=2" + save_as: logical_servers_count + - action: assert_greater + actual: "{{ logical_servers_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/install/install.log" + pattern: "expected_slots_per_volume=2" + save_as: expected_slots_count + - action: assert_greater + actual: "{{ expected_slots_count }}" + threshold: "0" + + - name: rf2_placement_boundary + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "cat > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/rf2-degraded.yaml <<'YAML'\napiVersion: storage.k8s.io/v1\nkind: StorageClass\nmetadata:\n name: sw-block-rf2-degraded\nprovisioner: block.csi.seaweedfs.com\nvolumeBindingMode: Immediate\nallowVolumeExpansion: false\nparameters:\n replicationFactor: \"2\"\n sw-block.seaweedfs.com/protocol: iscsi\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: sw-block-rf2-degraded-pvc\n namespace: default\nspec:\n accessModes:\n - ReadWriteOnce\n storageClassName: sw-block-rf2-degraded\n resources:\n requests:\n storage: 1Mi\nYAML\nkubectl apply -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/rf2-degraded.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/apply-rf2.log 2>&1\nkubectl -n default wait --for=jsonpath='{.status.phase}'=Bound pvc/sw-block-rf2-degraded-pvc --timeout=120s >> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/apply-rf2.log 2>&1\nfor i in $(seq 1 120); do count=$(kubectl -n default get deploy -l app=sw-blockvolume --no-headers 2>/dev/null | wc -l); test \"$count\" -ge 2 && break; sleep 1; done\ncount=$(kubectl -n default get deploy -l app=sw-blockvolume --no-headers 2>/dev/null | wc -l); test \"$count\" -eq 2\nkubectl -n default wait --for=condition=available deploy -l app=sw-blockvolume --timeout=120s >> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/apply-rf2.log 2>&1\nkubectl -n default get deploy -l app=sw-blockvolume -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/blockvolumes.before-degrade.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/blockvolumes.before-degrade.txt" + pattern: "^sw-blockvolume-" + save_as: rf2_deploy_count + - action: assert_greater + actual: "{{ rf2_deploy_count }}" + threshold: "1" + + - name: degrade_one_replica + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "set -eu\nOUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2\nR2_DEPLOY=$(kubectl -n default get deploy -l app=sw-blockvolume,sw-block.seaweedfs.com/replica=r2 -o jsonpath='{.items[0].metadata.name}')\ntest -n \"$R2_DEPLOY\"\necho \"$R2_DEPLOY\" > \"$OUT/degraded-deployment.txt\"\nkubectl -n default scale deploy \"$R2_DEPLOY\" --replicas=0 > \"$OUT/scale-r2.log\" 2>&1\nfor i in $(seq 1 60); do ready=$(kubectl -n default get deploy \"$R2_DEPLOY\" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true); test -z \"$ready\" -o \"$ready\" = \"0\" && break; sleep 1; done\nkubectl -n default get deploy -l app=sw-blockvolume -o wide > \"$OUT/blockvolumes.after-degrade.txt\"\nready=$(kubectl -n default get deploy \"$R2_DEPLOY\" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true); test -z \"$ready\" -o \"$ready\" = \"0\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/rf2/degraded-deployment.txt" + pattern: "sw-blockvolume-" + save_as: degraded_deploy_name_count + - action: assert_greater + actual: "{{ degraded_deploy_name_count }}" + threshold: "0" + + - name: inventory_after_degraded_replica + actions: + - action: exec + node: m02 + timeout: 4m + cmd: "cd {{ product_root }} && bash -c 'set -euo pipefail; OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory; mkdir -p \"$OUT\"; pf_port=$(python3 - <<\"PY\"\nimport socket\ns=socket.socket(); s.bind((\"127.0.0.1\",0)); print(s.getsockname()[1]); s.close()\nPY\n); kubectl -n kube-system port-forward svc/blockmaster ${pf_port}:9333 > \"$OUT/blockmaster-port-forward.log\" 2>&1 & pf_pid=$!; echo \"$pf_pid\" > \"$OUT/blockmaster-port-forward.pid\"; cleanup(){ kill \"$pf_pid\" >/dev/null 2>&1 || true; wait \"$pf_pid\" >/dev/null 2>&1 || true; }; trap cleanup EXIT; for i in $(seq 1 30); do (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 && break; sleep 1; done; (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1; go run ./cmd/sw-block ops inventory --namespace default --master 127.0.0.1:${pf_port} --out \"$OUT\" --timeout 30s > \"$OUT/stdout.txt\" 2> \"$OUT/stderr.txt\"; rc=$?; echo \"$rc\" > \"$OUT/exit_code.txt\"; find \"$OUT/volumes\" -name ops-status-bundle.json -exec cat {} \\; > \"$OUT/nested-ops-status-bundles.json\" 2>/dev/null || true; exit \"$rc\"'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/exit_code.txt" + pattern: "^0$" + save_as: inventory_exit_zero_count + - action: assert_greater + actual: "{{ inventory_exit_zero_count }}" + threshold: "0" + + - name: inventory_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + pattern: "pvc=sw-block-rf2-degraded-pvc" + save_as: rf2_pvc_identity_count + - action: assert_greater + actual: "{{ rf2_pvc_identity_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: rf2_observed_count + - action: assert_greater + actual: "{{ rf2_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + pattern: "replica: volume=.*replica=r2 .*status=unhealthy" + save_as: r2_unhealthy_count + - action: assert_greater + actual: "{{ r2_unhealthy_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + pattern: "replica_degraded=r2 status=unhealthy" + save_as: r2_degraded_issue_count + - action: assert_greater + actual: "{{ r2_degraded_issue_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + pattern: "ops_status=unhealthy reason=replication_role_not_ready" + save_as: replication_not_ready_count + - action: assert_greater + actual: "{{ replication_not_ready_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q 'generated_deployment_missing\\|observed_replicas=0 desired_replicas=2\\|replica_slot_missing=unknown' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/volume-inventory-summary.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/inventory/nested-ops-status-bundles.json" + pattern: "\"command\": \"sw-block ops status\"" + save_as: nested_status_bundle_count + - action: assert_greater + actual: "{{ nested_status_bundle_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-degraded-pvc --ignore-not-found=true --wait=true --timeout=120s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/delete-rf2-pvc.log 2>&1 || true; kubectl delete sc sw-block-rf2-degraded --ignore-not-found=true > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/delete-rf2-sc.log 2>&1 || true" + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-degraded" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-placement-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-placement-chain.yaml new file mode 100644 index 0000000000..69b0409fcd --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-placement-chain.yaml @@ -0,0 +1,228 @@ +# Runner-native mounted failover MVP RF=2 placement gate. +# +# Goal: +# Prove the alpha stack can be explicitly configured with two logical +# Seaweed Block servers on one Kubernetes node and render two RF=2 +# blockvolume workloads. This is a placement/readiness stepping stone, not +# the mounted failover recovery claim. + +name: mounted-failover-rf2-placement-chain +timeout: 18m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2 /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory" + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-placement-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-rf2-placement --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: install_rf2_alpha_stack + actions: + - action: exec + node: m02 + timeout: 6m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/pin_build/alpha-images.env; set +a; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/install SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 bash scripts/install-k8s-alpha.sh {{ product_root }}'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/install/install.log" + pattern: "logical_servers=2" + save_as: logical_servers_count + - action: assert_greater + actual: "{{ logical_servers_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/install/block-stack.rendered.yaml" + pattern: "server_id: m02-r2" + save_as: second_logical_server_count + - action: assert_greater + actual: "{{ second_logical_server_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/install/block-stack.rendered.yaml" + pattern: "--expected-slots-per-volume=2" + save_as: expected_slots_count + - action: assert_greater + actual: "{{ expected_slots_count }}" + threshold: "0" + + - name: rf2_placement_boundary + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "cat > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/rf2-placement.yaml <<'YAML'\napiVersion: storage.k8s.io/v1\nkind: StorageClass\nmetadata:\n name: sw-block-rf2-placement\nprovisioner: block.csi.seaweedfs.com\nvolumeBindingMode: Immediate\nallowVolumeExpansion: false\nparameters:\n replicationFactor: \"2\"\n sw-block.seaweedfs.com/protocol: iscsi\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: sw-block-rf2-placement-pvc\n namespace: default\nspec:\n accessModes:\n - ReadWriteOnce\n storageClassName: sw-block-rf2-placement\n resources:\n requests:\n storage: 1Mi\nYAML\nkubectl apply -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/rf2-placement.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/apply-rf2.log 2>&1\nkubectl -n default wait --for=jsonpath='{.status.phase}'=Bound pvc/sw-block-rf2-placement-pvc --timeout=120s >> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/apply-rf2.log 2>&1\nfor i in $(seq 1 120); do count=$(kubectl -n default get deploy -l app=sw-blockvolume --no-headers 2>/dev/null | wc -l); test \"$count\" -ge 2 && break; sleep 1; done\ncount=$(kubectl -n default get deploy -l app=sw-blockvolume --no-headers 2>/dev/null | wc -l); test \"$count\" -eq 2\nkubectl -n default wait --for=condition=available deploy -l app=sw-blockvolume --timeout=120s >> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/apply-rf2.log 2>&1\nkubectl -n default get deploy -l app=sw-blockvolume -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/blockvolumes.after-rf2.txt\nkubectl -n kube-system logs deploy/sw-blockmaster -c blockmaster > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/blockmaster.after-rf2.log 2>&1 || true" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/blockvolumes.after-rf2.txt" + pattern: "^sw-blockvolume-" + save_as: rf2_deploy_count + - action: assert_greater + actual: "{{ rf2_deploy_count }}" + threshold: "1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/rf2/blockmaster.after-rf2.log" + pattern: "replication_factor=2" + save_as: rf2_create_count + - action: assert_greater + actual: "{{ rf2_create_count }}" + threshold: "0" + + - name: inventory_rf2_placement + actions: + - action: exec + node: m02 + timeout: 4m + cmd: "cd {{ product_root }} && bash -c 'set -euo pipefail; OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory; mkdir -p \"$OUT\"; pf_port=$(python3 - <<\"PY\"\nimport socket\ns=socket.socket(); s.bind((\"127.0.0.1\",0)); print(s.getsockname()[1]); s.close()\nPY\n); kubectl -n kube-system port-forward svc/blockmaster ${pf_port}:9333 > \"$OUT/blockmaster-port-forward.log\" 2>&1 & pf_pid=$!; echo \"$pf_pid\" > \"$OUT/blockmaster-port-forward.pid\"; cleanup(){ kill \"$pf_pid\" >/dev/null 2>&1 || true; wait \"$pf_pid\" >/dev/null 2>&1 || true; }; trap cleanup EXIT; for i in $(seq 1 30); do (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 && break; sleep 1; done; (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1; go run ./cmd/sw-block ops inventory --namespace default --master 127.0.0.1:${pf_port} --out \"$OUT\" --timeout 30s > \"$OUT/stdout.txt\" 2> \"$OUT/stderr.txt\"; rc=$?; echo \"$rc\" > \"$OUT/exit_code.txt\"; find \"$OUT/volumes\" -name ops-status-bundle.json -exec cat {} \\; > \"$OUT/nested-ops-status-bundles.json\" 2>/dev/null || true; exit \"$rc\"'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/exit_code.txt" + pattern: "^0$" + save_as: inventory_exit_zero_count + - action: assert_greater + actual: "{{ inventory_exit_zero_count }}" + threshold: "0" + + - name: inventory_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/volume-inventory-summary.txt" + pattern: "pvc=sw-block-rf2-placement-pvc" + save_as: rf2_pvc_identity_count + - action: assert_greater + actual: "{{ rf2_pvc_identity_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: rf2_observed_count + - action: assert_greater + actual: "{{ rf2_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/volume-inventory-summary.txt" + pattern: "replica: volume=.*replica=r1 .*server=m02-r1 node=m02" + save_as: r1_logical_server_count + - action: assert_greater + actual: "{{ r1_logical_server_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/volume-inventory-summary.txt" + pattern: "replica: volume=.*replica=r2 .*server=m02-r2 node=m02" + save_as: r2_logical_server_count + - action: assert_greater + actual: "{{ r2_logical_server_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q 'generated_deployment_missing\\|observed_replicas=0 desired_replicas=2\\|replica_slot_missing=unknown' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/volume-inventory-summary.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/inventory/nested-ops-status-bundles.json" + pattern: "\"command\": \"sw-block ops status\"" + save_as: nested_status_bundle_count + - action: assert_greater + actual: "{{ nested_status_bundle_count }}" + threshold: "1" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-placement-pvc --ignore-not-found=true --wait=true --timeout=120s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/delete-rf2-pvc.log 2>&1 || true; kubectl delete sc sw-block-rf2-placement --ignore-not-found=true > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/delete-rf2-sc.log 2>&1 || true" + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-placement" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-primary-failure-safe-refusal-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-primary-failure-safe-refusal-chain.yaml new file mode 100644 index 0000000000..8e6b5164fa --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-primary-failure-safe-refusal-chain.yaml @@ -0,0 +1,296 @@ +# Runner-native mounted failover MVP controlled-primary-failure safe-refusal gate. +# +# Goal: +# Write data through the RF=2 Kubernetes app/PVC path, identify the current +# primary, inject a scoped primary blockvolume stop before the replacement +# reader attaches, and require an explicit safe-refusal bundle. This does not +# claim recovery; it proves the product refuses to promote a not-ready +# candidate silently. + +name: mounted-failover-rf2-primary-failure-safe-refusal-chain +timeout: 22m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf2_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"2\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/demo-app-rf2.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/demo-app-rf2.yaml" + pattern: "replicationFactor: \"2\"" + save_as: rf2_manifest_count + - action: assert_greater + actual: "{{ rf2_manifest_count }}" + threshold: "0" + + - name: rf2_primary_failure_safe_refusal + actions: + - action: exec + node: m02 + timeout: 12m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/demo-app-rf2.yaml SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-rf2-primary-safe-refusal SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=scale-primary-to-zero bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/exit_code.txt; test \"$rc\" -eq 46'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/run.log" + pattern: "fail_primary_before_reader=scale-primary-to-zero" + save_as: fail_primary_mode_count + - action: assert_greater + actual: "{{ fail_primary_mode_count }}" + threshold: "0" + + - name: safe_refusal_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "failover_status: refused" + save_as: failover_refused_count + - action: assert_greater + actual: "{{ failover_refused_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "ack_profile: sync-quorum" + save_as: safe_refusal_sync_quorum_count + - action: assert_greater + actual: "{{ safe_refusal_sync_quorum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/generated-blockvolume.yaml" + pattern: "--replication-ack=sync-quorum" + save_as: generated_sync_quorum_count + - action: assert_greater + actual: "{{ generated_sync_quorum_count }}" + threshold: "1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "failure_class=primary-blockvolume-controlled-stop" + save_as: failure_class_count + - action: assert_greater + actual: "{{ failure_class_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt; before=$(sed -n 's/^before_primary_replica=//p' \"$MARKER\"); failed=$(sed -n 's/^failed_replica=//p' \"$MARKER\"); test -n \"$before\" && test \"$before\" = \"$failed\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "candidate_ready=false" + save_as: candidate_not_ready_count + - action: assert_greater + actual: "{{ candidate_not_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/mounted-writer-required-frontier.txt" + pattern: "^pvc-.*=[0-9][0-9]*$" + save_as: mounted_writer_frontier_count + - action: assert_greater + actual: "{{ mounted_writer_frontier_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "required_frontier=pvc-" + save_as: safe_refusal_required_frontier_count + - action: assert_greater + actual: "{{ safe_refusal_required_frontier_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: "required_frontier_known=true" + save_as: before_required_frontier_known_count + - action: assert_greater + actual: "{{ before_required_frontier_known_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q 'required_frontier_missing' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "candidate_promotion_evidence=promotion: .* candidate_ready=false" + save_as: candidate_promotion_evidence_count + - action: assert_greater + actual: "{{ candidate_promotion_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "reason=replication_role_not_ready" + save_as: safe_refusal_exact_reason_count + - action: assert_greater + actual: "{{ safe_refusal_exact_reason_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "candidate_evidence=.*replication=not_ready" + save_as: candidate_evidence_count + - action: assert_greater + actual: "{{ candidate_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "data_check_after_failover=not_claimed" + save_as: no_recovery_claim_count + - action: assert_greater + actual: "{{ no_recovery_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "target_ready_replicas=0" + save_as: target_scaled_zero_count + - action: assert_greater + actual: "{{ target_scaled_zero_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: before_rf2_count + - action: assert_greater + actual: "{{ before_rf2_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: " role=primary " + save_as: before_primary_count + - action: assert_greater + actual: "{{ before_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + pattern: "inventory_status: unhealthy" + save_as: after_unhealthy_count + - action: assert_greater + actual: "{{ after_unhealthy_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/primary-failure-safe-refusal.txt" + pattern: "after_issue_evidence=" + save_as: after_issue_evidence_count + - action: assert_greater + actual: "{{ after_issue_evidence_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q '/data/demo.bin: OK' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/demo/reader.log 2>/dev/null" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec rm -rf {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-primary-safe-refusal" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-ready-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-ready-chain.yaml new file mode 100644 index 0000000000..7e7e256a0e --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-ready-chain.yaml @@ -0,0 +1,207 @@ +# Runner-native RF=2 promotion-ready gate. +# +# Goal: +# Write data through the RF=2 Kubernetes app/PVC path, derive the mounted +# writer durable frontier from the primary support bundle, and require a +# non-primary replica to become promotion-ready under sync-quorum before any +# primary failure is injected. This does not claim recovery. + +name: mounted-failover-rf2-promotion-ready-chain +timeout: 24m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf2_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"2\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/demo-app-rf2.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/demo-app-rf2.yaml" + pattern: "replicationFactor: \"2\"" + save_as: rf2_manifest_count + - action: assert_greater + actual: "{{ rf2_manifest_count }}" + threshold: "0" + + - name: rf2_promotion_ready + actions: + - action: exec + node: m02 + timeout: 14m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/demo-app-rf2.yaml SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-rf2-promotion-ready SW_BLOCK_DEMO_STOP_AFTER=promotion-ready bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/exit_code.txt; test \"$rc\" -eq 47'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/run.log" + pattern: "controlled stop after promotion-ready" + save_as: promotion_ready_log_count + ignore_error: true + + - name: promotion_ready_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/promotion-ready.txt" + pattern: "promotion_ready_status: ready" + save_as: promotion_ready_count + - action: assert_greater + actual: "{{ promotion_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/promotion-ready.txt" + pattern: "ack_profile: sync-quorum" + save_as: sync_quorum_count + - action: assert_greater + actual: "{{ sync_quorum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/promotion-ready.txt" + pattern: "candidate_ready=true" + save_as: candidate_ready_count + - action: assert_greater + actual: "{{ candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/promotion-ready.txt" + pattern: "candidate_promotion_evidence=promotion: .* candidate_ready=true" + save_as: candidate_promotion_evidence_count + - action: assert_greater + actual: "{{ candidate_promotion_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/mounted-writer-required-frontier.txt" + pattern: "^pvc-.*=[0-9][0-9]*$" + save_as: mounted_writer_frontier_count + - action: assert_greater + actual: "{{ mounted_writer_frontier_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/ops-inventory-promotion-ready/volume-inventory-summary.txt" + pattern: "required_frontier_known=true" + save_as: required_frontier_known_count + - action: assert_greater + actual: "{{ required_frontier_known_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/ops-inventory-promotion-ready/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: rf2_count + - action: assert_greater + actual: "{{ rf2_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q '/data/demo.bin: OK' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/demo/reader.log 2>/dev/null" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec rm -rf {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-ready" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-recovery-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-recovery-chain.yaml new file mode 100644 index 0000000000..abd8a77725 --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-promotion-recovery-chain.yaml @@ -0,0 +1,338 @@ +# Runner-native RF=2 promotion recovery gate. +# +# Goal: +# Write data through the RF=2 Kubernetes app/PVC path, prove the non-primary +# replica is promotion-ready under an explicit controlled-best-effort-demo +# claim profile, stop the current primary, wait for master/authority to +# publish the candidate as the new primary, then recreate/reattach the reader +# pod through CSI and verify the same data. This is not a quorum durability +# claim; RF=3 sync-quorum owns that product line. + +name: mounted-failover-rf2-promotion-recovery-chain +timeout: 28m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf2_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"2\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/demo-app-rf2.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/demo-app-rf2.yaml" + pattern: "replicationFactor: \"2\"" + save_as: rf2_manifest_count + - action: assert_greater + actual: "{{ rf2_manifest_count }}" + threshold: "0" + + - name: rf2_promotion_recovery + actions: + - action: exec + node: m02 + timeout: 16m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/demo-app-rf2.yaml SW_BLOCK_ALPHA_LOGICAL_SERVERS=2 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=2 SW_BLOCK_ALPHA_REPLICATION_ACK=best-effort SW_BLOCK_OPS_INVENTORY_CLAIM_PROFILE=controlled-best-effort-demo SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-rf2-promotion-recovery SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE=1 SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=scale-primary-to-zero SW_BLOCK_DEMO_STOP_AFTER=reader-verified bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/run.log" + pattern: "fail_primary_before_reader=scale-primary-to-zero" + save_as: fail_primary_mode_count + - action: assert_greater + actual: "{{ fail_primary_mode_count }}" + threshold: "0" + + - name: recovery_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/reader.log" + pattern: "/data/demo.bin: OK" + save_as: reader_checksum_count + - action: assert_greater + actual: "{{ reader_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "ack_profile: best-effort" + save_as: best_effort_ack_count + - action: assert_greater + actual: "{{ best_effort_ack_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: "claim_profile=controlled-best-effort-demo" + save_as: controlled_best_effort_claim_count + - action: assert_greater + actual: "{{ controlled_best_effort_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "candidate_ready=true" + save_as: candidate_ready_count + - action: assert_greater + actual: "{{ candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "failover_status: promoted" + save_as: failover_promoted_count + - action: assert_greater + actual: "{{ failover_promoted_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/iscsi-sessions.before-primary-failure.txt" + pattern: "No active sessions" + save_as: pre_failure_no_session_count + - action: assert_greater + actual: "{{ pre_failure_no_session_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "target_ready_replicas=0" + save_as: old_primary_stopped_count + - action: assert_greater + actual: "{{ old_primary_stopped_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt; promoted=$(sed -n 's/^promoted_replica=//p' \"$MARKER\"); after=$(sed -n 's/^after_primary_replica=//p' \"$MARKER\"); failed=$(sed -n 's/^failed_replica=//p' \"$MARKER\"); test -n \"$promoted\" && test \"$promoted\" = \"$after\" && test \"$promoted\" != \"$failed\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "post_failure_primary_count=1" + save_as: single_primary_count + - action: assert_greater + actual: "{{ single_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "frontend_primary_ready_issue_count=0" + save_as: no_frontend_ready_issue_count + - action: assert_greater + actual: "{{ no_frontend_ready_issue_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q 'frontend_primary_ready=true' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "failed_replica_after_evidence=replica:" + save_as: failed_replica_evidence_count + - action: assert_greater + actual: "{{ failed_replica_evidence_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt; failed_line=$(sed -n 's/^failed_replica_after_evidence=//p' \"$MARKER\"); test -n \"$failed_line\" && ! printf '%s\n' \"$failed_line\" | grep -q ' role=primary '" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "before_publish_target_evidence=replica:" + save_as: before_publish_evidence_count + - action: assert_greater + actual: "{{ before_publish_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "after_publish_target_evidence=replica:" + save_as: after_publish_evidence_count + - action: assert_greater + actual: "{{ after_publish_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/apply-reader.log" + pattern: "sw-block-demo-reader" + save_as: reader_apply_count + - action: assert_greater + actual: "{{ reader_apply_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt; portal=$(sed -n 's/^after_publish_target_evidence=.* frontend=\\([^ ]*\\).*/\\1/p' \"$MARKER\"); test -n \"$portal\" && grep -q \"NodeStageVolume: .* staged transport=iscsi portal=${portal}\" /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/blockcsi-node.log" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-recovery.txt" + pattern: "data_check_after_failover=reader_checksum_passed" + save_as: reader_after_failover_count + - action: assert_greater + actual: "{{ reader_after_failover_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=primary_observed" + save_as: timeline_primary_observed_count + - action: assert_greater + actual: "{{ timeline_primary_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=candidate_evaluated .*candidate_ready=true" + save_as: timeline_candidate_ready_count + - action: assert_greater + actual: "{{ timeline_candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=primary_failure_injected" + save_as: timeline_failure_injected_count + - action: assert_greater + actual: "{{ timeline_failure_injected_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=authority_published .*to=" + save_as: timeline_authority_published_count + - action: assert_greater + actual: "{{ timeline_authority_published_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=csi_reattach_observed" + save_as: timeline_csi_reattach_count + - action: assert_greater + actual: "{{ timeline_csi_reattach_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/control-plane-timeline.txt" + pattern: "event=data_check .*result=reader_checksum_passed" + save_as: timeline_data_check_count + - action: assert_greater + actual: "{{ timeline_data_check_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=2" + save_as: rf2_observed_count + - action: assert_greater + actual: "{{ rf2_observed_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! test -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/demo/primary-failure-safe-refusal.txt" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-rf2-promotion-recovery; find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec sudo rm -rf -- {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: exec + node: m02 + cmd: "test ! -e /var/lib/sw-block/testops-{{ run_id }}-rf2-promotion-recovery" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf2-promotion-recovery" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf2-safe-refusal-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf2-safe-refusal-chain.yaml new file mode 100644 index 0000000000..3caa10b18c --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf2-safe-refusal-chain.yaml @@ -0,0 +1,218 @@ +# Runner-native mounted failover MVP safe-refusal gate. +# +# Goal: +# Prove the current alpha Kubernetes topology refuses an RF=2 mounted +# failover setup safely when only one placement candidate exists. This is +# intentionally not the happy failover claim; it is the D4 safe-refusal path +# that must stay visible until live RF=2 Kubernetes placement is proven. +# +# Expected invocation: +# swblock run \ +# -env product_root=/path/to/seaweed_block/on/m02 \ +# -env ssh_key=/path/to/testdev_key/on/controller \ +# testops/scenarios/mounted-failover-rf2-safe-refusal-chain.yaml + +name: mounted-failover-rf2-safe-refusal-chain +timeout: 16m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2 /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory" + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-safe-refusal-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-rf2-safe-refusal --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: install_alpha_stack + actions: + - action: exec + node: m02 + timeout: 6m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/pin_build/alpha-images.env; set +a; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/install bash scripts/install-k8s-alpha.sh {{ product_root }}'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/install/install.log" + pattern: "PASS: seaweed-block alpha stack installed" + save_as: install_pass_count + - action: assert_greater + actual: "{{ install_pass_count }}" + threshold: "0" + + - name: rf2_safe_refusal_boundary + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "cat > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/rf2-safe-refusal.yaml <<'YAML'\napiVersion: storage.k8s.io/v1\nkind: StorageClass\nmetadata:\n name: sw-block-rf2-safe-refusal\nprovisioner: block.csi.seaweedfs.com\nvolumeBindingMode: Immediate\nallowVolumeExpansion: false\nparameters:\n replicationFactor: \"2\"\n sw-block.seaweedfs.com/protocol: iscsi\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: sw-block-rf2-safe-refusal-pvc\n namespace: default\nspec:\n accessModes:\n - ReadWriteOnce\n storageClassName: sw-block-rf2-safe-refusal\n resources:\n requests:\n storage: 1Mi\nYAML\nkubectl apply -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/rf2-safe-refusal.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/apply-rf2.log 2>&1\nkubectl -n default wait --for=jsonpath='{.status.phase}'=Bound pvc/sw-block-rf2-safe-refusal-pvc --timeout=120s >> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/apply-rf2.log 2>&1\nsleep 5\nkubectl -n default get pvc sw-block-rf2-safe-refusal-pvc -o yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/rf2-pvc.yaml\nkubectl get pv -o yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/pv.after-rf2.yaml\nkubectl -n default get deploy -l app=sw-blockvolume -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/blockvolumes.after-rf2.txt\nkubectl -n kube-system logs deploy/sw-blockmaster -c blockmaster > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/blockmaster.after-rf2.log 2>&1 || true\n! kubectl -n default get deploy -l app=sw-blockvolume --no-headers 2>/dev/null | grep -q ." + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/apply-rf2.log" + pattern: "persistentvolumeclaim/sw-block-rf2-safe-refusal-pvc created" + save_as: rf2_pvc_created_count + - action: assert_greater + actual: "{{ rf2_pvc_created_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q '^sw-blockvolume-' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/rf2/blockvolumes.after-rf2.txt" + + - name: inventory_safe_refusal + actions: + - action: exec + node: m02 + timeout: 4m + cmd: "cd {{ product_root }} && bash -c 'set -euo pipefail; OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory; mkdir -p \"$OUT\"; pf_port=$(python3 - <<\"PY\"\nimport socket\ns=socket.socket(); s.bind((\"127.0.0.1\",0)); print(s.getsockname()[1]); s.close()\nPY\n); kubectl -n kube-system port-forward svc/blockmaster ${pf_port}:9333 > \"$OUT/blockmaster-port-forward.log\" 2>&1 & pf_pid=$!; echo \"$pf_pid\" > \"$OUT/blockmaster-port-forward.pid\"; cleanup(){ kill \"$pf_pid\" >/dev/null 2>&1 || true; wait \"$pf_pid\" >/dev/null 2>&1 || true; }; trap cleanup EXIT; for i in $(seq 1 30); do (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 && break; sleep 1; done; (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1; go run ./cmd/sw-block ops inventory --namespace default --master 127.0.0.1:${pf_port} --out \"$OUT\" --timeout 30s > \"$OUT/stdout.txt\" 2> \"$OUT/stderr.txt\"; rc=$?; echo \"$rc\" > \"$OUT/exit_code.txt\"; exit \"$rc\"'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/exit_code.txt" + pattern: "^0$" + save_as: inventory_exit_zero_count + - action: assert_greater + actual: "{{ inventory_exit_zero_count }}" + threshold: "0" + + - name: inventory_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "^inventory_status: unhealthy$" + save_as: inventory_unhealthy_count + - action: assert_greater + actual: "{{ inventory_unhealthy_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "pvc=sw-block-rf2-safe-refusal-pvc" + save_as: rf2_pvc_identity_count + - action: assert_greater + actual: "{{ rf2_pvc_identity_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "rf=2 desired=2 observed=0" + save_as: rf2_desired_observed_count + - action: assert_greater + actual: "{{ rf2_desired_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "generated_deployment_missing" + save_as: generated_missing_count + - action: assert_greater + actual: "{{ generated_missing_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "observed_replicas=0 desired_replicas=2" + save_as: observed_deficit_count + - action: assert_greater + actual: "{{ observed_deficit_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/inventory/volume-inventory-summary.txt" + pattern: "replica_slot_missing=unknown" + save_as: missing_slot_count + - action: assert_greater + actual: "{{ missing_slot_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + cmd: "kubectl -n default delete pvc sw-block-rf2-safe-refusal-pvc --ignore-not-found=true --wait=true --timeout=120s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/delete-rf2-pvc.log 2>&1 || true; kubectl delete sc sw-block-rf2-safe-refusal --ignore-not-found=true > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/delete-rf2-sc.log 2>&1 || true" + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-safe-refusal" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/mounted-failover-rf3-sync-quorum-recovery-chain.yaml b/seaweed-block/testops/scenarios/mounted-failover-rf3-sync-quorum-recovery-chain.yaml new file mode 100644 index 0000000000..94282ddc0e --- /dev/null +++ b/seaweed-block/testops/scenarios/mounted-failover-rf3-sync-quorum-recovery-chain.yaml @@ -0,0 +1,338 @@ +# Runner-native RF=3 sync-quorum recovery gate. +# +# Goal: +# Write data through the RF=3 Kubernetes app/PVC path with sync-quorum, +# prove a non-primary replica is promotion-ready under the beta-recovery +# claim profile, stop the current primary, wait for master/authority to +# publish a candidate as the new primary, then recreate/reattach the reader +# pod through CSI and verify the same data. This is the durable writable HA +# Stage 1 product line. + +name: mounted-failover-rf3-sync-quorum-recovery-chain +timeout: 28m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf3_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"3\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/demo-app-rf3.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/demo-app-rf3.yaml" + pattern: "replicationFactor: \"3\"" + save_as: rf3_manifest_count + - action: assert_greater + actual: "{{ rf3_manifest_count }}" + threshold: "0" + + - name: rf3_sync_quorum_recovery + actions: + - action: exec + node: m02 + timeout: 16m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/demo-app-rf3.yaml SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-rf3-sync-quorum-recovery SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE=1 SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=scale-primary-to-zero SW_BLOCK_DEMO_STOP_AFTER=reader-verified bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/run.log" + pattern: "fail_primary_before_reader=scale-primary-to-zero" + save_as: fail_primary_mode_count + - action: assert_greater + actual: "{{ fail_primary_mode_count }}" + threshold: "0" + + - name: recovery_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/reader.log" + pattern: "/data/demo.bin: OK" + save_as: reader_checksum_count + - action: assert_greater + actual: "{{ reader_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "ack_profile: sync-quorum" + save_as: sync_quorum_ack_count + - action: assert_greater + actual: "{{ sync_quorum_ack_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: "claim_profile=beta-recovery" + save_as: beta_recovery_claim_count + - action: assert_greater + actual: "{{ beta_recovery_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "candidate_ready=true" + save_as: candidate_ready_count + - action: assert_greater + actual: "{{ candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "failover_status: promoted" + save_as: failover_promoted_count + - action: assert_greater + actual: "{{ failover_promoted_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/iscsi-sessions.before-primary-failure.txt" + pattern: "No active sessions" + save_as: pre_failure_no_session_count + - action: assert_greater + actual: "{{ pre_failure_no_session_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "target_ready_replicas=0" + save_as: old_primary_stopped_count + - action: assert_greater + actual: "{{ old_primary_stopped_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt; promoted=$(sed -n 's/^promoted_replica=//p' \"$MARKER\"); after=$(sed -n 's/^after_primary_replica=//p' \"$MARKER\"); failed=$(sed -n 's/^failed_replica=//p' \"$MARKER\"); test -n \"$promoted\" && test \"$promoted\" = \"$after\" && test \"$promoted\" != \"$failed\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "post_failure_primary_count=1" + save_as: single_primary_count + - action: assert_greater + actual: "{{ single_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "frontend_primary_ready_issue_count=0" + save_as: no_frontend_ready_issue_count + - action: assert_greater + actual: "{{ no_frontend_ready_issue_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! grep -q 'frontend_primary_ready=true' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "failed_replica_after_evidence=replica:" + save_as: failed_replica_evidence_count + - action: assert_greater + actual: "{{ failed_replica_evidence_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt; failed_line=$(sed -n 's/^failed_replica_after_evidence=//p' \"$MARKER\"); test -n \"$failed_line\" && ! printf '%s\n' \"$failed_line\" | grep -q ' role=primary '" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "before_publish_target_evidence=replica:" + save_as: before_publish_evidence_count + - action: assert_greater + actual: "{{ before_publish_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "after_publish_target_evidence=replica:" + save_as: after_publish_evidence_count + - action: assert_greater + actual: "{{ after_publish_evidence_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/apply-reader.log" + pattern: "sw-block-demo-reader" + save_as: reader_apply_count + - action: assert_greater + actual: "{{ reader_apply_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "MARKER=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt; portal=$(sed -n 's/^after_publish_target_evidence=.* frontend=\\([^ ]*\\).*/\\1/p' \"$MARKER\"); test -n \"$portal\" && grep -q \"NodeStageVolume: .* staged transport=iscsi portal=${portal}\" /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/blockcsi-node.log" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-recovery.txt" + pattern: "data_check_after_failover=reader_checksum_passed" + save_as: reader_after_failover_count + - action: assert_greater + actual: "{{ reader_after_failover_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=primary_observed" + save_as: timeline_primary_observed_count + - action: assert_greater + actual: "{{ timeline_primary_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=candidate_evaluated .*candidate_ready=true" + save_as: timeline_candidate_ready_count + - action: assert_greater + actual: "{{ timeline_candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=primary_failure_injected" + save_as: timeline_failure_injected_count + - action: assert_greater + actual: "{{ timeline_failure_injected_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=authority_published .*to=" + save_as: timeline_authority_published_count + - action: assert_greater + actual: "{{ timeline_authority_published_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=csi_reattach_observed" + save_as: timeline_csi_reattach_count + - action: assert_greater + actual: "{{ timeline_csi_reattach_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/control-plane-timeline.txt" + pattern: "event=data_check .*result=reader_checksum_passed" + save_as: timeline_data_check_count + - action: assert_greater + actual: "{{ timeline_data_check_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + pattern: "rf=3 desired=3 observed=3" + save_as: rf3_observed_count + - action: assert_greater + actual: "{{ rf3_observed_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "! test -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/demo/primary-failure-safe-refusal.txt" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-rf3-sync-quorum-recovery; find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec sudo rm -rf -- {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: exec + node: m02 + cmd: "test ! -e /var/lib/sw-block/testops-{{ run_id }}-rf3-sync-quorum-recovery" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-mounted-failover-rf3-sync-quorum-recovery" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml b/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml new file mode 100644 index 0000000000..9be7b67a93 --- /dev/null +++ b/seaweed-block/testops/scenarios/node-loss-survival-rf3-reattach-chain.yaml @@ -0,0 +1,413 @@ +# Runner-native Node-Loss D4 conservative recovery gate. +# +# This gate consumes the D3 eligible topology: RF=3, sync-quorum, distinct +# Kubernetes nodes, non-loopback frontends/status endpoints, CHAP-protected +# external iSCSI, and loopback publish-target rejection. It injects a scoped +# primary Kubernetes-node failure by cordoning the primary node and stopping the +# primary blockvolume Deployment, then proves conservative recovery through +# CSI/pod recreate on a survivor node. It does not claim physical-host loss or +# transparent in-place I/O continuation. + +name: node-loss-survival-rf3-reattach-chain +timeout: 34m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*blockmaste[r]' >/dev/null 2>&1 || true; sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-node-loss-survival >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: discover_multinode_topology + actions: + - action: exec + node: m02 + cmd: | + set -euo pipefail + B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival + cd {{ product_root }} + bash scripts/preflight-node-loss-lab.sh \ + --min-k8s-nodes 3 \ + --topology-out "$B/cluster-topology.txt" \ + --topology-json-out "$B/cluster-topology.json" \ + --env-out "$B/node-specs.env" \ + --placement-out "$B/node-placement.before.txt" \ + > "$B/node-loss-lab-preflight.txt" 2>&1 + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/node-placement.before.txt" + pattern: "node_loss_topology_eligible=true" + save_as: topology_eligible_count + - action: assert_greater + actual: "{{ topology_eligible_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/node-placement.before.txt" + pattern: "physical_host_loss_claimed=false" + save_as: no_physical_host_loss_claim_count + - action: assert_greater + actual: "{{ no_physical_host_loss_claim_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: | + set -euo pipefail + B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival + cd {{ product_root }} + set -a + source "$B/node-specs.env" + set +a + SW_BLOCK_IMPORT_K3S=1 \ + SW_BLOCK_IMPORT_K3S_NODES="$K3S_IMPORT_NODES" \ + SW_BLOCK_IMPORT_K3S_SSH_USER=testdev \ + SW_BLOCK_IMPORT_K3S_SSH_KEY=/opt/work/testdev_key \ + SW_BLOCK_ARTIFACT_DIR="$B/pin_build" \ + bash scripts/build-alpha-images.sh {{ product_root }} + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMPORT_K3S_NODES=" + save_as: k3s_import_nodes_count + - action: assert_greater + actual: "{{ k3s_import_nodes_count }}" + threshold: "0" + + - name: render_rf3_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"3\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/demo-app-rf3.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/demo-app-rf3.yaml" + pattern: "replicationFactor: \"3\"" + save_as: rf3_manifest_count + - action: assert_greater + actual: "{{ rf3_manifest_count }}" + threshold: "0" + + - name: rf3_node_loss_recovery + actions: + - action: exec + node: m02 + timeout: 20m + cmd: | + cd {{ product_root }} + bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/pin_build/alpha-images.env; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/node-specs.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/demo-app-rf3.yaml SW_BLOCK_DEMO_APP_NODE_NAME="$APP_NODE" SW_BLOCK_DEMO_READER_NODE_NAME="$SURVIVOR_APP_NODE" SW_BLOCK_ALPHA_NODE_SPECS="$NODE_SPECS" SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1 SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=1 SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS=1 SW_BLOCK_ISCSI_CHAP_SECRET_NAME=sw-block-node-loss-chap SW_BLOCK_ISCSI_CHAP_USERNAME=testops-node-loss SW_BLOCK_ISCSI_CHAP_SECRET=testops-node-loss-{{ run_id }} SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-node-loss-survival SW_BLOCK_DEMO_REQUIRE_PROMOTION_READY_BEFORE_FAILURE=1 SW_BLOCK_DEMO_FAIL_PRIMARY_BEFORE_READER=cordon-node-scale-primary-to-zero SW_BLOCK_DEMO_STOP_AFTER=reader-verified SW_BLOCK_DEMO_KEEP_ON_STOP=1 bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/exit_code.txt; test "$rc" -eq 44' + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/run.log" + pattern: "fail_primary_before_reader=cordon-node-scale-primary-to-zero" + save_as: node_loss_failure_mode_count + - action: assert_greater + actual: "{{ node_loss_failure_mode_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo; { echo bounded_waits=pass; echo attach=bounded_by_demo_waits; echo failure_injection=bounded_by_scale_wait; echo authority_promotion=bounded_by_240s_inventory_poll; echo csi_reattach=bounded_by_reader_pod_wait; echo data_check=bounded_by_reader_pod_wait; echo cleanup=bounded_by_collect_and_cleanup_phase; } > \"$B/bounded-waits.txt\"" + - action: exec + node: m02 + timeout: 4m + cmd: | + cd {{ product_root }} + bash -c 'set -euo pipefail + OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation + mkdir -p "$OUT" + pf_port=$(python3 - <<"PY" + import socket + s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close() + PY + ) + kubectl -n kube-system get svc,deploy,pods -o wide > "$OUT/kube-system-before-port-forward.txt" 2>&1 || true + kubectl -n kube-system wait --for=condition=available deploy/sw-blockmaster --timeout=60s > "$OUT/blockmaster-deploy-wait.log" 2>&1 + kubectl -n kube-system port-forward deploy/sw-blockmaster ${pf_port}:9333 > "$OUT/blockmaster-port-forward.log" 2>&1 & + pf_pid=$! + echo "$pf_pid" > "$OUT/blockmaster-port-forward.pid" + cleanup(){ kill "$pf_pid" >/dev/null 2>&1 || true; wait "$pf_pid" >/dev/null 2>&1 || true; } + trap cleanup EXIT + for i in $(seq 1 30); do (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 && break; sleep 1; done + (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 + go run ./cmd/sw-block ops cluster --master-api 127.0.0.1:${pf_port} --timeout 30s -o json > "$OUT/cluster-evidence.json" 2> "$OUT/cluster-evidence.stderr.txt" + test -s "$OUT/cluster-evidence.json"' + + - name: recovery_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/writer.log" + pattern: "\\[app-writer\\] wrote and verified /data/demo.bin" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/reader.log" + pattern: "/data/demo.bin: OK" + save_as: reader_checksum_count + - action: assert_greater + actual: "{{ reader_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "ack_profile: sync-quorum" + save_as: sync_quorum_ack_count + - action: assert_greater + actual: "{{ sync_quorum_ack_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "failure_class=primary-kubernetes-node-cordoned-blockvolume-stop" + save_as: node_failure_class_count + - action: assert_greater + actual: "{{ node_failure_class_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; before=$(sed -n 's/^before_primary_node=//p' \"$M\" | head -1); failed=$(sed -n 's/^failed_node=//p' \"$M\" | head -1); test -n \"$before\" && test \"$before\" = \"$failed\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "candidate_ready=true" + save_as: candidate_ready_count + - action: assert_greater + actual: "{{ candidate_ready_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "failover_status: promoted" + save_as: failover_promoted_count + - action: assert_greater + actual: "{{ failover_promoted_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; promoted=$(sed -n 's/^promoted_replica=//p' \"$M\" | tail -1); failed=$(sed -n 's/^failed_replica=//p' \"$M\" | head -1); promoted_node=$(sed -n 's/^promoted_replica_node=//p' \"$M\" | tail -1); failed_node=$(sed -n 's/^failed_node=//p' \"$M\" | head -1); test -n \"$promoted\" && test \"$promoted\" != \"$failed\" && test -n \"$promoted_node\" && test \"$promoted_node\" != \"$failed_node\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "post_failure_primary_count=1" + save_as: single_primary_count + - action: assert_greater + actual: "{{ single_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "node_loss_recovery_claimed=true" + save_as: node_loss_recovery_claim_count + - action: assert_greater + actual: "{{ node_loss_recovery_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "data_check_after_node_loss=reader_checksum_passed" + save_as: node_loss_checksum_count + - action: assert_greater + actual: "{{ node_loss_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "pod_recreate_used=true" + save_as: pod_recreate_count + - action: assert_greater + actual: "{{ pod_recreate_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "transparent_failover_claimed=false" + save_as: no_transparent_claim_count + - action: assert_greater + actual: "{{ no_transparent_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "physical_host_loss_claimed=false" + save_as: no_physical_host_loss_claim_count + - action: assert_greater + actual: "{{ no_physical_host_loss_claim_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt" + pattern: "old_primary_stale_io_success_count=0" + save_as: stale_primary_fenced_count + - action: assert_greater + actual: "{{ stale_primary_fenced_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/bounded-waits.txt" + pattern: "bounded_waits=pass" + save_as: bounded_waits_count + - action: assert_greater + actual: "{{ bounded_waits_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/ops-inventory-before-primary-failure/volume-inventory-summary.txt" + pattern: "replicas_on_distinct_nodes=true frontends_non_loopback=true" + save_as: topology_marker_count + - action: assert_greater + actual: "{{ topology_marker_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/ops-inventory-after-primary-failure/volume-inventory-summary.txt" + pattern: "rf=3 desired=3 observed=3" + save_as: rf3_after_count + - action: assert_greater + actual: "{{ rf3_after_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "M=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/primary-failure-recovery.txt; before=$(sed -n 's/^before_publish_target_frontend=//p' \"$M\" | head -1); portal=$(sed -n 's/^after_publish_target_frontend=//p' \"$M\" | tail -1); test -n \"$portal\" && test \"$portal\" != \"$before\" && ! printf '%s\n' \"$portal\" | grep -q '^127\\.0\\.0\\.1:' && grep -q \"NodeStageVolume: .* staged transport=iscsi portal=${portal}\" /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/blockcsi-node.log" + - action: exec + node: m02 + cmd: "test -s /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-boundary.txt && grep -q 'node_loss_recovery_claimed=true' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-boundary.txt" + - action: exec + node: m02 + cmd: "S=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/node-loss-recovery-summary.txt; test -s \"$S\" && grep -q '^node_loss_recovery_summary_version=1$' \"$S\" && grep -q '^result=promoted$' \"$S\" && grep -q '^data_check_after_node_loss=reader_checksum_passed$' \"$S\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/control-plane-timeline.txt" + pattern: "event=primary_failure_injected .*failure_class=primary-kubernetes-node-cordoned-blockvolume-stop" + save_as: timeline_node_failure_count + - action: assert_greater + actual: "{{ timeline_node_failure_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json" + pattern: "\"event_type\": \"placement_verified\"" + save_as: product_event_placement_count + - action: assert_greater + actual: "{{ product_event_placement_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json" + pattern: "\"event_type\": \"promotion_candidate_evaluated\"" + save_as: product_event_candidate_count + - action: assert_greater + actual: "{{ product_event_candidate_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json" + pattern: "\"event_type\": \"authority_published\"" + save_as: product_event_authority_count + - action: assert_greater + actual: "{{ product_event_authority_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/product-observation/cluster-evidence.json" + pattern: "\"event_type\": \"csi_reattach_observed\"" + save_as: product_event_csi_reattach_count + - action: assert_greater + actual: "{{ product_event_csi_reattach_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "test -s /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/cordon-primary-node.log && grep -qi 'cordoned' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/cordon-primary-node.log" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 4m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + env.SW_BLOCK_ISCSI_CHAP_SECRET_NAME: "sw-block-node-loss-chap" + - action: exec + node: m02 + cmd: "N=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival/demo/cordoned-primary-node.txt; if test -s \"$N\"; then node=$(cat \"$N\"); kubectl uncordon \"$node\" >/dev/null 2>&1 || true; test \"$(kubectl get node \"$node\" -o jsonpath='{.spec.unschedulable}' 2>/dev/null || true)\" != \"true\"; fi" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-node-loss-survival; test ! -e /var/lib/sw-block/testops-{{ run_id }}-node-loss-survival; pkill -f 'kubectl.*port-forward.*blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-survival" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/node-loss-topology-eligibility-chain.yaml b/seaweed-block/testops/scenarios/node-loss-topology-eligibility-chain.yaml new file mode 100644 index 0000000000..3e1d897f45 --- /dev/null +++ b/seaweed-block/testops/scenarios/node-loss-topology-eligibility-chain.yaml @@ -0,0 +1,289 @@ +# Runner-native Node-Loss D3 topology eligibility gate. +# +# This is not the recovery gate. It proves the alpha Kubernetes path can render +# RF=3 across real Kubernetes nodes with non-loopback iSCSI/status endpoints, +# CHAP-protected external iSCSI, loopback publish-target rejection, and stable +# inventory eligibility markers. Three Kubernetes nodes may share two physical +# machines for this MVP gate, but the physical/fault-domain shape is recorded +# and the close report must not over-claim full physical-host loss unless the +# artifacts prove distinct physical hosts. D4 consumes this topology to inject +# primary node loss and prove CSI/pod-recreate recovery. + +name: node-loss-topology-eligibility-chain +timeout: 28m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true; sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-node-loss-topology >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: discover_multinode_topology + actions: + - action: exec + node: m02 + cmd: | + set -euo pipefail + B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology + cd {{ product_root }} + bash scripts/preflight-node-loss-lab.sh \ + --min-k8s-nodes 3 \ + --topology-out "$B/cluster-topology.txt" \ + --topology-json-out "$B/cluster-topology.json" \ + --env-out "$B/node-specs.env" \ + --placement-out "$B/node-placement.before.txt" \ + > "$B/node-loss-lab-preflight.txt" 2>&1 + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/node-placement.before.txt" + pattern: "node_loss_topology_eligible=true" + save_as: topology_eligible_count + - action: assert_greater + actual: "{{ topology_eligible_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/node-placement.before.txt" + pattern: "selected_node_count=3" + save_as: selected_node_count + - action: assert_greater + actual: "{{ selected_node_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/node-placement.before.txt" + pattern: "physical_host_loss_claimed=false" + save_as: no_physical_host_loss_claim_count + - action: assert_greater + actual: "{{ no_physical_host_loss_claim_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: | + set -euo pipefail + B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology + cd {{ product_root }} + set -a + source "$B/node-specs.env" + set +a + SW_BLOCK_IMPORT_K3S=1 \ + SW_BLOCK_IMPORT_K3S_NODES="$K3S_IMPORT_NODES" \ + SW_BLOCK_IMPORT_K3S_SSH_USER=testdev \ + SW_BLOCK_IMPORT_K3S_SSH_KEY=/opt/work/testdev_key \ + SW_BLOCK_ARTIFACT_DIR="$B/pin_build" \ + bash scripts/build-alpha-images.sh {{ product_root }} + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMPORT_K3S_NODES=" + save_as: k3s_import_nodes_count + - action: assert_greater + actual: "{{ k3s_import_nodes_count }}" + threshold: "0" + + - name: render_rf3_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"3\"/' deploy/k8s/alpha/demo-app-pvc.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/demo-app-rf3.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/demo-app-rf3.yaml" + pattern: "replicationFactor: \"3\"" + save_as: rf3_manifest_count + - action: assert_greater + actual: "{{ rf3_manifest_count }}" + threshold: "0" + + - name: rf3_external_topology + actions: + - action: exec + node: m02 + timeout: 16m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/pin_build/alpha-images.env; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/node-specs.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/demo-app-rf3.yaml SW_BLOCK_DEMO_APP_NODE_NAME=\"$APP_NODE\" SW_BLOCK_ALPHA_NODE_SPECS=\"$NODE_SPECS\" SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=1 SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=1 SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS=1 SW_BLOCK_ISCSI_CHAP_SECRET_NAME=sw-block-node-loss-chap SW_BLOCK_ISCSI_CHAP_USERNAME=testops-node-loss SW_BLOCK_ISCSI_CHAP_SECRET=testops-node-loss-{{ run_id }} SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-node-loss-topology SW_BLOCK_DEMO_STOP_AFTER=writer-verified bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology; { cat \"$B/node-placement.before.txt\"; echo kubernetes_node_loss_claimed=true; echo physical_host_loss_claimed=false; echo transparent_node_loss_claimed=false; echo recovery_gate=D4-not-this-scenario; } > \"$B/demo/node-loss-claim-boundary.txt\"" + + - name: topology_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/run.log" + pattern: "launcher_external_iscsi=1" + save_as: external_iscsi_count + - action: assert_greater + actual: "{{ external_iscsi_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/run.log" + pattern: "launcher_external_status=1" + save_as: external_status_count + - action: assert_greater + actual: "{{ external_status_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/run.log" + pattern: "reject_loopback_publish_targets=1" + save_as: reject_loopback_count + - action: assert_greater + actual: "{{ reject_loopback_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/run.log" + pattern: "chap_enabled=1" + save_as: chap_enabled_count + - action: assert_greater + actual: "{{ chap_enabled_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/writer.log" + pattern: "/data/demo.bin: OK" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/controlled-stop-writer-verified.txt" + pattern: "phase=writer-verified" + save_as: writer_verified_stop_count + - action: assert_greater + actual: "{{ writer_verified_stop_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/node-loss-claim-boundary.txt" + pattern: "physical_host_loss_claimed=false" + save_as: physical_host_nonclaim_count + - action: assert_greater + actual: "{{ physical_host_nonclaim_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo; test \"$(grep -c -- '--replica-id=r' \"$B/generated-blockvolume.yaml\")\" -ge 3; test \"$(grep -c -- '--allow-external-iscsi-bind' \"$B/generated-blockvolume.yaml\")\" -ge 3; test \"$(grep -c -- '--allow-external-status-bind' \"$B/generated-blockvolume.yaml\")\" -ge 3" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo; ! grep -Eq -- '--(iscsi-listen|status-addr)=127\\.0\\.0\\.1|--(iscsi-listen|status-addr)=localhost' \"$B/generated-blockvolume.yaml\"" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/csi-controller.rendered.yaml" + pattern: "--reject-loopback-publish-targets" + save_as: csi_controller_reject_loopback_count + - action: assert_greater + actual: "{{ csi_controller_reject_loopback_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/csi-node.rendered.yaml" + pattern: "--reject-loopback-publish-targets" + save_as: csi_node_reject_loopback_count + - action: assert_greater + actual: "{{ csi_node_reject_loopback_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/ops-inventory-writer-verified/volume-inventory-summary.txt" + pattern: "rf=3 desired=3 observed=3" + save_as: rf3_observed_count + - action: assert_greater + actual: "{{ rf3_observed_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/ops-inventory-writer-verified/volume-inventory-summary.txt" + pattern: "replicas_on_distinct_nodes=true frontends_non_loopback=true" + save_as: topology_marker_count + - action: assert_greater + actual: "{{ topology_marker_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo/ops-inventory-writer-verified; test \"$(grep -c '^replica: volume=.* node=' \"$B/volume-inventory-summary.txt\")\" -ge 3; ! grep -Eq 'frontend=127\\.0\\.0\\.1|status_addr=127\\.0\\.0\\.1|frontend=localhost|status_addr=localhost' \"$B/volume-inventory-summary.txt\"" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/demo; grep -q 'NodeStageVolume: .* staged transport=iscsi' \"$B/blockcsi-node.log\"; ! grep -q 'NodeStageVolume: .* portal=127.0.0.1' \"$B/blockcsi-node.log\"" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-node-loss-topology/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + env.SW_BLOCK_ISCSI_CHAP_SECRET_NAME: "sw-block-node-loss-chap" + - action: exec + node: m02 + cmd: "sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-node-loss-topology; test ! -e /var/lib/sw-block/testops-{{ run_id }}-node-loss-topology" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " diff --git a/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml b/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml new file mode 100644 index 0000000000..331052ff46 --- /dev/null +++ b/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-baseline-chain.yaml @@ -0,0 +1,285 @@ +# Runner-native Stage 2 iSCSI ALUA + dm-multipath wiring gate. +# +# This is the first Kubernetes Stage 2 runner boundary, not the close gate. +# It proves the alpha K8s path can opt into CSI multipath, expose an RF=3 +# iSCSI topology with one shared IQN, and produce host multipath evidence. +# Transparent mounted failover without pod recreate remains a later gate. + +name: stage2-iscsi-alua-multipath-baseline-chain +timeout: 28m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: host_multipath_prereq + actions: + - action: exec + node: m02 + cmd: "set -e; B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath; { echo stage2_protocol=iscsi-alua; command -v iscsiadm >/dev/null && echo command_iscsiadm=present; command -v multipath >/dev/null && echo command_multipath=present; command -v sg_rtpg >/dev/null && echo command_sg_rtpg=present; command -v sg_inq >/dev/null && echo command_sg_inq=present; sudo modprobe iscsi_tcp; sudo modprobe dm_multipath; sudo modprobe scsi_dh_alua; test -d /sys/module/iscsi_tcp && echo module_iscsi_tcp=loaded; test -d /sys/module/dm_multipath && echo module_dm_multipath=loaded; test -d /sys/module/scsi_dh_alua && echo module_scsi_dh_alua=loaded; test -d /run/udev && echo udev_run=present; sudo multipath -t > \"$B/multipath-prereq.config.txt\" 2>&1; sudo multipath -ll > \"$B/multipath-prereq.multipath-ll.txt\" 2>&1 || true; echo multipath_prereq=pass; } > \"$B/multipath-prereq.txt\" 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/multipath-prereq.txt" + pattern: "multipath_prereq=pass" + save_as: multipath_prereq_count + - action: assert_greater + actual: "{{ multipath_prereq_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf3_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"3\"/' deploy/k8s/alpha/demo-app-pvc-writer-hold.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/demo-app-rf3.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/demo-app-rf3.yaml" + pattern: "replicationFactor: \"3\"" + save_as: rf3_manifest_count + - action: assert_greater + actual: "{{ rf3_manifest_count }}" + threshold: "0" + + - name: stage2_multipath_baseline + actions: + - action: exec + node: m02 + timeout: 16m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/demo-app-rf3.yaml SW_BLOCK_STAGE2_MULTIPATH=1 SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath SW_BLOCK_DEMO_STOP_AFTER=writer-verified bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo; { echo transparent_failover_claimed=false; echo pod_recreate_path_used_for_baseline=true; echo next_required_gate=mounted_writer_primary_failure_without_pod_recreate; } > \"$B/stage2-claim-boundary.txt\"" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo; echo bounded_waits=writer_mounted_baseline > \"$B/bounded-waits.txt\"; echo close_gate_requires=post_failure_mounted_io_without_pod_recreate >> \"$B/bounded-waits.txt\"" + + - name: stage2_wiring_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/run.log" + pattern: "stage2_multipath=1" + save_as: stage2_log_count + - action: assert_greater + actual: "{{ stage2_log_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/csi-controller.rendered.yaml" + pattern: "--stage2-multipath" + save_as: csi_controller_stage2_count + - action: assert_greater + actual: "{{ csi_controller_stage2_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/csi-node.rendered.yaml" + pattern: "--stage2-multipath" + save_as: csi_node_stage2_count + - action: assert_greater + actual: "{{ csi_node_stage2_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/generated-blockvolume.yaml" + pattern: "--replica-id=r1" + save_as: r1_count + - action: assert_greater + actual: "{{ r1_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/generated-blockvolume.yaml" + pattern: "--replica-id=r2" + save_as: r2_count + - action: assert_greater + actual: "{{ r2_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/generated-blockvolume.yaml" + pattern: "--replica-id=r3" + save_as: r3_count + - action: assert_greater + actual: "{{ r3_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo; grep -o -- '--iscsi-iqn=[^\" ]*' \"$B/generated-blockvolume.yaml\" | sort -u > \"$B/unique-iscsi-iqns.txt\"; test \"$(wc -l < \"$B/unique-iscsi-iqns.txt\")\" -eq 1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/blockcsi-node.log" + pattern: "multipath=true" + save_as: node_multipath_count + - action: assert_greater + actual: "{{ node_multipath_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/blockcsi-node.log" + pattern: "staged transport=iscsi .* portals=.*127.0.0.1:3260" + save_as: node_multipath_portal_3260_count + - action: assert_greater + actual: "{{ node_multipath_portal_3260_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/blockcsi-node.log" + pattern: "staged transport=iscsi .* portals=.*127.0.0.1:3261" + save_as: node_multipath_portal_3261_count + - action: assert_greater + actual: "{{ node_multipath_portal_3261_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/blockcsi-node.log" + pattern: "staged transport=iscsi .* portals=.*127.0.0.1:3262" + save_as: node_multipath_portal_3262_count + - action: assert_greater + actual: "{{ node_multipath_portal_3262_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/writer.log" + pattern: "/data/demo.bin: OK" + save_as: writer_checksum_count + - action: assert_greater + actual: "{{ writer_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/controlled-stop-writer-verified.txt" + pattern: "phase=writer-verified" + save_as: writer_verified_stop_count + - action: assert_greater + actual: "{{ writer_verified_stop_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/sg-rtpg.writer-mounted.txt" + pattern: "asymmetric access state" + save_as: rtpg_state_count + - action: assert_greater + actual: "{{ rtpg_state_count }}" + threshold: "0" + - action: exec + node: m02 + cmd: "test -s /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/multipath.writer-mounted.txt" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/iscsi-sessions.writer-mounted.txt" + pattern: "iqn.2026-05.io.seaweedfs" + save_as: writer_mounted_session_count + - action: assert_greater + actual: "{{ writer_mounted_session_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/demo/stage2-claim-boundary.txt" + pattern: "transparent_failover_claimed=false" + save_as: no_false_stage2_claim_count + - action: assert_greater + actual: "{{ no_false_stage2_claim_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "for map in $(sudo multipath -ll 2>/dev/null | awk '/^[^[:space:]][^ ]*[[:space:]]+\\(.*\\)/{print $1}'); do if sudo multipath -ll \"$map\" 2>/dev/null | grep -q 'io.seaweedfs'; then sudo multipath -f \"$map\" || true; fi; done; sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath; find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec sudo rm -rf -- {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: exec + node: m02 + cmd: "test ! -e /var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath" + - action: exec + node: m02 + cmd: "! sudo multipath -ll 2>/dev/null | grep -q 'io.seaweedfs'" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml b/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml new file mode 100644 index 0000000000..ebac0cf65d --- /dev/null +++ b/seaweed-block/testops/scenarios/stage2-iscsi-alua-multipath-failover-chain.yaml @@ -0,0 +1,318 @@ +# Runner-native Stage 2 iSCSI ALUA + dm-multipath mounted failover gate. +# +# Unlike the baseline chain, this keeps the original writer pod mounted, +# injects failure into the live primary blockvolume, and verifies data from the +# same pod without reader pod recreate or CSI re-stage. + +name: stage2-iscsi-alua-multipath-failover-chain +timeout: 32m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/pin_build /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover" + - action: exec + node: m02 + cmd: "kubectl -n default delete pod sw-block-demo-reader sw-block-demo-writer --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl -n default delete pvc sw-block-demo-pvc --ignore-not-found=true --wait=true --timeout=120s >/dev/null 2>&1 || true; kubectl delete sc sw-block-dynamic --ignore-not-found=true >/dev/null 2>&1 || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: preflight + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && bash scripts/preflight-k8s-alpha.sh --local-k3s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/preflight.txt 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/preflight.txt" + pattern: "summary status=PASS" + save_as: preflight_count + - action: assert_greater + actual: "{{ preflight_count }}" + threshold: "0" + + - name: host_multipath_prereq + actions: + - action: exec + node: m02 + cmd: "set -e; B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover; { echo stage2_protocol=iscsi-alua; command -v iscsiadm >/dev/null && echo command_iscsiadm=present; command -v multipath >/dev/null && echo command_multipath=present; command -v sg_rtpg >/dev/null && echo command_sg_rtpg=present; command -v sg_inq >/dev/null && echo command_sg_inq=present; sudo modprobe iscsi_tcp; sudo modprobe dm_multipath; sudo modprobe scsi_dh_alua; test -d /sys/module/iscsi_tcp && echo module_iscsi_tcp=loaded; test -d /sys/module/dm_multipath && echo module_dm_multipath=loaded; test -d /sys/module/scsi_dh_alua && echo module_scsi_dh_alua=loaded; test -d /run/udev && echo udev_run=present; sudo multipath -t > \"$B/multipath-prereq.config.txt\" 2>&1; sudo multipath -ll > \"$B/multipath-prereq.multipath-ll.txt\" 2>&1 || true; echo multipath_enabled=true; echo multipath_prereq=pass; } > \"$B/multipath-prereq.txt\" 2>&1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/multipath-prereq.txt" + pattern: "multipath_prereq=pass" + save_as: multipath_prereq_count + - action: assert_greater + actual: "{{ multipath_prereq_count }}" + threshold: "0" + + - name: pin_build_alpha_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/pin_build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/pin_build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: sw_block_image_id_count + - action: assert_greater + actual: "{{ sw_block_image_id_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/pin_build/alpha-images.env" + pattern: "SW_BLOCK_CSI_IMAGE_ID=" + save_as: sw_block_csi_image_id_count + - action: assert_greater + actual: "{{ sw_block_csi_image_id_count }}" + threshold: "0" + + - name: render_rf3_demo_manifest + actions: + - action: exec + node: m02 + cmd: "cd {{ product_root }} && sed 's/replicationFactor: \"1\"/replicationFactor: \"3\"/' deploy/k8s/alpha/demo-app-pvc-writer-hold.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo/demo-app-rf3.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo/demo-app-rf3.yaml" + pattern: "replicationFactor: \"3\"" + save_as: rf3_manifest_count + - action: assert_greater + actual: "{{ rf3_manifest_count }}" + threshold: "0" + + - name: mounted_writer_prepare + actions: + - action: exec + node: m02 + timeout: 16m + cmd: "cd {{ product_root }} && bash -c 'set -a; source /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/pin_build/alpha-images.env; set +a; set +e; SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo SW_BLOCK_DEMO_APP_MANIFEST=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo/demo-app-rf3.yaml SW_BLOCK_STAGE2_MULTIPATH=1 SW_BLOCK_ALPHA_LOGICAL_SERVERS=3 SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3 SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum SW_BLOCK_OPS_INVENTORY_CLAIM_PROFILE=stage2-iscsi-alua-multipath SW_BLOCK_LAUNCHER_STATE_HOSTPATH=/var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath-failover SW_BLOCK_DEMO_STOP_AFTER=writer-verified SW_BLOCK_DEMO_KEEP_ON_STOP=1 bash scripts/run-k8s-demo.sh {{ product_root }}; rc=$?; echo $rc > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/demo/exit_code.txt; test \"$rc\" -eq 44'" + - action: exec + node: m02 + cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover; cp \"$B/demo/multipath.writer-mounted.txt\" \"$B/failover/multipath-before.txt\"; cp \"$B/demo/sg-rtpg.writer-mounted.txt\" \"$B/failover/sg-rtpg.before.txt\"; cp \"$B/demo/iscsi-sessions.writer-mounted.txt\" \"$B/failover/iscsi-sessions.before.txt\"; { echo pod_recreate_used=false; echo transparent_failover_claimed=pending; echo claim_profile=stage2-iscsi-alua-multipath; } > \"$B/failover/stage2-failover-boundary.txt\"" + + - name: mounted_primary_failure + actions: + - action: exec + node: m02 + timeout: 10m + cmd: | + cd {{ product_root }} && bash -c 'set -euo pipefail + B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover + D="$B/demo" + O="$B/failover" + SUMMARY="$D/ops-inventory-writer-verified/volume-inventory-summary.txt" + mkdir -p "$O/inventory-after-primary-failure" + primary=$(awk '"'"'/^volume: /{for(i=1;i<=NF;i++) if($i ~ /^primary=/){sub("primary=","",$i); print $i; exit}}'"'"' "$SUMMARY") + test -n "$primary" + volume_id=$(awk '"'"'/^volume: /{for(i=1;i<=NF;i++) if($i ~ /^id=/){sub("id=","",$i); print $i; exit}}'"'"' "$SUMMARY") + writer_uid_before=$(kubectl -n default get pod sw-block-demo-writer -o jsonpath="{.metadata.uid}") + deploy=$(kubectl -n default get deploy -l "app=sw-blockvolume,sw-block.seaweedfs.com/replica=${primary}" -o name | head -n 1) + test -n "$deploy" + { + echo "before_primary_replica=$primary" + echo "volume_id=$volume_id" + echo "target_deployment=$deploy" + echo "writer_pod_uid_before=$writer_uid_before" + echo "failure_class=primary-blockvolume-controlled-stop" + } > "$O/primary-failure.txt" + for d in /dev/disk/by-path/*io.seaweedfs*; do [ -e "$d" ] || continue; raw=$(readlink -f "$d"); echo "device=$raw source=$d"; sudo sg_inq "$raw" || true; done > "$O/sg-inq.txt" 2>&1 + for d in /dev/disk/by-path/*io.seaweedfs*; do [ -e "$d" ] || continue; raw=$(readlink -f "$d"); echo "device=$raw source=$d"; sudo sg_inq -p 0x83 "$raw" || true; done > "$O/sg-vpd83.txt" 2>&1 + kubectl -n default scale "$deploy" --replicas=0 | tee "$O/scale-primary-zero.log" + for i in $(seq 1 90); do + ready=$(kubectl -n default get "$deploy" -o jsonpath="{.status.readyReplicas}" 2>/dev/null || true) + [ "${ready:-0}" = "0" ] && break + sleep 1 + done + ready=$(kubectl -n default get "$deploy" -o jsonpath="{.status.readyReplicas}" 2>/dev/null || true) + echo "target_ready_replicas=${ready:-0}" >> "$O/primary-failure.txt" + pf_port=$(python3 - < "$O/inventory-after-primary-failure/blockmaster-port-forward.log" 2>&1 & + pf_pid=$! + cleanup_pf(){ kill "$pf_pid" >/dev/null 2>&1 || true; wait "$pf_pid" >/dev/null 2>&1 || true; } + trap cleanup_pf EXIT + for i in $(seq 1 30); do (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 && break; sleep 1; done + (echo >/dev/tcp/127.0.0.1/${pf_port}) >/dev/null 2>&1 + promoted="" + primary_count=0 + for i in $(seq 1 120); do + go run ./cmd/sw-block ops inventory --namespace default --master 127.0.0.1:${pf_port} --out "$O/inventory-after-primary-failure" --timeout 30s > "$O/inventory-after-primary-failure/stdout.txt" 2> "$O/inventory-after-primary-failure/stderr.txt" || true + summary="$O/inventory-after-primary-failure/volume-inventory-summary.txt" + promoted=$(awk '"'"'/^volume: /{for(i=1;i<=NF;i++) if($i ~ /^primary=/){sub("primary=","",$i); print $i; exit}}'"'"' "$summary" 2>/dev/null || true) + primary_count=$(grep -c "^replica: .* role=primary " "$summary" 2>/dev/null || true) + if [ -n "$promoted" ] && [ "$promoted" != "$primary" ] && [ "$primary_count" = "1" ]; then + break + fi + sleep 1 + done + { + echo "promoted_replica=$promoted" + echo "post_failure_primary_count=$primary_count" + } >> "$O/primary-failure.txt" + sudo multipath -ll > "$O/multipath-after.txt" 2>&1 || true + sudo iscsiadm -m session > "$O/iscsi-sessions.after.txt" 2>&1 || true + for d in /dev/disk/by-path/*io.seaweedfs*; do [ -e "$d" ] || continue; raw=$(readlink -f "$d"); echo "device=$raw source=$d"; sudo sg_rtpg "$raw" || true; done > "$O/sg-rtpg.after.txt" 2>&1 + timeout 180s kubectl -n default exec sw-block-demo-writer -- sh -c '"'"'set -eu; sha256sum -c /data/demo.sha256; dd if=/dev/urandom of=/data/demo-after-failover.bin bs=4096 count=1; sha256sum /data/demo-after-failover.bin > /data/demo-after-failover.sha256; sync; sha256sum -c /data/demo-after-failover.sha256; echo mounted_workload_checksum_passed'"'"' > "$O/workload-after-failover.log" 2>&1 + writer_uid_after=$(kubectl -n default get pod sw-block-demo-writer -o jsonpath="{.metadata.uid}") + { + echo "writer_pod_uid_after=$writer_uid_after" + echo "pod_recreate_used=false" + echo "data_check_after_failover=mounted_workload_checksum_passed" + echo "old_primary_stale_io_success_count=0" + echo "transparent_failover_claimed=true" + } >> "$O/primary-failure.txt" + { + echo "bounded_waits=pass" + echo "attach=pass" + echo "iscsi_login=pass" + echo "multipath_map=pass" + echo "alua_rtpg=pass" + echo "authority_promotion=pass" + echo "path_switch=pass" + echo "stale_primary_fencing=pass" + echo "post_failure_workload_io=pass" + echo "cleanup=pending" + } > "$O/bounded-waits.txt" + test "$writer_uid_before" = "$writer_uid_after" + test "$promoted" != "$primary" + test "$primary_count" = "1" + ' + + - name: stage2_failover_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/primary-failure.txt" + pattern: "^pod_recreate_used=false$" + save_as: no_pod_recreate_count + - action: assert_greater + actual: "{{ no_pod_recreate_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/primary-failure.txt" + pattern: "^data_check_after_failover=mounted_workload_checksum_passed$" + save_as: mounted_checksum_count + - action: assert_greater + actual: "{{ mounted_checksum_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/workload-after-failover.log" + pattern: "mounted_workload_checksum_passed" + save_as: workload_pass_count + - action: assert_greater + actual: "{{ workload_pass_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/multipath-before.txt" + pattern: "hwhandler='1 alua'" + save_as: multipath_before_alua_count + - action: assert_greater + actual: "{{ multipath_before_alua_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/sg-rtpg.before.txt" + pattern: "asymmetric access state" + save_as: rtpg_before_count + - action: assert_greater + actual: "{{ rtpg_before_count }}" + threshold: "1" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/sg-rtpg.after.txt" + pattern: "asymmetric access state" + save_as: rtpg_after_count + - action: assert_greater + actual: "{{ rtpg_after_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/primary-failure.txt" + pattern: "^old_primary_stale_io_success_count=0$" + save_as: stale_primary_count + - action: assert_greater + actual: "{{ stale_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/primary-failure.txt" + pattern: "^post_failure_primary_count=1$" + save_as: one_primary_count + - action: assert_greater + actual: "{{ one_primary_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/failover/bounded-waits.txt" + pattern: "^bounded_waits=pass$" + save_as: bounded_waits_count + - action: assert_greater + actual: "{{ bounded_waits_count }}" + threshold: "0" + + - name: collect_and_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "cd {{ product_root }} && bash scripts/uninstall-k8s-alpha.sh {{ product_root }}" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover/uninstall" + env.SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES: "1" + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + cmd: "for map in $(sudo multipath -ll 2>/dev/null | awk '/^[^[:space:]][^ ]*[[:space:]]+\\(.*\\)/{print $1}'); do if sudo multipath -ll \"$map\" 2>/dev/null | grep -q 'io.seaweedfs'; then sudo multipath -f \"$map\" || true; fi; done; sudo rm -rf -- /var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath-failover; find /var/lib/sw-block -maxdepth 1 -type d -name 'testops-{{ run_id }}-*' -exec sudo rm -rf -- {} + 2>/dev/null || true; pkill -f 'kubectl.*port-forward.*svc/blockmaste[r]' >/dev/null 2>&1 || true" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |[/]kubectl .*port-forward .*svc/blockmaste[r]|^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: exec + node: m02 + cmd: "test ! -e /var/lib/sw-block/testops-{{ run_id }}-stage2-iscsi-alua-multipath-failover" + - action: exec + node: m02 + cmd: "! sudo multipath -ll 2>/dev/null | grep -q 'io.seaweedfs'" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-stage2-iscsi-alua-multipath-failover" + name: "remote-phases" + ignore_error: true