cmd/k8s-operator/e2e: consolidate shared test helpers and fix PeerRelay test

Move the readiness and reachability checks for ingress, ProxyGroup and API
server proxy tests into shared helpers in helpers_test.go so the upcoming
upgrade/downgrade suite can reuse them.

Also change the PeerRelay verify helpers from exact-equality to subset
checks so this does not fail in real clusters once the Service gets a
LoadBalancer address.

Updates tailscale/corp#34562

Signed-off-by: Becky Pauley <[email protected]>
This commit is contained in:
Becky Pauley committed 2026-11-25 11:00:25 +00:00
1 parent 445df50dcf
commit e43a07e65b
6 files changed
+197 -70

No files matched your search

+5 -18
View File
@@ -15,7 +15,6 @@ import (
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
@@ -93,9 +92,7 @@ func TestAPIServerProxyGroupAuth(t *testing.T) {
proxyURL := waitForKubeAPIServerProxyReady(t, pg.Name)
proxyCl, err := client.New(&rest.Config{Host: proxyURL}, client.Options{
HTTPClient: newHTTPClient(tnClient),
})
proxyCl, err := apiServerProxyClient(proxyURL)
if err != nil {
t.Fatalf("creating client for %s: %v", proxyURL, err)
}
@@ -262,29 +259,19 @@ func applyProxyGroupProxyClass(t *testing.T) string {
// TLS cert issued, and the Tailscale Service advertised by the replicas.
func waitForKubeAPIServerProxyReady(t *testing.T, pgName string) string {
t.Helper()
pg := &tsapi.ProxyGroup{ObjectMeta: metav1.ObjectMeta{Name: pgName}}
var pg *tsapi.ProxyGroup
trigger := triggerReconcile(t, client.ObjectKey{Name: pgName}, &tsapi.ProxyGroup{}, 30*time.Second)
if err := tstest.WaitFor(5*time.Minute, func() error {
trigger()
if err := get(t.Context(), kubeClient, pg); err != nil {
var err error
pg, err = proxyGroupReady(t.Context(), pgName)
if err != nil {
return err
}
if !tsoperator.ProxyGroupIsReady(pg) {
ready := meta.FindStatusCondition(pg.Status.Conditions, string(tsapi.ProxyGroupReady))
if ready == nil {
return fmt.Errorf("ProxyGroup %s has no %s condition yet", pgName, tsapi.ProxyGroupReady)
}
return fmt.Errorf("ProxyGroup %s not ready: reason=%s message=%q", pgName, ready.Reason, ready.Message)
}
if pg.Status.URL == "" {
return fmt.Errorf("ProxyGroup %s is ready but status.url is not set yet", pgName)
}
return nil
}); err != nil {
t.Fatalf("waiting for ProxyGroup %s to be ready: %v", pgName, err)
+114
View File
@@ -9,6 +9,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"net/netip"
"slices"
@@ -19,7 +20,9 @@ import (
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"tailscale.com/client/tailscale/v2"
"tailscale.com/ipn/store/mem"
@@ -31,6 +34,13 @@ import (
"tailscale.com/types/logger"
)
const (
tsNamespace = "tailscale"
LabelParentType = "tailscale.com/parent-resource-type"
LabelParentName = "tailscale.com/parent-resource"
LabelParentNamespace = "tailscale.com/parent-resource-ns"
)
func generateName(prefix string) string {
return fmt.Sprintf("%s-%s", prefix, strings.ToLower(rand.Text()))
}
@@ -347,6 +357,110 @@ func waitForProxyClassReady(t *testing.T, name string) {
}
}
// proxyGroupReady fetches the named ProxyGroup and returns it only if it reports
// Ready. It does not poll itself, so callers control timing.
func proxyGroupReady(ctx context.Context, name string) (*tsapi.ProxyGroup, error) {
pg := &tsapi.ProxyGroup{ObjectMeta: metav1.ObjectMeta{Name: name}}
if err := get(ctx, kubeClient, pg); err != nil {
return nil, err
}
if !tsoperator.ProxyGroupIsReady(pg) {
if ready := meta.FindStatusCondition(pg.Status.Conditions, string(tsapi.ProxyGroupReady)); ready != nil {
return nil, fmt.Errorf("ProxyGroup %s not ready: reason=%s message=%q", name, ready.Reason, ready.Message)
}
return nil, fmt.Errorf("ProxyGroup %s has no %s condition yet", name, tsapi.ProxyGroupReady)
}
return pg, nil
}
// waitForProxyGroupReady waits until the named ProxyGroup reports Ready.
func waitForProxyGroupReady(t *testing.T, name string) {
t.Helper()
trigger := triggerReconcile(t, client.ObjectKey{Name: name}, &tsapi.ProxyGroup{}, 30*time.Second)
if err := tstest.WaitFor(5*time.Minute, func() error {
trigger()
_, err := proxyGroupReady(t.Context(), name)
return err
}); err != nil {
t.Fatalf("waiting for ProxyGroup %s to become ready: %v", name, err)
}
}
func apiServerProxyClient(proxyURL string) (client.Client, error) {
return client.New(&rest.Config{Host: proxyURL}, client.Options{
HTTPClient: newHTTPClient(tnClient),
})
}
// proxyDeviceIPForService returns the proxy device IP matching the family of the
// named Service's primary ClusterIP, read from the proxy's state Secret.
func proxyDeviceIPForService(t *testing.T, svcName string) string {
t.Helper()
var proxyIP string
if err := tstest.WaitFor(2*time.Minute, func() error {
var secrets corev1.SecretList
if err := kubeClient.List(t.Context(), &secrets,
client.InNamespace(tsNamespace),
client.MatchingLabels{LabelParentName: svcName, LabelParentNamespace: ns},
); err != nil {
return err
}
if len(secrets.Items) == 0 {
return fmt.Errorf("no state Secret for Service %s yet", svcName)
}
var deviceIPs []string
if err := json.Unmarshal(secrets.Items[0].Data[kubetypes.KeyDeviceIPs], &deviceIPs); err != nil {
return fmt.Errorf("decoding device IPs: %w", err)
}
svc := &corev1.Service{ObjectMeta: objectMeta(ns, svcName)}
if err := get(t.Context(), kubeClient, svc); err != nil {
return err
}
proxyIP = ipMatchingFamily(deviceIPs, svc.Spec.ClusterIP)
if proxyIP == "" {
return fmt.Errorf("device has no IP matching Service %s ClusterIP family", svcName)
}
return nil
}); err != nil {
t.Fatalf("waiting for matching-family proxy IP for Service %s: %v", svcName, err)
}
return proxyIP
}
// requireL3ProxyReachable curls the singleton L3 ingress proxy over the tailnet
// using the proxy device IP matching the Service's primary ClusterIP family.
func requireL3ProxyReachable(t *testing.T, svcName string) {
t.Helper()
proxyIP := proxyDeviceIPForService(t, svcName)
if err := testIngressIsReachable(t, newHTTPClient(tnClient), "http://"+net.JoinHostPort(proxyIP, "80")); err != nil {
t.Fatalf("L3 ingress %s not reachable: %v", svcName, err)
}
}
// waitForL3HAIngressReady waits until the L3 ingress Service is
// IngressSvcConfigured and has a LoadBalancer IP assigned.
func waitForL3HAIngressReady(t *testing.T, svcName string) {
t.Helper()
forceReconcile := triggerReconcile(t, client.ObjectKey{Namespace: ns, Name: svcName}, &corev1.Service{}, 30*time.Second)
if err := tstest.WaitFor(5*time.Minute, func() error {
forceReconcile()
svc := &corev1.Service{ObjectMeta: objectMeta(ns, svcName)}
if err := get(t.Context(), kubeClient, svc); err != nil {
return err
}
c := meta.FindStatusCondition(svc.Status.Conditions, string(tsapi.IngressSvcConfigured))
if c == nil || c.Status != metav1.ConditionTrue {
return fmt.Errorf("Service %s not IngressSvcConfigured yet", svcName)
}
if len(svc.Status.LoadBalancer.Ingress) == 0 {
return fmt.Errorf("Service %s has no LoadBalancer IP yet", svcName)
}
return nil
}); err != nil {
t.Fatalf("waiting for L3 HA ingress %s: %v", svcName, err)
}
}
// removeStaticEndpoints removes the static endpoints configuration from the
// named ProxyClass and waits for the change to be accepted.
func removeStaticEndpoints(t *testing.T, name string) {
+24 -37
View File
@@ -187,41 +187,28 @@ func TestL3HAIngress(t *testing.T) {
createAndCleanup(t, kubeClient, svc)
var svcIPs []string
forceReconcile := triggerReconcile(t,
client.ObjectKey{Namespace: ns, Name: svc.Name},
&corev1.Service{}, 30*time.Second)
// Wait for Service to be ready
if err := tstest.WaitFor(5*time.Minute, func() error {
maybeReadySvc := &corev1.Service{ObjectMeta: objectMeta(ns, svc.Name)}
forceReconcile()
if err := get(t.Context(), kubeClient, maybeReadySvc); err != nil {
waitForL3HAIngressReady(t, svc.Name)
if err := tstest.WaitFor(2*time.Minute, func() error {
readySvc := &corev1.Service{ObjectMeta: objectMeta(ns, svc.Name)}
if err := get(t.Context(), kubeClient, readySvc); err != nil {
return err
}
for _, cond := range maybeReadySvc.Status.Conditions {
if cond.Type == string(tsapi.IngressSvcConfigured) && cond.Status == metav1.ConditionTrue {
if len(maybeReadySvc.Status.LoadBalancer.Ingress) == 0 {
return fmt.Errorf("Service does not have an IP assigned yet")
}
tsSvc, err := tsClient.VIPServices().Get(t.Context(), "svc:default-"+svc.Name)
if err != nil {
return fmt.Errorf("getting Tailscale Service: %w", err)
}
ips := make([]string, 0, len(maybeReadySvc.Spec.ClusterIPs))
for _, clusterIP := range maybeReadySvc.Spec.ClusterIPs {
ip := ipMatchingFamily(tsSvc.Addrs, clusterIP)
if ip == "" {
return fmt.Errorf("Tailscale Service has no IP matching Kubernetes ClusterIP %s family", clusterIP)
}
ips = append(ips, ip)
}
svcIPs = ips
return nil
}
tsSvc, err := tsClient.VIPServices().Get(t.Context(), "svc:default-"+svc.Name)
if err != nil {
return fmt.Errorf("getting Tailscale Service: %w", err)
}
return fmt.Errorf("Service is not ready yet")
ips := make([]string, 0, len(readySvc.Spec.ClusterIPs))
for _, clusterIP := range readySvc.Spec.ClusterIPs {
ip := ipMatchingFamily(tsSvc.Addrs, clusterIP)
if ip == "" {
return fmt.Errorf("Tailscale Service has no IP matching Kubernetes ClusterIP %s family", clusterIP)
}
ips = append(ips, ip)
}
svcIPs = ips
return nil
}); err != nil {
t.Fatalf("error waiting for the Service to become ready: %v", err)
t.Fatalf("error resolving Tailscale Service IPs: %v", err)
}
for _, svcIP := range svcIPs {
@@ -279,10 +266,10 @@ func TestL7Ingress(t *testing.T) {
createAndCleanup(t, kubeClient, ingress)
hostname, err := waitForIngressHostname(t, ns, ingress.Name)
if err != nil {
t.Fatalf("error waiting for Ingress hostname: %v", err)
t.Fatalf("waiting for Ingress %s hostname: %v", ingress.Name, err)
}
if err := testIngressIsReachable(t, newHTTPClient(tnClient), fmt.Sprintf("https://%s:443", hostname)); err != nil {
t.Fatal(err)
t.Fatalf("Ingress %s not reachable: %v", ingress.Name, err)
}
})
}
@@ -383,10 +370,10 @@ func TestL7HAIngress(t *testing.T) {
hostname, err := waitForIngressHostname(t, ns, ingress.Name)
if err != nil {
t.Fatalf("error waiting for Ingress hostname: %v", err)
t.Fatalf("waiting for Ingress %s hostname: %v", ingress.Name, err)
}
if err := testIngressIsReachable(t, newHTTPClient(tnClient), fmt.Sprintf("https://%s:443", hostname)); err != nil {
t.Fatal(err)
t.Fatalf("Ingress %s not reachable: %v", ingress.Name, err)
}
})
}
@@ -466,10 +453,10 @@ func TestL7HAIngressMultiTailnet(t *testing.T) {
}
hostname, err := waitForIngressHostname(t, ns, ingress.Name)
if err != nil {
t.Fatalf("error waiting for Ingress hostname: %v", err)
t.Fatalf("waiting for Ingress %s hostname: %v", ingress.Name, err)
}
if err := testIngressIsReachable(t, newHTTPClient(secondTNClient), fmt.Sprintf("https://%s:443", hostname)); err != nil {
t.Fatal(err)
t.Fatalf("Ingress %s not reachable: %v", ingress.Name, err)
}
}
+17 -8
View File
@@ -152,10 +152,13 @@ func verifyPeerRelayConfigSecret(t *testing.T, prName string, replica int32, wan
if *conf.RelayServerPort != wantPort {
t.Fatalf("config Secret %s: RelayServerPort = %d, want %d", s.Name, *conf.RelayServerPort, wantPort)
}
// The kind cluster's LoadBalancer Services never get an address, so the config's advertised endpoints must be
// exactly the spec's static endpoints.
if !slices.Equal(conf.RelayServerStaticEndpoints, wantStaticEndpoints) {
t.Fatalf("config Secret %s: RelayServerStaticEndpoints = %v, want %v", s.Name, conf.RelayServerStaticEndpoints, wantStaticEndpoints)
// On a real cloud cluster the replica's LoadBalancer Service is assigned public addresses that the reconciler
// advertises alongside the static endpoints, so the config must contain the static endpoints rather than list
// them exclusively.
for _, w := range wantStaticEndpoints {
if !slices.Contains(conf.RelayServerStaticEndpoints, w) {
t.Fatalf("config Secret %s: RelayServerStaticEndpoints = %v, missing static endpoint %v", s.Name, conf.RelayServerStaticEndpoints, w)
}
}
}
@@ -188,8 +191,10 @@ func waitForPeerRelayReady(t *testing.T, prName string) {
}
}
// verifyPeerRelayStatusEndpoints asserts that every replica's status.endpoints entries are exactly the spec's
// static endpoints. The kind cluster's LoadBalancer Services never get an address, so nothing else may appear.
// verifyPeerRelayStatusEndpoints asserts that every replica's status.endpoints contains the spec's static
// endpoints. On a real cloud cluster each replica's LoadBalancer Service is also assigned one or more public
// addresses, which the reconciler advertises alongside the static endpoints, so we
// require the static endpoints to be present rather than to be the only entries.
func verifyPeerRelayStatusEndpoints(t *testing.T, prName string, replicas int32, want []netip.AddrPort) {
t.Helper()
@@ -213,9 +218,13 @@ func verifyPeerRelayStatusEndpoints(t *testing.T, prName string, replicas int32,
got = append(got, netip.AddrPortFrom(addr, uint16(ep.Port)))
}
if !slices.Equal(got, want) {
t.Errorf("PeerRelay %s replica %d: status.endpoints = %v, want %v", prName, i, got, want)
for _, w := range want {
if !slices.Contains(got, w) {
t.Errorf("PeerRelay %s replica %d: status.endpoints = %v, missing static endpoint %v", prName, i, got, w)
}
}
t.Logf("PeerRelay %s replica %d: status.endpoints = %v (static %v)", prName, i, got, want)
}
}
+2 -6
View File
@@ -14,7 +14,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"tailscale.com/client/tailscale/v2"
tsoperator "tailscale.com/k8s-operator"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/tstest"
)
@@ -192,13 +191,10 @@ func waitForProxyGroupDevices(t *testing.T, name string, replicas int, wantStati
var devices []staticEndpointsDevice
if err := tstest.WaitFor(5*time.Minute, func() error {
trigger()
pg := &tsapi.ProxyGroup{ObjectMeta: metav1.ObjectMeta{Name: name}}
if err := get(t.Context(), kubeClient, pg); err != nil {
pg, err := proxyGroupReady(t.Context(), name)
if err != nil {
return err
}
if !tsoperator.ProxyGroupIsReady(pg) {
return fmt.Errorf("ProxyGroup %s not ready: %v", name, pg.Status.Conditions)
}
devices = devices[:0]
for _, d := range pg.Status.Devices {
devices = append(devices, staticEndpointsDevice{tailnetIPs: d.TailnetIPs, staticEndpoints: d.StaticEndpoints})
+35 -1
View File
@@ -855,11 +855,16 @@ func applyDefaultProxyClass(ctx context.Context, logger *zap.SugaredLogger, cl c
}
func deployNameserver(ctx context.Context, logger *zap.SugaredLogger, cl client.Client, img *tsapi.NameserverImage) (*tsapi.DNSConfig, error) {
// Delete any DNSConfig left behind by a previous run that didn't reach cleanup.
if err := deleteDNSConfigAndWait(ctx, logger, cl); err != nil {
return nil, err
}
dc := &tsapi.DNSConfig{
ObjectMeta: metav1.ObjectMeta{Name: "dns"},
Spec: tsapi.DNSConfigSpec{Nameserver: &tsapi.Nameserver{Image: img}},
}
if err := createOrUpdate(ctx, cl, dc); err != nil {
if err := cl.Create(ctx, dc); err != nil {
return nil, fmt.Errorf("failed to create DNSConfig: %w", err)
}
@@ -884,6 +889,35 @@ func deployNameserver(ctx context.Context, logger *zap.SugaredLogger, cl client.
}
}
func deleteDNSConfigAndWait(ctx context.Context, logger *zap.SugaredLogger, cl client.Client) error {
dc := &tsapi.DNSConfig{ObjectMeta: metav1.ObjectMeta{Name: "dns"}}
if err := cl.Delete(ctx, dc); err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("deleting stale DNSConfig: %w", err)
}
logger.Info("deleting stale DNSConfig from a previous run; waiting for it to be removed...")
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for stale DNSConfig to be deleted (likely a stuck operator finalizer): %w", ctx.Err())
case <-ticker.C:
switch err := cl.Get(ctx, client.ObjectKeyFromObject(dc), dc); {
case apierrors.IsNotFound(err):
return nil
case err != nil:
return fmt.Errorf("waiting for stale DNSConfig deletion: %w", err)
}
}
}
}
func patchClusterDNS(ctx context.Context, logger *zap.SugaredLogger, nameserverIP string) (func(), error) {
if cm := getDNSConfigMap(ctx, "coredns"); cm != nil && cm.Data["Corefile"] != "" {
corefile := stripTSNetZone(cm.Data["Corefile"]) + fmt.Sprintf(`