mirror of
https://github.com/tailscale/tailscale.git
synced 2026-11-27 20:16:28 -08:00
k8s-proxy did not serve /livez or /readyz, so the operator skipped the probes for the kube-apiserver ProxyGroup even when a ProxyClass set them. This adds both to k8s-proxy (/livez passes while the LocalAPI answers, /readyz once the node has its tailnet IPs) and drops the exception from the operator. k8s-proxy takes its port from the config file that the operator writes, so its probes always use port 9002 and ignore TS_LOCAL_ADDR_PORT and TS_ENABLE_HEALTH_CHECK. The local server now starts before Up, so /livez answers while Up runs and while waiting for a reissued auth key. Updates tailscale/corp#38175 Signed-off-by: chaosinthecrd <[email protected]>
577 lines
28 KiB
Go
577 lines
28 KiB
Go
// Copyright (c) Tailscale Inc & contributors
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
//go:build !plan9
|
|
|
|
package main
|
|
|
|
import (
|
|
_ "embed"
|
|
"fmt"
|
|
"maps"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/google/go-cmp/cmp"
|
|
"go.uber.org/zap"
|
|
appsv1 "k8s.io/api/apps/v1"
|
|
corev1 "k8s.io/api/core/v1"
|
|
"k8s.io/apimachinery/pkg/api/resource"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
|
"sigs.k8s.io/yaml"
|
|
"tailscale.com/client/tailscale/v2"
|
|
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
|
"tailscale.com/k8s-operator/tsclient"
|
|
"tailscale.com/kube/kubetypes"
|
|
"tailscale.com/types/key"
|
|
)
|
|
|
|
// Test_statefulSetNameBase tests that parent name portion in a StatefulSet name
|
|
// base will be truncated if the parent name is longer than 43 chars to ensure
|
|
// that the total does not exceed 52 chars.
|
|
// How many chars need to be cut off parent name depends on an internal var in
|
|
// kube name generation code that can change at which point this test will break
|
|
// and need to be changed. This is okay as we do not rely on that value in
|
|
// code whilst being aware when it changes might still be useful.
|
|
// https://github.com/kubernetes/kubernetes/blob/v1.28.4/staging/src/k8s.io/apiserver/pkg/storage/names/generate.go#L45.
|
|
// https://github.com/kubernetes/kubernetes/pull/116430
|
|
func Test_statefulSetNameBase(t *testing.T) {
|
|
// Service name lengths can be 1 - 63 chars, be paranoid and test them all.
|
|
var b strings.Builder
|
|
for b.Len() < 63 {
|
|
if _, err := b.WriteString("a"); err != nil {
|
|
t.Fatalf("error writing to string builder: %v", err)
|
|
}
|
|
baseLength := min(b.Len(), 43) // currently 43 is the max base length
|
|
wantsNameR := regexp.MustCompile(`^ts-a{` + fmt.Sprint(baseLength) + `}-$`) // to match a string like ts-aaaa-
|
|
gotName := statefulSetNameBase(b.String())
|
|
if !wantsNameR.MatchString(gotName) {
|
|
t.Fatalf("expected string %s to match regex %s ", gotName, wantsNameR.String()) // fatal rather than error as this test is called 63 times
|
|
}
|
|
}
|
|
}
|
|
|
|
func Test_applyProxyClassToStatefulSet(t *testing.T) {
|
|
zl, err := zap.NewDevelopment()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Setup
|
|
proxyClassAllOpts := &tsapi.ProxyClass{
|
|
Spec: tsapi.ProxyClassSpec{
|
|
UseLetsEncryptStagingEnvironment: true,
|
|
StatefulSet: &tsapi.StatefulSet{
|
|
Labels: tsapi.Labels{"foo": "bar"},
|
|
Annotations: map[string]string{"foo.io/bar": "foo"},
|
|
Pod: &tsapi.Pod{
|
|
Labels: tsapi.Labels{"bar": "foo"},
|
|
Annotations: map[string]string{"bar.io/foo": "foo"},
|
|
SecurityContext: &corev1.PodSecurityContext{
|
|
RunAsUser: new(int64(0)),
|
|
},
|
|
ImagePullSecrets: []corev1.LocalObjectReference{{Name: "docker-creds"}},
|
|
NodeName: "some-node",
|
|
NodeSelector: map[string]string{"beta.kubernetes.io/os": "linux"},
|
|
Affinity: &corev1.Affinity{NodeAffinity: &corev1.NodeAffinity{RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{}}},
|
|
Tolerations: []corev1.Toleration{{Key: "", Operator: "Exists"}},
|
|
PriorityClassName: "high-priority",
|
|
TopologySpreadConstraints: []corev1.TopologySpreadConstraint{
|
|
{
|
|
WhenUnsatisfiable: "DoNotSchedule",
|
|
TopologyKey: "kubernetes.io/hostname",
|
|
MaxSkew: 3,
|
|
LabelSelector: &metav1.LabelSelector{
|
|
MatchLabels: map[string]string{"foo": "bar"},
|
|
},
|
|
},
|
|
},
|
|
DNSPolicy: new(corev1.DNSClusterFirstWithHostNet),
|
|
DNSConfig: &corev1.PodDNSConfig{
|
|
Nameservers: []string{"1.1.1.1", "8.8.8.8"},
|
|
Searches: []string{"example.com", "test.local"},
|
|
Options: []corev1.PodDNSConfigOption{
|
|
{Name: "ndots", Value: new("2")},
|
|
{Name: "edns0"},
|
|
},
|
|
},
|
|
TailscaleContainer: &tsapi.Container{
|
|
SecurityContext: &corev1.SecurityContext{
|
|
Privileged: new(true),
|
|
},
|
|
Resources: corev1.ResourceRequirements{
|
|
Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1000m"), corev1.ResourceMemory: resource.MustParse("128Mi")},
|
|
Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("500m"), corev1.ResourceMemory: resource.MustParse("64Mi")},
|
|
},
|
|
Env: []tsapi.Env{{Name: "foo", Value: "bar"}, {Name: "TS_USERSPACE", Value: "true"}, {Name: "bar"}},
|
|
ImagePullPolicy: "IfNotPresent",
|
|
Image: "ghcr.io/my-repo/tailscale:v0.01testsomething",
|
|
},
|
|
TailscaleInitContainer: &tsapi.Container{
|
|
SecurityContext: &corev1.SecurityContext{
|
|
Privileged: new(true),
|
|
RunAsUser: new(int64(0)),
|
|
},
|
|
Resources: corev1.ResourceRequirements{
|
|
Limits: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("1000m"), corev1.ResourceMemory: resource.MustParse("128Mi")},
|
|
Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("500m"), corev1.ResourceMemory: resource.MustParse("64Mi")},
|
|
},
|
|
Env: []tsapi.Env{{Name: "foo", Value: "bar"}, {Name: "TS_USERSPACE", Value: "true"}, {Name: "bar"}},
|
|
ImagePullPolicy: "IfNotPresent",
|
|
Image: "ghcr.io/my-repo/tailscale:v0.01testsomething",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
proxyClassJustLabels := &tsapi.ProxyClass{
|
|
Spec: tsapi.ProxyClassSpec{
|
|
StatefulSet: &tsapi.StatefulSet{
|
|
Labels: tsapi.Labels{"foo": "bar"},
|
|
Annotations: map[string]string{"foo.io/bar": "foo"},
|
|
Pod: &tsapi.Pod{
|
|
Labels: tsapi.Labels{"bar": "foo"},
|
|
Annotations: map[string]string{"bar.io/foo": "foo"},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
proxyClassWithMetricsDebug := func(metrics bool, debug *bool) *tsapi.ProxyClass {
|
|
return &tsapi.ProxyClass{
|
|
Spec: tsapi.ProxyClassSpec{
|
|
Metrics: &tsapi.Metrics{Enable: metrics},
|
|
StatefulSet: func() *tsapi.StatefulSet {
|
|
if debug == nil {
|
|
return nil
|
|
}
|
|
|
|
return &tsapi.StatefulSet{
|
|
Pod: &tsapi.Pod{
|
|
TailscaleContainer: &tsapi.Container{
|
|
Debug: &tsapi.Debug{Enable: *debug},
|
|
},
|
|
},
|
|
}
|
|
}(),
|
|
},
|
|
}
|
|
}
|
|
var userspaceProxySS, nonUserspaceProxySS appsv1.StatefulSet
|
|
if err := yaml.Unmarshal(userspaceProxyYaml, &userspaceProxySS); err != nil {
|
|
t.Fatalf("unmarshaling userspace proxy template: %v", err)
|
|
}
|
|
if err := yaml.Unmarshal(proxyYaml, &nonUserspaceProxySS); err != nil {
|
|
t.Fatalf("unmarshaling non-userspace proxy template: %v", err)
|
|
}
|
|
// Set a couple additional fields so we can test that we don't
|
|
// mistakenly override those.
|
|
labels := map[string]string{
|
|
kubetypes.LabelManaged: "true",
|
|
LabelParentName: "foo",
|
|
}
|
|
annots := map[string]string{
|
|
podAnnotationLastSetClusterIP: "1.2.3.4",
|
|
}
|
|
env := []corev1.EnvVar{{Name: "TS_HOSTNAME", Value: "nginx"}}
|
|
userspaceProxySS.Labels = labels
|
|
userspaceProxySS.Annotations = annots
|
|
userspaceProxySS.Spec.Template.Spec.Containers[0].Image = "tailscale/tailscale:v0.0.1"
|
|
userspaceProxySS.Spec.Template.Spec.Containers[0].Env = env
|
|
nonUserspaceProxySS.ObjectMeta.Labels = labels
|
|
nonUserspaceProxySS.ObjectMeta.Annotations = annots
|
|
nonUserspaceProxySS.Spec.Template.Spec.Containers[0].Env = env
|
|
nonUserspaceProxySS.Spec.Template.Spec.InitContainers[0].Image = "tailscale/tailscale:v0.0.1"
|
|
|
|
// 1. Test that a ProxyClass with all fields set gets correctly applied
|
|
// to a Statefulset built from non-userspace proxy template.
|
|
wantSS := nonUserspaceProxySS.DeepCopy()
|
|
updateMap(wantSS.ObjectMeta.Labels, proxyClassAllOpts.Spec.StatefulSet.Labels.Parse())
|
|
updateMap(wantSS.ObjectMeta.Annotations, proxyClassAllOpts.Spec.StatefulSet.Annotations)
|
|
wantSS.Spec.Template.Labels = proxyClassAllOpts.Spec.StatefulSet.Pod.Labels.Parse()
|
|
wantSS.Spec.Template.Annotations = proxyClassAllOpts.Spec.StatefulSet.Pod.Annotations
|
|
wantSS.Spec.Template.Spec.SecurityContext = proxyClassAllOpts.Spec.StatefulSet.Pod.SecurityContext
|
|
wantSS.Spec.Template.Spec.ImagePullSecrets = proxyClassAllOpts.Spec.StatefulSet.Pod.ImagePullSecrets
|
|
wantSS.Spec.Template.Spec.NodeName = proxyClassAllOpts.Spec.StatefulSet.Pod.NodeName
|
|
wantSS.Spec.Template.Spec.NodeSelector = proxyClassAllOpts.Spec.StatefulSet.Pod.NodeSelector
|
|
wantSS.Spec.Template.Spec.Affinity = proxyClassAllOpts.Spec.StatefulSet.Pod.Affinity
|
|
wantSS.Spec.Template.Spec.Tolerations = proxyClassAllOpts.Spec.StatefulSet.Pod.Tolerations
|
|
wantSS.Spec.Template.Spec.TopologySpreadConstraints = proxyClassAllOpts.Spec.StatefulSet.Pod.TopologySpreadConstraints
|
|
wantSS.Spec.Template.Spec.Containers[0].SecurityContext = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleContainer.SecurityContext
|
|
wantSS.Spec.Template.Spec.InitContainers[0].SecurityContext = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleInitContainer.SecurityContext
|
|
wantSS.Spec.Template.Spec.Containers[0].Resources = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleContainer.Resources
|
|
wantSS.Spec.Template.Spec.InitContainers[0].Resources = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleInitContainer.Resources
|
|
wantSS.Spec.Template.Spec.InitContainers[0].Env = append(wantSS.Spec.Template.Spec.InitContainers[0].Env, []corev1.EnvVar{{Name: "foo", Value: "bar"}, {Name: "TS_USERSPACE", Value: "true"}, {Name: "bar"}}...)
|
|
wantSS.Spec.Template.Spec.Containers[0].Env = append(wantSS.Spec.Template.Spec.Containers[0].Env, []corev1.EnvVar{{Name: "foo", Value: "bar"}, {Name: "TS_USERSPACE", Value: "true"}, {Name: "bar"}}...)
|
|
wantSS.Spec.Template.Spec.Containers[0].Image = "ghcr.io/my-repo/tailscale:v0.01testsomething"
|
|
wantSS.Spec.Template.Spec.Containers[0].ImagePullPolicy = "IfNotPresent"
|
|
wantSS.Spec.Template.Spec.InitContainers[0].Image = "ghcr.io/my-repo/tailscale:v0.01testsomething"
|
|
wantSS.Spec.Template.Spec.InitContainers[0].ImagePullPolicy = "IfNotPresent"
|
|
wantSS.Spec.Template.Spec.PriorityClassName = proxyClassAllOpts.Spec.StatefulSet.Pod.PriorityClassName
|
|
wantSS.Spec.Template.Spec.DNSPolicy = corev1.DNSClusterFirstWithHostNet
|
|
wantSS.Spec.Template.Spec.DNSConfig = proxyClassAllOpts.Spec.StatefulSet.Pod.DNSConfig
|
|
|
|
gotSS := applyProxyClassToStatefulSet(proxyClassAllOpts, nonUserspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with all fields set to a StatefulSet for non-userspace proxy (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 2. Test that a ProxyClass with custom labels and annotations for
|
|
// StatefulSet and Pod set gets correctly applied to a Statefulset built
|
|
// from non-userspace proxy template.
|
|
wantSS = nonUserspaceProxySS.DeepCopy()
|
|
updateMap(wantSS.ObjectMeta.Labels, proxyClassJustLabels.Spec.StatefulSet.Labels.Parse())
|
|
updateMap(wantSS.ObjectMeta.Annotations, proxyClassJustLabels.Spec.StatefulSet.Annotations)
|
|
wantSS.Spec.Template.Labels = proxyClassJustLabels.Spec.StatefulSet.Pod.Labels.Parse()
|
|
wantSS.Spec.Template.Annotations = proxyClassJustLabels.Spec.StatefulSet.Pod.Annotations
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassJustLabels, nonUserspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with custom labels and annotations to a StatefulSet for non-userspace proxy (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 3. Test that a ProxyClass with all fields set gets correctly applied
|
|
// to a Statefulset built from a userspace proxy template.
|
|
wantSS = userspaceProxySS.DeepCopy()
|
|
updateMap(wantSS.ObjectMeta.Labels, proxyClassAllOpts.Spec.StatefulSet.Labels.Parse())
|
|
updateMap(wantSS.ObjectMeta.Annotations, proxyClassAllOpts.Spec.StatefulSet.Annotations)
|
|
wantSS.Spec.Template.Labels = proxyClassAllOpts.Spec.StatefulSet.Pod.Labels.Parse()
|
|
wantSS.Spec.Template.Annotations = proxyClassAllOpts.Spec.StatefulSet.Pod.Annotations
|
|
wantSS.Spec.Template.Spec.SecurityContext = proxyClassAllOpts.Spec.StatefulSet.Pod.SecurityContext
|
|
wantSS.Spec.Template.Spec.ImagePullSecrets = proxyClassAllOpts.Spec.StatefulSet.Pod.ImagePullSecrets
|
|
wantSS.Spec.Template.Spec.NodeName = proxyClassAllOpts.Spec.StatefulSet.Pod.NodeName
|
|
wantSS.Spec.Template.Spec.NodeSelector = proxyClassAllOpts.Spec.StatefulSet.Pod.NodeSelector
|
|
wantSS.Spec.Template.Spec.Affinity = proxyClassAllOpts.Spec.StatefulSet.Pod.Affinity
|
|
wantSS.Spec.Template.Spec.Tolerations = proxyClassAllOpts.Spec.StatefulSet.Pod.Tolerations
|
|
wantSS.Spec.Template.Spec.TopologySpreadConstraints = proxyClassAllOpts.Spec.StatefulSet.Pod.TopologySpreadConstraints
|
|
wantSS.Spec.Template.Spec.Containers[0].SecurityContext = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleContainer.SecurityContext
|
|
wantSS.Spec.Template.Spec.Containers[0].Resources = proxyClassAllOpts.Spec.StatefulSet.Pod.TailscaleContainer.Resources
|
|
wantSS.Spec.Template.Spec.Containers[0].Env = append(wantSS.Spec.Template.Spec.Containers[0].Env, []corev1.EnvVar{{Name: "foo", Value: "bar"}, {Name: "TS_USERSPACE", Value: "true"}, {Name: "bar"}}...)
|
|
wantSS.Spec.Template.Spec.Containers[0].ImagePullPolicy = "IfNotPresent"
|
|
wantSS.Spec.Template.Spec.Containers[0].Image = "ghcr.io/my-repo/tailscale:v0.01testsomething"
|
|
wantSS.Spec.Template.Spec.PriorityClassName = proxyClassAllOpts.Spec.StatefulSet.Pod.PriorityClassName
|
|
wantSS.Spec.Template.Spec.DNSPolicy = corev1.DNSClusterFirstWithHostNet
|
|
wantSS.Spec.Template.Spec.DNSConfig = proxyClassAllOpts.Spec.StatefulSet.Pod.DNSConfig
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassAllOpts, userspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with all options to a StatefulSet for a userspace proxy (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 4. Test that a ProxyClass with custom labels and annotations gets correctly applied
|
|
// to a Statefulset built from a userspace proxy template.
|
|
wantSS = userspaceProxySS.DeepCopy()
|
|
updateMap(wantSS.ObjectMeta.Labels, proxyClassJustLabels.Spec.StatefulSet.Labels.Parse())
|
|
updateMap(wantSS.ObjectMeta.Annotations, proxyClassJustLabels.Spec.StatefulSet.Annotations)
|
|
wantSS.Spec.Template.Labels = proxyClassJustLabels.Spec.StatefulSet.Pod.Labels.Parse()
|
|
wantSS.Spec.Template.Annotations = proxyClassJustLabels.Spec.StatefulSet.Pod.Annotations
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassJustLabels, userspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with custom labels and annotations to a StatefulSet for a userspace proxy (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 5. Metrics enabled defaults to enabling both metrics and debug.
|
|
wantSS = nonUserspaceProxySS.DeepCopy()
|
|
wantSS.Spec.Template.Spec.Containers[0].Env = append(wantSS.Spec.Template.Spec.Containers[0].Env,
|
|
corev1.EnvVar{Name: "TS_DEBUG_ADDR_PORT", Value: "$(POD_IP):9001"},
|
|
corev1.EnvVar{Name: "TS_TAILSCALED_EXTRA_ARGS", Value: "--debug=$(TS_DEBUG_ADDR_PORT)"},
|
|
corev1.EnvVar{Name: "TS_LOCAL_ADDR_PORT", Value: "$(POD_IP):9002"},
|
|
corev1.EnvVar{Name: "TS_ENABLE_METRICS", Value: "true"},
|
|
)
|
|
wantSS.Spec.Template.Spec.Containers[0].Ports = []corev1.ContainerPort{
|
|
{Name: "debug", Protocol: "TCP", ContainerPort: 9001},
|
|
{Name: "metrics", Protocol: "TCP", ContainerPort: 9002},
|
|
}
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassWithMetricsDebug(true, nil), nonUserspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with metrics enabled to a StatefulSet (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 6. Enable _just_ metrics by explicitly disabling debug.
|
|
wantSS = nonUserspaceProxySS.DeepCopy()
|
|
wantSS.Spec.Template.Spec.Containers[0].Env = append(wantSS.Spec.Template.Spec.Containers[0].Env,
|
|
corev1.EnvVar{Name: "TS_LOCAL_ADDR_PORT", Value: "$(POD_IP):9002"},
|
|
corev1.EnvVar{Name: "TS_ENABLE_METRICS", Value: "true"},
|
|
)
|
|
wantSS.Spec.Template.Spec.Containers[0].Ports = []corev1.ContainerPort{{Name: "metrics", Protocol: "TCP", ContainerPort: 9002}}
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassWithMetricsDebug(true, new(false)), nonUserspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with metrics enabled to a StatefulSet (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 7. Enable _just_ debug without metrics.
|
|
wantSS = nonUserspaceProxySS.DeepCopy()
|
|
wantSS.Spec.Template.Spec.Containers[0].Env = append(wantSS.Spec.Template.Spec.Containers[0].Env,
|
|
corev1.EnvVar{Name: "TS_DEBUG_ADDR_PORT", Value: "$(POD_IP):9001"},
|
|
corev1.EnvVar{Name: "TS_TAILSCALED_EXTRA_ARGS", Value: "--debug=$(TS_DEBUG_ADDR_PORT)"},
|
|
)
|
|
wantSS.Spec.Template.Spec.Containers[0].Ports = []corev1.ContainerPort{{Name: "debug", Protocol: "TCP", ContainerPort: 9001}}
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassWithMetricsDebug(false, new(true)), nonUserspaceProxySS.DeepCopy(), new(tailscaleSTSConfig), zl.Sugar())
|
|
if diff := cmp.Diff(gotSS, wantSS); diff != "" {
|
|
t.Errorf("Unexpected result applying ProxyClass with metrics enabled to a StatefulSet (-got +want):\n%s", diff)
|
|
}
|
|
|
|
// 8. A Kubernetes API proxy with letsencrypt staging enabled
|
|
gotSS = applyProxyClassToStatefulSet(proxyClassAllOpts, nonUserspaceProxySS.DeepCopy(), &tailscaleSTSConfig{proxyType: string(tsapi.ProxyGroupTypeKubernetesAPIServer)}, zl.Sugar())
|
|
verifyEnvVar(t, gotSS, "TS_DEBUG_ACME_DIRECTORY_URL", letsEncryptStagingEndpoint)
|
|
}
|
|
|
|
func Test_applyHealthzProbes(t *testing.T) {
|
|
withProbes := func(liveness, readiness *tsapi.Probe) *tsapi.ProxyClass {
|
|
return &tsapi.ProxyClass{
|
|
Spec: tsapi.ProxyClassSpec{
|
|
StatefulSet: &tsapi.StatefulSet{
|
|
Pod: &tsapi.Pod{TailscaleContainer: &tsapi.Container{LivenessProbe: liveness, ReadinessProbe: readiness}},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
both := withProbes(&tsapi.Probe{}, &tsapi.Probe{})
|
|
for name, tt := range map[string]struct {
|
|
pc *tsapi.ProxyClass
|
|
env []corev1.EnvVar
|
|
wantLiveness bool
|
|
wantReadiness bool
|
|
wantPeriod int32
|
|
wantPort int
|
|
}{
|
|
"nil_proxyclass_defaults_off": {},
|
|
"unset_probes_default_off": {pc: withProbes(nil, nil)},
|
|
"liveness_set": {pc: withProbes(&tsapi.Probe{}, nil), wantLiveness: true, wantPort: defaultLocalAddrPort},
|
|
"readiness_set": {pc: withProbes(nil, &tsapi.Probe{}), wantReadiness: true, wantPeriod: 10, wantPort: defaultLocalAddrPort},
|
|
"both_set": {pc: both, wantLiveness: true, wantReadiness: true, wantPeriod: 10, wantPort: defaultLocalAddrPort},
|
|
"custom_readiness_period": {pc: withProbes(nil, &tsapi.Probe{PeriodSeconds: 30}), wantReadiness: true, wantPeriod: 30, wantPort: defaultLocalAddrPort},
|
|
"custom_local_addr_port": {pc: both, env: []corev1.EnvVar{{Name: "TS_LOCAL_ADDR_PORT", Value: "$(POD_IP):9010"}}, wantLiveness: true, wantReadiness: true, wantPeriod: 10, wantPort: 9010},
|
|
"loopback_local_addr_port": {pc: both, env: []corev1.EnvVar{{Name: "TS_LOCAL_ADDR_PORT", Value: "127.0.0.1:9002"}}},
|
|
"localhost_local_addr_port": {pc: both, env: []corev1.EnvVar{{Name: "TS_LOCAL_ADDR_PORT", Value: "localhost:9002"}}},
|
|
"health_check_disabled": {pc: both, env: []corev1.EnvVar{{Name: "TS_ENABLE_HEALTH_CHECK", Value: "false"}}},
|
|
"health_check_enabled": {pc: both, env: []corev1.EnvVar{{Name: "TS_ENABLE_HEALTH_CHECK", Value: "true"}}, wantLiveness: true, wantReadiness: true, wantPeriod: 10, wantPort: defaultLocalAddrPort},
|
|
"deprecated_healthcheck": {pc: both, env: []corev1.EnvVar{{Name: "TS_HEALTHCHECK_ADDR_PORT", Value: "[::]:8080"}}},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
var ss appsv1.StatefulSet
|
|
if err := yaml.Unmarshal(proxyYaml, &ss); err != nil {
|
|
t.Fatalf("unmarshaling proxy template: %v", err)
|
|
}
|
|
ss.Spec.Template.Spec.Containers[0].Env = append(ss.Spec.Template.Spec.Containers[0].Env, tt.env...)
|
|
applyHealthzProbes(tt.pc, &ss, false)
|
|
c := ss.Spec.Template.Spec.Containers[0]
|
|
|
|
if got := c.LivenessProbe != nil; got != tt.wantLiveness {
|
|
t.Errorf("liveness probe present = %v, want %v", got, tt.wantLiveness)
|
|
}
|
|
if got := c.ReadinessProbe != nil; got != tt.wantReadiness {
|
|
t.Errorf("readiness probe present = %v, want %v", got, tt.wantReadiness)
|
|
}
|
|
if c.LivenessProbe != nil {
|
|
if c.LivenessProbe.HTTPGet.Path != "/livez" {
|
|
t.Errorf("liveness path = %q, want /livez", c.LivenessProbe.HTTPGet.Path)
|
|
}
|
|
if got := c.LivenessProbe.HTTPGet.Port.IntValue(); got != tt.wantPort {
|
|
t.Errorf("liveness port = %d, want %d", got, tt.wantPort)
|
|
}
|
|
if c.LivenessProbe.TimeoutSeconds != 5 {
|
|
t.Errorf("liveness timeout = %d, want 5", c.LivenessProbe.TimeoutSeconds)
|
|
}
|
|
}
|
|
if c.ReadinessProbe != nil {
|
|
if c.ReadinessProbe.HTTPGet.Path != "/readyz" {
|
|
t.Errorf("readiness path = %q, want /readyz", c.ReadinessProbe.HTTPGet.Path)
|
|
}
|
|
if got := c.ReadinessProbe.HTTPGet.Port.IntValue(); got != tt.wantPort {
|
|
t.Errorf("readiness port = %d, want %d", got, tt.wantPort)
|
|
}
|
|
if c.ReadinessProbe.PeriodSeconds != tt.wantPeriod {
|
|
t.Errorf("readiness period = %d, want %d", c.ReadinessProbe.PeriodSeconds, tt.wantPeriod)
|
|
}
|
|
if c.ReadinessProbe.TimeoutSeconds != 1 {
|
|
t.Errorf("readiness timeout = %d, want 1", c.ReadinessProbe.TimeoutSeconds)
|
|
}
|
|
}
|
|
v, _ := lookupEnv(c.Env, "TS_ENABLE_HEALTH_CHECK")
|
|
if got, want := v == "true", tt.wantLiveness || tt.wantReadiness; got != want {
|
|
t.Errorf("TS_ENABLE_HEALTH_CHECK = %q, want enabled %v", v, want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func Test_mergeStatefulSetLabelsOrAnnots(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
current map[string]string
|
|
custom map[string]string
|
|
managed []string
|
|
want map[string]string
|
|
}{
|
|
{
|
|
name: "no-custom-labels-none-present",
|
|
current: map[string]string{kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
want: map[string]string{kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "no-custom-labels-some-present",
|
|
current: map[string]string{"foo": "bar", "something.io/foo": "bar", kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
want: map[string]string{kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "custom-labels-with-managed-only",
|
|
current: map[string]string{kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
custom: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
want: map[string]string{"foo": "bar", "something.io/foo": "bar", kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "custom-labels-stale-removed",
|
|
current: map[string]string{"foo": "bar", "bar": "baz", "app": "1234", kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
custom: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
want: map[string]string{"foo": "bar", "something.io/foo": "bar", "app": "1234", kubetypes.LabelManaged: "true", LabelParentName: "foo", LabelParentType: "svc", LabelParentNamespace: "foo"},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "no-current-labels-return-custom",
|
|
custom: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
want: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "no-current-no-custom-return-empty",
|
|
want: map[string]string{},
|
|
managed: tailscaleManagedLabels,
|
|
},
|
|
{
|
|
name: "no-custom-annots-none-present",
|
|
current: map[string]string{podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
want: map[string]string{podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
{
|
|
name: "no-custom-annots-some-present",
|
|
current: map[string]string{"foo": "bar", "something.io/foo": "bar", podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
want: map[string]string{podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
{
|
|
name: "custom-annots-with-managed-only",
|
|
current: map[string]string{podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
custom: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
want: map[string]string{"foo": "bar", "something.io/foo": "bar", podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
{
|
|
name: "custom-annots-stale-removed",
|
|
current: map[string]string{"foo": "bar", "something.io/foo": "bar", podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
custom: map[string]string{"something.io/foo": "bar"},
|
|
want: map[string]string{"something.io/foo": "bar", podAnnotationLastSetClusterIP: "1.2.3.4"},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
{
|
|
name: "no-current-annots-return-custom",
|
|
custom: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
want: map[string]string{"foo": "bar", "something.io/foo": "bar"},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
{
|
|
name: "no-current-annots-no-custom-return-empty",
|
|
want: map[string]string{},
|
|
managed: tailscaleManagedAnnotations,
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := mergeStatefulSetLabelsOrAnnots(tt.current, tt.custom, tt.managed); !reflect.DeepEqual(got, tt.want) {
|
|
t.Errorf("mergeStatefulSetLabels() = %v, want %v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestCleanupUnreportedDevices tests that Cleanup deletes devices that
|
|
// registered but never wrote their device ID to the state Secret, by looking
|
|
// them up by the machine key tailscaled stored there.
|
|
func TestCleanupUnreportedDevices(t *testing.T) {
|
|
mk := key.NewMachine()
|
|
mkText, err := mk.MarshalText()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mkPub := mk.Public().String()
|
|
labels := childResourceLabels("test", "default", "svc")
|
|
|
|
tests := []struct {
|
|
name string
|
|
data map[string][]byte
|
|
devices []tailscale.Device
|
|
wantDeleted []string
|
|
}{
|
|
{
|
|
name: "deletes_device_matching_machine_key",
|
|
data: map[string][]byte{"_machinekey": mkText},
|
|
devices: []tailscale.Device{
|
|
{NodeID: "nodeid-0", MachineKey: mkPub},
|
|
{NodeID: "nodeid-1", MachineKey: key.NewMachine().Public().String()},
|
|
},
|
|
wantDeleted: []string{"nodeid-0"},
|
|
},
|
|
{
|
|
name: "uses_reported_device_id",
|
|
data: map[string][]byte{
|
|
"_machinekey": mkText,
|
|
"device_id": []byte("nodeid-0"),
|
|
},
|
|
devices: []tailscale.Device{{NodeID: "nodeid-0", MachineKey: mkPub}},
|
|
wantDeleted: []string{"nodeid-0"},
|
|
},
|
|
{
|
|
name: "no_machine_key",
|
|
devices: []tailscale.Device{{NodeID: "nodeid-0", MachineKey: mkPub}},
|
|
},
|
|
{
|
|
name: "invalid_machine_key",
|
|
data: map[string][]byte{"_machinekey": []byte("not-a-key")},
|
|
devices: []tailscale.Device{{NodeID: "nodeid-0", MachineKey: mkPub}},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
fc := fake.NewClientBuilder().
|
|
WithScheme(tsapi.GlobalScheme).
|
|
WithObjects(&corev1.Secret{
|
|
ObjectMeta: metav1.ObjectMeta{
|
|
Name: "ts-test-abcde-0",
|
|
Namespace: "operator-ns",
|
|
Labels: labels,
|
|
},
|
|
Data: tt.data,
|
|
}).
|
|
Build()
|
|
ft := &fakeTSClient{devices: tt.devices}
|
|
r := &tailscaleSTSReconciler{
|
|
Client: fc,
|
|
clients: tsclient.NewProvider(ft),
|
|
operatorNamespace: "operator-ns",
|
|
}
|
|
|
|
done, err := r.Cleanup(t.Context(), operatorTailnet, zap.Must(zap.NewDevelopment()).Sugar(), labels, proxyTypeIngressService)
|
|
if err != nil {
|
|
t.Fatalf("Cleanup() error = %v", err)
|
|
}
|
|
if !done {
|
|
t.Errorf("Cleanup() done = %v, want true", done)
|
|
}
|
|
if diff := cmp.Diff(tt.wantDeleted, ft.deleted); diff != "" {
|
|
t.Errorf("Cleanup() deleted devices mismatch (-want +got):\n%s", diff)
|
|
}
|
|
expectMissing[corev1.Secret](t, fc, "operator-ns", "ts-test-abcde-0")
|
|
})
|
|
}
|
|
}
|
|
|
|
// updateMap updates map a with the values from map b.
|
|
func updateMap(a, b map[string]string) {
|
|
maps.Copy(a, b)
|
|
}
|