The tests waited on `bao status`, which answers once the node is unsealed and before raft has elected it, so the first policy write raced the election and failed with "local node not active but active cluster node not found". `unseal_bao` unseals and then waits for sys/leader to say the node is the leader; the four tests that bootstrap the store use it at both unseal sites. Closes #6807
156 lines
5.9 KiB
Python
156 lines
5.9 KiB
Python
# Helpers for a test script whose node imports `lib/k3s-node.nix`. A test's
|
|
# `testScript` is this file's text followed by its own. Every helper takes the
|
|
# node first and fails the test through the driver (`succeed`, `wait_until_*`)
|
|
# or an `AssertionError` naming what it saw.
|
|
import json
|
|
import time
|
|
|
|
from test_driver.machine import QemuMachine
|
|
|
|
# Container states that never turn into a running container on their own.
|
|
STUCK_WAITING = {
|
|
"ErrImageNeverPull",
|
|
"ErrImagePull",
|
|
"ImagePullBackOff",
|
|
"InvalidImageName",
|
|
"CreateContainerError",
|
|
"CreateContainerConfigError",
|
|
}
|
|
|
|
|
|
def kube(node: QemuMachine, args: str, timeout: int = 60) -> str:
|
|
return node.succeed(f"kubectl {args}", timeout=timeout)
|
|
|
|
|
|
def wait_node_ready(node: QemuMachine, timeout: int = 300) -> None:
|
|
"""Starts the node and waits until its k8s Node is Ready and the `default`
|
|
namespace has its ServiceAccount, which a pod there needs, at most
|
|
`timeout` seconds from the start."""
|
|
start = time.monotonic()
|
|
node.start()
|
|
node.wait_until_succeeds(
|
|
"kubectl get node -o jsonpath="
|
|
"'{.items[0].status.conditions[?(@.type==\"Ready\")].status}' | grep -qx True",
|
|
timeout=timeout,
|
|
)
|
|
left = max(1, int(timeout - (time.monotonic() - start)))
|
|
node.wait_until_succeeds("kubectl get serviceaccount default", timeout=left)
|
|
|
|
|
|
def containerd_ref(ref: str) -> str:
|
|
"""The name containerd lists an image under: a reference without a
|
|
registry is on docker.io, and a one-part name under `library/`."""
|
|
first = ref.split("/", 1)[0]
|
|
if "/" in ref and ("." in first or ":" in first or first == "localhost"):
|
|
return ref
|
|
return "docker.io/" + (ref if "/" in ref else "library/" + ref)
|
|
|
|
|
|
def image_refs(node: QemuMachine) -> list[str]:
|
|
"""The references of the images the node module was given."""
|
|
return node.succeed("cat /etc/k3s-node/images").split()
|
|
|
|
|
|
def wait_images(node: QemuMachine, timeout: int = 120) -> None:
|
|
"""Waits until containerd lists every image the node module was given."""
|
|
for ref in image_refs(node):
|
|
node.wait_until_succeeds(
|
|
f"k3s ctr images ls -q | grep -qxF '{containerd_ref(ref)}'",
|
|
timeout=timeout,
|
|
)
|
|
|
|
|
|
def unseal_bao(node: QemuMachine, init_file: str, timeout: int = 120) -> None:
|
|
"""Unseals the store with the key `bao operator init` saved in `init_file`,
|
|
then waits until the store's node is the active one. `bao status` answers
|
|
as soon as the node is unsealed, before raft has elected it, and a write
|
|
in that gap fails with "local node not active but active cluster node not
|
|
found"."""
|
|
node.succeed(f"bao operator unseal \"$(jq -r '.unseal_keys_b64[0]' {init_file})\"")
|
|
# `sys/leader` needs no token. The answer is the bare object, or under
|
|
# `.data` where the client wraps it.
|
|
node.wait_until_succeeds(
|
|
"bao read -format=json sys/leader | jq -e '(.data // .).is_self == true'",
|
|
timeout=timeout,
|
|
)
|
|
|
|
|
|
def pod(node: QemuMachine, name: str) -> dict:
|
|
return json.loads(kube(node, f"get pod {name} -o json"))
|
|
|
|
|
|
def container_state(node: QemuMachine, name: str) -> dict:
|
|
"""The first container's status of pod `name`, `{}` before it has one."""
|
|
statuses = pod(node, name)["status"].get("containerStatuses") or [{}]
|
|
return statuses[0]
|
|
|
|
|
|
def is_ready(p: dict) -> bool:
|
|
return any(
|
|
c["type"] == "Ready" and c["status"] == "True"
|
|
for c in p["status"].get("conditions", [])
|
|
)
|
|
|
|
|
|
def wait_pod(
|
|
node: QemuMachine,
|
|
name: str,
|
|
phase: str | None = None,
|
|
ready: bool | None = None,
|
|
timeout: int = 120,
|
|
) -> dict:
|
|
"""Waits until pod `name` is in `phase` and its Ready condition is `ready`
|
|
(each when given), and answers the pod. Fails at once on a container that
|
|
cannot start (`STUCK_WAITING`)."""
|
|
deadline = time.monotonic() + timeout
|
|
while True:
|
|
p = pod(node, name)
|
|
state = (p["status"].get("containerStatuses") or [{}])[0].get("state", {})
|
|
reason = state.get("waiting", {}).get("reason")
|
|
assert reason not in STUCK_WAITING, f"{name}: container cannot start: {state}"
|
|
if (phase is None or p["status"].get("phase") == phase) and (
|
|
ready is None or is_ready(p) == ready
|
|
):
|
|
return p
|
|
assert time.monotonic() < deadline, (
|
|
f"{name}: not phase={phase} ready={ready} after {timeout} s: {p['status']}"
|
|
)
|
|
time.sleep(2)
|
|
|
|
|
|
def http_status(node: QemuMachine, name: str, port: int, path: str) -> int:
|
|
"""The HTTP status pod `name` answers on its IP for `path`."""
|
|
ip = pod(node, name)["status"]["podIP"]
|
|
return int(
|
|
node.succeed(
|
|
f"curl -s -o /dev/null -m 5 -w '%{{http_code}}' http://{ip}:{port}{path}"
|
|
)
|
|
)
|
|
|
|
|
|
def delete_pod(node: QemuMachine, name: str, timeout: int = 60) -> tuple[dict, float]:
|
|
"""Deletes pod `name` and answers its container's final `terminated` state
|
|
and the seconds the delete took until the pod was gone."""
|
|
watch = f"/tmp/watch-{name}.json"
|
|
node.succeed(
|
|
f"timeout {timeout + 30} kubectl get pod {name} --watch --output-watch-events "
|
|
f"-o json > {watch} 2>&1 &"
|
|
)
|
|
node.wait_until_succeeds(f"test -s {watch}", timeout=30)
|
|
start = time.monotonic()
|
|
kube(node, f"delete pod {name} --wait=true --timeout={timeout}s", timeout + 10)
|
|
took = time.monotonic() - start
|
|
node.wait_until_succeeds(f"grep -q DELETED {watch}", timeout=30)
|
|
text = node.succeed(f"cat {watch}")
|
|
decoder = json.JSONDecoder()
|
|
terminated: dict = {}
|
|
i = 0
|
|
while i < len(text):
|
|
if text[i].isspace():
|
|
i += 1
|
|
continue
|
|
event, i = decoder.raw_decode(text, i)
|
|
for c in event["object"]["status"].get("containerStatuses", []):
|
|
terminated = c.get("state", {}).get("terminated") or terminated
|
|
assert terminated, f"{name}: no terminated state seen while deleting: {text}"
|
|
return terminated, took
|