v0.2 alpha: Day-1 activation and first-volume loop (#48)

Package the Kubernetes alpha into a script-based Day-1 activation loop: activate the stack, create the first PVC-backed volume, verify writer/reader data, collect product-owned observation evidence, render a local read-only report, and clean up.

Includes multi-node-safe activation defaults, first-volume example automation, read-only ops report output, README/quickstart/release note updates, and review-driven hardening for fail-fast configuration, promotion evidence, inventory fail-closed behavior, and test guards.

Validated by Day-1 activation run 20260517-205252-04e9 and read-only report run 20260517-212358-bfba. Local targeted tests passed.
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-05-18 16:43:35 -07:00
1 parent e387d4e4bb
commit 5c4f995c55
150 files changed
+27572 -1466

No files matched your search

+5
View File
@@ -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
+137 -39
View File
@@ -1,35 +1,65 @@
# seaweed-block
# Seaweed Block
`seaweed-block` is an experimental block storage service for Kubernetes.
<p align="center">
<img src="docs/assets/seaweed-block-hero.svg" alt="Seaweed Block alpha architecture: Kubernetes PVC to CSI, blockmaster, blockvolume, iSCSI, and WAL-backed recovery" width="100%">
</p>
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-<commit>` 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
@@ -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",
@@ -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:-<single-node>}",
} {
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-<commit> 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`) {
+26 -9
View File
@@ -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{
+26
View File
@@ -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")
+21 -1
View File
@@ -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,
@@ -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(),
@@ -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",
+49 -11
View File
@@ -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=<id> 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)
+35 -1
View File
@@ -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
}
}
@@ -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
+641 -13
View File
@@ -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 <dir>|--namespace <ns>] <volume-id>\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: <volume-id> 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 <id> --master <addr> --status-addr <addr|url> --out <dir>")
fmt.Fprintln(w, " sw-block ops inventory --namespace <ns> [--master <addr>] --out <dir>")
fmt.Fprintln(w, " sw-block ops cluster --namespace <ns> [--master <addr>|--master-api <addr>] [-o json]")
fmt.Fprintln(w, " sw-block ops volumes --namespace <ns> [--master <addr>] [-o json]")
fmt.Fprintln(w, " sw-block ops describe volume --from-bundle <dir> <volume-id> [-o json]")
fmt.Fprintln(w, " sw-block ops describe volume <volume-id> --namespace <ns> [--master <addr>] [--out <dir>]")
fmt.Fprintln(w, " sw-block ops timeline volume --from-bundle <dir> <volume-id> [-o jsonl]")
fmt.Fprintln(w, " sw-block ops explain volume --from-bundle <dir> <volume-id>")
fmt.Fprintln(w, " sw-block ops explain volume <volume-id> --namespace <ns> [--master <addr>] [--out <dir>]")
fmt.Fprintln(w, " sw-block ops report --from-bundle <dir> --out <dir>")
fmt.Fprintln(w, " sw-block ops report --master-api <addr> --out <dir>")
}
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
}
+495
View File
@@ -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()
+9
View File
@@ -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.
+34
View File
@@ -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
+58 -15
View File
@@ -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{}
}
}
+46 -11
View File
@@ -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 {
@@ -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"})
+48 -9
View File
@@ -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
+26
View File
@@ -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{
+186 -9
View File
@@ -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 {
+54
View File
@@ -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)
}
}
+128 -21
View File
@@ -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()
}
+235 -4
View File
@@ -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
+227 -23
View File
@@ -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]
+379 -23
View File
@@ -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" {
@@ -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
}
@@ -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,
},
}
}
@@ -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.
@@ -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])
}
})
}
}
@@ -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,
}
@@ -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)
}
})
}
+18 -4
View File
@@ -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.
@@ -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{}
}
@@ -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
}
@@ -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
}
@@ -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())
+40 -23
View File
@@ -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
+33 -15
View File
@@ -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
@@ -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)
@@ -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{}
}
@@ -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())
}
@@ -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))
}
}
@@ -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
}
@@ -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
}
+371 -1
View File
@@ -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 {
@@ -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 {
@@ -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
}
@@ -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)
}
+64 -4
View File
@@ -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
@@ -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"},
@@ -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 —
@@ -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
@@ -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{
+63 -12
View File
@@ -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:
}
}
@@ -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
@@ -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
@@ -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.
@@ -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,
+35 -6
View File
@@ -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
+7 -3
View File
@@ -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
@@ -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(`---
+23 -4
View File
@@ -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 {
@@ -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{
+71 -3
View File
@@ -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
@@ -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 {
@@ -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 {
@@ -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
}
@@ -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 {
@@ -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
}
+74 -13
View File
@@ -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"`
}
@@ -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": [
{
+242
View File
@@ -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
}
@@ -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
}
@@ -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)
}
}
@@ -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("<!doctype html><html><head><meta charset=\"utf-8\">")
b.WriteString("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">")
b.WriteString("<title>sw-block status report</title>")
b.WriteString("<style>")
b.WriteString("body{font-family:ui-sans-serif,Segoe UI,Arial,sans-serif;margin:0;background:#f7f4ee;color:#15120d}")
b.WriteString("header{padding:28px 34px;background:#172019;color:#f6f0e4}")
b.WriteString("main{padding:24px 34px;display:grid;gap:22px}")
b.WriteString(".cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}")
b.WriteString(".card,section{background:#fffaf0;border:1px solid #d9cdb8;border-radius:14px;padding:16px;box-shadow:0 1px 0 #eee}")
b.WriteString(".label{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:#6f6558}.value{font-size:24px;font-weight:700;margin-top:4px}")
b.WriteString("table{width:100%;border-collapse:collapse}th,td{padding:9px 8px;border-bottom:1px solid #eadfcd;text-align:left;font-size:14px;vertical-align:top}")
b.WriteString("th{color:#5b5145;font-size:12px;text-transform:uppercase;letter-spacing:.05em}.ok{color:#12613a}.bad{color:#9b2c1d}code{background:#efe3cf;padding:2px 5px;border-radius:5px}")
b.WriteString("</style></head><body>")
fmt.Fprintf(&b, "<header><h1>sw-block read-only status</h1><p>status=%s captured=%s product=%s</p><p>This report is observation-only. It does not promote, repair, delete, or mutate Kubernetes resources.</p></header>",
esc(emptyAsDash(cluster.Status)), esc(cluster.CapturedAt.Format("2006-01-02T15:04:05Z07:00")), esc(emptyAsDash(cluster.ProductRevision)))
b.WriteString("<main>")
b.WriteString("<div class=\"cards\">")
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("</div>")
b.WriteString("<section><h2>Volumes</h2><table><thead><tr><th>Volume</th><th>PVC</th><th>Status</th><th>RF</th><th>Primary</th><th>Frontend</th><th>Reason</th></tr></thead><tbody>")
for _, volume := range cluster.Volumes {
class := "ok"
if volume.Status != ObservationStatusOK {
class = "bad"
}
fmt.Fprintf(&b, "<tr><td><code>%s</code></td><td>%s/%s</td><td class=\"%s\">%s</td><td>%d</td><td>%s@%s</td><td>%s</td><td>%s</td></tr>",
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("</tbody></table></section>")
b.WriteString("<section><h2>Nodes</h2><table><thead><tr><th>Node</th><th>IP</th><th>Ready</th><th>Schedulable</th><th>Replicas</th><th>Missing Images</th></tr></thead><tbody>")
for _, node := range cluster.Nodes {
fmt.Fprintf(&b, "<tr><td>%s</td><td>%s</td><td>%t</td><td>%t</td><td>%d</td><td>%s</td></tr>",
esc(emptyAsDash(node.NodeName)), esc(emptyAsDash(node.InternalIP)), node.Ready, node.Schedulable, node.ReplicaCount, esc(strings.Join(node.MissingImages, ", ")))
}
b.WriteString("</tbody></table></section>")
b.WriteString("<section><h2>Recent Timeline</h2><table><thead><tr><th>Time</th><th>Type</th><th>Reason</th><th>Volume</th><th>Replica</th><th>Message</th></tr></thead><tbody>")
for _, event := range events {
fmt.Fprintf(&b, "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
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("</tbody></table></section>")
b.WriteString("<section><h2>Machine Artifacts</h2><p><code>cluster-evidence.json</code>, <code>timeline.jsonl</code>, and <code>summary.txt</code> are generated next to this page.</p></section>")
b.WriteString("</main></body></html>\n")
return b.String()
}
func reportCard(b *strings.Builder, label, value, class string) {
if class != "" {
fmt.Fprintf(b, "<div class=\"card\"><div class=\"label\">%s</div><div class=\"value %s\">%s</div></div>", esc(label), class, esc(value))
return
}
fmt.Fprintf(b, "<div class=\"card\"><div class=\"label\">%s</div><div class=\"value\">%s</div></div>", esc(label), esc(value))
}
func esc(value string) string {
return html.EscapeString(value)
}
+242
View File
@@ -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",
}
}
@@ -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
}
}
@@ -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
}
+307 -77
View File
@@ -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
}
+545 -18
View File
@@ -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,
}
}
@@ -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,
})
@@ -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"})
@@ -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),
@@ -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{
+20
View File
@@ -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
+52 -2
View File
@@ -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{} {
@@ -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) {
File diff suppressed because it is too large. Load diff
@@ -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"
+150
View File
@@ -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;
@@ -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
@@ -5,5 +5,6 @@ metadata:
spec:
attachRequired: true
podInfoOnMount: false
fsGroupPolicy: File
volumeLifecycleModes:
- Persistent
+12 -1
View File
@@ -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
+3 -5
View File
@@ -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
@@ -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"
@@ -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/*
@@ -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:
+397 -3
View File
@@ -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 <volume-id>
sw-block ops timeline volume <volume-id>
sw-block ops timeline volume <volume-id> -o jsonl
sw-block ops explain volume <volume-id>
sw-block ops report --master-api 127.0.0.1:9333 --out /tmp/sw-block-report
sw-block ops report --from-bundle <bundle-dir> --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=<deployment>
blockvolume-process-without-placement=<server>
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=<rN>
promoted_replica=<rM>
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=<rN>
before_primary_node=<node-a>
failed_replica=<same rN>
failed_node=<same node-a>
promoted_replica=<rM>
promoted_replica_node=<node-b>
post_failure_primary_count=1
before_publish_target_frontend=<node-a-ip:port>
after_publish_target_frontend=<node-b-ip:port>
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
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more