diff --git a/.github/workflows/k8s-native-e2e.yaml b/.github/workflows/k8s-native-e2e.yaml index 1eff4ea5ea..3135e7d006 100644 --- a/.github/workflows/k8s-native-e2e.yaml +++ b/.github/workflows/k8s-native-e2e.yaml @@ -1442,6 +1442,7 @@ jobs: --set csiConfig.simplybk.ip="http://simplyblock-webappapi.simplyblock:5000" \ --set prometheus.server.persistentVolume.storageClass=${SC_NAME} \ --set controlplane.observability.enabled=true \ + --set operatorMetrics.enabled=true \ --set opensearch.persistence.storageClass=${SC_NAME} \ --set controlplane.observability.minio.storageClass=${SC_NAME} \ $TLS_FLAGS $CSI_FLAGS @@ -2778,13 +2779,25 @@ jobs: # error rather than a no-op. BAO_NS=vault BAO_POD=openbao-0 + # Every bao call needs an address on OpenBao's certificate and a + # token. The pod's own BAO_ADDR is https://127.0.0.1:8200, which the + # certificate carries no IP SAN for, and an exec carries no token: + # on run 45100042373 every call below exited 2, the seal wait ran + # its full five minutes, and the gateway got no IAM at all. + # setup-kms.sh talks to the same address and leaves the root token + # in ./openbao-init.txt. Tracing stays off while the token is in + # scope. + set +x + BAO_ADDR_IN=https://openbao.vault.svc:8200 + BAO_ROOT=$(grep -E '^Initial Root Token:' ./openbao-init.txt 2>/dev/null | awk '{print $NF}' || true) + bao_exec() { kubectl exec -i -n $BAO_NS $BAO_POD -- env BAO_ADDR=$BAO_ADDR_IN BAO_TOKEN="$BAO_ROOT" bao "$@"; } if ! kubectl get pod $BAO_POD -n $BAO_NS >/dev/null 2>&1; then echo "::warning title=no OpenBao::OpenBao is not deployed, so the gateway serves its root account alone. TC-S3-006 reports itself not applicable rather than failing." else # The openbao-unsealer Deployment created earlier keeps this true; # the wait is for the case where this step runs before it has acted. for i in $(seq 1 30); do - SEALED=$(kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao status -format=json 2>/dev/null || true' | grep -o '"sealed":[^,]*' | head -1 || true) + SEALED=$(bao_exec status -format=json 2>/dev/null | grep -o '"sealed":[^,]*' | head -1 || true) echo "openbao: ${SEALED:-unknown} ($i/30)" case "$SEALED" in *false*) break;; esac sleep 10 @@ -2802,24 +2815,26 @@ jobs: echo 'path "secret/metadata/s3" { capabilities = ["read","list"] }' >> /tmp/s3-policy.hcl cat /tmp/s3-policy.hcl - kubectl cp /tmp/s3-policy.hcl $BAO_NS/$BAO_POD:/tmp/s3-policy.hcl || true - kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao secrets enable -path=secret -version=2 kv' 2>&1 | tail -1 || true - kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao auth enable approle' 2>&1 | tail -1 || true - kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao policy write simplyblock-s3-policy /tmp/s3-policy.hcl' 2>&1 | tail -1 || true - kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao write auth/approle/role/simplyblock-s3 token_policies=simplyblock-s3-policy token_ttl=1h token_max_ttl=24h' 2>&1 | tail -1 || true - - ROLE_ID=$(kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao read -field=role_id auth/approle/role/simplyblock-s3/role-id 2>/dev/null' || true) - SECRET_ID=$(kubectl exec -n $BAO_NS $BAO_POD -- sh -c 'bao write -f -field=secret_id auth/approle/role/simplyblock-s3/secret-id 2>/dev/null' || true) - if [ -n "${ROLE_ID:-}" ] && [ -n "${SECRET_ID:-}" ]; then + bao_exec secrets enable -path=secret -version=2 kv 2>&1 | tail -1 || true + bao_exec auth enable approle 2>&1 | tail -1 || true + bao_exec policy write simplyblock-s3-policy - < /tmp/s3-policy.hcl 2>&1 | tail -1 || true + bao_exec write auth/approle/role/simplyblock-s3 token_policies=simplyblock-s3-policy token_ttl=1h token_max_ttl=24h 2>&1 | tail -1 || true + + ROLE_ID=$(bao_exec read -field=role_id auth/approle/role/simplyblock-s3/role-id 2>/dev/null || true) + SECRET_ID=$(bao_exec write -f -field=secret_id auth/approle/role/simplyblock-s3/secret-id 2>/dev/null || true) + # The gateway verifies OpenBao's certificate, which the chart's own + # CA signed, so it is handed that CA alongside the endpoint. + BAO_CA=$(kubectl exec -n $BAO_NS $BAO_POD -- cat /openbao/tls/ca.crt 2>/dev/null || true) + if [ -n "${ROLE_ID:-}" ] && [ -n "${SECRET_ID:-}" ] && [ -n "${BAO_CA:-}" ]; then # set +x around these two deliberately. A role_id and a secret_id # together ARE the gateway's IAM credential, and this workflow's # trace is readable by anyone who can see the run. set +x - kubectl create secret generic simplyblock-s3-iam -n $NS --from-literal=VGW_IAM_VAULT_ENDPOINT_URL=https://openbao-0.openbao-internal.vault.svc:8200 --from-literal=VGW_IAM_VAULT_SECRET_STORAGE_PATH=s3 --from-literal=VGW_IAM_VAULT_MOUNT_PATH=secret --from-literal=VGW_IAM_VAULT_ROLE_ID="$ROLE_ID" --from-literal=VGW_IAM_VAULT_ROLE_SECRET="$SECRET_ID" --dry-run=client -o yaml | kubectl apply -f - >/dev/null + kubectl create secret generic simplyblock-s3-iam -n $NS --from-literal=VGW_IAM_VAULT_ENDPOINT_URL=$BAO_ADDR_IN --from-literal=VGW_IAM_VAULT_SECRET_STORAGE_PATH=s3 --from-literal=VGW_IAM_VAULT_MOUNT_PATH=secret --from-literal=VGW_IAM_VAULT_ROLE_ID="$ROLE_ID" --from-literal=VGW_IAM_VAULT_ROLE_SECRET="$SECRET_ID" --from-literal=VGW_IAM_VAULT_SERVER_CERT="$BAO_CA" --dry-run=client -o yaml | kubectl apply -f - >/dev/null set -x echo "Secret/simplyblock-s3-iam written (values not echoed)" else - echo "::warning title=no AppRole credential::could not read the AppRole role_id/secret_id, so the gateway falls back to its root account only" + echo "::warning title=no AppRole credential::could not read the AppRole role_id/secret_id or OpenBao's CA, so the gateway falls back to its root account only" fi fi diff --git a/.github/workflows/k8s-native-stress.yaml b/.github/workflows/k8s-native-stress.yaml index b2e455b92c..8cb6359bae 100644 --- a/.github/workflows/k8s-native-stress.yaml +++ b/.github/workflows/k8s-native-stress.yaml @@ -1376,6 +1376,7 @@ jobs: --set csiConfig.simplybk.ip="http://simplyblock-webappapi.simplyblock:5000" \ --set prometheus.server.persistentVolume.storageClass=${SC_NAME} \ --set controlplane.observability.enabled=true \ + --set operatorMetrics.enabled=true \ --set opensearch.persistence.storageClass=${SC_NAME} \ --set controlplane.observability.minio.storageClass=${SC_NAME} \ $TLS_FLAGS $CSI_FLAGS diff --git a/e2e/e2e_tests/objectstore/test_objectstore_gateway.py b/e2e/e2e_tests/objectstore/test_objectstore_gateway.py index a97edff868..35f8e12413 100644 --- a/e2e/e2e_tests/objectstore/test_objectstore_gateway.py +++ b/e2e/e2e_tests/objectstore/test_objectstore_gateway.py @@ -709,33 +709,68 @@ def run(self): # ── TC-S3-021: kill one pod ───────────────────────────────────── pods = s3.gateway_pods(self.k8s_utils, self.STORE) + existing = {p[0] for p in pods} victim, victim_node, _, _ = pods[0] + delivered_before = s3.delivered_nodes(s3.s3bucket(self.k8s_utils, name)) self.k8s_utils._exec_kubectl( f"kubectl delete pod {victim} -n {self.ns} --wait=false") + # Any new Ready pod is the replacement, wherever it landed. M-01 does + # not ask for the same node, and the gateway Deployment could not + # honor it: required pod anti-affinity on hostname and no + # nodeSelector, so while the victim is terminating its node is the + # one place the replacement may not go. deadline = time.time() + 600 replacement = None while time.time() < deadline: rows = [p for p in s3.gateway_pods(self.k8s_utils, self.STORE) - if p[0] != victim and p[3] and p[1] == victim_node] + if p[0] not in existing and p[3]] if rows: replacement = rows[0] break time.sleep(5) if not replacement: + self._log_gateway_placement() raise s3.S3EvidenceError( - f"[TC-S3-021] no replacement gateway pod became Ready on " - f"{victim_node} within 10 minutes") + f"[TC-S3-021] no replacement for gateway pod {victim} (on " + f"{victim_node}) became Ready within 10 minutes") + new_node = replacement[1] + same_node = new_node in delivered_before + self.logger.info( + "[TC-S3-021] replacement %s on %s; bucket was delivered to %s", + replacement[0], new_node, delivered_before) + + if not same_node: + # A node the bucket never reached needs a delivery before the pod + # can serve it. That delivery is the operator's job, so wait for + # the bucket's own status to name the node. + deadline = time.time() + 300 + while time.time() < deadline: + if new_node in s3.delivered_nodes( + s3.s3bucket(self.k8s_utils, name)): + break + time.sleep(5) + else: + self._log_gateway_placement() + raise s3.S3EvidenceError( + f"[TC-S3-021] the replacement pod {replacement[0]} landed " + f"on {new_node}, which the bucket was not delivered to, " + f"and 5 minutes later status.mountDeliveredNodes still " + f"does not name it: " + f"{s3.delivered_nodes(s3.s3bucket(self.k8s_utils, name))}") got = client.call(self.pod_cfg(replacement[2]), "get_object", bucket=name, key="seed.bin", size=16 * 1024 ** 2, seed="tc021") if got.get("status") != 200 or not got.get("match"): + self._log_gateway_placement() raise s3.S3EvidenceError( - f"[TC-S3-021] the replacement pod {replacement[0]} cannot " - f"serve a bucket that was already delivered to its node: " - f"{got}. M-01's claim is that the delivery is targeted at the " - f"node, not the pod, so no re-delivery is needed.") + f"[TC-S3-021] the replacement pod {replacement[0]} on " + f"{new_node} cannot serve a bucket " + + ("that was already delivered to its node: " + if same_node else "the operator reports delivered there: ") + + f"{got}. M-01's claim is that the delivery is targeted at " + f"the node, not the pod.") after = s3.scrape_operator_metrics(self.k8s_utils) deliveries_after = s3.metric_total( @@ -743,6 +778,14 @@ def run(self): redelivered = deliveries_after - deliveries_before self.logger.info("[TC-S3-021] DeliverBucket calls across the kill: %s", redelivered) + # "No re-delivery" is M-01's claim only for a pod that comes back on a + # node that already had the bucket. A new node needs one. + if same_node and redelivered: + self.logger.error( + "[TC-S3-021] FINDING: the replacement came back on %s, which " + "already had the bucket, and the operator still made %s " + "DeliverBucket call(s). M-01 says the delivery is per node.", + new_node, redelivered) # ── TC-S3-022: a rolling update, under traffic ────────────────── # Traffic during the roll, so the question is "what does a client @@ -801,6 +844,8 @@ def drive(): self.record("tc021_pod_kill_and_roll", { "replicas": replicas, "killed_pod": victim, "node": victim_node, + "replacement_pod": replacement[0], "replacement_node": new_node, + "replacement_on_delivered_node": same_node, "deliver_calls_across_kill": redelivered, "roll_seconds": round(roll_seconds, 1), "reads_ok": oks, "reads_failed": len(errors), @@ -813,3 +858,9 @@ def drive(): "A multi-replica roll should be invisible to a client.", replicas, len(errors), errors[:10]) self.logger.info("[TC-S3-021/022] PASS") + + def _log_gateway_placement(self): + """Log where every gateway pod is, so a placement failure is visible.""" + self.k8s_utils._exec_kubectl( + f"kubectl get pods -n {self.ns} -l {s3.GATEWAY_LABEL}={self.STORE} " + f"-o wide") diff --git a/e2e/e2e_tests/objectstore/test_objectstore_lifecycle.py b/e2e/e2e_tests/objectstore/test_objectstore_lifecycle.py index 4fe4c19f16..6bc1759755 100644 --- a/e2e/e2e_tests/objectstore/test_objectstore_lifecycle.py +++ b/e2e/e2e_tests/objectstore/test_objectstore_lifecycle.py @@ -140,12 +140,26 @@ class S3ObjectStoreDeletedWithBucketsK8s(_ObjectStoreBase): cannot cover for want of a garbage collector, and the invariant each of dev's two plans assigns to the other. - The design does not state which of two behaviours is correct, so this case - *records* which one happened and fails only on the outcomes that are - unambiguously wrong: a bucket left `Ready` with no gateway, or an orphaned - PVC. If neither behaviour is specified, that is the finding. + `design-objectstore` decides it: the delete is held. The request succeeds + and sets `deletionTimestamp`, but the finalizer + `storage.simplyblock.io/objectstore-buckets` stays until no `S3Bucket` + references the store. Meanwhile the phase is unchanged, `BucketsRemaining` + is `True` and names the buckets, the owned Deployment and Service are not + collected, and the gateway keeps serving. A new bucket against the + terminating store degrades with `ObjectStoreNotFound`. Once the last + bucket goes, so do the store and everything it owns. """ + #: How long the held delete is watched. Long enough for several + #: reconciles and for a garbage collector that was going to act to have + #: acted. + HOLD_SECONDS = 180 + + #: How long the store and its owned objects get to disappear once the + #: last bucket is gone. The design says one reconcile; the garbage + #: collector follows on its own schedule. + RELEASE_TIMEOUT = 300 + def run(self): self.logger.info("=== TC-S3-002 ObjectStore deleted with live buckets ===") self.make_storage_class() @@ -173,86 +187,160 @@ def run(self): supress_logs=True) owned[kind] = sorted((out or "").split()) self.logger.info("[TC-S3-002] owned before delete: %s", owned) + for kind in ("deployment", "service"): + if not owned[kind]: + raise s3.S3ProbeError( + f"[TC-S3-002] found no {kind} owned by ObjectStore " + f"{self.STORE} before the delete, so the case could not " + f"tell a collected one from one that never existed") + phase_before = s3.phase_of(s3.objectstore(self.k8s_utils, self.STORE)) self.k8s_utils._exec_kubectl( f"kubectl delete objectstore {self.STORE} -n {self.ns} " f"--wait=false --ignore-not-found") - # Five minutes, sampling, so the report can say what happened over the - # window rather than only at its end. + # ── the delete is held ────────────────────────────────────────── + # Sampled over a window rather than checked once: a finalizer that + # is released a minute later is the same defect as none at all. timeline = [] - deadline = time.time() + 300 - while time.time() < deadline: + t0 = time.time() + while True: store = s3.objectstore(self.k8s_utils, self.STORE) + meta = store.get("metadata") or {} + cond = s3.condition(store, s3.CONDITION_BUCKETS_REMAINING) + gateways = s3.gateway_pods(self.k8s_utils, self.STORE) row = { - "t": round(time.time() - (deadline - 300)), + "t": round(time.time() - t0), "store_present": bool(store), + "deleting": bool(meta.get("deletionTimestamp")), + "finalizers": meta.get("finalizers") or [], "store_phase": s3.phase_of(store), + "buckets_remaining": cond.get("status"), "buckets": {n: s3.phase_of(s3.s3bucket(self.k8s_utils, n)) for n in names}, - "gateway_pods": len(s3.gateway_pods(self.k8s_utils, self.STORE)), + "ready_gateways": len([p for p in gateways if p[3]]), + "owned_left": {k: [i for i in v if self.k8s_utils + .get_resource_json(k, i)] + for k, v in owned.items()}, } if not timeline or row != {**timeline[-1], "t": row["t"]}: timeline.append(row) + self.logger.info("[TC-S3-002] %s", row) + self._assert_held(row, cond, owned, phase_before, names) + if time.time() - t0 >= self.HOLD_SECONDS: + break time.sleep(15) - store_gone = not s3.objectstore(self.k8s_utils, self.STORE) - final = {n: s3.s3bucket(self.k8s_utils, n) for n in names} - gateways = s3.gateway_pods(self.k8s_utils, self.STORE) - - if store_gone: - outcome = "delete proceeded" - # The serious failure: a bucket still claiming Ready with nothing - # to serve it. Degraded is a defensible answer; Ready is not. - for n, obj in final.items(): - if s3.phase_of(obj) == "Ready" and not gateways: - raise s3.S3EvidenceError( - f"[TC-S3-002] S3Bucket/{n} is still Ready after its " - f"ObjectStore was deleted and every gateway pod is " - f"gone. Nothing serves it, and nothing says so.") - reasons = {n: [ln.split()[0] for ln in s3.events_for( - self.k8s_utils, "S3Bucket", n) if ln.split()] for n in final} - self.logger.info("[TC-S3-002] bucket events after delete: %s", reasons) - # The live half of I-04: owned objects actually collected. - still = {} - for kind, items in owned.items(): - left = [i for i in items - if self.k8s_utils.get_resource_json(kind, i)] - if left: - still[kind] = left - if still: - raise s3.S3EvidenceError( - f"[TC-S3-002] the ObjectStore is gone but objects it " - f"owned were not garbage-collected: {still}. " - f"ownerReferences are the only mechanism here, so this is " - f"the live half of I-04 failing.") - else: - outcome = "delete held" - store = s3.objectstore(self.k8s_utils, self.STORE) - finalizers = (store.get("metadata") or {}).get("finalizers") or [] - if not finalizers: + # The gateway is still serving, not merely still running. + for n in names: + got = pod.call(cfg, "get_object", bucket=n, key="probe.bin", + size=4 * 1024 ** 2, seed=f"{n}-seed") + if got.get("status") != 200 or not got.get("match"): raise s3.S3EvidenceError( - "[TC-S3-002] the ObjectStore delete neither completed nor " - "is held by a finalizer -- it is simply stuck, which is " - "neither of the two defensible behaviours.") - self.logger.info("[TC-S3-002] held by finalizers %s", finalizers) + f"[TC-S3-002] the ObjectStore delete is held, but a GET " + f"of {n}/probe.bin through its gateway fails: {got}. The " + f"hold exists so the remaining buckets keep serving.") + + # ── a new bucket against the terminating store ────────────────── + late = "tc002-late" + self.make_bucket(late, wait=False) + late_obj, _ = s3.wait_phase( + self.k8s_utils, "s3bucket", late, "Degraded", timeout=300, + forbid="Ready") + reasons = [c.get("reason") for c in + ((late_obj.get("status") or {}).get("conditions") or [])] + events = s3.events_for(self.k8s_utils, "S3Bucket", late) + if (s3.EVENT_OBJECTSTORE_NOT_FOUND not in reasons + and not any(ln.split()[0] == s3.EVENT_OBJECTSTORE_NOT_FOUND + for ln in events)): + raise s3.S3EvidenceError( + f"[TC-S3-002] S3Bucket/{late}, created against an ObjectStore " + f"being deleted, is Degraded but neither a condition nor an " + f"event says {s3.EVENT_OBJECTSTORE_NOT_FOUND}: condition " + f"reasons {reasons}, events {events[-5:]}") + self.k8s_utils.delete_resource("s3bucket", late) + s3.wait_gone(self.k8s_utils, "s3bucket", late, timeout=600) + self.buckets = [b for b in self.buckets if b[0] != late] + + # ── the last bucket goes, and the store with it ───────────────── + for n in names: + self.k8s_utils.delete_resource("s3bucket", n) + for n in names: + s3.wait_gone(self.k8s_utils, "s3bucket", n, timeout=600) + self.buckets = [b for b in self.buckets if b[0] not in names] + + s3.wait_gone(self.k8s_utils, "objectstore", self.STORE, + timeout=self.RELEASE_TIMEOUT) + self.stores = [st for st in self.stores if st[0] != self.STORE] + deadline = time.time() + self.RELEASE_TIMEOUT + still = {} + while time.time() < deadline: + still = {k: left for k, v in owned.items() + if (left := [i for i in v if self.k8s_utils + .get_resource_json(k, i)])} + if not still: + break + time.sleep(10) + if still: + raise s3.S3EvidenceError( + f"[TC-S3-002] the ObjectStore is gone but objects it owned " + f"were not garbage-collected within {self.RELEASE_TIMEOUT}s: " + f"{still}. ownerReferences are the only mechanism here, so " + f"this is the live half of I-04 failing.") - # Whichever happened, no PVC may be orphaned. + # No PVC may outlive its bucket. orphans = [p for p in pvcs.values() - if self.k8s_utils.get_resource_json("pvc", p) - and not s3.s3bucket(self.k8s_utils, - next(n for n, q in pvcs.items() if q == p))] + if self.k8s_utils.get_resource_json("pvc", p)] if orphans: raise s3.S3EvidenceError( f"[TC-S3-002] PVC(s) {orphans} survive with no S3Bucket " f"describing them") self.record("tc002_objectstore_delete", { - "outcome": outcome, "owned_before": owned, + "owned_before": owned, + "phase_before": phase_before, "timeline": timeline, - "final_phases": {n: s3.phase_of(o) for n, o in final.items()}, + "late_bucket_reasons": reasons, }) - self.logger.info("[TC-S3-002] PASS -- %s", outcome) + self.logger.info("[TC-S3-002] PASS -- delete held for %ds, then " + "released with the last bucket", self.HOLD_SECONDS) + + def _assert_held(self, row, cond, owned, phase_before, names): + """Fail on the first sample that breaks the held-delete contract.""" + problems = [] + if not row["store_present"]: + problems.append("the ObjectStore is gone") + else: + if not row["deleting"]: + problems.append("metadata.deletionTimestamp is not set") + if s3.OBJECTSTORE_BUCKETS_FINALIZER not in row["finalizers"]: + problems.append( + f"finalizer {s3.OBJECTSTORE_BUCKETS_FINALIZER} is absent " + f"(finalizers {row['finalizers']})") + if row["store_phase"] != phase_before: + problems.append( + f"phase moved {phase_before} -> {row['store_phase']}") + missing = [n for n in names if n not in (cond.get("message") or "")] + if cond.get("status") != "True" or missing: + problems.append( + f"condition {s3.CONDITION_BUCKETS_REMAINING} is " + f"{cond or 'absent'}, expected status True naming {names}") + for kind in ("deployment", "service"): + if owned[kind] and row["owned_left"].get(kind) != owned[kind]: + problems.append( + f"owned {kind} {owned[kind]} was collected " + f"(left: {row['owned_left'].get(kind)})") + if not row["ready_gateways"]: + problems.append("no gateway pod is Ready") + not_ready = {n: ph for n, ph in row["buckets"].items() if ph != "Ready"} + if not_ready: + problems.append(f"buckets no longer Ready: {not_ready}") + if problems: + raise s3.S3EvidenceError( + f"[TC-S3-002] {row['t']}s after deleting ObjectStore " + f"{self.STORE} with buckets {names} still referencing it, " + f"the delete is not held as the design requires: " + + "; ".join(problems)) class S3BucketCapacityExhaustionK8s(_ObjectStoreBase): diff --git a/e2e/e2e_tests/objectstore/test_objectstore_resilience.py b/e2e/e2e_tests/objectstore/test_objectstore_resilience.py index d21c1d9e97..d81f2a2d39 100644 --- a/e2e/e2e_tests/objectstore/test_objectstore_resilience.py +++ b/e2e/e2e_tests/objectstore/test_objectstore_resilience.py @@ -25,26 +25,52 @@ class S3OpenBaoSealedK8s(_ObjectStoreBase): OpenBao re-seals whenever its pod restarts, and only a rerun of this script unseals it. - Single replica, pebbledb, unseal key in `Secret/openbao-init`. The - interesting question is not whether a sealed Bao breaks IAM -- it must -- - but *how*: a clean 5xx is survivable, a hang is not, and an operation that - half-succeeds with the wrong identity is the one that matters. + Single replica, pebbledb, unseal keys in `Secret/openbao-unseal-keys`. + The interesting question is not whether a sealed Bao breaks IAM -- it + must -- but *how*: a clean 5xx is survivable, a hang is not, and an + operation that half-succeeds with the wrong identity is the one that + matters. + + The lane also runs `Deployment/openbao-unsealer`, which re-unseals within + seconds of a seal. Left running, it would send this case down its + auto-unseal exit and the sealed state would never be tested, so it is + scaled to zero for the case and restored afterwards. """ BAO_NS = "vault" BAO_POD = "openbao-0" + UNSEALER = "openbao-unsealer" def run(self): self.logger.info("=== TC-S3-006 OpenBao sealed mid-run ===") + out, _ = self.k8s_utils._exec_kubectl( + f"kubectl get deployment {self.UNSEALER} -n {self.BAO_NS} " + f"-o jsonpath='{{.spec.replicas}}' 2>/dev/null || true", + supress_logs=True) + unsealer_replicas = (out or "").strip() + if unsealer_replicas: + self.k8s_utils._exec_kubectl( + f"kubectl scale deployment {self.UNSEALER} -n {self.BAO_NS} " + f"--replicas=0") + try: + self._run_sealed() + finally: + if unsealer_replicas: + self.k8s_utils._exec_kubectl( + f"kubectl scale deployment {self.UNSEALER} " + f"-n {self.BAO_NS} --replicas={unsealer_replicas}") + + def _run_sealed(self): probe = s3.BaoUnsealer(self.k8s_utils, namespace=self.BAO_NS, pod=self.BAO_POD) state = probe.sealed() if state is None: raise s3.S3ProbeError( f"[TC-S3-006] cannot read OpenBao's seal state from " - f"{self.BAO_NS}/{self.BAO_POD}. This case needs Vault-backed " - f"IAM deployed; without it the gateway serves the root " - f"account alone and there is nothing to seal.") + f"{self.BAO_NS}/{self.BAO_POD} ({probe.last_status}). This " + f"case needs Vault-backed IAM deployed; without it the " + f"gateway serves the root account alone and there is nothing " + f"to seal.") if state and not probe.unseal(): raise s3.S3ProbeError( "[TC-S3-006] OpenBao is sealed at the start and could not be " @@ -88,9 +114,10 @@ def run(self): time.sleep(5) else: self.logger.warning( - "[TC-S3-006] OpenBao came back unsealed -- auto-unseal is " - "configured on this cluster, which makes the whole scenario " - "moot. Recording that rather than forcing it.") + "[TC-S3-006] OpenBao came back unsealed with %s scaled to " + "zero -- auto-unseal is configured on this cluster, which " + "makes the whole scenario moot. Recording that rather than " + "forcing it. Last status: %s", self.UNSEALER, probe.last_status) self.record("tc006_openbao", {"auto_unseal": True}) return sealed_at = time.time() @@ -237,17 +264,24 @@ def run(self): warm_median = warm_sorted[len(warm_sorted) // 2] # ── E-07: the histogram records both, distinguishably ─────────── + # A scrape that fails raises S3ProbeError naming the HTTP status, so + # everything below reads a real /metrics body: an empty family here + # is the operator's, not the harness's. text = s3.scrape_operator_metrics(self.k8s_utils) hist = s3.histogram_quantiles(text, s3.METRIC_PROVISIONING_SECONDS) phases = s3.metric_samples(text, s3.METRIC_BUCKET_PHASE) self.logger.info("[TC-S3-014] histogram: %s", hist) if not hist: + families = sorted({ln.split()[2] for ln in text.splitlines() + if ln.startswith("# TYPE simplyblock_")}) raise s3.S3EvidenceError( - f"[TC-S3-014] {s3.METRIC_PROVISIONING_SECONDS} has no samples " - f"after {1 + self.WARM_COUNT} buckets reached Ready. The " - f"metric is the only answer Open Question 4 has, and E-07 " - f"exists to prove it records real values.") + f"[TC-S3-014] the operator's /metrics was scraped, but " + f"{s3.METRIC_PROVISIONING_SECONDS} has no samples after " + f"{1 + self.WARM_COUNT} buckets reached Ready. The metric is " + f"the only answer Open Question 4 has, and E-07 exists to " + f"prove it records real values. simplyblock families " + f"exposed: {families}") if hist.get("count", 0) < 1 + self.WARM_COUNT: raise s3.S3EvidenceError( f"[TC-S3-014] the histogram counted {hist.get('count')} " @@ -256,8 +290,20 @@ def run(self): # A bucket stuck outside Ready is the cheapest detector there is, so # the gauge is checked here too while every bucket is known-Ready. - not_ready = [(lbl, v) for lbl, v in phases - if v == 1 and lbl.get("phase") not in ("Ready", "")] + # The operator rebuilds it on a timer rather than on each reconcile, + # so a bucket that turned Ready seconds ago still reads its old phase + # until the next rebuild: re-scrape for two rebuilds before calling a + # phase stuck. Run 2026-11-23 on cluster91 read tc014-warm-3 as + # Pending 8s after it was Ready, one scrape and no retry. + deadline = time.time() + 2 * s3.PHASE_COLLECT_INTERVAL + while True: + not_ready = [(lbl, v) for lbl, v in phases + if v == 1 and lbl.get("phase") not in ("Ready", "")] + if not not_ready or time.time() >= deadline: + break + time.sleep(5) + phases = s3.metric_samples( + s3.scrape_operator_metrics(self.k8s_utils), s3.METRIC_BUCKET_PHASE) if not_ready: raise s3.S3EvidenceError( f"[TC-S3-014] {s3.METRIC_BUCKET_PHASE} reports buckets outside " @@ -301,6 +347,10 @@ class S3OperatorRestartK8s(_ObjectStoreBase): memory, which is the whole reason that field exists. """ + #: How long the PVC, PV, and NFSExport get to disappear after the bucket + #: has. The PV goes last and asynchronously, through csi-provisioner. + RELEASE_TIMEOUT = 120 + def run(self): self.logger.info("=== TC-S3-015/016 operator restart ===") self.make_storage_class() @@ -374,18 +424,22 @@ def run(self): s3.wait_gone(self.k8s_utils, "s3bucket", victim, timeout=900) self.buckets = [b for b in self.buckets if b[0] != victim] + # The S3Bucket's finalizer waits for its own objects, not for what + # they release in turn: the PV has reclaim policy Delete, and + # csi-provisioner removes it on its own schedule after the PVC is gone. + # A single look right after the finalizer released is a race, and in + # run 45100042373 the PV was gone 0.8s after that look. Each one gets + # a window instead; one that outlives it is a leak. leaked = [] - if self.k8s_utils.get_resource_json("pvc", vpvc): - leaked.append(f"PVC {vpvc}") - if vpv and self.k8s_utils.get_resource_json("pv", vpv): - leaked.append(f"PV {vpv}") - if vexport and self.k8s_utils.get_resource_json("nfsexport", vexport): - leaked.append(f"NFSExport {vexport}") + for kind, obj in (("pvc", vpvc), ("pv", vpv), ("nfsexport", vexport)): + if obj and not self._gone(kind, obj, timeout=self.RELEASE_TIMEOUT): + leaked.append(f"{kind} {obj}") if leaked: raise s3.S3EvidenceError( f"[TC-S3-016] the operator was restarted mid-delete and the " - f"S3Bucket finalized, but {', '.join(leaked)} survive. The " - f"finalizer's whole purpose is that this cannot happen.") + f"S3Bucket finalized, but {', '.join(leaked)} still exist " + f"{self.RELEASE_TIMEOUT}s later. The finalizer's whole purpose " + f"is that this cannot happen.") # The withdrawal has to have happened on every node the bucket was # delivered to, or a mount is left that nothing describes. @@ -417,53 +471,78 @@ def run(self): }) self.logger.info("[TC-S3-015/016] PASS") - def _restart_operator(self): - """Delete the operator pod(s) and wait for a replacement to be Ready.""" + def _gone(self, kind, name, timeout): + """True once *kind*/*name* no longer exists, False if it outlives *timeout*.""" + deadline = time.time() + timeout + while self.k8s_utils.get_resource_json(kind, name): + if time.time() >= deadline: + return False + time.sleep(5) + return True + + def _operator_selector(self): + """The label selector of the operator's pods. + + The chart's label first. If no pod carries it, the selector is read + off the `simplyblock-operator` Deployment itself -- by exact name, so + that a different operator in the same namespace can never be taken for + this one: run 45100042373 restarted `mongodb-kubernetes-operator` + twice, because its name contains "operator", and passed TC-S3-015 on + a kill that never happened. + """ + if self._operator_pods(s3.OPERATOR_SELECTOR): + return s3.OPERATOR_SELECTOR + dep = self.k8s_utils.get_resource_json( + "deployment", s3.OPERATOR_DEPLOYMENT, self.ns) + labels = (((dep.get("spec") or {}).get("selector") or {}) + .get("matchLabels") or {}) + if not labels: + raise s3.S3ProbeError( + f"[TC-S3-015] no pod in {self.ns} matches " + f"{s3.OPERATOR_SELECTOR} and there is no Deployment " + f"{s3.OPERATOR_DEPLOYMENT} to read a selector from; the case " + f"cannot kill what it cannot name") + return ",".join(f"{k}={v}" for k, v in sorted(labels.items())) + + def _operator_pods(self, selector): + """``[(name, uid, ready)]`` for the pods *selector* matches.""" out, _ = self.k8s_utils._exec_kubectl( - f"kubectl get pods -n {self.ns} -l control-plane=controller-manager " - f"-o jsonpath='{{range .items[*]}}{{.metadata.name}} {{end}}' " + f"kubectl get pods -n {self.ns} -l {selector} " + f"-o jsonpath='{{range .items[*]}}{{.metadata.name}}:" + f"{{.metadata.uid}}:{{.status.containerStatuses[0].ready}} {{end}}' " f"2>/dev/null || true", supress_logs=True) - pods = (out or "").split() - if not pods: - # The operator is not always labelled the same way across charts; - # fall back to the deployment name rather than silently skipping - # the kill, which would make the case pass for no reason. - out, _ = self.k8s_utils._exec_kubectl( - f"kubectl get deploy -n {self.ns} " - f"-o jsonpath='{{range .items[*]}}{{.metadata.name}} {{end}}' " - f"2>/dev/null || true", supress_logs=True) - target = next((d for d in (out or "").split() - if "operator" in d), "") - if not target: - raise s3.S3ProbeError( - "[TC-S3-015] cannot find the operator pod or Deployment; " - "the case cannot kill what it cannot name") - self.k8s_utils._exec_kubectl( - f"kubectl rollout restart deploy/{target} -n {self.ns}") - self.k8s_utils._exec_kubectl( - f"kubectl rollout status deploy/{target} -n {self.ns} " - f"--timeout=300s || true") - return [target] + rows = [r.split(":") for r in (out or "").split()] + return [(r[0], r[1], r[2] == "true") for r in rows if len(r) == 3] + + def _restart_operator(self): + """Delete the operator pod(s) and wait for a replacement to be Ready. + + The replacement is told apart by UID, not by name or by readiness: a + pod that was never deleted is Ready too, so only a UID that did not + exist before the kill proves the restart happened. + """ + selector = self._operator_selector() + before = self._operator_pods(selector) + if not before: + raise s3.S3ProbeError( + f"[TC-S3-015] the operator Deployment selects {selector}, " + f"but no pod in {self.ns} matches it") + old_uids = {uid for _, uid, _ in before} + pods = [name for name, _, _ in before] for p in pods: self.k8s_utils._exec_kubectl( f"kubectl delete pod {p} -n {self.ns} --wait=false") deadline = time.time() + 300 + rows = before while time.time() < deadline: - out, _ = self.k8s_utils._exec_kubectl( - f"kubectl get pods -n {self.ns} " - f"-l control-plane=controller-manager " - f"-o jsonpath='{{range .items[*]}}{{.metadata.name}}:" - f"{{.status.containerStatuses[0].ready}} {{end}}' " - f"2>/dev/null || true", supress_logs=True) - rows = [r.split(":") for r in (out or "").split() if ":" in r] - fresh = [r for r in rows if r[0] not in pods and r[1] == "true"] - if fresh: + rows = self._operator_pods(selector) + if any(uid not in old_uids and ready for _, uid, ready in rows): return pods time.sleep(5) raise s3.S3ProbeError( - "[TC-S3-015] the operator did not come back Ready within 5 " - "minutes of being killed") + f"[TC-S3-015] no operator pod with a new UID became Ready within " + f"5 minutes of deleting {pods}; pods now {rows}") class S3RBACFullCycleK8s(_ObjectStoreBase): @@ -505,7 +584,7 @@ def run(self): # non-critical path (events, say) completes the cycle and still means # the shipped role is wrong. out, _ = self.k8s_utils._exec_kubectl( - f"kubectl logs -n {self.ns} -l control-plane=controller-manager " + f"kubectl logs -n {self.ns} -l {s3.OPERATOR_SELECTOR} " f"--since-time={since} --tail=-1 --all-containers 2>/dev/null " f"| grep -iE 'forbidden|cannot (get|list|watch|create|update|" f"patch|delete)|RBAC' | head -40 || true", supress_logs=True) diff --git a/e2e/utils/s3_utils.py b/e2e/utils/s3_utils.py index 04d0b56835..40a19b3b47 100644 --- a/e2e/utils/s3_utils.py +++ b/e2e/utils/s3_utils.py @@ -41,8 +41,13 @@ import json import re import shlex +import socket +import ssl +import subprocess import threading import time +import urllib.error +import urllib.request from logger_config import setup_logger @@ -72,6 +77,12 @@ class S3ProbeError(S3EvidenceError): #: ``S3BucketFinalizer`` in ``operator/api/v1alpha2/s3bucket_types.go``. S3BUCKET_FINALIZER = "storage.simplyblock.io/s3bucket" +#: The ObjectStore's finalizer while an S3Bucket still references it, and the +#: condition that names those buckets (``design-objectstore.md`` §4, the +#: deletion paragraph). +OBJECTSTORE_BUCKETS_FINALIZER = "storage.simplyblock.io/objectstore-buckets" +CONDITION_BUCKETS_REMAINING = "BucketsRemaining" + #: ``S3BucketOwnerAnnotation``, same file. Present only on a bucket the #: gateway created for a ``CreateBucket`` request, absent on a bucket created #: directly through the CRD. @@ -83,6 +94,14 @@ class S3ProbeError(S3EvidenceError): #: (``objectstore_types.go``, the type's own doc comment). GATEWAY_LABEL = "storage.simplyblock.io/objectstore" +#: The operator's own Deployment and the label its pods carry, from the +#: operator chart's ``templates/simplyblock-operator.yaml``. Not +#: ``control-plane=controller-manager``: that is kubebuilder's scaffold label, +#: which the chart does not use for the operator, and which the csi-addons and +#: ramen controllers in the same chart do carry. +OPERATOR_DEPLOYMENT = "simplyblock-operator" +OPERATOR_SELECTOR = "app=simplyblock-operator" + #: ``S3BucketPhase`` / ``ObjectStorePhase`` enums. ``Deleting`` exists only on #: a bucket. BUCKET_PHASES = ("Pending", "Provisioning", "Ready", "Degraded", "Deleting") @@ -112,6 +131,12 @@ class S3ProbeError(S3EvidenceError): METRIC_STORE_PHASE = "simplyblock_objectstore_phase_state" METRIC_READY_REPLICAS = "simplyblock_objectstore_ready_replicas_count" +#: Seconds between the operator's rebuilds of the two phase gauges, so a +#: phase reads up to this stale. Mirrors ``DefaultCollectInterval`` in the +#: operator's ``internal/controllers/objectstore/collector.go``; the two must +#: move together. +PHASE_COLLECT_INTERVAL = 30 + # ── The in-pod S3 client ───────────────────────────────────────────────── @@ -581,32 +606,154 @@ def service_host(store, namespace): # ── Operator metrics ───────────────────────────────────────────────────── -def scrape_operator_metrics(k8s, namespace=None, selector="control-plane=controller-manager"): +#: The operator pod's container port for the manager's controller-runtime +#: secure metrics endpoint (self-signed certificate). The operator chart +#: declares it only when installed with ``operatorMetrics.enabled=true`` (off +#: by default), and puts no Service in front of it: the metrics belong to one +#: pod. Addressed by name so the chart's ``operatorMetrics.port`` can change. +#: The chart always creates the ClusterRole that grants GET on the +#: ``/metrics`` nonResourceURL. The endpoint authenticates the bearer token +#: and authorizes it against that URL, so an anonymous scrape is refused. +OPERATOR_METRICS_PORT = "metrics" +OPERATOR_METRICS_READER_ROLE = "simplyblock-operator-metrics-reader" + +#: The identity this suite scrapes as. Created on first use and left in +#: place: it holds no permission beyond reading ``/metrics``. +METRICS_SCRAPER_SA = "e2e-metrics-scraper" + + +def ensure_metrics_scraper(k8s, namespace): + """Apply the scraper's ServiceAccount and its binding. Idempotent.""" + k8s.apply_yaml( + f"apiVersion: v1\n" + f"kind: ServiceAccount\n" + f"metadata:\n" + f" name: {METRICS_SCRAPER_SA}\n" + f" namespace: {namespace}\n", + namespace=namespace) + k8s.apply_yaml_cluster_scoped( + f"apiVersion: rbac.authorization.k8s.io/v1\n" + f"kind: ClusterRoleBinding\n" + f"metadata:\n" + f" name: {METRICS_SCRAPER_SA}-{namespace}\n" + f"roleRef:\n" + f" apiGroup: rbac.authorization.k8s.io\n" + f" kind: ClusterRole\n" + f" name: {OPERATOR_METRICS_READER_ROLE}\n" + f"subjects:\n" + f"- kind: ServiceAccount\n" + f" name: {METRICS_SCRAPER_SA}\n" + f" namespace: {namespace}\n") + + +def scrape_operator_metrics(k8s, namespace=None): """Raw Prometheus text from the operator's ``/metrics``. - Scraped from inside the operator pod rather than through a Service: the - endpoint is commonly protected by kube-rbac-proxy, and ``curl`` from the - pod's own localhost skips a layer that has nothing to do with what is - being measured. + Fetched from the test host through a port-forward to the operator pod's + :data:`OPERATOR_METRICS_PORT`, with a bearer token for + :data:`METRICS_SCRAPER_SA`. Not from inside the operator pod: its image + is ubi-minimal and has no ``curl``, and the endpoint wants a token that + pod's own identity is not authorized to present. + + Raises :class:`S3ProbeError` when the scrape itself fails, naming the + HTTP status or the transport error, and when there is not exactly one + live operator pod: the samples are that pod's own, so picking one of + several would read an arbitrary replica. An empty result is never returned, + so a caller can tell "the scrape failed" from "the metric family has no + samples". """ ns = namespace or k8s.namespace - out, _ = k8s._exec_kubectl( - f"kubectl get pods -n {ns} -l {selector} " - f"-o jsonpath='{{.items[0].metadata.name}}' 2>/dev/null || true", + if not k8s.use_local_kubectl: + raise S3ProbeError( + "operator metrics scrape needs a local kubectl (K8S_LOCAL_KUBECTL=1) " + "to port-forward from the test host") + target = f"pod/{_operator_pod(k8s, ns)}" + ensure_metrics_scraper(k8s, ns) + token, err = k8s._exec_kubectl( + f"kubectl create token {METRICS_SCRAPER_SA} -n {ns} --duration=10m", supress_logs=True) - pod = (out or "").strip() - if not pod: - return "" - for port in (8080, 8443): - scheme = "http" if port == 8080 else "https -k" - text = k8s.exec_in_pod_container( - pod, "", f"curl -s {'-k ' if port == 8443 else ''}" - f"{'https' if port == 8443 else 'http'}://127.0.0.1:{port}/metrics", - namespace=ns, timeout=60) - del scheme - if METRIC_BUCKET_PHASE in text or "go_goroutines" in text: - return text - return "" + token = (token or "").strip() + if not token: + raise S3ProbeError( + f"operator metrics scrape failed: no token for " + f"{ns}/{METRICS_SCRAPER_SA}: {(err or '').strip()[:300]}") + + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + proc = subprocess.Popen( + ["kubectl", "port-forward", "-n", ns, + target, f"{port}:{OPERATOR_METRICS_PORT}"], + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True) + try: + _wait_listening(proc, port, target, timeout=15) + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + req = urllib.request.Request( + f"https://127.0.0.1:{port}/metrics", + headers={"Authorization": f"Bearer {token}"}) + try: + with urllib.request.urlopen(req, context=ctx, timeout=60) as resp: + text = resp.read().decode(errors="replace") + except urllib.error.HTTPError as exc: + raise S3ProbeError( + f"operator metrics scrape failed: HTTP {exc.code} {exc.reason} " + f"from {target}: " + f"{exc.read()[:300]!r}") from exc + except (urllib.error.URLError, OSError) as exc: + raise S3ProbeError( + f"operator metrics scrape failed: " + f"{getattr(exc, 'reason', exc)} from {target}") from exc + finally: + proc.kill() + proc.wait(timeout=10) + if not text.strip(): + raise S3ProbeError( + f"operator metrics scrape failed: {target} " + f"answered 200 with an empty body") + return text + + +def _operator_pod(k8s, namespace): + """Name of the one operator pod that is running and not being deleted.""" + out, err = k8s._exec_kubectl( + f"kubectl get pods -n {namespace} -l {OPERATOR_SELECTOR} -o json", + supress_logs=True) + try: + items = json.loads(out or "")["items"] + except (ValueError, KeyError) as exc: + raise S3ProbeError( + f"operator metrics scrape failed: cannot list {OPERATOR_SELECTOR} " + f"pods in {namespace}: {(err or out or '').strip()[:300]}") from exc + live = [p["metadata"]["name"] for p in items + if p.get("status", {}).get("phase") == "Running" + and not p["metadata"].get("deletionTimestamp")] + if len(live) != 1: + raise S3ProbeError( + f"operator metrics scrape failed: expected one running " + f"{OPERATOR_SELECTOR} pod in {namespace}, found {len(live)}: {live}") + return live[0] + + +def _wait_listening(proc, port, target, timeout): + """Return once *port* accepts a connection; raise if *proc* dies or times out.""" + deadline = time.time() + timeout + while time.time() < deadline: + if proc.poll() is not None: + raise S3ProbeError( + f"operator metrics scrape failed: port-forward to " + f"{target} exited: " + f"{(proc.stderr.read() or '').strip()[:300]}") + try: + socket.create_connection(("127.0.0.1", port), timeout=0.5).close() + return + except OSError: + time.sleep(0.25) + raise S3ProbeError( + f"operator metrics scrape failed: port-forward to " + f"{target} was not listening within {timeout}s") def metric_samples(text, name): @@ -698,59 +845,78 @@ class BaoUnsealer(threading.Thread): """ def __init__(self, k8s, namespace="vault", pod="openbao-0", - secret="openbao-init", interval=15): + secret="openbao-unseal-keys", interval=15): super().__init__(daemon=True, name="bao-unsealer") self.k8s = k8s self.namespace = namespace self.pod = pod self.secret = secret self.interval = interval + #: Where ``bao`` in the server pod connects. ``setup-kms.sh`` uses the + #: same address: it is a SAN on the server certificate, verified + #: against the ``BAO_CACERT`` the chart sets in the pod. The chart's + #: own default, ``https://127.0.0.1:8200``, is not a SAN, so every + #: call against it fails TLS verification. + self.addr = f"https://openbao.{namespace}:8200/" self._stop = threading.Event() #: ``[(iso_time, event)]`` -- every seal observed and every unseal #: performed, so a case can report the window rather than just the fact. self.events = [] self.unseal_count = 0 + #: Raw stdout and stderr of the last ``bao status``, kept so a seal + #: state that cannot be read can say why. + self.last_status = "" self.logger = logger # -- state -------------------------------------------------------- + def _bao(self, args, timeout=30): + """Run ``bao `` in the server pod. Returns ``(stdout, stderr)``. + + Through ``_exec_kubectl`` rather than ``exec_in_pod_container``: that + one discards stderr and the exit status, which is what made a seal + state that could not be read undiagnosable. + """ + out, err = self.k8s._exec_kubectl( + f"kubectl exec -n {self.namespace} {self.pod} -- " + f"env BAO_ADDR={self.addr} bao {args}", + supress_logs=True, timeout=timeout) + return out or "", err or "" + def sealed(self): - out = self.k8s.exec_in_pod_container( - self.pod, "", "bao status -format=json 2>/dev/null || " - "vault status -format=json 2>/dev/null || true", - namespace=self.namespace, timeout=30) - for line in (out or "").splitlines(): - try: - return bool(json.loads(line).get("sealed")) - except Exception: - continue - return None # unknown: pod not up, or no CLI in it + """True or False, or None when the state cannot be read. + + ``bao status`` exits 2 for a sealed server and still prints the + status, so the output is parsed whatever the exit status. It is one + indented JSON document spread over many lines, parsed as a whole. + """ + out, err = self._bao("status -format=json") + self.last_status = f"stdout={out.strip()[:400]!r} stderr={err.strip()[:400]!r}" + start, end = out.find("{"), out.rfind("}") + if start < 0 or end < start: + return None # pod not up, or bao could not reach the server + try: + return bool(json.loads(out[start:end + 1])["sealed"]) + except (ValueError, KeyError): + return None def unseal_keys(self): + """The unseal keys, in order, from the lane's Secret. + + The workflow writes the first three keys of ``bao operator init`` as + ``KEY1``..``KEY3``, the threshold the init default asks for. + """ out, _ = self.k8s._exec_kubectl( f"kubectl get secret {self.secret} -n {self.namespace} -o json " f"2>/dev/null || true", supress_logs=True) try: data = json.loads((out or "{}").strip() or "{}").get("data") or {} - except Exception: + except ValueError: return [] import base64 - keys = [] - for k, v in sorted(data.items()): - if "unseal" in k.lower() or "key" in k.lower(): - try: - text = base64.b64decode(v).decode().strip() - except Exception: - continue - # The init Secret has been seen holding either the raw key or - # the whole `bao operator init` JSON. Take both shapes. - try: - blob = json.loads(text) - keys.extend(blob.get("unseal_keys_b64") - or blob.get("keys_base64") or blob.get("keys") or []) - except Exception: - keys.append(text) - return [k for k in keys if k] + numbered = sorted((int(k[3:]), v) for k, v in data.items() + if re.fullmatch(r"KEY\d+", k)) + return [base64.b64decode(v).decode().strip() for _, v in numbered] def unseal(self): keys = self.unseal_keys() @@ -760,17 +926,14 @@ def unseal(self): self.namespace, self.secret) return False for key in keys[:5]: - self.k8s.exec_in_pod_container( - self.pod, "", - f"bao operator unseal {shlex.quote(key)} >/dev/null 2>&1 || " - f"vault operator unseal {shlex.quote(key)} >/dev/null 2>&1 || true", - namespace=self.namespace, timeout=45) + self._bao(f"operator unseal {shlex.quote(key)}", timeout=45) if self.sealed() is False: self.unseal_count += 1 self.events.append((time.strftime("%Y-%m-%d %H:%M:%S"), "unsealed")) self.logger.info("[bao] unsealed (%d so far)", self.unseal_count) return True - self.logger.warning("[bao] still sealed after trying %d key(s)", len(keys[:5])) + self.logger.warning("[bao] still sealed after trying %d key(s): %s", + len(keys[:5]), self.last_status) return False # -- thread -------------------------------------------------------