diff --git a/deploy/containerlab/README.md b/deploy/containerlab/README.md index ec079bf37..1082e624d 100644 --- a/deploy/containerlab/README.md +++ b/deploy/containerlab/README.md @@ -563,6 +563,7 @@ task deploy | `verify:traffic-policy` | Every binding installed; each path forwards what it grants and drops, and counts, what it does not | | `verify:masque-service` | Run the shipped MASQUE service and grant authority against dfw's gVPC workloads (about 20 min; restarts dfw-worker2; not in `verify`) | | `verify:masque-listener` | Reach the shipped MASQUE service through dfw's public listener from remote-host (needs gateway local delivery; not in `verify`) | +| `verify:listener-failover` | Prove the public listener's failover with two MASQUE instances on dfw (takes a dfw edge node off the fabric; not in `verify`) | | `deploy:looking-glass` | Enable the Looking Glass service on dfw in the documented order (restarts dfw's FRR twice); issue its test certificates | | `verify:looking-glass` | Qualify the Looking Glass service on dfw with the independent client, with faults (about 45 min; not in `verify`) | | `undeploy:looking-glass` | Switch the Looking Glass service off on dfw and roll its enabling steps back (restarts dfw's FRR twice) | diff --git a/deploy/containerlab/Taskfile.yaml b/deploy/containerlab/Taskfile.yaml index 9684cc02d..a32ae1037 100644 --- a/deploy/containerlab/Taskfile.yaml +++ b/deploy/containerlab/Taskfile.yaml @@ -1374,6 +1374,24 @@ tasks: cmds: - EDGE_CONFORMANCE_KUBECONFIG={{.ROOT_DIR}}/dfw.kubeconfig LAB={{.LAB}} go test -count=1 -v -timeout 40m -run '^TestMASQUEPublicListener$' ./tests/edgeconformance/ + # Not part of verify: Phase 4's failover proof of + # docs/designs/edge-public-listener.md (#1511). It serves the MASQUE + # service through dfw's public listener as verify:masque-listener does, but + # from two instances, one on each dfw edge node, and checks from remote-host + # that new connections leave an instance that goes unready, that a draining + # one serves until its deadline, that one cut off from the API leaves + # within 15.5 s of its last lease renewal, that every gateway withdraws the + # listener with no instance left, and that the client keeps its instance + # when the gateway it entered through loses its links. It takes one dfw + # edge node off the fabric and restores it, as verify:gateway-node-loss + # does. Same prerequisites as verify:masque-listener. Results land in + # bin/edge-conformance/. + "verify:listener-failover": + desc: Prove the public listener's failover with two MASQUE instances on dfw + dir: ../.. + cmds: + - EDGE_CONFORMANCE_KUBECONFIG={{.ROOT_DIR}}/dfw.kubeconfig LAB={{.LAB}} go test -count=1 -v -timeout 60m -run '^TestListenerFailover$' ./tests/edgeconformance/ + "verify:ns10": desc: Verify ns10 ping (IPv6-only, 3-site mesh) cmds: diff --git a/deploy/containerlab/scripts/lib.sh b/deploy/containerlab/scripts/lib.sh index 6faf912f1..afd15f799 100755 --- a/deploy/containerlab/scripts/lib.sh +++ b/deploy/containerlab/scripts/lib.sh @@ -43,8 +43,11 @@ copy_to() { # (see deploy-cni.sh and deploy-galactic-router.sh): they're copied into a base/ # subdirectory nested under the consuming kustomization's own root, since # kubectl apply -k refuses to load resource files from outside that root. +# +# rm -rf first: docker cp nests SRC inside an existing DEST. copy_config() { local node="$1" + docker exec "${node}" rm -rf /galactic/config docker cp "${CONFIG_DIR}" "${node}:/galactic/config" } diff --git a/tests/edgeconformance/listener_failover_test.go b/tests/edgeconformance/listener_failover_test.go new file mode 100644 index 000000000..6e42707c4 --- /dev/null +++ b/tests/edgeconformance/listener_failover_test.go @@ -0,0 +1,744 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeconformance_test + +import ( + "context" + "errors" + "fmt" + "os" + "sort" + "strconv" + "strings" + "testing" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" +) + +// TestListenerFailover is the lab failover test for the Edge public +// listener. It serves the MASQUE service through dfw's public listener as +// TestMASQUEPublicListener does, but from two provider instances, one on each +// dfw edge node, and an off-fabric client on remote-host. Every dfw edge node +// also runs a gateway, which serves the instance on its own node by local +// delivery. +// +// Each connection uses its own connector, and the instance that served it is +// the one whose accepted-request counter moved. With the listener's session +// affinity set to None, Maglev spreads new connections over both instances. +// Each row checks one failover criterion: +// +// - unready: an instance that stops being ready (its pod is deleted, so the +// provider clears Ready) leaves both gateways' backend sets, and new +// connections all reach the other instance; +// - drain: an instance core marks Draining keeps taking new connections +// until its drain deadline, and none after it. The provider clears Ready +// on shutdown, so no pod event drains it while Ready; the row writes the +// Draining condition and deadline core writes, as the cluster admin; +// - lease: an instance cut off from the API server leaves both gateways' +// backend sets within 15.5 s of its lease's last renewal; +// - no-instances: with both instances gone, every gateway withdraws the +// listener's advertisements and the client gets no answer; +// - gateway-loss: with client affinity, the client's instance serves it +// through the other gateway once the gateway it entered through loses its +// links. +// +// Needs galactic-edge deployed with the lab controller overlay's ingress +// flags and gateways with local delivery. Run it with task +// verify:listener-failover. +func TestListenerFailover(t *testing.T) { + l := getLab(t) + t.Cleanup(func() { l.writeSummary(t) }) + s := &service{l: l, ca: newTestCA(t, "masque listener CA"), otherCA: newTestCA(t, "masque other CA"), + links: map[string]string{}, unrelated: map[string]types.UID{}} + fo := &failover{pl: &publicListener{s: s}} + if os.Getenv("EDGE_CONFORMANCE_KEEP") == "" { + t.Cleanup(func() { fo.pl.teardown(t) }) + t.Cleanup(fo.pl.unpin) + t.Cleanup(func() { + if err := fo.restoreLinks(); err != nil { + t.Error(err) + } + }) + } + if !t.Run("setup", fo.setup) { + t.FailNow() + } + if !t.Run("both-serving", fo.rowBothServing) { + t.FailNow() + } + t.Run("unready", fo.rowUnready) + t.Run("drain", fo.rowDrain) + t.Run("lease", fo.rowLease) + t.Run("no-instances", fo.rowNoInstances) + t.Run("gateway-loss", fo.rowGatewayLoss) + l.record(t, "connections answered 503 while a connector route moved", fo.unavailable) + l.record(t, "connections answered without echoes after a gateway loss", fo.noEchoes) +} + +// The failover test's fixed values. +const ( + // foInstances is how many provider instances serve, one per node in + // foNodes. + foInstances = 2 + // foNewInstance is the node connect reports for a connection that an + // instance answered but none the row knows counted: a replacement pod. + foNewInstance = "new instance" + // foConnectors is how many connectors the client rotates through, so a + // connector is reused rarely: a reuse that lands on the other instance + // is answered 503 until core moves the connector's route there. + foConnectors = 24 + // foSample is how many connections a row sends to see where new + // connections go; with two instances and no affinity, all of them on one + // instance by chance has probability 2^-11. + foSample = 12 + // foDrain is how far ahead the drain row sets the deadline. + foDrain = 25 * time.Second + // foLeaseBound is #1511's bound from a lease's last renewal to its + // instance leaving every gateway's backend set. + foLeaseBound = 15500 * time.Millisecond +) + +// foNodes run the provider instances, one each. +var foNodes = []string{edgeNode1, edgeNode2} + +// foServices are the listener's NetworkServices, one per port. +var foServices = []string{plListener + "-udp-443", plListener + "-tcp-443"} + +// failover is TestListenerFailover's state. +type failover struct { + pl *publicListener + // pods maps each node in foNodes to its provider pod. + pods map[string]*corev1.Pod + // connectors are rotated through, one per connection. + connectors []*svcConnector + next int + // unavailable counts connections an instance answered 503, for the + // summary. + unavailable int + // echoless lets connect count a 200 without echoes as delivered, and + // noEchoes counts those, for the summary. + echoless bool + noEchoes int + // mark is the counter snapshot taken when the current batch of + // connections began. Snapshotting before every connection takes + // several seconds, too long for the drain row's window, so a + // connection no instance answered records what rose since its batch + // began instead. + mark map[string]float64 + // downed is the node whose links the gateway-loss row took down, for + // cleanup. + downed string +} + +// foOverlay runs one provider instance on each dfw edge node and sets the +// listener's session affinity to None, so new connections spread. +const foOverlay = ` - target: {kind: Deployment, name: masque-provider} + patch: |- + - {op: replace, path: /spec/replicas, value: 2} + - {op: remove, path: /spec/template/spec/nodeSelector} + - op: add + path: /spec/template/spec/affinity/podAntiAffinity + value: + requiredDuringSchedulingIgnoredDuringExecution: + - topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: {app.kubernetes.io/name: masque-provider} + - target: {kind: EdgeListener, name: masque-public} + patch: |- + - {op: replace, path: /spec/sessionAffinity, value: None} +` + +func (fo *failover) setup(t *testing.T) { + pl, s := fo.pl, fo.pl.s + pl.setupWith(t, foOverlay, foNodes...) + fo.refreshPods(t) + for i := range foConnectors { + fo.connectors = append(fo.connectors, + s.grant(t, fmt.Sprintf("fo%d", i), svcTenant10, 0x5b00+i, 0)) + } + // Every packet enters at one gateway until the gateway-loss row; the + // instance on that node is reached by local delivery, the other over + // SRv6. + for _, f := range listenerVIPs { + pl.pin(t, f, plGateway) + } +} + +// refreshPods records the current ready provider pod on each node. +func (fo *failover) refreshPods(t *testing.T) { + t.Helper() + fo.pods = map[string]*corev1.Pod{} + for _, n := range foNodes { + fo.pods[n] = fo.pl.s.waitReady(t, "masque-provider", n, "") + } +} + +// counters snapshots, on each dfw node, what says where a flow to the +// listener went: the gateway's drops by reason, its local deliveries and +// neighbor fallbacks, its packets for the listener's IPv6 VIP, and the uSID +// datapath's drops by reason. +func (fo *failover) counters(t *testing.T) map[string]float64 { + t.Helper() + l := fo.pl.s.l + out := map[string]float64{} + vip := listenerVIPs[0].vip + for _, n := range foNodes { + for _, line := range strings.Split(l.gatewayMetrics(t, n), "\n") { + switch { + case strings.HasPrefix(line, "galactic_edge_drops_total"), + strings.HasPrefix(line, "galactic_edge_local_deliveries_total"), + strings.HasPrefix(line, "galactic_edge_neigh_fallbacks_total"), + strings.HasPrefix(line, "galactic_edge_rule_packets_total{") && strings.Contains(line, vip): + out[n+" "+line[:strings.LastIndexByte(line, ' ')]] += sampleValue(line) + } + } + usid, err := nodeExec(n, "curl", "-s", "--max-time", "4", + "http://localhost:"+strconv.Itoa(usidMetricsPort)+"/metrics") + if err != nil { + continue + } + for _, line := range strings.Split(usid, "\n") { + if strings.HasPrefix(line, "galactic_usid_drops_total{") { + out[n+" "+line[:strings.LastIndexByte(line, ' ')]] += sampleValue(line) + } + } + } + return out +} + +// recordCounters records which counters rose since before, under what. +// Several connections may have run since before, so a counter that rose +// points at where to look rather than at one connection. +func (fo *failover) recordCounters(t *testing.T, what string, before map[string]float64) { + t.Helper() + var rose []string + for k, v := range fo.counters(t) { + if d := v - before[k]; d > 0 { + rose = append(rose, fmt.Sprintf("%s +%v", k, d)) + } + } + sort.Strings(rose) + fo.pl.s.l.record(t, what+": counters that rose", rose) +} + +// requests is each instance's CONNECT-IP request count, whatever it +// answered, by node. An instance a row took away has no count: its pod +// is gone or no longer answers, and no connection can be attributed to it. +func (fo *failover) requests(t *testing.T) map[string]float64 { + t.Helper() + out := map[string]float64{} + for n, p := range fo.pods { + ms, err := scrapePod(p) + if err != nil { + continue + } + out[n] = sum(ms, "galactic_connectip_requests_total") + } + return out +} + +// connect opens one HTTP/3 connection over f with the next connector and +// returns the node of the instance the listener delivered it to, or "" and +// the error when no instance answered. +// +// The instance is the one whose request count moved, whatever it answered: +// #1511 is about where new connections go. An instance answers 503 when an +// earlier connection left the connector's route with the other instance and +// core has not moved it yet; that is the connector, not the listener, so it +// counts as delivered. +func (fo *failover) connect(t *testing.T, f listenerFamily) (string, error) { + t.Helper() + pl := fo.pl + c := fo.connectors[fo.next%len(fo.connectors)] + fo.next++ + w := pl.s.l.workloadOn(t, c.tn, computeNode) + before := fo.requests(t) + evs, err := pl.remote(pl.remoteArgs(f, c, "h3", time.Second, w.addr)) + if err != nil { + if fo.mark != nil { + fo.recordCounters(t, "unanswered connection", fo.mark) + } + return "", err + } + code := status(evs) + switch { + case code == 503: + fo.unavailable++ + case code == 200 && len(echoes(evs, w.addr)) == 0 && fo.echoless: + fo.noEchoes++ + case code != 200 || len(echoes(evs, w.addr)) == 0: + return "", fmt.Errorf("status %d, %d echoes", code, len(echoes(evs, w.addr))) + } + after := fo.requests(t) + for n := range after { + if _, ok := before[n]; ok && after[n] > before[n] { + return n, nil + } + } + // None of the instances the row knows counted it, yet one answered: a + // pod that replaced one the row took away, which serves as soon as its + // attachment is Ready again. + return foNewInstance, nil +} + +// sample opens n connections over the IPv6 VIP and counts them by serving +// node; failed connections count under "". +func (fo *failover) sample(t *testing.T, n int) map[string]int { + t.Helper() + fo.mark = fo.counters(t) + got := map[string]int{} + for range n { + node, err := fo.connect(t, listenerVIPs[0]) + if err != nil { + t.Logf("connection failed: %v", err) + } + got[node]++ + } + return got +} + +// backends is how many backends gateway node has in its Maglev table for +// the listener's UDP service. +func (fo *failover) backends(t *testing.T, node string) float64 { + t.Helper() + vip := listenerVIPs[0].vip + for _, line := range strings.Split(fo.pl.s.l.gatewayMetrics(t, node), "\n") { + if strings.HasPrefix(line, "galactic_edge_rule_backends{") && strings.Contains(line, `vip="`+vip+`"`) && + strings.Contains(line, `proto="udp"`) { + return sampleValue(line) + } + } + return 0 +} + +// waitBackends waits until every dfw gateway has want backends for the +// listener and returns when the last one got there. +func (fo *failover) waitBackends(t *testing.T, want float64, timeout time.Duration) time.Time { + t.Helper() + if !fo.backendsWithin(t, want, timeout) { + fo.diagnose(t) + got := map[string]float64{} + for _, n := range foNodes { + got[n] = fo.backends(t, n) + } + t.Fatalf("timed out after %v waiting for %v listener backends on every gateway: %v", timeout, want, got) + } + return time.Now() +} + +// diagnose records what decides the gateways' backend sets: the listener's +// conditions and backends, its NetworkServices' conditions, and each dfw +// gateway's rule_backends samples for the listener's VIPs. +func (fo *failover) diagnose(t *testing.T) { + t.Helper() + l := fo.pl.s.l + for _, q := range []struct{ ns, what, path string }{ + {plNamespace, "edgelistener/" + plListener, `{.status.conditions}{"\n"}{.status.backends}`}, + {plNamespace, "networkservices", + `{range .items[*]}{.metadata.name} {.spec.edgeListenerRef} {.status.conditions}{"\n"}{end}`}, + {svcNS, "edgeattachments", `{range .items[*]}{.metadata.name} {.spec.serviceRef.name} ` + + `{.status.nodeName} {.status.conditions}{"\n"}{end}`}, + // A gateway leaves out a backend its own node reports Unhealthy; + // the probe's error is in the binding's health message. + {plNamespace, "servicevipbindings", `{range .items[*]}{.metadata.name} {.spec.backendAddress} ` + + `{.status.health}{"\n"}{end}`}, + } { + out, err := l.kubectl("-n", q.ns, "get", q.what, "-o", "jsonpath="+q.path) + if err != nil { + out = err.Error() + } + l.record(t, "diagnose: "+q.ns+"/"+q.what, out) + } + for _, n := range foNodes { + var lines []string + for _, line := range strings.Split(l.gatewayMetrics(t, n), "\n") { + if strings.HasPrefix(line, "galactic_edge_rule_backends{") && + (strings.Contains(line, listenerVIPs[0].vip) || strings.Contains(line, listenerVIPs[1].vip)) { + lines = append(lines, line) + } + } + l.record(t, "diagnose: "+n+" rule_backends", lines) + } +} + +// restore waits for an instance on every node and both in every gateway's +// backend set. A row that takes an instance away calls it when done, and +// every later row calls it first too, so a row that failed partway leaves +// the next neither a stale pod nor a missing instance. +func (fo *failover) restore(t *testing.T) { + t.Helper() + fo.refreshPods(t) + fo.waitBackends(t, foInstances, 3*time.Minute) +} + +// rowBothServing checks the starting point: both instances in every +// gateway's backend set, and new connections reaching both. +func (fo *failover) rowBothServing(t *testing.T) { + l := fo.pl.s.l + fo.waitBackends(t, foInstances, 3*time.Minute) + got := fo.sample(t, foSample) + l.record(t, "connections by instance", got) + if got[""] > 0 { + t.Errorf("%d of %d connections failed", got[""], foSample) + } + for _, n := range foNodes { + if got[n] == 0 { + t.Errorf("no connection reached the instance on %s: %v", n, got) + } + } +} + +// rowUnready deletes one instance's pod, so its provider clears Ready, and +// checks that it leaves every gateway's backend set and that new +// connections all reach the other instance while the pod is replaced. +func (fo *failover) rowUnready(t *testing.T) { + l := fo.pl.s.l + gone, other := foNodes[0], foNodes[1] + p := fo.pods[gone] + start := time.Now() + if _, err := l.kubectl("-n", svcNS, "delete", "pod", p.Name, "--wait=false"); err != nil { + t.Fatal(err) + } + delete(fo.pods, gone) + left := fo.waitBackends(t, foInstances-1, 30*time.Second) + l.record(t, "unready instance left every gateway after", left.Sub(start).Round(time.Millisecond)) + got := map[string]int{} + for range foSample { + node, err := fo.connect(t, listenerVIPs[0]) + if err != nil { + t.Errorf("connection failed with one instance unready: %v", err) + } + got[node]++ + } + l.record(t, "connections by instance while unready", got) + if got[gone] > 0 { + t.Errorf("%d new connections reached the unready instance on %s", got[gone], gone) + } + if got[other] == 0 { + t.Errorf("no connection reached the ready instance on %s", other) + } + fo.restore(t) +} + +// listenerAttachment returns the listener EdgeAttachment of pod. +func (fo *failover) listenerAttachment(t *testing.T, pod *corev1.Pod) *galacticv1alpha1.EdgeAttachment { + t.Helper() + var list galacticv1alpha1.EdgeAttachmentList + if err := fo.pl.s.l.c.List(context.Background(), &list, client.InNamespace(svcNS)); err != nil { + t.Fatal(err) + } + for i := range list.Items { + a := &list.Items[i] + if a.Spec.PodUID == string(pod.UID) && a.Spec.ServiceRef.Name == plService { + return a + } + } + t.Fatalf("pod %s has no %s attachment", pod.Name, plService) + return nil +} + +// rowDrain marks one instance's listener attachment Draining with a deadline +// foDrain ahead, as core does, and checks that the instance keeps taking new +// connections until the deadline and takes none after it. +func (fo *failover) rowDrain(t *testing.T) { + l := fo.pl.s.l + fo.restore(t) + drained, other := foNodes[1], foNodes[0] + att := fo.listenerAttachment(t, fo.pods[drained]) + deadline := metav1.NewTime(time.Now().Add(foDrain).Truncate(time.Second)) + meta.SetStatusCondition(&att.Status.Conditions, metav1.Condition{ + Type: galacticv1alpha1.EdgeAttachmentDraining, Status: metav1.ConditionTrue, + Reason: "LabDrain", Message: "TestListenerFailover drains this attachment", + }) + att.Status.DrainDeadline = &deadline + if err := l.c.Status().Update(context.Background(), att); err != nil { + t.Fatal(err) + } + l.record(t, "drain deadline", deadline.Format(time.RFC3339)) + + before := map[string]int{} + fo.mark = fo.counters(t) + for time.Until(deadline.Time) > 3*time.Second { + node, err := fo.connect(t, listenerVIPs[0]) + if err != nil { + t.Errorf("connection failed before the drain deadline: %v", err) + } + before[node]++ + } + l.record(t, "connections by instance before the deadline", before) + if before[drained] == 0 { + t.Errorf("the draining instance on %s took no new connection before its deadline", drained) + } + + left := fo.waitBackends(t, foInstances-1, 30*time.Second) + l.record(t, "draining instance left every gateway after its deadline by", + left.Sub(deadline.Time).Round(time.Millisecond)) + if left.Before(deadline.Time) { + fo.diagnose(t) + t.Errorf("the draining instance left the gateways %v before its deadline", deadline.Sub(left)) + } + // Past its deadline the drained attachment is deleted. The instance + // itself is not: its provider makes another attachment and serves + // again once that is Ready, so connections reaching dfw's instance + // after the deadline are no fault. What must hold is that the drained + // attachment goes and every connection is answered meanwhile. + key := client.ObjectKeyFromObject(att) + eventually(t, time.Minute, time.Second, "the drained attachment is deleted", func() (bool, error) { + var cur galacticv1alpha1.EdgeAttachment + err := l.c.Get(context.Background(), key, &cur) + if apierrors.IsNotFound(err) || (err == nil && cur.UID != att.UID) { + return true, nil + } + if err != nil { + return false, fmt.Errorf("attachment %s: %w", key.Name, err) + } + return false, fmt.Errorf("attachment %s still present", key.Name) + }) + after := fo.sample(t, foSample) + l.record(t, "connections by instance after the deadline", after) + if after[""] > 0 { + t.Errorf("%d connections went unanswered after the drain", after[""]) + } + if after[other] == 0 { + t.Errorf("no connection reached the instance on %s after the drain", other) + } + fo.restore(t) +} + +// rowLease cuts one instance's pod off from the API server, so its lease is +// not renewed, and checks that the instance leaves every gateway's backend +// set within foLeaseBound of the lease's last renewal. +func (fo *failover) rowLease(t *testing.T) { + l := fo.pl.s.l + fo.restore(t) + cut, other := foNodes[0], foNodes[1] + p := fo.pods[cut] + _, heal := l.partitionAPI(t, cut, podPID(t, cut, svcNS, p.Name)) + left := fo.waitBackends(t, foInstances-1, 45*time.Second) + + var le coordinationv1.Lease + if err := l.c.Get(context.Background(), client.ObjectKey{Namespace: svcNS, Name: "ei-" + string(p.UID)}, + &le); err != nil { + t.Fatal(err) + } + if le.Spec.RenewTime == nil { + t.Fatalf("lease ei-%s has no renew time", p.UID) + } + since := left.Sub(le.Spec.RenewTime.Time) + l.record(t, "instance left every gateway after its last renewal by", since.Round(time.Millisecond)) + if since > foLeaseBound { + t.Errorf("the instance left %v after its last renewal, past %v", since, foLeaseBound) + } + got := fo.sample(t, foSample) + l.record(t, "connections by instance without the lease", got) + if got[cut] > 0 { + t.Errorf("%d new connections reached the instance without its lease on %s", got[cut], cut) + } + if got[other] == 0 { + t.Errorf("no connection reached the instance on %s", other) + } + heal() + // The provider gives up its lease when it lapses and takes it back once + // the API answers again; replace the pod if it has not within a minute. + if !fo.backendsWithin(t, foInstances, time.Minute) { + if _, err := l.kubectl("-n", svcNS, "delete", "pod", p.Name, "--wait=false"); err != nil { + t.Fatal(err) + } + } + fo.restore(t) +} + +// backendsWithin reports whether every gateway reaches want backends within +// timeout, without failing the test when they do not. +func (fo *failover) backendsWithin(t *testing.T, want float64, timeout time.Duration) bool { + t.Helper() + for end := time.Now().Add(timeout); time.Now().Before(end); time.Sleep(time.Second) { + ok := true + for _, n := range foNodes { + if fo.backends(t, n) != want { + ok = false + } + } + if ok { + return true + } + } + return false +} + +// ruleAdvertisements counts the gateways' advertisements of the listener's +// NetworkServices. +func (fo *failover) ruleAdvertisements(t *testing.T) int { + t.Helper() + n := 0 + for _, svc := range foServices { + var list networkv1alpha1.BGPAdvertisementList + if err := fo.pl.s.l.c.List(context.Background(), &list, client.InNamespace(plNamespace), + client.MatchingLabels{"galactic.datum.net/network-rule": svc}); err != nil { + t.Fatal(err) + } + n += len(list.Items) + } + return n +} + +// rowNoInstances scales the provider to zero and checks that every gateway +// withdraws the listener's advertisements and the client gets no answer, +// then scales it back. +func (fo *failover) rowNoInstances(t *testing.T) { + l := fo.pl.s.l + fo.restore(t) + before := fo.ruleAdvertisements(t) + l.record(t, "listener advertisements while serving", before) + if before == 0 { + t.Fatal("no gateway advertises the listener while it serves") + } + scale := func(n int) { + if _, err := l.kubectl("-n", svcNS, "scale", "deployment", "masque-provider", + fmt.Sprintf("--replicas=%d", n)); err != nil { + t.Fatal(err) + } + } + scale(0) + start := time.Now() + eventually(t, 2*time.Minute, time.Second, "every gateway withdraws the listener", func() (bool, error) { + n := fo.ruleAdvertisements(t) + return n == 0, fmt.Errorf("%d advertisements left", n) + }) + l.record(t, "listener withdrawn after", time.Since(start).Round(time.Millisecond)) + if _, err := fo.connect(t, listenerVIPs[0]); err == nil { + t.Error("the client got an answer with no instance left") + } + scale(foInstances) + fo.restore(t) +} + +// rowGatewayLoss sets client affinity, finds the instance that serves the +// client through one gateway, takes the other dfw gateway's node off the +// fabric after entering through it, and checks that the same instance +// serves the client through the remaining gateway. +func (fo *failover) rowGatewayLoss(t *testing.T) { + pl, l := fo.pl, fo.pl.s.l + fo.restore(t) + f := listenerVIPs[0] + if _, err := l.kubectl("-n", plNamespace, "patch", "edgelistener", plListener, "--type=merge", "-p", + `{"spec":{"sessionAffinity":"ClientIP"}}`); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = l.kubectl("-n", plNamespace, "patch", "edgelistener", plListener, "--type=merge", "-p", + `{"spec":{"sessionAffinity":"None"}}`) + }) + // Every connection from the one client address now reaches one instance. + var home string + eventually(t, time.Minute, 2*time.Second, "client affinity on every gateway", func() (bool, error) { + got := fo.sample(t, 4) + if len(got) == 1 && got[""] == 0 { + for n := range got { + home = n + } + return true, nil + } + return false, fmt.Errorf("connections by instance %v", got) + }) + lost := foNodes[0] + if lost == home { + lost = foNodes[1] + } + l.record(t, "client's instance", home) + l.record(t, "gateway lost", lost) + + pl.pin(t, f, lost) + if node, err := fo.connect(t, f); err != nil || node != home { + t.Fatalf("through %s the client reached %q (%v), want the instance on %s", lost, node, err, home) + } + survivor := home + before := l.rulePackets(t, survivor, f.vip) + fo.takeDown(t, lost) + pl.unpin() + eventually(t, 90*time.Second, 2*time.Second, "tr1 routes the VIP away from "+lost, func() (bool, error) { + node, err := fo.connect(t, f) + return err == nil && node == home, fmt.Errorf("reached %q: %w", node, err) + }) + // The lost node's instance may have held some connectors' routes. A + // connection that reuses one is answered by the client's instance, + // which takes the route over, but the workload's echoes follow the + // fabric's old route until it converges. Where the connection went is + // what this row is about, so such a connection still counts. + fo.echoless = true + defer func() { fo.echoless = false }() + for range foSample { + if node, err := fo.connect(t, f); err != nil || node != home { + t.Errorf("with %s lost the client reached %q (%v), want the instance on %s", lost, node, err, home) + } + } + if after := l.rulePackets(t, survivor, f.vip); after <= before { + t.Errorf("%s counted no packets for %s after %s was lost", survivor, f.vip, lost) + } + if err := fo.restoreLinks(); err != nil { + t.Fatal(err) + } + for _, vf := range listenerVIPs { + pl.pin(t, vf, plGateway) + } +} + +// foLinks are the dfw edge nodes' fabric links, as +// scripts/verify-gateway-node-loss.sh takes them down. +var foLinks = []string{"eth1", "eth2", "eth3", "eth4"} + +// takeDown takes node off the fabric by setting its fabric links down. +func (fo *failover) takeDown(t *testing.T, node string) { + t.Helper() + fo.downed = node + for _, link := range foLinks { + if _, err := nodeExec(node, "ip", "link", "set", link, "down"); err != nil { + t.Fatal(err) + } + } +} + +// restoreLinks brings takeDown's links back up and waits for tr1 to route +// to the node again. It returns an error when a link does not come up or +// the route does not return within two minutes, and keeps the node marked +// until the route is back, so a later call, the test's cleanup included, +// tries again rather than leaving the gateway off the fabric. +func (fo *failover) restoreLinks() error { + node := fo.downed + if node == "" { + return nil + } + var errs []error + for _, link := range foLinks { + if _, err := nodeExec(node, "ip", "link", "set", link, "up"); err != nil { + errs = append(errs, fmt.Errorf("bring %s %s up: %w", node, link, err)) + } + } + if err := errors.Join(errs...); err != nil { + return err + } + up := listenerVIPs[0].uplinks[node] + var out string + for end := time.Now().Add(2 * time.Minute); time.Now().Before(end); time.Sleep(2 * time.Second) { + var err error + out, err = nodeExec(transitRouter(), "ip", "-6", "route", "show", "2001:db8:6060:1::/64") + if err == nil && strings.Contains(out, up[1]) { + fo.downed = "" + return nil + } + } + return fmt.Errorf("%s routes 2001:db8:6060:1::/64 without %s's uplink %s two minutes after its links came up: %q", + transitRouter(), node, up[1], out) +} diff --git a/tests/edgeconformance/masque_listener_test.go b/tests/edgeconformance/masque_listener_test.go index 7b007ae71..fb9c0443e 100644 --- a/tests/edgeconformance/masque_listener_test.go +++ b/tests/edgeconformance/masque_listener_test.go @@ -118,7 +118,12 @@ type pinnedRoute struct { prior string } -func (pl *publicListener) setup(t *testing.T) { +func (pl *publicListener) setup(t *testing.T) { pl.setupWith(t, "", plBackendNode) } + +// setupWith is setup with extra appended to the provider overlay's patches, +// as further list items, and a ready provider pod awaited on each of nodes; +// pl.s.pod is the one on nodes[0]. +func (pl *publicListener) setupWith(t *testing.T, extra string, nodes ...string) { s, l := pl.s, pl.s.l for i := 1; i <= 3; i++ { p := l.clientPod(t, svcTenant10, i) @@ -167,8 +172,10 @@ func (pl *publicListener) setup(t *testing.T) { patch: |- - {op: replace, path: /spec/vpcRef/uid, value: %q} - {op: replace, path: /spec/clientPool, value: %q} -`, plService, uid, network), nil) - s.pod = s.waitReady(t, "masque-provider", plBackendNode, "") +`, plService, uid, network)+extra, nil) + for i := len(nodes) - 1; i >= 0; i-- { + s.pod = s.waitReady(t, "masque-provider", nodes[i], "") + } // Every packet enters at plGateway, not the backend's node. for _, f := range listenerVIPs { diff --git a/tests/edgeconformance/masque_service_test.go b/tests/edgeconformance/masque_service_test.go index a2896d375..45cd27a82 100644 --- a/tests/edgeconformance/masque_service_test.go +++ b/tests/edgeconformance/masque_service_test.go @@ -806,10 +806,20 @@ type metric struct { // scrape reads pod's /metrics from its node. func (s *service) scrape(t *testing.T, pod *corev1.Pod) []metric { t.Helper() + ms, err := scrapePod(pod) + if err != nil { + t.Fatal(err) + } + return ms +} + +// scrapePod reads pod's /metrics from its node, for a caller that can carry +// on without them. +func scrapePod(pod *corev1.Pod) ([]metric, error) { out, err := nodeExec(pod.Spec.NodeName, "curl", "-sf", "--max-time", "5", "http://["+pod.Status.PodIP+"]:"+strconv.Itoa(svcHealthPort)+"/metrics") if err != nil { - t.Fatal(err) + return nil, err } var ms []metric for _, line := range strings.Split(out, "\n") { @@ -831,7 +841,7 @@ func (s *service) scrape(t *testing.T, pod *corev1.Pod) []metric { } ms = append(ms, m) } - return ms + return ms, nil } // splitLabels splits a label set at the commas between its pairs.