mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 07:13:49 +09:00
Add e2e test for upgrading k8s operator (#22360)
* 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 <becky@tailscale.com> * cmd/k8s-operator/e2e: add test for upgrade/downgrade of the operator TestOperatorVersionChange installs the operator at one version, performs baseline checks, changes the operator to another version, and asserts the resources stay healthy across the change. Tests can be run as an upgrade, downgrade or a round-trip (upgrade then rollback). After each version change, the test re-verifies every managed resource (ingress, egress, ProxyGroup, API server proxy, PeerRelay), confirms the operator and proxy workloads actually rolled to the new image, and performs connectivity checks. Also skip rebuilding and side-loading a kind image when the node already has the tagged image, matching the existing EnsurePushed logic when using the --registry path. Updates tailscale/corp#34836 Change-Id: Id643255f99a06cf9fbabb722dd37293c8f097c61 Signed-off-by: Becky Pauley <becky@tailscale.com> --------- Signed-off-by: Becky Pauley <becky@tailscale.com>
This commit is contained in:
1 parent
945494e329
commit
08caf267a0
9 files changed
+1792
-227
No files matched your search
@@ -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)
|
||||
|
||||
@@ -3,6 +3,21 @@
|
||||
|
||||
// Package e2e runs end-to-end tests for the Tailscale Kubernetes operator.
|
||||
//
|
||||
// There are two modes, one mode can run at a time:
|
||||
//
|
||||
// - Standard mode (default): runs the full suite against the operator's
|
||||
// managed resources.
|
||||
// - Upgrade/downgrade mode (--from-version set): runs only
|
||||
// TestOperatorVersionChange, which installs the operator at one version,
|
||||
// changes it to another, and asserts the managed resources stay healthy
|
||||
// across the change. The rest of the suite is skipped, since this mode
|
||||
// installs and upgrades the operator and can conflict with other tests.
|
||||
//
|
||||
// The standard-mode requirements and flags are described first, followed by
|
||||
// upgrade/downgrade mode.
|
||||
//
|
||||
// # Standard mode
|
||||
//
|
||||
// To run without arguments, it requires:
|
||||
//
|
||||
// * Kubernetes cluster with local kubeconfig for it (direct connection, no API server proxy)
|
||||
@@ -36,4 +51,23 @@
|
||||
// * go
|
||||
// * container runtime with the docker daemon API available
|
||||
// * devcontrol: ./tool/go run --tags=tailscale_saas ./cmd/devcontrol --generate-test-devices=k8s-operator-e2e --scenario-output-dir=/tmp/k8s-operator-e2e --test-dns=http://localhost:8055
|
||||
//
|
||||
// # Upgrade/downgrade mode
|
||||
//
|
||||
// This mode runs TestOperatorVersionChange and skips the rest of the suite. The
|
||||
// operator is installed at --from-version and then changed to --to-version. Each
|
||||
// takes any git ref - a version tag, commit SHA, or "HEAD" for the current
|
||||
// checkout. --round-trip then changes back to --from-version in the same run,
|
||||
// exercising the change in both directions. The test is direction-neutral: pass
|
||||
// the older version as --from-version for an upgrade, or as --to-version for a
|
||||
// downgrade.
|
||||
//
|
||||
// For example, to upgrade from a released version to the current checkout against
|
||||
// devcontrol:
|
||||
//
|
||||
// go test -timeout=30m -v ./cmd/k8s-operator/e2e/ --build --cluster --devcontrol --from-version=v1.104.7 --to-version=HEAD
|
||||
//
|
||||
// To test an upgrade/downgrade round-trip against a real cluster and tailnet:
|
||||
//
|
||||
// go test -timeout=30m -v ./cmd/k8s-operator/e2e/ --build --registry my-registry --from-version=v1.104.7 --to-version=HEAD --round-trip
|
||||
package e2e
|
||||
@@ -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,148 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// requireL3HAReachable curls the ProxyGroup L3 HA ingress over the tailnet on
|
||||
// the VIPService address of every IP family of the Service's ClusterIP.
|
||||
func requireL3HAReachable(t *testing.T, svcName string) {
|
||||
t.Helper()
|
||||
var svcIPs []string
|
||||
if err := tstest.WaitFor(2*time.Minute, func() error {
|
||||
svc := &corev1.Service{ObjectMeta: objectMeta(ns, svcName)}
|
||||
if err := get(t.Context(), kubeClient, svc); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(svc.Spec.ClusterIPs) == 0 {
|
||||
return fmt.Errorf("Service %s has no ClusterIPs yet", svcName)
|
||||
}
|
||||
tsSvc, err := tsClient.VIPServices().Get(t.Context(), "svc:default-"+svcName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting Tailscale Service for %s: %w", svcName, err)
|
||||
}
|
||||
ips := make([]string, 0, len(svc.Spec.ClusterIPs))
|
||||
for _, clusterIP := range svc.Spec.ClusterIPs {
|
||||
ip := ipMatchingFamily(tsSvc.Addrs, clusterIP)
|
||||
if ip == "" {
|
||||
return fmt.Errorf("Tailscale Service for %s has no address matching ClusterIP %s family (addrs %v)", svcName, clusterIP, tsSvc.Addrs)
|
||||
}
|
||||
ips = append(ips, ip)
|
||||
}
|
||||
svcIPs = ips
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("resolving Tailscale Service IPs for %s: %v", svcName, err)
|
||||
}
|
||||
|
||||
for _, svcIP := range svcIPs {
|
||||
if err := testIngressIsReachable(t, newHTTPClient(tnClient), "http://"+net.JoinHostPort(svcIP, "80")); err != nil {
|
||||
t.Fatalf("L3 HA ingress %s not reachable on %s: %v", svcName, svcIP, 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) {
|
||||
|
||||
@@ -186,49 +186,8 @@ 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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("Service is not ready yet")
|
||||
}); err != nil {
|
||||
t.Fatalf("error waiting for the Service to become ready: %v", err)
|
||||
}
|
||||
|
||||
for _, svcIP := range svcIPs {
|
||||
if err := testIngressIsReachable(t, newHTTPClient(tnClient), "http://"+net.JoinHostPort(svcIP, "80")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
waitForL3HAIngressReady(t, svc.Name)
|
||||
requireL3HAReachable(t, svc.Name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -279,10 +238,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 +342,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 +425,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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,85 @@ func Tag(dir string) (tag string, dirty bool, err error) {
|
||||
return tag, dirty, nil
|
||||
}
|
||||
|
||||
// WorktreeForRef creates a detached git worktree of ref under a temp dir and
|
||||
// returns its path plus a cleanup func. Point Opts.Dir at it to build that ref's
|
||||
// images, chart, and CRDs; repoRoot may be any path inside the repository.
|
||||
func WorktreeForRef(ctx context.Context, repoRoot, ref string) (dir string, cleanup func(), err error) {
|
||||
dir, err = os.MkdirTemp("", "ts-k8s-e2e-worktree-")
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to create worktree temp dir: %w", err)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "git", "worktree", "add", "--detach", dir, ref)
|
||||
cmd.Dir = repoRoot
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
os.RemoveAll(dir)
|
||||
return "", nil, fmt.Errorf("git worktree add %s at %q: %w: %s", ref, dir, err, out)
|
||||
}
|
||||
cleanup = func() {
|
||||
// --force because the e2e build writes into the worktree (generated
|
||||
// CRDs, chart artifacts), leaving it dirty.
|
||||
rm := exec.Command("git", "worktree", "remove", "--force", dir)
|
||||
rm.Dir = repoRoot
|
||||
if _, err := rm.CombinedOutput(); err != nil {
|
||||
// Best-effort: fall back to removing the dir and pruning the
|
||||
// stale worktree registration.
|
||||
os.RemoveAll(dir)
|
||||
prune := exec.Command("git", "worktree", "prune")
|
||||
prune.Dir = repoRoot
|
||||
prune.Run()
|
||||
}
|
||||
}
|
||||
return dir, cleanup, nil
|
||||
}
|
||||
|
||||
// RemoveLeakedWorktrees removes leftover ts-k8s-e2e-worktree-* worktrees from a prior
|
||||
// interrupted run, which would otherwise accumulate. It force-removes any
|
||||
// ts-k8s-e2e-worktree-* worktree that is not locked. It is best-effort:
|
||||
// individual failures are ignored.
|
||||
func RemoveLeakedWorktrees(ctx context.Context, repoRoot string) {
|
||||
for _, path := range leakedWorktrees(ctx, repoRoot) {
|
||||
rm := exec.CommandContext(ctx, "git", "worktree", "remove", "--force", path)
|
||||
rm.Dir = repoRoot
|
||||
if err := rm.Run(); err != nil {
|
||||
os.RemoveAll(path)
|
||||
}
|
||||
}
|
||||
// Drop any registrations left pointing at now-removed directories.
|
||||
prune := exec.CommandContext(ctx, "git", "worktree", "prune")
|
||||
prune.Dir = repoRoot
|
||||
prune.Run()
|
||||
}
|
||||
|
||||
// leakedWorktrees returns the paths of registered worktrees whose directory
|
||||
// basename starts with the ts-k8s-e2e-worktree- prefix and that are not locked.
|
||||
func leakedWorktrees(ctx context.Context, repoRoot string) []string {
|
||||
list := exec.CommandContext(ctx, "git", "worktree", "list", "--porcelain")
|
||||
list.Dir = repoRoot
|
||||
out, err := list.Output()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var leaked []string
|
||||
// Porcelain output is one blank-line-separated stanza per worktree: a
|
||||
// "worktree <path>" line followed by attribute lines (e.g. "locked").
|
||||
for _, stanza := range strings.Split(strings.TrimSpace(string(out)), "\n\n") {
|
||||
var path string
|
||||
var locked bool
|
||||
for _, line := range strings.Split(stanza, "\n") {
|
||||
switch {
|
||||
case strings.HasPrefix(line, "worktree "):
|
||||
path = strings.TrimPrefix(line, "worktree ")
|
||||
case line == "locked" || strings.HasPrefix(line, "locked "):
|
||||
locked = true
|
||||
}
|
||||
}
|
||||
if path != "" && !locked && strings.HasPrefix(filepath.Base(path), "ts-k8s-e2e-worktree-") {
|
||||
leaked = append(leaked, path)
|
||||
}
|
||||
}
|
||||
return leaked
|
||||
}
|
||||
|
||||
// ImageRepo returns the image repository for name: <registry>/<name>, or
|
||||
// local/<name> when no registry is configured.
|
||||
func ImageRepo(registry, name string) string {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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})
|
||||
|
||||
+279
-146
@@ -53,6 +53,7 @@ import (
|
||||
kzap "sigs.k8s.io/controller-runtime/pkg/log/zap"
|
||||
"sigs.k8s.io/kind/pkg/apis/config/v1alpha4"
|
||||
"sigs.k8s.io/kind/pkg/cluster"
|
||||
"sigs.k8s.io/kind/pkg/cluster/nodes"
|
||||
"sigs.k8s.io/kind/pkg/cluster/nodeutils"
|
||||
"sigs.k8s.io/kind/pkg/cmd"
|
||||
|
||||
@@ -77,15 +78,16 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
tsClient *tailscale.Client // For API calls to control.
|
||||
tnClient *tsnet.Server // For testing real tailnet traffic on first tailnet.
|
||||
secondTSClient *tailscale.Client // For API calls to the secondary tailnet (_second_tailnet).
|
||||
secondTNClient *tsnet.Server // For testing real tailnet traffic on second tailnet.
|
||||
restCfg *rest.Config // For constructing a client-go client if necessary.
|
||||
kubeClient client.WithWatch // For k8s API calls.
|
||||
clusterLoginServer string
|
||||
clusterIPv4Support bool // whether the test cluster supports IPv4.
|
||||
clusterIPv6Support bool // whether the test cluster supports IPv6.
|
||||
tsClient *tailscale.Client // For API calls to control.
|
||||
tnClient *tsnet.Server // For testing real tailnet traffic on first tailnet.
|
||||
secondTSClient *tailscale.Client // For API calls to the secondary tailnet (_second_tailnet).
|
||||
secondTNClient *tsnet.Server // For testing real tailnet traffic on second tailnet.
|
||||
restCfg *rest.Config // For constructing a client-go client if necessary.
|
||||
kubeClient client.WithWatch // For k8s API calls.
|
||||
clusterLoginServer string
|
||||
clusterIPv4Support bool // whether the test cluster supports IPv4.
|
||||
clusterIPv6Support bool // whether the test cluster supports IPv6.
|
||||
clusterPrimaryFamily corev1.IPFamily // the cluster's primary IP family (Service.spec.ipFamilies[0]).
|
||||
|
||||
//go:embed certs/pebble.minica.crt
|
||||
pebbleMiniCACert []byte
|
||||
@@ -116,6 +118,27 @@ var (
|
||||
fBuild = flag.Bool("build", false, "if true, build and deploy the operator and container images from the current checkout; otherwise assume the operator is already running and the required images are available in the registry")
|
||||
fBaseImage = flag.String("base-image", "", "if set, use this image as the base for all images built by --build, instead of the default base image in build_docker.sh")
|
||||
fRegistry = flag.String("registry", "", `if set, use images from this registry instead of loading them into a kind node. Required with --build when testing against a remote cluster.`)
|
||||
fFromVersion = flag.String("from-version", "", "git ref to install first; its presence enables the operator version-change test.")
|
||||
fToVersion = flag.String("to-version", "", "git ref to change the operator to.")
|
||||
fRoundTrip = flag.Bool("round-trip", false, "after changing from --from-version to --to-version, change back to --from-version on the same resources")
|
||||
)
|
||||
|
||||
func upgradeMode() bool { return *fFromVersion != "" }
|
||||
|
||||
// Install plumbing shared between runTests (normal mode) and
|
||||
// TestOperatorVersionChange. These are populated by runTests once the
|
||||
// cluster and tailnet credentials are ready, so the test can install the operator
|
||||
// stack from an arbitrary git ref.
|
||||
var (
|
||||
repoRoot string // top-level dir of the current checkout.
|
||||
e2eLogger *zap.SugaredLogger
|
||||
helmCfg *action.Configuration
|
||||
kindProvider *cluster.Provider // non-nil when --cluster side-loads images.
|
||||
kubeconfig string
|
||||
operatorCreds oauthCreds // operator OAuth client for the first tailnet.
|
||||
secondOperatorCreds oauthCreds // operator OAuth client for the second tailnet (empty unless the second tailnet was set up).
|
||||
imageCAPaths []string // extra CA cert paths baked into built images.
|
||||
relName = "tailscale-operator" // helm release name.
|
||||
)
|
||||
|
||||
func runTests(m *testing.M) (int, error) {
|
||||
@@ -124,11 +147,35 @@ func runTests(m *testing.M) (int, error) {
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer cancel()
|
||||
|
||||
// Reject incompatible flag combinations before any setup runs.
|
||||
run := flag.Lookup("test.run").Value.String()
|
||||
switch {
|
||||
// Image delivery: --cluster side-loads into the kind node, --registry pushes.
|
||||
// --build needs exactly one path to get images onto the cluster.
|
||||
case *fCluster && *fRegistry != "":
|
||||
return 0, fmt.Errorf("--cluster side-loads images into the kind node and doesn't take --registry")
|
||||
case *fBuild && !*fCluster && *fRegistry == "":
|
||||
return 0, fmt.Errorf("--build without --cluster needs --registry to push images to; there is no kind node to side-load into")
|
||||
|
||||
// Upgrade/downgrade mode: runs when using --from-version.
|
||||
case *fRoundTrip && !upgradeMode():
|
||||
return 0, fmt.Errorf("--round-trip requires --from-version (it is only meaningful for the version-change test)")
|
||||
case upgradeMode() && *fToVersion == "":
|
||||
return 0, fmt.Errorf("--from-version requires --to-version")
|
||||
case upgradeMode() && !*fBuild:
|
||||
return 0, fmt.Errorf("--from-version requires --build to build images from each ref's worktree")
|
||||
case upgradeMode() && !*fCluster && *fRegistry == "":
|
||||
return 0, fmt.Errorf("--from-version needs --cluster (side-load images into the kind node) or --registry (push images) to deliver each ref's built images")
|
||||
// Upgrade mode runs only the version-change test, so a -run aimed elsewhere is
|
||||
// incompatible, otherwise run can default to TestOperatorVersionChange.
|
||||
case upgradeMode() && run != "" && run != "TestOperatorVersionChange" &&
|
||||
!strings.HasPrefix(run, "TestOperatorVersionChange/"):
|
||||
return 0, fmt.Errorf("--from-version runs only TestOperatorVersionChange and cannot be used with -run=%q", run)
|
||||
}
|
||||
if upgradeMode() && run == "" {
|
||||
if err := flag.Set("test.run", "TestOperatorVersionChange"); err != nil {
|
||||
return 0, fmt.Errorf("failed to restrict tests to TestOperatorVersionChange: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ossDir, err := build.RepoRoot()
|
||||
@@ -136,6 +183,9 @@ func runTests(m *testing.M) (int, error) {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
repoRoot = ossDir
|
||||
e2eLogger = logger
|
||||
|
||||
if err = os.MkdirAll(tmp, 0755); err != nil {
|
||||
return 0, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
@@ -143,10 +193,6 @@ func runTests(m *testing.M) (int, error) {
|
||||
logger.Infof("temp dir: %q", tmp)
|
||||
logger.Infof("oss dir: %q", ossDir)
|
||||
|
||||
var (
|
||||
kubeconfig string
|
||||
kindProvider *cluster.Provider
|
||||
)
|
||||
if *fCluster {
|
||||
kubeconfig = filepath.Join(tmp, "kubeconfig")
|
||||
kindProvider = cluster.NewProvider(
|
||||
@@ -197,13 +243,7 @@ func runTests(m *testing.M) (int, error) {
|
||||
return 0, fmt.Errorf("error detecting cluster IP families: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
operatorCreds oauthCreds // Operator's OAuth client for the first tailnet.
|
||||
secondOperatorCreds oauthCreds // Operator's OAuth client for the second tailnet.
|
||||
|
||||
imageCAPaths []string // Extra CAs the image needs in its system trust store to issue certs; it is only populated for pebble.
|
||||
pebbleCAChain []byte
|
||||
)
|
||||
var pebbleCAChain []byte
|
||||
if *fDevcontrol {
|
||||
// Deploy pebble and get its certs.
|
||||
if err = applyPebbleResources(ctx, kubeClient); err != nil {
|
||||
@@ -405,19 +445,132 @@ func runTests(m *testing.M) (int, error) {
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), caCM)
|
||||
|
||||
var ossTag string
|
||||
settings := cli.New()
|
||||
settings.KubeConfig = kubeconfig
|
||||
settings.SetNamespace("tailscale")
|
||||
helmCfg = &action.Configuration{}
|
||||
if err := helmCfg.Init(settings.RESTClientGetter(), "tailscale", "", logger.Infof); err != nil {
|
||||
return 0, fmt.Errorf("failed to initialize helm action configuration: %w", err)
|
||||
}
|
||||
|
||||
// Provision the operator from the current checkout, unless running
|
||||
// upgrade/downgrade mode, where TestOperatorVersionChange handles installation.
|
||||
if !upgradeMode() {
|
||||
cleanup, err := provisionOperatorStack(ctx, logger, ossDir)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer cleanup()
|
||||
}
|
||||
|
||||
caps := tailscale.KeyCapabilities{}
|
||||
caps.Devices.Create.Preauthorized = true
|
||||
caps.Devices.Create.Ephemeral = true
|
||||
caps.Devices.Create.Tags = []string{"tag:k8s"}
|
||||
|
||||
authKey, err := tsClient.Keys().CreateAuthKey(ctx, tailscale.CreateKeyRequest{Capabilities: caps})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create auth key for first tailnet: %w", err)
|
||||
}
|
||||
defer tsClient.Keys().Delete(context.Background(), authKey.ID)
|
||||
|
||||
tnClient = &tsnet.Server{
|
||||
ControlURL: tsClient.BaseURL.String(),
|
||||
Hostname: "test-proxy",
|
||||
Ephemeral: true,
|
||||
Store: &mem.Store{},
|
||||
AuthKey: authKey.Key,
|
||||
UserLogf: tslogger.Discard,
|
||||
}
|
||||
_, err = tnClient.Up(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tnClient.Close()
|
||||
|
||||
secondAuthKey, err := secondTSClient.Keys().CreateAuthKey(ctx, tailscale.CreateKeyRequest{Capabilities: caps})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create auth key for second tailnet: %w", err)
|
||||
}
|
||||
defer secondTSClient.Keys().Delete(context.Background(), secondAuthKey.ID)
|
||||
|
||||
secondTNClient = &tsnet.Server{
|
||||
ControlURL: secondTSClient.BaseURL.String(),
|
||||
Hostname: "test-proxy",
|
||||
Ephemeral: true,
|
||||
Store: &mem.Store{},
|
||||
AuthKey: secondAuthKey.Key,
|
||||
UserLogf: tslogger.Discard,
|
||||
}
|
||||
_, err = secondTNClient.Up(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer secondTNClient.Close()
|
||||
|
||||
// In upgrade/downgrade mode the operator isn't installed yet, so the
|
||||
// multi-tailnet resource creates these itself after it installs the
|
||||
// operator.
|
||||
if !upgradeMode() {
|
||||
secret := secondTailnetCredentialsSecret()
|
||||
if err := createOrUpdate(ctx, kubeClient, secret); err != nil {
|
||||
return 0, fmt.Errorf("failed to create second-tailnet-credentials Secret: %w", err)
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), secret)
|
||||
|
||||
tn := secondTailnetCR()
|
||||
if err := createOrUpdate(ctx, kubeClient, tn); err != nil {
|
||||
return 0, fmt.Errorf("failed to create second-tailnet Tailnet: %w", err)
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), tn)
|
||||
}
|
||||
|
||||
return m.Run(), nil
|
||||
}
|
||||
|
||||
// secondTailnetCredentialsSecret returns the Secret the operator reads to join
|
||||
// the second tailnet, built from secondOperatorCreds.
|
||||
func secondTailnetCredentialsSecret() *corev1.Secret {
|
||||
data := map[string][]byte{"client_id": []byte(secondOperatorCreds.clientID)}
|
||||
if secondOperatorCreds.audience != "" {
|
||||
data["audience"] = []byte(secondOperatorCreds.audience)
|
||||
} else {
|
||||
data["client_secret"] = []byte(secondOperatorCreds.clientSecret)
|
||||
}
|
||||
return &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "second-tailnet-credentials", Namespace: "tailscale"},
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// secondTailnetCR returns the Tailnet CR naming the second tailnet, referencing
|
||||
// the Secret from [secondTailnetCredentialsSecret].
|
||||
func secondTailnetCR() *tsapi.Tailnet {
|
||||
return &tsapi.Tailnet{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "second-tailnet"},
|
||||
Spec: tsapi.TailnetSpec{
|
||||
LoginURL: clusterLoginServer,
|
||||
Credentials: tsapi.TailnetCredentials{SecretName: "second-tailnet-credentials"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// installOrUpgradeOperatorStack builds+loads the e2e images from ossDir (with
|
||||
// --build), generates the CRDs, and helm install-or-upgrades the operator from
|
||||
// ossDir's chart. It returns the deployed image tag, or "" when nothing built.
|
||||
func installOrUpgradeOperatorStack(ctx context.Context, logger *zap.SugaredLogger, ossDir string) (ossTag string, err error) {
|
||||
if *fBuild || *fRegistry != "" {
|
||||
var dirty bool
|
||||
ossTag, dirty, err = build.Tag(ossDir)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return "", err
|
||||
}
|
||||
logger.Infof("using OSS image tag: %q", ossTag)
|
||||
logger.Infof("using OSS image tag: %q (from %q)", ossTag, ossDir)
|
||||
if !*fBuild && dirty {
|
||||
// Without --build the images must already exist in the registry,
|
||||
// but a dirty tree gets a random tag suffix that nothing has
|
||||
// pushed.
|
||||
return 0, fmt.Errorf("--registry without --build derives the image tag from the current commit, which requires a clean working tree")
|
||||
return "", fmt.Errorf("--registry without --build derives the image tag from the current commit, which requires a clean working tree")
|
||||
}
|
||||
}
|
||||
if *fBuild {
|
||||
@@ -438,31 +591,39 @@ func runTests(m *testing.M) (int, error) {
|
||||
if *fRegistry != "" {
|
||||
opts.Arch, err = detectNodeArch(ctx, kubeClient)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to detect node architecture: %w", err)
|
||||
return "", fmt.Errorf("failed to detect node architecture: %w", err)
|
||||
}
|
||||
logger.Infof("building images for node architecture %q, pushing to %q", opts.Arch, *fRegistry)
|
||||
if err := build.EnsurePushed(ctx, opts); err != nil {
|
||||
return 0, err
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
nodes, err := kindProvider.ListInternalNodes(kindClusterName)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to list kind nodes: %w", err)
|
||||
}
|
||||
for imgName := range build.Targets {
|
||||
if err := build.Build(ctx, opts, imgName); err != nil {
|
||||
return 0, err
|
||||
tagged := fmt.Sprintf("%s:%s", build.ImageRepo("", imgName), ossTag)
|
||||
// Skip the build and side-load if every node already has this exact
|
||||
// tag. The tag is the commit SHA, so a present tag is the right
|
||||
// image.
|
||||
if nodesHaveImage(nodes, tagged) {
|
||||
logger.Infof("image %s already on all kind nodes, skipping build and load", tagged)
|
||||
continue
|
||||
}
|
||||
nodes, err := kindProvider.ListInternalNodes(kindClusterName)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to list kind nodes: %w", err)
|
||||
if err := build.Build(ctx, opts, imgName); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// TODO(tomhjp): can be made more efficient and portable if we
|
||||
// stream built image tarballs straight to the node rather than
|
||||
// going via the daemon.
|
||||
imgRef, err := name.ParseReference(fmt.Sprintf("%s:%s", build.ImageRepo("", imgName), ossTag))
|
||||
imgRef, err := name.ParseReference(tagged)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse image reference: %w", err)
|
||||
return "", fmt.Errorf("failed to parse image reference: %w", err)
|
||||
}
|
||||
img, err := daemon.Image(imgRef)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to get image from daemon: %w", err)
|
||||
return "", fmt.Errorf("failed to get image from daemon: %w", err)
|
||||
}
|
||||
pr, pw := io.Pipe()
|
||||
go func() {
|
||||
@@ -473,7 +634,7 @@ func runTests(m *testing.M) (int, error) {
|
||||
}()
|
||||
for _, n := range nodes {
|
||||
if err := nodeutils.LoadImageArchive(n, pr); err != nil {
|
||||
return 0, fmt.Errorf("failed to load image into node %q: %w", n.String(), err)
|
||||
return "", fmt.Errorf("failed to load image into node %q: %w", n.String(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,13 +646,13 @@ func runTests(m *testing.M) (int, error) {
|
||||
cmd.Dir = ossDir
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to generate CRD: %v: %s", err, out)
|
||||
return "", fmt.Errorf("failed to generate CRD: %v: %s", err, out)
|
||||
}
|
||||
|
||||
// Load and install helm chart.
|
||||
chart, err := loader.Load(filepath.Join(ossDir, "cmd", "k8s-operator", "deploy", "chart"))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to load helm chart: %w", err)
|
||||
return "", fmt.Errorf("failed to load helm chart: %w", err)
|
||||
}
|
||||
// Image repo/tag are left empty unless we built or were given prebuilt
|
||||
// images (ossTag is set), so the chart uses the 'stable' defaults.
|
||||
@@ -538,127 +699,64 @@ func runTests(m *testing.M) (int, error) {
|
||||
},
|
||||
}
|
||||
|
||||
settings := cli.New()
|
||||
settings.KubeConfig = kubeconfig
|
||||
settings.SetNamespace("tailscale")
|
||||
helmCfg := &action.Configuration{}
|
||||
if err := helmCfg.Init(settings.RESTClientGetter(), "tailscale", "", logger.Infof); err != nil {
|
||||
return 0, fmt.Errorf("failed to initialize helm action configuration: %w", err)
|
||||
}
|
||||
|
||||
const relName = "tailscale-operator" // TODO(tomhjp): maybe configurable if others use a different value.
|
||||
f := upgraderOrInstaller(helmCfg, relName)
|
||||
if _, err := f(ctx, relName, chart, values); err != nil {
|
||||
return 0, fmt.Errorf("failed to install %q via helm: %w", relName, err)
|
||||
return "", fmt.Errorf("failed to install %q via helm: %w", relName, err)
|
||||
}
|
||||
return ossTag, nil
|
||||
}
|
||||
|
||||
if err := applyDefaultProxyClass(ctx, logger, kubeClient); err != nil {
|
||||
return 0, fmt.Errorf("failed to apply default ProxyClass: %w", err)
|
||||
// nodesHaveImage reports whether every node already has the tagged image, so a
|
||||
// side-load can be skipped. A node that lacks it (crictl inspecti exits non-zero)
|
||||
// makes this return false.
|
||||
func nodesHaveImage(ns []nodes.Node, taggedImage string) bool {
|
||||
for _, n := range ns {
|
||||
if _, err := nodeutils.ImageID(n, taggedImage); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(ns) > 0
|
||||
}
|
||||
|
||||
// Leave the nameserver image unset when nothing was built so
|
||||
// the operator falls back to the default.
|
||||
nameserverImg := &tsapi.NameserverImage{}
|
||||
if ossTag != "" {
|
||||
nameserverImg.Repo = build.ImageRepo(*fRegistry, build.ImgNameserver)
|
||||
nameserverImg.Tag = ossTag
|
||||
}
|
||||
dnsConfig, err := deployNameserver(ctx, logger, kubeClient, nameserverImg)
|
||||
// provisionOperatorStack fully brings up the operator from ossDir: install +
|
||||
// default ProxyClass + nameserver + the cluster-DNS patch for *.ts.net, returning
|
||||
// a cleanup.
|
||||
func provisionOperatorStack(ctx context.Context, logger *zap.SugaredLogger, ossDir string) (cleanup func(), err error) {
|
||||
tag, err := installOrUpgradeOperatorStack(ctx, logger, ossDir)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to deploy nameserver: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
if err := applyDefaultProxyClass(ctx, logger, kubeClient); err != nil {
|
||||
return nil, fmt.Errorf("applying default ProxyClass: %w", err)
|
||||
}
|
||||
dnsConfig, err := deployNameserver(ctx, logger, kubeClient, nameserverImage(*fRegistry, tag))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("deploying nameserver: %w", err)
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), dnsConfig)
|
||||
|
||||
restoreClusterDNS, err := patchClusterDNS(ctx, logger, dnsConfig.Status.Nameserver.IP)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to patch cluster DNS: %w", err)
|
||||
kubeClient.Delete(context.Background(), dnsConfig)
|
||||
return nil, fmt.Errorf("patching cluster DNS: %w", err)
|
||||
}
|
||||
defer restoreClusterDNS()
|
||||
return func() {
|
||||
restoreClusterDNS()
|
||||
// Wait for the delete to finish so it isn't stuck in Terminating
|
||||
// which otherwise blocks the next run against a reused cluster.
|
||||
if err := deleteDNSConfigAndWait(context.Background(), logger, kubeClient); err != nil {
|
||||
logger.Infof("cleaning up DNSConfig: %v", err)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
caps := tailscale.KeyCapabilities{}
|
||||
caps.Devices.Create.Preauthorized = true
|
||||
caps.Devices.Create.Ephemeral = true
|
||||
caps.Devices.Create.Tags = []string{"tag:k8s"}
|
||||
|
||||
authKey, err := tsClient.Keys().CreateAuthKey(ctx, tailscale.CreateKeyRequest{Capabilities: caps})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create auth key for first tailnet: %w", err)
|
||||
// nameserverImage returns the NameserverImage for the given registry and image
|
||||
// tag.
|
||||
func nameserverImage(registry, tag string) *tsapi.NameserverImage {
|
||||
img := &tsapi.NameserverImage{}
|
||||
if tag != "" {
|
||||
img.Repo = build.ImageRepo(registry, build.ImgNameserver)
|
||||
img.Tag = tag
|
||||
}
|
||||
defer tsClient.Keys().Delete(context.Background(), authKey.ID)
|
||||
|
||||
secondAuthKey, err := secondTSClient.Keys().CreateAuthKey(ctx, tailscale.CreateKeyRequest{Capabilities: caps})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create auth key for second tailnet: %w", err)
|
||||
}
|
||||
defer secondTSClient.Keys().Delete(context.Background(), secondAuthKey.ID)
|
||||
|
||||
tnClient = &tsnet.Server{
|
||||
ControlURL: tsClient.BaseURL.String(),
|
||||
Hostname: "test-proxy",
|
||||
Ephemeral: true,
|
||||
Store: &mem.Store{},
|
||||
AuthKey: authKey.Key,
|
||||
UserLogf: tslogger.Discard,
|
||||
}
|
||||
_, err = tnClient.Up(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tnClient.Close()
|
||||
|
||||
secondTNClient = &tsnet.Server{
|
||||
ControlURL: secondTSClient.BaseURL.String(),
|
||||
Hostname: "test-proxy",
|
||||
Ephemeral: true,
|
||||
Store: &mem.Store{},
|
||||
AuthKey: secondAuthKey.Key,
|
||||
UserLogf: tslogger.Discard,
|
||||
}
|
||||
_, err = secondTNClient.Up(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer secondTNClient.Close()
|
||||
|
||||
// Create the tailnet Secret in the tailscale namespace.
|
||||
secretData := map[string][]byte{
|
||||
"client_id": []byte(secondOperatorCreds.clientID),
|
||||
}
|
||||
if secondOperatorCreds.audience != "" {
|
||||
secretData["audience"] = []byte(secondOperatorCreds.audience)
|
||||
} else {
|
||||
secretData["client_secret"] = []byte(secondOperatorCreds.clientSecret)
|
||||
}
|
||||
secret := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "second-tailnet-credentials",
|
||||
Namespace: "tailscale",
|
||||
},
|
||||
Data: secretData,
|
||||
}
|
||||
if err := createOrUpdate(ctx, kubeClient, secret); err != nil {
|
||||
return 0, fmt.Errorf("failed to create second-tailnet-credentials Secret: %w", err)
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), secret)
|
||||
|
||||
// Create the Tailnet resource.
|
||||
tn := &tsapi.Tailnet{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "second-tailnet",
|
||||
},
|
||||
Spec: tsapi.TailnetSpec{
|
||||
LoginURL: clusterLoginServer,
|
||||
Credentials: tsapi.TailnetCredentials{
|
||||
SecretName: "second-tailnet-credentials",
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := createOrUpdate(ctx, kubeClient, tn); err != nil {
|
||||
return 0, fmt.Errorf("failed to create second-tailnet Tailnet: %w", err)
|
||||
}
|
||||
defer kubeClient.Delete(context.Background(), tn)
|
||||
|
||||
return m.Run(), nil
|
||||
return img
|
||||
}
|
||||
|
||||
func clientIDFromSecret(clientSecret string) (string, error) {
|
||||
@@ -855,11 +953,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 +987,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(`
|
||||
@@ -1139,6 +1271,7 @@ func detectClusterIPFamilies(ctx context.Context, logger *zap.SugaredLogger, cl
|
||||
if !clusterIPv4Support && !clusterIPv6Support {
|
||||
return fmt.Errorf("Service %s/%s reported no IP families", svc.Namespace, svc.Name)
|
||||
}
|
||||
clusterPrimaryFamily = svc.Spec.IPFamilies[0]
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user