mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
cmd/k8s-operator,k8s-operator: move egress reconcilers into their own package
This commit moves the four egress reconcilers for ProxyGroups into k8s-operator/reconciler/egress, following the earlier Recorder, ProxyClass, DNSConfig and nameserver moves. Each reconciler now has a constructor and registers its own watches and field index. Three event handlers that logged through the unnamed operator logger now use the logger of their reconciler. The helpers that the egress code shared with package main move into k8s-operator/reconciler: the Service annotations, ValidateService, the cluster domain lookup, and the ProxyGroup labels, replica count, egress ConfigMap name and readiness gate. All callers in package main use the hoisted copies, and the egress code uses the existing shared label and finalizer helpers. The controller names, watches and labels do not change. Updates tailscale/corp#46764 Change-Id: Ide6cebdaeb262352239eb05bb01ed6dfa6fe206e Signed-off-by: David Bond <davidsbond93@gmail.com>
This commit is contained in:
30 files changed
+1620
-1268
No files matched your search
@@ -123,7 +123,7 @@ func (r *KubeAPIServerTSServiceReconciler) maybeProvision(ctx context.Context, s
|
||||
// Update the condition based on how many pods are advertising the service
|
||||
conditionStatus := metav1.ConditionFalse
|
||||
conditionReason := reasonKubeAPIServerProxyNoBackends
|
||||
conditionMessage := fmt.Sprintf("%d/%d proxy backends ready and advertising", podsAdvertising, pgReplicas(pg))
|
||||
conditionMessage := fmt.Sprintf("%d/%d proxy backends ready and advertising", podsAdvertising, reconciler.ProxyGroupReplicas(pg))
|
||||
|
||||
pg.Status.URL = ""
|
||||
if podsAdvertising > 0 {
|
||||
|
||||
@@ -347,7 +347,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
|
||||
k8s.io/apimachinery/third_party/forked/golang/reflect from k8s.io/apimachinery/pkg/conversion
|
||||
k8s.io/apiserver/pkg/authentication/user from k8s.io/apiserver/pkg/endpoints/request
|
||||
k8s.io/apiserver/pkg/endpoints/request from tailscale.com/k8s-operator/api-proxy
|
||||
k8s.io/apiserver/pkg/storage/names from tailscale.com/cmd/k8s-operator
|
||||
k8s.io/apiserver/pkg/storage/names from tailscale.com/cmd/k8s-operator+
|
||||
k8s.io/client-go/applyconfigurations/admissionregistration/v1 from k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1+
|
||||
k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1 from k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1
|
||||
k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1 from k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1
|
||||
@@ -770,6 +770,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
|
||||
tailscale.com/k8s-operator/apis/v1alpha1 from tailscale.com/cmd/k8s-operator+
|
||||
tailscale.com/k8s-operator/reconciler from tailscale.com/k8s-operator/reconciler/tailnet+
|
||||
tailscale.com/k8s-operator/reconciler/dnsrecords from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/k8s-operator/reconciler/egress from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/k8s-operator/reconciler/nameserver from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/k8s-operator/reconciler/peerrelay from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/k8s-operator/reconciler/proxyclass from tailscale.com/cmd/k8s-operator
|
||||
@@ -783,7 +784,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
|
||||
tailscale.com/k8s-operator/sessionrecording/tsrecorder from tailscale.com/k8s-operator/sessionrecording+
|
||||
tailscale.com/k8s-operator/sessionrecording/ws from tailscale.com/k8s-operator/sessionrecording
|
||||
tailscale.com/k8s-operator/tsclient from tailscale.com/cmd/k8s-operator+
|
||||
tailscale.com/kube/egressservices from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/kube/egressservices from tailscale.com/cmd/k8s-operator+
|
||||
tailscale.com/kube/ingressservices from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/kube/k8s-proxy/conf from tailscale.com/cmd/k8s-operator
|
||||
tailscale.com/kube/kubeapi from tailscale.com/ipn/store/kubestore+
|
||||
@@ -801,7 +802,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
|
||||
tailscale.com/net/connreject from tailscale.com/net/tstun+
|
||||
tailscale.com/net/dns from tailscale.com/ipn/ipnlocal+
|
||||
tailscale.com/net/dns/publicdns from tailscale.com/net/dns+
|
||||
tailscale.com/net/dns/resolvconffile from tailscale.com/cmd/k8s-operator+
|
||||
tailscale.com/net/dns/resolvconffile from tailscale.com/k8s-operator/reconciler+
|
||||
tailscale.com/net/dns/resolver from tailscale.com/net/dns+
|
||||
tailscale.com/net/dnscache from tailscale.com/control/controlclient+
|
||||
tailscale.com/net/dnsfallback from tailscale.com/control/controlclient+
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
"tailscale.com/ipn"
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/k8s-operator/tsclient"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
@@ -116,7 +117,7 @@ func (r *HAIngressReconciler) Reconcile(ctx context.Context, req reconcile.Reque
|
||||
hostname := hostnameForIngress(ing)
|
||||
logger = logger.With("hostname", hostname)
|
||||
|
||||
pgName := ing.Annotations[AnnotationProxyGroup]
|
||||
pgName := ing.Annotations[reconciler.AnnotationProxyGroup]
|
||||
pg := &tsapi.ProxyGroup{}
|
||||
|
||||
err = r.Get(ctx, client.ObjectKey{Name: pgName}, pg)
|
||||
@@ -176,7 +177,7 @@ func (r *HAIngressReconciler) maybeProvision(ctx context.Context, hostname strin
|
||||
}
|
||||
|
||||
// We only act on services that are annotated as using a proxy group.
|
||||
pgName := ing.Annotations[AnnotationProxyGroup]
|
||||
pgName := ing.Annotations[reconciler.AnnotationProxyGroup]
|
||||
if pgName == "" {
|
||||
return false, nil
|
||||
}
|
||||
@@ -333,7 +334,7 @@ func (r *HAIngressReconciler) maybeProvision(ctx context.Context, hostname strin
|
||||
|
||||
// 4. Ensure that the Tailscale Service exists and is up to date.
|
||||
tags := r.defaultTags
|
||||
if tstr, ok := ing.Annotations[AnnotationTags]; ok {
|
||||
if tstr, ok := ing.Annotations[reconciler.AnnotationTags]; ok {
|
||||
tags = strings.Split(tstr, ",")
|
||||
}
|
||||
|
||||
@@ -665,7 +666,7 @@ func (r *HAIngressReconciler) shouldExpose(ing *networkingv1.Ingress) bool {
|
||||
isTSIngress := ing != nil &&
|
||||
ing.Spec.IngressClassName != nil &&
|
||||
*ing.Spec.IngressClassName == r.ingressClassName
|
||||
pgAnnot := ing.Annotations[AnnotationProxyGroup]
|
||||
pgAnnot := ing.Annotations[reconciler.AnnotationProxyGroup]
|
||||
return isTSIngress && pgAnnot != ""
|
||||
}
|
||||
|
||||
@@ -679,7 +680,7 @@ func (r *HAIngressReconciler) validateIngress(ctx context.Context, ing *networki
|
||||
var errs []error
|
||||
|
||||
// Validate tags if present
|
||||
violations := tagViolations(ing)
|
||||
violations := reconciler.TagViolations(ing)
|
||||
if len(violations) > 0 {
|
||||
errs = append(errs, fmt.Errorf("Ingress contains invalid tags: %v", strings.Join(violations, ",")))
|
||||
}
|
||||
@@ -1022,8 +1023,8 @@ func cleanupAllCertResources(ctx context.Context, cl client.Client, tsNamespace,
|
||||
opts := []client.DeleteAllOfOption{
|
||||
client.InNamespace(tsNamespace),
|
||||
client.MatchingLabels{
|
||||
kubetypes.LabelManaged: "true",
|
||||
labelProxyGroup: pgName,
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelProxyGroup: pgName,
|
||||
},
|
||||
client.HasLabels{labelDomain},
|
||||
}
|
||||
@@ -1130,9 +1131,9 @@ func certSecret(pgName, namespace, domain string, parent client.Object) *corev1.
|
||||
|
||||
func certResourceLabels(pgName, domain string) map[string]string {
|
||||
return map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
labelProxyGroup: pgName,
|
||||
labelDomain: tsoperator.TruncateWithHash(domain),
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelProxyGroup: pgName,
|
||||
labelDomain: tsoperator.TruncateWithHash(domain),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1159,22 +1160,3 @@ func hasCerts(ctx context.Context, cl client.Client, ns string, svc tailcfg.Serv
|
||||
|
||||
return len(cert) > 0 && len(key) > 0, nil
|
||||
}
|
||||
|
||||
func tagViolations(obj client.Object) []string {
|
||||
var violations []string
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
tags, ok := obj.GetAnnotations()[AnnotationTags]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for tag := range strings.SplitSeq(tags, ",") {
|
||||
tag = strings.TrimSpace(tag)
|
||||
if err := tailcfg.CheckTag(tag); err != nil {
|
||||
violations = append(violations, fmt.Sprintf("invalid tag %q: %v", tag, err))
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"tailscale.com/ipn"
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/k8s-operator/tsclient"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
@@ -337,7 +338,7 @@ func TestValidateIngress(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationProxyGroup: "test-pg",
|
||||
reconciler.AnnotationProxyGroup: "test-pg",
|
||||
},
|
||||
},
|
||||
Spec: networkingv1.IngressSpec{
|
||||
@@ -398,7 +399,7 @@ func TestValidateIngress(t *testing.T) {
|
||||
Name: baseIngress.Name,
|
||||
Namespace: baseIngress.Namespace,
|
||||
Annotations: map[string]string{
|
||||
AnnotationTags: "tag:invalid!",
|
||||
reconciler.AnnotationTags: "tag:invalid!",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -471,7 +472,7 @@ func TestValidateIngress(t *testing.T) {
|
||||
Name: "existing-ingress",
|
||||
Namespace: "default",
|
||||
Annotations: map[string]string{
|
||||
AnnotationProxyGroup: "test-pg",
|
||||
reconciler.AnnotationProxyGroup: "test-pg",
|
||||
},
|
||||
},
|
||||
Spec: networkingv1.IngressSpec{
|
||||
@@ -1001,10 +1002,10 @@ func populateTLSSecret(t *testing.T, c client.Client, pgName, domain string) {
|
||||
Name: domain,
|
||||
Namespace: "operator-ns",
|
||||
Labels: map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
labelProxyGroup: pgName,
|
||||
labelDomain: domain,
|
||||
kubetypes.LabelSecretType: kubetypes.LabelSecretTypeCerts,
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelProxyGroup: pgName,
|
||||
labelDomain: domain,
|
||||
kubetypes.LabelSecretType: kubetypes.LabelSecretTypeCerts,
|
||||
},
|
||||
},
|
||||
Type: corev1.SecretTypeTLS,
|
||||
|
||||
@@ -229,7 +229,7 @@ func (a *IngressReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
|
||||
crl := childResourceLabels(ing.Name, ing.Namespace, "ingress")
|
||||
var tags []string
|
||||
if tstr, ok := ing.Annotations[AnnotationTags]; ok {
|
||||
if tstr, ok := ing.Annotations[reconciler.AnnotationTags]; ok {
|
||||
tags = strings.Split(tstr, ",")
|
||||
}
|
||||
hostname := hostnameForIngress(ing)
|
||||
@@ -296,7 +296,7 @@ func (a *IngressReconciler) shouldExpose(ing *networkingv1.Ingress) bool {
|
||||
return ing != nil &&
|
||||
ing.Spec.IngressClassName != nil &&
|
||||
*ing.Spec.IngressClassName == a.ingressClassName &&
|
||||
ing.Annotations[AnnotationProxyGroup] == ""
|
||||
ing.Annotations[reconciler.AnnotationProxyGroup] == ""
|
||||
}
|
||||
|
||||
// validateIngressClass attempts to validate that 'tailscale' IngressClass
|
||||
|
||||
+18
-324
@@ -11,7 +11,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -53,7 +52,9 @@ import (
|
||||
"tailscale.com/ipn/store/kubestore"
|
||||
apiproxy "tailscale.com/k8s-operator/api-proxy"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/dnsrecords"
|
||||
"tailscale.com/k8s-operator/reconciler/egress"
|
||||
"tailscale.com/k8s-operator/reconciler/nameserver"
|
||||
"tailscale.com/k8s-operator/reconciler/peerrelay"
|
||||
"tailscale.com/k8s-operator/reconciler/proxyclass"
|
||||
@@ -577,79 +578,23 @@ func runReconcilers(opts reconcilerOpts) {
|
||||
startlog.Fatalf("could not create nameserver reconciler: %v", err)
|
||||
}
|
||||
|
||||
egressSvcFilter := handler.EnqueueRequestsFromMapFunc(egressSvcsHandler)
|
||||
egressSvcFromEpsFilter := handler.EnqueueRequestsFromMapFunc(egressSvcFromEps)
|
||||
egressProxyGroupFilter := handler.EnqueueRequestsFromMapFunc(egressSvcsFromEgressProxyGroup(mgr.GetClient(), opts.log))
|
||||
err = builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named("egress-svcs-reconciler").
|
||||
Watches(&corev1.Service{}, egressSvcFilter).
|
||||
Watches(&tsapi.ProxyGroup{}, egressProxyGroupFilter).
|
||||
Watches(&discoveryv1.EndpointSlice{}, egressSvcFromEpsFilter).
|
||||
Complete(&egressSvcsReconciler{
|
||||
Client: mgr.GetClient(),
|
||||
tsNamespace: opts.tailscaleNamespace,
|
||||
recorder: eventRecorder,
|
||||
clock: tstime.DefaultClock{},
|
||||
logger: opts.log.Named("egress-svcs-reconciler"),
|
||||
})
|
||||
if err != nil {
|
||||
egressOptions := egress.ReconcilerOptions{
|
||||
Client: mgr.GetClient(),
|
||||
Recorder: eventRecorder,
|
||||
TailscaleNamespace: opts.tailscaleNamespace,
|
||||
Logger: opts.log,
|
||||
Clock: tstime.DefaultClock{},
|
||||
}
|
||||
if err = egress.NewReconciler(egressOptions).Register(mgr); err != nil {
|
||||
startlog.Fatalf("could not create egress Services reconciler: %v", err)
|
||||
}
|
||||
if err := mgr.GetFieldIndexer().IndexField(context.Background(), new(corev1.Service), indexEgressProxyGroup, indexEgressServices); err != nil {
|
||||
startlog.Fatalf("failed setting up indexer for egress Services: %v", err)
|
||||
}
|
||||
|
||||
err = builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named("egress-svcs-readiness-reconciler").
|
||||
Watches(&corev1.Service{}, egressSvcFilter).
|
||||
Watches(&discoveryv1.EndpointSlice{}, egressSvcFromEpsFilter).
|
||||
Complete(&egressSvcsReadinessReconciler{
|
||||
Client: mgr.GetClient(),
|
||||
tsNamespace: opts.tailscaleNamespace,
|
||||
clock: tstime.DefaultClock{},
|
||||
logger: opts.log.Named("egress-svcs-readiness-reconciler"),
|
||||
})
|
||||
if err != nil {
|
||||
if err = egress.NewReadinessReconciler(egressOptions).Register(mgr); err != nil {
|
||||
startlog.Fatalf("could not create egress Services readiness reconciler: %v", err)
|
||||
}
|
||||
|
||||
epsFilter := handler.EnqueueRequestsFromMapFunc(egressEpsHandler)
|
||||
podsFilter := handler.EnqueueRequestsFromMapFunc(egressEpsFromPGPods(mgr.GetClient(), opts.tailscaleNamespace))
|
||||
secretsFilter := handler.EnqueueRequestsFromMapFunc(egressEpsFromPGStateSecrets(mgr.GetClient(), opts.tailscaleNamespace))
|
||||
epsFromExtNSvcFilter := handler.EnqueueRequestsFromMapFunc(epsFromExternalNameService(mgr.GetClient(), opts.log, opts.tailscaleNamespace))
|
||||
|
||||
err = builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named("egress-eps-reconciler").
|
||||
Watches(&discoveryv1.EndpointSlice{}, epsFilter).
|
||||
Watches(&corev1.Pod{}, podsFilter).
|
||||
Watches(&corev1.Secret{}, secretsFilter).
|
||||
Watches(&corev1.Service{}, epsFromExtNSvcFilter).
|
||||
Complete(&egressEpsReconciler{
|
||||
Client: mgr.GetClient(),
|
||||
tsNamespace: opts.tailscaleNamespace,
|
||||
logger: opts.log.Named("egress-eps-reconciler"),
|
||||
})
|
||||
if err != nil {
|
||||
if err = egress.NewEndpointSliceReconciler(egressOptions).Register(mgr); err != nil {
|
||||
startlog.Fatalf("could not create egress EndpointSlices reconciler: %v", err)
|
||||
}
|
||||
|
||||
podsForEps := handler.EnqueueRequestsFromMapFunc(podsFromEgressEps(mgr.GetClient(), opts.log, opts.tailscaleNamespace))
|
||||
podsER := handler.EnqueueRequestsFromMapFunc(egressPodsHandler)
|
||||
err = builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named("egress-pods-readiness-reconciler").
|
||||
Watches(&discoveryv1.EndpointSlice{}, podsForEps).
|
||||
Watches(&corev1.Pod{}, podsER).
|
||||
Complete(&egressPodsReconciler{
|
||||
Client: mgr.GetClient(),
|
||||
tsNamespace: opts.tailscaleNamespace,
|
||||
clock: tstime.DefaultClock{},
|
||||
logger: opts.log.Named("egress-pods-readiness-reconciler"),
|
||||
})
|
||||
if err != nil {
|
||||
if err = egress.NewPodReconciler(egressOptions).Register(mgr); err != nil {
|
||||
startlog.Fatalf("could not create egress Pods readiness reconciler: %v", err)
|
||||
}
|
||||
|
||||
@@ -1263,7 +1208,7 @@ func serviceHandlerForIngress(cl client.Client, logger *zap.SugaredLogger, ingre
|
||||
}
|
||||
|
||||
func serviceHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if _, ok := o.GetAnnotations()[AnnotationProxyGroup]; ok {
|
||||
if _, ok := o.GetAnnotations()[reconciler.AnnotationProxyGroup]; ok {
|
||||
// Do not reconcile Services for ProxyGroup.
|
||||
return nil
|
||||
}
|
||||
@@ -1286,101 +1231,6 @@ func serviceHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
}
|
||||
}
|
||||
|
||||
// isMagicDNSName reports whether name is a full tailnet node FQDN (with or
|
||||
// without final dot).
|
||||
func isMagicDNSName(name string) bool {
|
||||
validMagicDNSName := regexp.MustCompile(`^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.ts\.net\.?$`)
|
||||
return validMagicDNSName.MatchString(name)
|
||||
}
|
||||
|
||||
// egressSvcsHandler returns accepts a Kubernetes object and returns a reconcile
|
||||
// request for it , if the object is a Tailscale egress Service meant to be
|
||||
// exposed on a ProxyGroup.
|
||||
func egressSvcsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if !isEgressSvcForProxyGroup(o) {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsHandler returns accepts an EndpointSlice and, if the EndpointSlice
|
||||
// is for an egress service, returns a reconcile request for it.
|
||||
func egressEpsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[labelSvcType]; typ != typeEgress {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func egressPodsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[LabelParentType]; typ != proxyTypeProxyGroup {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsFromEgressPods returns a Pod event handler that checks if Pod is a replica for a ProxyGroup and if it is,
|
||||
// returns reconciler requests for all egress EndpointSlices for that ProxyGroup.
|
||||
func egressEpsFromPGPods(cl client.Client, ns string) handler.MapFunc {
|
||||
return func(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if v, ok := o.GetLabels()[kubetypes.LabelManaged]; !ok || v != "true" {
|
||||
return nil
|
||||
}
|
||||
// TODO(irbekrm): for now this is good enough as all ProxyGroups are egress. Add a type check once we
|
||||
// have ingress ProxyGroups.
|
||||
if typ := o.GetLabels()[LabelParentType]; typ != "proxygroup" {
|
||||
return nil
|
||||
}
|
||||
pg, ok := o.GetLabels()[LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return reconcileRequestsForPG(pg, cl, ns)
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsFromPGStateSecrets returns a Secret event handler that checks if Secret is a state Secret for a ProxyGroup and if it is,
|
||||
// returns reconciler requests for all egress EndpointSlices for that ProxyGroup.
|
||||
func egressEpsFromPGStateSecrets(cl client.Client, ns string) handler.MapFunc {
|
||||
return func(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if v, ok := o.GetLabels()[kubetypes.LabelManaged]; !ok || v != "true" {
|
||||
return nil
|
||||
}
|
||||
if parentType := o.GetLabels()[LabelParentType]; parentType != "proxygroup" {
|
||||
return nil
|
||||
}
|
||||
if secretType := o.GetLabels()[kubetypes.LabelSecretType]; secretType != kubetypes.LabelSecretTypeState {
|
||||
return nil
|
||||
}
|
||||
pg, ok := o.GetLabels()[LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return reconcileRequestsForPG(pg, cl, ns)
|
||||
}
|
||||
}
|
||||
|
||||
func ingressSvcFromEps(cl client.Client, logger *zap.SugaredLogger) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
svcName := o.GetLabels()[discoveryv1.LabelServiceName]
|
||||
@@ -1397,7 +1247,7 @@ func ingressSvcFromEps(cl client.Client, logger *zap.SugaredLogger) handler.MapF
|
||||
return nil
|
||||
}
|
||||
|
||||
pgName := svc.Annotations[AnnotationProxyGroup]
|
||||
pgName := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
if pgName == "" {
|
||||
return nil
|
||||
}
|
||||
@@ -1413,58 +1263,12 @@ func ingressSvcFromEps(cl client.Client, logger *zap.SugaredLogger) handler.MapF
|
||||
}
|
||||
}
|
||||
|
||||
// egressSvcFromEps is an event handler for EndpointSlices. If an EndpointSlice is for an egress ExternalName Service
|
||||
// meant to be exposed on a ProxyGroup, returns a reconcile request for the Service.
|
||||
func egressSvcFromEps(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[labelSvcType]; typ != typeEgress {
|
||||
return nil
|
||||
}
|
||||
if v, ok := o.GetLabels()[kubetypes.LabelManaged]; !ok || v != "true" {
|
||||
return nil
|
||||
}
|
||||
svcName, ok := o.GetLabels()[LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
svcNs, ok := o.GetLabels()[LabelParentNamespace]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: svcNs,
|
||||
Name: svcName,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func reconcileRequestsForPG(pg string, cl client.Client, ns string) []reconcile.Request {
|
||||
epsList := discoveryv1.EndpointSliceList{}
|
||||
if err := cl.List(context.Background(), &epsList,
|
||||
client.InNamespace(ns),
|
||||
client.MatchingLabels(map[string]string{labelProxyGroup: pg})); err != nil {
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, ep := range epsList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: ep.Namespace,
|
||||
Name: ep.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
|
||||
func isTLSSecret(secret *corev1.Secret) bool {
|
||||
return secret.Type == corev1.SecretTypeTLS &&
|
||||
secret.ObjectMeta.Labels[kubetypes.LabelManaged] == "true" &&
|
||||
secret.ObjectMeta.Labels[kubetypes.LabelSecretType] == kubetypes.LabelSecretTypeCerts &&
|
||||
secret.ObjectMeta.Labels[labelDomain] != "" &&
|
||||
secret.ObjectMeta.Labels[labelProxyGroup] != ""
|
||||
secret.ObjectMeta.Labels[reconciler.LabelProxyGroup] != ""
|
||||
}
|
||||
|
||||
func isPGStateSecret(secret *corev1.Secret) bool {
|
||||
@@ -1593,37 +1397,6 @@ func kubeAPIServerPGsFromSecret(cl client.Client, logger *zap.SugaredLogger) han
|
||||
}
|
||||
}
|
||||
|
||||
// egressSvcsFromEgressProxyGroup is an event handler for egress ProxyGroups. It returns reconcile requests for all
|
||||
// user-created ExternalName Services that should be exposed on this ProxyGroup.
|
||||
func egressSvcsFromEgressProxyGroup(cl client.Client, logger *zap.SugaredLogger) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
pg, ok := o.(*tsapi.ProxyGroup)
|
||||
if !ok {
|
||||
logger.Warn("ProxyGroup handler triggered for an object that is not a ProxyGroup")
|
||||
return nil
|
||||
}
|
||||
|
||||
if pg.Spec.Type != tsapi.ProxyGroupTypeEgress {
|
||||
return nil
|
||||
}
|
||||
svcList := &corev1.ServiceList{}
|
||||
if err := cl.List(ctx, svcList, client.MatchingFields{indexEgressProxyGroup: pg.Name}); err != nil {
|
||||
logger.Infof("error listing Services: %v, skipping a reconcile for event on ProxyGroup %s", err, pg.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, svc := range svcList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: svc.Namespace,
|
||||
Name: svc.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
// ingressesFromIngressProxyGroup is an event handler for ingress ProxyGroups. It returns reconcile requests for all
|
||||
// user-created Ingresses that should be exposed on this ProxyGroup.
|
||||
func ingressesFromIngressProxyGroup(cl client.Client, logger *zap.SugaredLogger) handler.MapFunc {
|
||||
@@ -1686,76 +1459,6 @@ func servicesFromIngressProxyGroup(cl client.Client, logger *zap.SugaredLogger)
|
||||
}
|
||||
}
|
||||
|
||||
// epsFromExternalNameService is an event handler for ExternalName Services that define a Tailscale egress service that
|
||||
// should be exposed on a ProxyGroup. It returns reconcile requests for EndpointSlices created for this Service.
|
||||
func epsFromExternalNameService(cl client.Client, logger *zap.SugaredLogger, ns string) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
svc, ok := o.(*corev1.Service)
|
||||
if !ok {
|
||||
logger.Warn("Service handler triggered for an object that is not a Service")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isEgressSvcForProxyGroup(svc) {
|
||||
return nil
|
||||
}
|
||||
epsList := &discoveryv1.EndpointSliceList{}
|
||||
if err := cl.List(ctx, epsList, client.InNamespace(ns),
|
||||
client.MatchingLabels(egressSvcChildResourceLabels(svc))); err != nil {
|
||||
logger.Infof("error listing EndpointSlices: %v, skipping a reconcile for event on Service %s", err, svc.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, eps := range epsList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: eps.Namespace,
|
||||
Name: eps.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
func podsFromEgressEps(cl client.Client, logger *zap.SugaredLogger, ns string) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
eps, ok := o.(*discoveryv1.EndpointSlice)
|
||||
if !ok {
|
||||
logger.Warn("EndpointSlice handler triggered for an object that is not a EndpointSlice")
|
||||
return nil
|
||||
}
|
||||
|
||||
if eps.Labels[labelProxyGroup] == "" {
|
||||
return nil
|
||||
}
|
||||
if eps.Labels[labelSvcType] != "egress" {
|
||||
return nil
|
||||
}
|
||||
podLabels := map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
LabelParentType: "proxygroup",
|
||||
LabelParentName: eps.Labels[labelProxyGroup],
|
||||
}
|
||||
podList := &corev1.PodList{}
|
||||
if err := cl.List(ctx, podList, client.InNamespace(ns),
|
||||
client.MatchingLabels(podLabels)); err != nil {
|
||||
logger.Infof("error listing EndpointSlices: %v, skipping a reconcile for event on EndpointSlice %s", err, eps.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, pod := range podList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: pod.Namespace,
|
||||
Name: pod.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
// crdTransformer gets called before a CRD is stored to c/r cache, it removes the CRD spec to reduce memory consumption.
|
||||
func crdTransformer(log *zap.SugaredLogger) toolscache.TransformFunc {
|
||||
return func(o any) (any, error) {
|
||||
@@ -1770,22 +1473,13 @@ func crdTransformer(log *zap.SugaredLogger) toolscache.TransformFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// indexEgressServices adds a local index to cached Tailscale egress Services meant to be exposed on a ProxyGroup. The
|
||||
// index is used a list filter.
|
||||
func indexEgressServices(o client.Object) []string {
|
||||
if !isEgressSvcForProxyGroup(o) {
|
||||
return nil
|
||||
}
|
||||
return []string{o.GetAnnotations()[AnnotationProxyGroup]}
|
||||
}
|
||||
|
||||
// indexPGIngresses is used to select ProxyGroup-backed Services which are
|
||||
// locally indexed in the cache for efficient listing without requiring labels.
|
||||
func indexPGIngresses(o client.Object) []string {
|
||||
if !hasProxyGroupAnnotation(o) {
|
||||
return nil
|
||||
}
|
||||
return []string{o.GetAnnotations()[AnnotationProxyGroup]}
|
||||
return []string{o.GetAnnotations()[reconciler.AnnotationProxyGroup]}
|
||||
}
|
||||
|
||||
// serviceHandlerForIngressPG returns a handler for Service events that ensures that if the Service
|
||||
@@ -1825,7 +1519,7 @@ func serviceHandlerForIngressPG(cl client.Client, logger *zap.SugaredLogger, ing
|
||||
}
|
||||
|
||||
func hasProxyGroupAnnotation(obj client.Object) bool {
|
||||
return obj.GetAnnotations()[AnnotationProxyGroup] != ""
|
||||
return obj.GetAnnotations()[reconciler.AnnotationProxyGroup] != ""
|
||||
}
|
||||
|
||||
func hasProxyClassAnnotation(obj client.Object) bool {
|
||||
|
||||
@@ -32,13 +32,12 @@ import (
|
||||
"tailscale.com/ipn"
|
||||
"tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/k8s-operator/tsclient"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/net/dns/resolvconffile"
|
||||
"tailscale.com/tstest"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/dnsname"
|
||||
"tailscale.com/util/mak"
|
||||
)
|
||||
|
||||
@@ -72,7 +71,7 @@ func TestLoadBalancerClass(t *testing.T) {
|
||||
// on it being set.
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "invalid.example.com",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "invalid.example.com",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -95,7 +94,7 @@ func TestLoadBalancerClass(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "invalid.example.com",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "invalid.example.com",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -251,7 +250,7 @@ func TestTailnetTargetFQDNAnnotation(t *testing.T) {
|
||||
// on it being set.
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -286,7 +285,7 @@ func TestTailnetTargetFQDNAnnotation(t *testing.T) {
|
||||
Finalizers: []string{"tailscale.com/finalizer"},
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -308,7 +307,7 @@ func TestTailnetTargetFQDNAnnotation(t *testing.T) {
|
||||
tailnetTargetFQDN = "bar.baz.ts.net"
|
||||
mustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
s.ObjectMeta.Annotations = map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -364,7 +363,7 @@ func TestTailnetTargetFQDNAnnotationLongName(t *testing.T) {
|
||||
Namespace: ns,
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -395,7 +394,7 @@ func TestTailnetTargetFQDNAnnotationLongName(t *testing.T) {
|
||||
Finalizers: []string{"tailscale.com/finalizer"},
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -439,7 +438,7 @@ func TestTailnetTargetIPAnnotation(t *testing.T) {
|
||||
// on it being set.
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -474,7 +473,7 @@ func TestTailnetTargetIPAnnotation(t *testing.T) {
|
||||
Finalizers: []string{"tailscale.com/finalizer"},
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -496,7 +495,7 @@ func TestTailnetTargetIPAnnotation(t *testing.T) {
|
||||
tailnetTargetIP = "100.77.77.77"
|
||||
mustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
s.ObjectMeta.Annotations = map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -545,7 +544,7 @@ func TestTailnetTargetIPAnnotation_IPCouldNotBeParsed(t *testing.T) {
|
||||
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -565,7 +564,7 @@ func TestTailnetTargetIPAnnotation_IPCouldNotBeParsed(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -613,7 +612,7 @@ func TestTailnetTargetIPAnnotation_InvalidIP(t *testing.T) {
|
||||
|
||||
UID: "1234-UID",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -633,7 +632,7 @@ func TestTailnetTargetIPAnnotation_InvalidIP(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
reconciler.AnnotationTailnetTargetIP: tailnetTargetIP,
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -1582,37 +1581,6 @@ func TestProxyFirewallMode(t *testing.T) {
|
||||
expectEqual(t, fc, expectedSTS(t, fc, o), removeResourceReqs)
|
||||
}
|
||||
|
||||
func Test_isMagicDNSName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "foo-tail4567-ts-net",
|
||||
in: "foo.tail4567.ts.net",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "foo-tail4567-ts-net-trailing-dot",
|
||||
in: "foo.tail4567.ts.net.",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "foo-tail4567",
|
||||
in: "foo.tail4567",
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isMagicDNSName(tt.in); got != tt.want {
|
||||
t.Errorf("isMagicDNSName(%q) = %v, want %v", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_HeadlessService(t *testing.T) {
|
||||
fc := fake.NewFakeClient()
|
||||
zl := zap.Must(zap.NewDevelopment())
|
||||
@@ -1837,72 +1805,6 @@ func Test_serviceHandlerForIngress_multipleIngressClasses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_clusterDomainFromResolverConf(t *testing.T) {
|
||||
zl := zap.Must(zap.NewDevelopment())
|
||||
tests := []struct {
|
||||
name string
|
||||
conf *resolvconffile.Config
|
||||
namespace string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "success-custom-domain",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "foo.svc.department.org.io"), toFQDN(t, "svc.department.org.io"), toFQDN(t, "department.org.io")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "department.org.io",
|
||||
},
|
||||
{
|
||||
name: "success-default-domain",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "foo.svc.cluster.local."), toFQDN(t, "svc.cluster.local."), toFQDN(t, "cluster.local.")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "only-two-search-domains",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "svc.department.org.io"), toFQDN(t, "department.org.io")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "first-search-domain-mismatch",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "foo.bar.department.org.io"), toFQDN(t, "svc.department.org.io"), toFQDN(t, "some.other.fqdn")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "second-search-domain-mismatch",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "foo.svc.department.org.io"), toFQDN(t, "foo.department.org.io"), toFQDN(t, "some.other.fqdn")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "third-search-domain-mismatch",
|
||||
conf: &resolvconffile.Config{
|
||||
SearchDomains: []dnsname.FQDN{toFQDN(t, "foo.svc.department.org.io"), toFQDN(t, "svc.department.org.io"), toFQDN(t, "some.other.fqdn")},
|
||||
},
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := clusterDomainFromResolverConf(tt.conf, tt.namespace, zl.Sugar()); got != tt.want {
|
||||
t.Errorf("clusterDomainFromResolverConf() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_authKeyRemoval(t *testing.T) {
|
||||
fc := fake.NewFakeClient()
|
||||
ft := &fakeTSClient{}
|
||||
@@ -2198,14 +2100,14 @@ func Test_servicesFromIngressProxyGroup(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "svc-1",
|
||||
Namespace: "ns-1",
|
||||
Annotations: map[string]string{AnnotationProxyGroup: "ingress-pg"},
|
||||
Annotations: map[string]string{reconciler.AnnotationProxyGroup: "ingress-pg"},
|
||||
},
|
||||
}
|
||||
svcForOtherPG := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "svc-2",
|
||||
Namespace: "ns-2",
|
||||
Annotations: map[string]string{AnnotationProxyGroup: "other-pg"},
|
||||
Annotations: map[string]string{reconciler.AnnotationProxyGroup: "other-pg"},
|
||||
},
|
||||
}
|
||||
fc := fake.NewClientBuilder().
|
||||
@@ -2231,15 +2133,6 @@ func Test_servicesFromIngressProxyGroup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func toFQDN(t *testing.T, s string) dnsname.FQDN {
|
||||
t.Helper()
|
||||
fqdn, err := dnsname.ToFQDN(s)
|
||||
if err != nil {
|
||||
t.Fatalf("error coverting %q to dnsname.FQDN: %v", s, err)
|
||||
}
|
||||
return fqdn
|
||||
}
|
||||
|
||||
func proxyCreatedCondition(clock tstime.Clock) []metav1.Condition {
|
||||
return []metav1.Condition{{
|
||||
Type: string(tsapi.ProxyReady),
|
||||
|
||||
@@ -479,7 +479,7 @@ func (r *ProxyGroupReconciler) maybeProvision(ctx context.Context, tsClient tscl
|
||||
mo := &metricsOpts{
|
||||
tsNamespace: r.tsNamespace,
|
||||
proxyStsName: pg.Name,
|
||||
proxyLabels: pgLabels(pg.Name, nil),
|
||||
proxyLabels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
proxyType: "proxygroup",
|
||||
}
|
||||
if err := reconcileMetricsResources(ctx, logger, mo, proxyClass, r.Client); err != nil {
|
||||
@@ -515,7 +515,7 @@ func (r *ProxyGroupReconciler) maybeUpdateStatus(ctx context.Context, logger *za
|
||||
|
||||
pg.Status.Devices = devices
|
||||
|
||||
desiredReplicas := int(pgReplicas(pg))
|
||||
desiredReplicas := int(reconciler.ProxyGroupReplicas(pg))
|
||||
|
||||
// Set ProxyGroupAvailable condition.
|
||||
status := metav1.ConditionFalse
|
||||
@@ -590,10 +590,10 @@ func (r *ProxyGroupReconciler) maybeReplaceStatefulSet(ctx context.Context, ss *
|
||||
func (r *ProxyGroupReconciler) ensureNodePortServiceCreated(ctx context.Context, pg *tsapi.ProxyGroup, pc *tsapi.ProxyClass) (map[string]uint16, *uint16, error) {
|
||||
return staticendpoints.EnsureNodePortServices(ctx, r.Client, staticendpoints.Config{
|
||||
Namespace: r.tsNamespace,
|
||||
ParentType: proxyTypeProxyGroup,
|
||||
ParentType: reconciler.ParentTypeProxyGroup,
|
||||
ParentName: pg.Name,
|
||||
ProxyClassName: pc.Name,
|
||||
Replicas: pgReplicas(pg),
|
||||
Replicas: reconciler.ProxyGroupReplicas(pg),
|
||||
PortRanges: pc.Spec.StaticEndpoints.NodePort.Ports,
|
||||
MakeService: func(_ int32, name string) *corev1.Service {
|
||||
return pgNodePortService(pg, name, r.tsNamespace)
|
||||
@@ -611,7 +611,7 @@ func (r *ProxyGroupReconciler) cleanupDanglingResources(ctx context.Context, tsC
|
||||
}
|
||||
|
||||
for _, m := range metadata {
|
||||
if m.ordinal+1 <= pgReplicas(pg) {
|
||||
if m.ordinal+1 <= reconciler.ProxyGroupReplicas(pg) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -650,7 +650,7 @@ func (r *ProxyGroupReconciler) cleanupDanglingResources(ctx context.Context, tsC
|
||||
if pc != nil && pc.Spec.StaticEndpoints == nil {
|
||||
labels := map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
LabelParentType: proxyTypeProxyGroup,
|
||||
LabelParentType: reconciler.ParentTypeProxyGroup,
|
||||
LabelParentName: pg.Name,
|
||||
}
|
||||
if err := r.DeleteAllOf(ctx, &corev1.Service{}, client.InNamespace(r.tsNamespace), client.MatchingLabels(labels)); err != nil {
|
||||
@@ -684,7 +684,7 @@ func (r *ProxyGroupReconciler) maybeCleanup(ctx context.Context, tsClient tsclie
|
||||
}
|
||||
|
||||
mo := &metricsOpts{
|
||||
proxyLabels: pgLabels(pg.Name, nil),
|
||||
proxyLabels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
tsNamespace: r.tsNamespace,
|
||||
proxyType: "proxygroup",
|
||||
}
|
||||
@@ -711,8 +711,8 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(
|
||||
svcToNodePorts map[string]uint16,
|
||||
) (endpoints map[string][]netip.AddrPort, err error) {
|
||||
logger := r.logger(pg.Name)
|
||||
endpoints = make(map[string][]netip.AddrPort, pgReplicas(pg)) // keyed by Service name.
|
||||
for i := range pgReplicas(pg) {
|
||||
endpoints = make(map[string][]netip.AddrPort, reconciler.ProxyGroupReplicas(pg)) // keyed by Service name.
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
logger = logger.With("Pod", fmt.Sprintf("%s-%d", pg.Name, i))
|
||||
cfgSecret := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
@@ -793,7 +793,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(
|
||||
// as containerboot does for ingress-pg-reconciler.
|
||||
IssueCerts: opt.NewBool(i == 0),
|
||||
},
|
||||
LocalPort: new(uint16(defaultLocalAddrPort)),
|
||||
LocalPort: new(uint16(tailscaled.HealthCheckPort)),
|
||||
HealthCheckEnabled: opt.NewBool(true),
|
||||
},
|
||||
}
|
||||
@@ -958,7 +958,7 @@ func (r *ProxyGroupReconciler) ensureStateAddedForProxyGroup(pg *tsapi.ProxyGrou
|
||||
gaugeIngressProxyGroupResources.Set(int64(r.ingressProxyGroups.Len()))
|
||||
gaugeAPIServerProxyGroupResources.Set(int64(r.apiServerProxyGroups.Len()))
|
||||
|
||||
r.reissuer.EnsureState(pg.Name, int(pgReplicas(pg)))
|
||||
r.reissuer.EnsureState(pg.Name, int(reconciler.ProxyGroupReplicas(pg)))
|
||||
}
|
||||
|
||||
// ensureStateRemovedForProxyGroup ensures the gauge metric for the ProxyGroup resource type is updated when the
|
||||
|
||||
@@ -7,7 +7,6 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -21,6 +20,8 @@ import (
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/ingressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
@@ -40,7 +41,7 @@ func pgNodePortService(pg *tsapi.ProxyGroup, name string, namespace string) *cor
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -85,15 +86,15 @@ func pgStatefulSet(pg *tsapi.ProxyGroup, namespace, image, tsFirewallMode string
|
||||
ss.ObjectMeta = metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
}
|
||||
ss.Spec.Replicas = new(pgReplicas(pg))
|
||||
ss.Spec.Replicas = new(reconciler.ProxyGroupReplicas(pg))
|
||||
// Start Pods in parallel so one that isn't ready yet, e.g. while its
|
||||
// device awaits approval, doesn't hold back the others.
|
||||
ss.Spec.PodManagementPolicy = appsv1.ParallelPodManagement
|
||||
ss.Spec.Selector = &metav1.LabelSelector{
|
||||
MatchLabels: pgLabels(pg.Name, nil),
|
||||
MatchLabels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
}
|
||||
|
||||
// Template config.
|
||||
@@ -101,18 +102,18 @@ func pgStatefulSet(pg *tsapi.ProxyGroup, namespace, image, tsFirewallMode string
|
||||
tmpl.ObjectMeta = metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
DeletionGracePeriodSeconds: new(int64(10)),
|
||||
}
|
||||
tmpl.Spec.ServiceAccountName = pg.Name
|
||||
tmpl.Spec.InitContainers[0].Image = image
|
||||
proxyConfigVolName := pgEgressCMName(pg.Name)
|
||||
proxyConfigVolName := reconciler.ProxyGroupEgressConfigMapName(pg.Name)
|
||||
if pg.Spec.Type == tsapi.ProxyGroupTypeIngress {
|
||||
proxyConfigVolName = pgIngressCMName(pg.Name)
|
||||
}
|
||||
tmpl.Spec.Volumes = func() []corev1.Volume {
|
||||
var volumes []corev1.Volume
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
volumes = append(volumes, corev1.Volume{
|
||||
Name: fmt.Sprintf("tailscaledconfig-%d", i),
|
||||
VolumeSource: corev1.VolumeSource{
|
||||
@@ -146,7 +147,7 @@ func pgStatefulSet(pg *tsapi.ProxyGroup, namespace, image, tsFirewallMode string
|
||||
// TODO(tomhjp): Read config directly from the secret instead. The
|
||||
// mounts change on scaling up/down which causes unnecessary restarts
|
||||
// for pods that haven't meaningfully changed.
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
mounts = append(mounts, corev1.VolumeMount{
|
||||
Name: fmt.Sprintf("tailscaledconfig-%d", i),
|
||||
ReadOnly: true,
|
||||
@@ -296,7 +297,7 @@ func pgStatefulSet(pg *tsapi.ProxyGroup, namespace, image, tsFirewallMode string
|
||||
PreStop: &corev1.LifecycleHandler{
|
||||
HTTPGet: &corev1.HTTPGetAction{
|
||||
Path: kubetypes.EgessServicesPreshutdownEP,
|
||||
Port: intstr.FromInt(defaultLocalAddrPort),
|
||||
Port: intstr.FromInt(tailscaled.HealthCheckPort),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -305,15 +306,15 @@ func pgStatefulSet(pg *tsapi.ProxyGroup, namespace, image, tsFirewallMode string
|
||||
ss.Spec.Template.DeletionGracePeriodSeconds = new(deletionGracePeriodSeconds)
|
||||
|
||||
// Add a readiness gate so that kubelet does not mark a replica Pod as
|
||||
// ready before egressPodsReconciler has confirmed that cluster traffic
|
||||
// ready before egress.PodReconciler has confirmed that cluster traffic
|
||||
// for all egress services is being routed to it. Because StatefulSet
|
||||
// rolling updates only restart the next replica once the previous one
|
||||
// is ready, this prevents a window during updates where every replica
|
||||
// has been recreated but none is yet serving traffic, which would drop
|
||||
// cluster egress traffic. The reconciler sets the corresponding
|
||||
// condition; see egress-pod-readiness.go.
|
||||
// condition; see k8s-operator/reconciler/egress/pods.go.
|
||||
tmpl.Spec.ReadinessGates = append(tmpl.Spec.ReadinessGates, corev1.PodReadinessGate{
|
||||
ConditionType: tsEgressReadinessGate,
|
||||
ConditionType: reconciler.EgressReadinessGate,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -325,20 +326,20 @@ func kubeAPIServerStatefulSet(pg *tsapi.ProxyGroup, namespace, image string, por
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
Spec: appsv1.StatefulSetSpec{
|
||||
Replicas: new(pgReplicas(pg)),
|
||||
Replicas: new(reconciler.ProxyGroupReplicas(pg)),
|
||||
PodManagementPolicy: appsv1.ParallelPodManagement,
|
||||
Selector: &metav1.LabelSelector{
|
||||
MatchLabels: pgLabels(pg.Name, nil),
|
||||
MatchLabels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
},
|
||||
Template: corev1.PodTemplateSpec{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
DeletionGracePeriodSeconds: new(int64(10)),
|
||||
},
|
||||
Spec: corev1.PodSpec{
|
||||
@@ -433,7 +434,7 @@ func pgServiceAccount(pg *tsapi.ProxyGroup, namespace string) *corev1.ServiceAcc
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
}
|
||||
@@ -444,7 +445,7 @@ func pgRole(pg *tsapi.ProxyGroup, namespace string, shareACMEAccount bool) *rbac
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
Rules: []rbacv1.PolicyRule{
|
||||
@@ -465,7 +466,7 @@ func pgRole(pg *tsapi.ProxyGroup, namespace string, shareACMEAccount bool) *rbac
|
||||
"update",
|
||||
},
|
||||
ResourceNames: func() (secrets []string) {
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
secrets = append(secrets,
|
||||
pgConfigSecretName(pg.Name, i), // Config with auth key.
|
||||
pgPodName(pg.Name, i), // State.
|
||||
@@ -498,7 +499,7 @@ func pgRoleBinding(pg *tsapi.ProxyGroup, namespace string) *rbacv1.RoleBinding {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pg.Name,
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
Subjects: []rbacv1.Subject{
|
||||
@@ -570,7 +571,7 @@ func isAuthAPIServerProxy(pg *tsapi.ProxyGroup) bool {
|
||||
// them to find the tailnet devices, so a foreground delete must not remove
|
||||
// them first. ProxyGroupReconciler.maybeCleanup deletes them.
|
||||
func pgStateSecrets(pg *tsapi.ProxyGroup, namespace string) (secrets []*corev1.Secret) {
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
secrets = append(secrets, &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgStateSecretName(pg.Name, i),
|
||||
@@ -588,9 +589,9 @@ func pgEgressCM(pg *tsapi.ProxyGroup, namespace string) (*corev1.ConfigMap, []by
|
||||
hpBs := []byte(strconv.Itoa(hp))
|
||||
return &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName(pg.Name),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName(pg.Name),
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
BinaryData: map[string][]byte{egressservices.KeyHEPPings: hpBs},
|
||||
@@ -602,41 +603,22 @@ func pgIngressCM(pg *tsapi.ProxyGroup, namespace string) *corev1.ConfigMap {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgIngressCMName(pg.Name),
|
||||
Namespace: namespace,
|
||||
Labels: pgLabels(pg.Name, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg.Name, nil),
|
||||
OwnerReferences: pgOwnerReference(pg),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func pgSecretLabels(pgName, secretType string) map[string]string {
|
||||
return pgLabels(pgName, map[string]string{
|
||||
return reconciler.ProxyGroupLabels(pgName, map[string]string{
|
||||
kubetypes.LabelSecretType: secretType, // "config" or "state".
|
||||
})
|
||||
}
|
||||
|
||||
func pgLabels(pgName string, customLabels map[string]string) map[string]string {
|
||||
labels := make(map[string]string, len(customLabels)+3)
|
||||
maps.Copy(labels, customLabels)
|
||||
|
||||
labels[kubetypes.LabelManaged] = "true"
|
||||
labels[LabelParentType] = "proxygroup"
|
||||
labels[LabelParentName] = pgName
|
||||
|
||||
return labels
|
||||
}
|
||||
|
||||
func pgOwnerReference(owner *tsapi.ProxyGroup) []metav1.OwnerReference {
|
||||
return []metav1.OwnerReference{*metav1.NewControllerRef(owner, tsapi.SchemeGroupVersion.WithKind("ProxyGroup"))}
|
||||
}
|
||||
|
||||
func pgReplicas(pg *tsapi.ProxyGroup) int32 {
|
||||
if pg.Spec.Replicas != nil {
|
||||
return *pg.Spec.Replicas
|
||||
}
|
||||
|
||||
return 2
|
||||
}
|
||||
|
||||
func pgPodName(pgName string, i int32) string {
|
||||
return fmt.Sprintf("%s-%d", pgName, i)
|
||||
}
|
||||
@@ -657,10 +639,6 @@ func pgStateSecretName(pgName string, i int32) string {
|
||||
return fmt.Sprintf("%s-%d", pgName, i)
|
||||
}
|
||||
|
||||
func pgEgressCMName(pg string) string {
|
||||
return fmt.Sprintf("%s-egress-config", pg)
|
||||
}
|
||||
|
||||
// hasLocalAddrPortSet returns true if the proxyclass has the TS_LOCAL_ADDR_PORT env var set. For egress ProxyGroups,
|
||||
// currently (2025-01-26) this means that the ProxyGroup does not support graceful failover.
|
||||
func hasLocalAddrPortSet(proxyClass *tsapi.ProxyClass) bool {
|
||||
@@ -675,7 +653,7 @@ func hasLocalAddrPortSet(proxyClass *tsapi.ProxyClass) bool {
|
||||
// hepPings returns the number of times a health check endpoint exposed by a Service fronting ProxyGroup replicas should
|
||||
// be pinged to ensure that all currently configured backend replicas are hit.
|
||||
func hepPings(pg *tsapi.ProxyGroup) int {
|
||||
rc := pgReplicas(pg)
|
||||
rc := reconciler.ProxyGroupReplicas(pg)
|
||||
// Assuming a Service implemented using round robin load balancing, number-of-replica-times should be enough, but in
|
||||
// practice, we cannot assume that the requests will be load balanced perfectly.
|
||||
return int(rc) * 3
|
||||
|
||||
@@ -37,6 +37,7 @@ import (
|
||||
"tailscale.com/ipn"
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/proxyclass"
|
||||
"tailscale.com/k8s-operator/reconciler/staticendpoints"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
@@ -1243,7 +1244,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
})
|
||||
|
||||
zl, _ := zap.NewDevelopment()
|
||||
reconciler := &ProxyGroupReconciler{
|
||||
pgr := &ProxyGroupReconciler{
|
||||
tsNamespace: tsNamespace,
|
||||
tsProxyImage: testProxyImage,
|
||||
Client: fc,
|
||||
@@ -1267,8 +1268,8 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
}
|
||||
mustCreate(t, fc, pg)
|
||||
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, reconciler, 0, 1, 0)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, pgr, 0, 1, 0)
|
||||
|
||||
sts := &appsv1.StatefulSet{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
@@ -1318,7 +1319,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
PreStop: &corev1.LifecycleHandler{
|
||||
HTTPGet: &corev1.HTTPGetAction{
|
||||
Path: kubetypes.EgessServicesPreshutdownEP,
|
||||
Port: intstr.FromInt(defaultLocalAddrPort),
|
||||
Port: intstr.FromInt(tailscaled.HealthCheckPort),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -1329,9 +1330,9 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
t.Errorf("unexpected deletion grace period seconds %d, want %d", *sts.Spec.Template.DeletionGracePeriodSeconds, deletionGracePeriodSeconds)
|
||||
}
|
||||
if !slices.ContainsFunc(sts.Spec.Template.Spec.ReadinessGates, func(r corev1.PodReadinessGate) bool {
|
||||
return r.ConditionType == tsEgressReadinessGate
|
||||
return r.ConditionType == reconciler.EgressReadinessGate
|
||||
}) {
|
||||
t.Errorf("expected egress readiness gate %q to be set, got %v", tsEgressReadinessGate, sts.Spec.Template.Spec.ReadinessGates)
|
||||
t.Errorf("expected egress readiness gate %q to be set, got %v", reconciler.EgressReadinessGate, sts.Spec.Template.Spec.ReadinessGates)
|
||||
}
|
||||
|
||||
// Unlike legacy egress proxies, egress ProxyGroups only DNAT their mapped ports, so they get probes.
|
||||
@@ -1348,14 +1349,14 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
mustUpdate(t, fc, "", pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
p.Spec.ProxyClass = pc.Name
|
||||
})
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
t.Fatalf("failed to get StatefulSet: %v", err)
|
||||
}
|
||||
if diff := cmp.Diff(httpProbe("/livez", defaultLocalAddrPort, &tsapi.Probe{}, 5), sts.Spec.Template.Spec.Containers[0].LivenessProbe); diff != "" {
|
||||
if diff := cmp.Diff(httpProbe("/livez", tailscaled.HealthCheckPort, &tsapi.Probe{}, 5), sts.Spec.Template.Spec.Containers[0].LivenessProbe); diff != "" {
|
||||
t.Errorf("unexpected liveness probe (-want +got):\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(httpProbe("/readyz", defaultLocalAddrPort, &tsapi.Probe{}, 1), sts.Spec.Template.Spec.Containers[0].ReadinessProbe); diff != "" {
|
||||
if diff := cmp.Diff(httpProbe("/readyz", tailscaled.HealthCheckPort, &tsapi.Probe{}, 1), sts.Spec.Template.Spec.Containers[0].ReadinessProbe); diff != "" {
|
||||
t.Errorf("unexpected readiness probe (-want +got):\n%s", diff)
|
||||
}
|
||||
})
|
||||
@@ -1384,7 +1385,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
},
|
||||
}
|
||||
})
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
|
||||
sts := &appsv1.StatefulSet{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
@@ -1395,7 +1396,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
t.Error("lifecycle hook was set when TS_LOCAL_ADDR_PORT was configured via ProxyClass")
|
||||
}
|
||||
if slices.ContainsFunc(sts.Spec.Template.Spec.ReadinessGates, func(r corev1.PodReadinessGate) bool {
|
||||
return r.ConditionType == tsEgressReadinessGate
|
||||
return r.ConditionType == reconciler.EgressReadinessGate
|
||||
}) {
|
||||
t.Error("egress readiness gate was set when TS_LOCAL_ADDR_PORT was configured via ProxyClass")
|
||||
}
|
||||
@@ -1419,8 +1420,8 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, reconciler, 1, 2, 0)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, pgr, 1, 2, 0)
|
||||
|
||||
sts := &appsv1.StatefulSet{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
@@ -1497,7 +1498,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("ingress_type_shared_acme_opt_out", func(t *testing.T) {
|
||||
// The reconciler has sharedACMEAccountKey=true, so ingress PGs
|
||||
// The pgr has sharedACMEAccountKey=true, so ingress PGs
|
||||
// default to shared. Explicit tailscale.com/share-acme-account=false
|
||||
// must opt this PG out: no shared-Secret env vars, no Role
|
||||
// access to the shared Secret, and TS_DEBUG_ACME_FORCE_RENEWAL
|
||||
@@ -1518,7 +1519,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
if err := fc.Create(t.Context(), pg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
|
||||
sts := &appsv1.StatefulSet{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
@@ -1560,7 +1561,7 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
StatefulSet: &tsapi.StatefulSet{
|
||||
Pod: &tsapi.Pod{
|
||||
TailscaleContainer: &tsapi.Container{
|
||||
// k8s-proxy ignores this, so the probes must stay on defaultLocalAddrPort.
|
||||
// k8s-proxy ignores this, so the probes must stay on tailscaled.HealthCheckPort.
|
||||
Env: []tsapi.Env{{Name: "TS_LOCAL_ADDR_PORT", Value: "0.0.0.0:8080"}},
|
||||
LivenessProbe: &tsapi.Probe{},
|
||||
ReadinessProbe: &tsapi.Probe{},
|
||||
@@ -1595,8 +1596,8 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
expectReconciled(t, reconciler, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, reconciler, 2, 2, 1)
|
||||
expectReconciled(t, pgr, "", pg.Name)
|
||||
verifyProxyGroupCounts(t, pgr, 2, 2, 1)
|
||||
|
||||
sts := &appsv1.StatefulSet{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: tsNamespace, Name: pg.Name}, sts); err != nil {
|
||||
@@ -1616,10 +1617,10 @@ func TestProxyGroupTypes(t *testing.T) {
|
||||
if sts.Spec.PodManagementPolicy != appsv1.ParallelPodManagement {
|
||||
t.Errorf("unexpected PodManagementPolicy %q, want %q", sts.Spec.PodManagementPolicy, appsv1.ParallelPodManagement)
|
||||
}
|
||||
if diff := cmp.Diff(httpProbe("/livez", defaultLocalAddrPort, &tsapi.Probe{}, 5), sts.Spec.Template.Spec.Containers[0].LivenessProbe); diff != "" {
|
||||
if diff := cmp.Diff(httpProbe("/livez", tailscaled.HealthCheckPort, &tsapi.Probe{}, 5), sts.Spec.Template.Spec.Containers[0].LivenessProbe); diff != "" {
|
||||
t.Errorf("unexpected liveness probe (-want +got):\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(httpProbe("/readyz", defaultLocalAddrPort, &tsapi.Probe{}, 1), sts.Spec.Template.Spec.Containers[0].ReadinessProbe); diff != "" {
|
||||
if diff := cmp.Diff(httpProbe("/readyz", tailscaled.HealthCheckPort, &tsapi.Probe{}, 1), sts.Spec.Template.Spec.Containers[0].ReadinessProbe); diff != "" {
|
||||
t.Errorf("unexpected readiness probe (-want +got):\n%s", diff)
|
||||
}
|
||||
if _, ok := lookupEnv(sts.Spec.Template.Spec.Containers[0].Env, "TS_ENABLE_HEALTH_CHECK"); ok {
|
||||
@@ -2408,7 +2409,7 @@ func expectProxyGroupResources(t *testing.T, fc client.WithWatch, pg *tsapi.Prox
|
||||
// The state Secrets are created before the ProxyClass is checked, so
|
||||
// they exist even when the other resources do not.
|
||||
var expectedSecrets []string
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
expectedSecrets = append(expectedSecrets, fmt.Sprintf("%s-%d", pg.Name, i))
|
||||
if shouldExist {
|
||||
expectedSecrets = append(expectedSecrets, pgConfigSecretName(pg.Name, i))
|
||||
@@ -2438,7 +2439,7 @@ func expectSecrets(t *testing.T, fc client.WithWatch, expected []string) {
|
||||
func addNodeIDToStateSecrets(t *testing.T, fc client.WithWatch, pg *tsapi.ProxyGroup) {
|
||||
t.Helper()
|
||||
const key = "profile-abc"
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
bytes, err := json.Marshal(map[string]any{
|
||||
"Config": map[string]any{
|
||||
"NodeID": fmt.Sprintf("nodeid-%d", i),
|
||||
|
||||
+4
-33
@@ -65,15 +65,7 @@ const (
|
||||
FinalizerName = "tailscale.com/finalizer"
|
||||
|
||||
// Annotations settable by users on services.
|
||||
AnnotationExpose = "tailscale.com/expose"
|
||||
AnnotationTags = "tailscale.com/tags"
|
||||
AnnotationHostname = "tailscale.com/hostname"
|
||||
annotationTailnetTargetIPOld = "tailscale.com/ts-tailnet-target-ip"
|
||||
AnnotationTailnetTargetIP = "tailscale.com/tailnet-ip"
|
||||
// MagicDNS name of tailnet node.
|
||||
AnnotationTailnetTargetFQDN = "tailscale.com/tailnet-fqdn"
|
||||
|
||||
AnnotationProxyGroup = "tailscale.com/proxy-group"
|
||||
AnnotationExpose = "tailscale.com/expose"
|
||||
|
||||
// AnnotationShareACMEAccount opts a single ProxyGroup into ("true")
|
||||
// or out of ("false") using the shared per-tailnet ACME account key.
|
||||
@@ -118,10 +110,8 @@ const (
|
||||
proxyTypeIngressService = "ingress_service"
|
||||
proxyTypeIngressResource = "ingress_resource"
|
||||
proxyTypeConnector = "connector"
|
||||
proxyTypeProxyGroup = "proxygroup"
|
||||
|
||||
envVarTSLocalAddrPort = "TS_LOCAL_ADDR_PORT"
|
||||
defaultLocalAddrPort = 9002 // metrics and health check port
|
||||
|
||||
letsEncryptStagingEndpoint = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||
|
||||
@@ -1269,7 +1259,7 @@ func isMainContainer(c *corev1.Container) bool {
|
||||
// sets it. pc may be nil. It is a no-op if neither probe is set, or if the
|
||||
// container's env leaves the endpoints unreachable, see [healthzPort]. If
|
||||
// k8sProxy is set, the container runs k8s-proxy, which serves the endpoints on
|
||||
// defaultLocalAddrPort from its config file and ignores the env.
|
||||
// tailscaled.HealthCheckPort from its config file and ignores the env.
|
||||
func applyHealthzProbes(pc *tsapi.ProxyClass, ss *appsv1.StatefulSet, k8sProxy bool) {
|
||||
var liveness, readiness *tsapi.Probe
|
||||
if pc != nil && pc.Spec.StatefulSet != nil && pc.Spec.StatefulSet.Pod != nil && pc.Spec.StatefulSet.Pod.TailscaleContainer != nil {
|
||||
@@ -1284,7 +1274,7 @@ func applyHealthzProbes(pc *tsapi.ProxyClass, ss *appsv1.StatefulSet, k8sProxy b
|
||||
if !isMainContainer(&c) {
|
||||
continue
|
||||
}
|
||||
port := defaultLocalAddrPort
|
||||
port := tailscaled.HealthCheckPort
|
||||
if !k8sProxy {
|
||||
var ok bool
|
||||
if port, ok = healthzPort(c.Env); !ok {
|
||||
@@ -1322,7 +1312,7 @@ func healthzPort(env []corev1.EnvVar) (int, bool) {
|
||||
}
|
||||
v, ok := lookupEnv(env, envVarTSLocalAddrPort)
|
||||
if !ok {
|
||||
return defaultLocalAddrPort, true
|
||||
return tailscaled.HealthCheckPort, true
|
||||
}
|
||||
// The host may be an env var reference such as $(POD_IP).
|
||||
host, port, err := net.SplitHostPort(v)
|
||||
@@ -1625,25 +1615,6 @@ func defaultEnv(envName, defVal string) string {
|
||||
return v
|
||||
}
|
||||
|
||||
func nameForService(svc *corev1.Service) string {
|
||||
if h, ok := svc.Annotations[AnnotationHostname]; ok {
|
||||
return h
|
||||
}
|
||||
name := svc.Namespace + "-" + svc.Name
|
||||
if isEgressService(svc) {
|
||||
// The hostname of an egress proxy is not user facing, so instead of
|
||||
// failing validation, shorten a default that is longer than a DNS
|
||||
// label allows. Defaults that already fit are unchanged.
|
||||
return tsoperator.TruncateWithHash(name)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// isEgressService reports whether svc exposes a tailnet target to the cluster.
|
||||
func isEgressService(svc *corev1.Service) bool {
|
||||
return tailnetTargetAnnotation(svc) != "" || svc.Annotations[AnnotationTailnetTargetFQDN] != ""
|
||||
}
|
||||
|
||||
// markedForDeletion reports whether obj has a deletion timestamp, i.e. the API server is waiting on finalizers
|
||||
// before it can garbage collect it.
|
||||
func markedForDeletion(obj metav1.Object) bool {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"sigs.k8s.io/yaml"
|
||||
"tailscale.com/client/tailscale/v2"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/k8s-operator/tsclient"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/types/key"
|
||||
@@ -337,15 +338,15 @@ func Test_applyHealthzProbes(t *testing.T) {
|
||||
}{
|
||||
"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},
|
||||
"liveness_set": {pc: withProbes(&tsapi.Probe{}, nil), wantLiveness: true, wantPort: tailscaled.HealthCheckPort},
|
||||
"readiness_set": {pc: withProbes(nil, &tsapi.Probe{}), wantReadiness: true, wantPeriod: 10, wantPort: tailscaled.HealthCheckPort},
|
||||
"both_set": {pc: both, wantLiveness: true, wantReadiness: true, wantPeriod: 10, wantPort: tailscaled.HealthCheckPort},
|
||||
"custom_readiness_period": {pc: withProbes(nil, &tsapi.Probe{PeriodSeconds: 30}), wantReadiness: true, wantPeriod: 30, wantPort: tailscaled.HealthCheckPort},
|
||||
"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},
|
||||
"health_check_enabled": {pc: both, env: []corev1.EnvVar{{Name: "TS_ENABLE_HEALTH_CHECK", Value: "true"}}, wantLiveness: true, wantReadiness: true, wantPeriod: 10, wantPort: tailscaled.HealthCheckPort},
|
||||
"deprecated_healthcheck": {pc: both, env: []corev1.EnvVar{{Name: "TS_HEALTHCHECK_ADDR_PORT", Value: "[::]:8080"}}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
|
||||
@@ -134,7 +134,7 @@ func (r *HAServiceReconciler) Reconcile(ctx context.Context, req reconcile.Reque
|
||||
return res, fmt.Errorf("failed to get Service: %w", err)
|
||||
}
|
||||
|
||||
pgName := svc.Annotations[AnnotationProxyGroup]
|
||||
pgName := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
if pgName == "" {
|
||||
// If we hold a finalizer, the annotation was removed after we
|
||||
// provisioned this Service and we still need to clean up; recover the
|
||||
@@ -175,7 +175,7 @@ func (r *HAServiceReconciler) Reconcile(ctx context.Context, req reconcile.Reque
|
||||
return res, fmt.Errorf("failed to get tailscale client: %w", err)
|
||||
}
|
||||
|
||||
hostname := nameForService(svc)
|
||||
hostname := reconciler.NameForService(svc)
|
||||
logger = logger.With("hostname", hostname)
|
||||
|
||||
if !svc.DeletionTimestamp.IsZero() || !r.isTailscaleService(svc) {
|
||||
@@ -275,7 +275,7 @@ func (r *HAServiceReconciler) maybeProvision(ctx context.Context, hostname strin
|
||||
// appears that the Tailscale Service has been created by a non-operator actor).
|
||||
updatedAnnotations, err := ownerAnnotations(r.operatorID, existingTSSvc)
|
||||
if err != nil {
|
||||
instr := fmt.Sprintf("To proceed, you can either manually delete the existing Tailscale Service or choose a different hostname with the '%s' annotaion", AnnotationHostname)
|
||||
instr := fmt.Sprintf("To proceed, you can either manually delete the existing Tailscale Service or choose a different hostname with the '%s' annotaion", reconciler.AnnotationHostname)
|
||||
msg := fmt.Sprintf("error ensuring ownership of Tailscale Service %s: %v. %s", hostname, err, instr)
|
||||
logger.Warn(msg)
|
||||
r.recorder.Event(svc, corev1.EventTypeWarning, "InvalidTailscaleService", msg)
|
||||
@@ -284,7 +284,7 @@ func (r *HAServiceReconciler) maybeProvision(ctx context.Context, hostname strin
|
||||
}
|
||||
|
||||
tags := r.defaultTags
|
||||
if tstr, ok := svc.Annotations[AnnotationTags]; ok && tstr != "" {
|
||||
if tstr, ok := svc.Annotations[reconciler.AnnotationTags]; ok && tstr != "" {
|
||||
tags = strings.Split(tstr, ",")
|
||||
}
|
||||
|
||||
@@ -402,7 +402,7 @@ func (r *HAServiceReconciler) maybeProvision(ctx context.Context, hostname strin
|
||||
conditionStatus := metav1.ConditionFalse
|
||||
conditionType := tsapi.IngressSvcConfigured
|
||||
conditionReason := reasonIngressSvcNoBackendsConfigured
|
||||
conditionMessage := fmt.Sprintf("%d/%d proxy backends ready and advertising", count, pgReplicas(pg))
|
||||
conditionMessage := fmt.Sprintf("%d/%d proxy backends ready and advertising", count, reconciler.ProxyGroupReplicas(pg))
|
||||
if count != 0 {
|
||||
dnsName, err := dnsNameForService(ctx, r.Client, serviceName, pg, r.tsNamespace)
|
||||
if err != nil {
|
||||
@@ -503,7 +503,7 @@ func (r *HAServiceReconciler) maybeCleanupProxyGroup(ctx context.Context, proxyG
|
||||
for tsSvcName, cfg := range config {
|
||||
found := false
|
||||
for _, svc := range svcList.Items {
|
||||
if strings.EqualFold(fmt.Sprintf("svc:%s", nameForService(&svc)), tsSvcName) {
|
||||
if strings.EqualFold(fmt.Sprintf("svc:%s", reconciler.NameForService(&svc)), tsSvcName) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
@@ -559,7 +559,7 @@ func (r *HAServiceReconciler) deleteFinalizer(ctx context.Context, svc *corev1.S
|
||||
}
|
||||
|
||||
func (r *HAServiceReconciler) isTailscaleService(svc *corev1.Service) bool {
|
||||
proxyGroup := svc.Annotations[AnnotationProxyGroup]
|
||||
proxyGroup := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
return r.shouldExpose(svc) && proxyGroup != ""
|
||||
}
|
||||
|
||||
@@ -880,7 +880,7 @@ func (r *HAServiceReconciler) validateService(ctx context.Context, svc *corev1.S
|
||||
errs = append(errs, fmt.Errorf("ProxyGroup %q is of type %q but must be of type %q",
|
||||
pg.Name, pg.Spec.Type, tsapi.ProxyGroupTypeIngress))
|
||||
}
|
||||
if violations := validateService(svc); len(violations) > 0 {
|
||||
if violations := reconciler.ValidateService(svc); len(violations) > 0 {
|
||||
errs = append(errs, fmt.Errorf("invalid Service: %s", strings.Join(violations, ", ")))
|
||||
}
|
||||
svcList := &corev1.ServiceList{}
|
||||
@@ -888,7 +888,7 @@ func (r *HAServiceReconciler) validateService(ctx context.Context, svc *corev1.S
|
||||
errs = append(errs, fmt.Errorf("error listing Services: %w", err))
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
svcName := nameForService(svc)
|
||||
svcName := reconciler.NameForService(svc)
|
||||
for _, s := range svcList.Items {
|
||||
if s.UID == svc.UID {
|
||||
continue
|
||||
@@ -902,7 +902,7 @@ func (r *HAServiceReconciler) validateService(ctx context.Context, svc *corev1.S
|
||||
if !r.isTailscaleService(&s) {
|
||||
continue
|
||||
}
|
||||
if nameForService(&s) != svcName {
|
||||
if reconciler.NameForService(&s) != svcName {
|
||||
continue
|
||||
}
|
||||
// Two ProxyGroups joined to different tailnets each have their own
|
||||
@@ -911,7 +911,7 @@ func (r *HAServiceReconciler) validateService(ctx context.Context, svc *corev1.S
|
||||
// duplicate report when the tailnets differ; if the lookup fails
|
||||
// fall through and flag the collision so a genuine duplicate isn't
|
||||
// silently allowed.
|
||||
otherPGName := s.Annotations[AnnotationProxyGroup]
|
||||
otherPGName := s.Annotations[reconciler.AnnotationProxyGroup]
|
||||
if otherPGName != "" && otherPGName != pg.Name {
|
||||
otherPG := &tsapi.ProxyGroup{}
|
||||
if err := r.Get(ctx, client.ObjectKey{Name: otherPGName}, otherPG); err == nil && otherPG.Spec.Tailnet != pg.Spec.Tailnet {
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"tailscale.com/ipn"
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/k8s-operator/tsclient"
|
||||
"tailscale.com/kube/ingressservices"
|
||||
@@ -99,7 +100,7 @@ func TestServicePGReconciler_UpdateHostname(t *testing.T) {
|
||||
|
||||
hostname := "foobarbaz"
|
||||
mustUpdate(t, fc, svc.Namespace, svc.Name, func(s *corev1.Service) {
|
||||
mak.Set(&s.Annotations, AnnotationHostname, hostname)
|
||||
mak.Set(&s.Annotations, reconciler.AnnotationHostname, hostname)
|
||||
})
|
||||
|
||||
// NOTE: we need to update the ingress config Secret because there is no containerboot in the fake proxy Pod
|
||||
@@ -585,7 +586,7 @@ func TestServicePGReconciler_CleanupOnAnnotationRemoved(t *testing.T) {
|
||||
|
||||
// Remove the ProxyGroup annotation.
|
||||
mustUpdate(t, fc, svc.Namespace, svc.Name, func(s *corev1.Service) {
|
||||
delete(s.Annotations, AnnotationProxyGroup)
|
||||
delete(s.Annotations, reconciler.AnnotationProxyGroup)
|
||||
})
|
||||
expectReconciled(t, svcPGR, "default", svc.Name)
|
||||
|
||||
|
||||
+10
-97
@@ -28,17 +28,12 @@ import (
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/net/dns/resolvconffile"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/clientmetric"
|
||||
"tailscale.com/util/dnsname"
|
||||
"tailscale.com/util/set"
|
||||
)
|
||||
|
||||
const (
|
||||
resolvConfPath = "/etc/resolv.conf"
|
||||
defaultClusterDomain = "cluster.local"
|
||||
|
||||
reasonProxyCreated = "ProxyCreated"
|
||||
reasonProxyInvalid = "ProxyInvalid"
|
||||
reasonProxyFailed = "ProxyFailed"
|
||||
@@ -95,7 +90,7 @@ func childResourceLabels(name, ns, typ string) map[string]string {
|
||||
|
||||
func (a *ServiceReconciler) isTailscaleService(svc *corev1.Service) bool {
|
||||
targetIP := tailnetTargetAnnotation(svc)
|
||||
targetFQDN := svc.Annotations[AnnotationTailnetTargetFQDN]
|
||||
targetFQDN := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]
|
||||
return shouldExpose(svc, a.isDefaultLoadBalancer) || targetIP != "" || targetFQDN != ""
|
||||
}
|
||||
|
||||
@@ -114,7 +109,7 @@ func (a *ServiceReconciler) Reconcile(ctx context.Context, req reconcile.Request
|
||||
return reconcile.Result{}, fmt.Errorf("failed to get svc: %w", err)
|
||||
}
|
||||
|
||||
if _, ok := svc.Annotations[AnnotationProxyGroup]; ok {
|
||||
if _, ok := svc.Annotations[reconciler.AnnotationProxyGroup]; ok {
|
||||
return reconcile.Result{}, nil // this reconciler should not look at Services for ProxyGroup
|
||||
}
|
||||
|
||||
@@ -222,7 +217,7 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
tsoperator.SetServiceCondition(svc, tsapi.ProxyReady, metav1.ConditionFalse, reasonProxyInvalid, msg, a.clock, logger)
|
||||
return nil
|
||||
}
|
||||
if violations := validateService(svc); len(violations) > 0 {
|
||||
if violations := reconciler.ValidateService(svc); len(violations) > 0 {
|
||||
msg := fmt.Sprintf("unable to provision proxy resources: invalid Service: %s", strings.Join(violations, ", "))
|
||||
a.recorder.Event(svc, corev1.EventTypeWarning, "INVALIDSERVICE", msg)
|
||||
a.logger.Error(msg)
|
||||
@@ -259,7 +254,7 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
}
|
||||
crl := childResourceLabels(svc.Name, svc.Namespace, "svc")
|
||||
var tags []string
|
||||
if tstr, ok := svc.Annotations[AnnotationTags]; ok {
|
||||
if tstr, ok := svc.Annotations[reconciler.AnnotationTags]; ok {
|
||||
tags = strings.Split(tstr, ",")
|
||||
}
|
||||
|
||||
@@ -267,7 +262,7 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
Replicas: 1,
|
||||
ParentResourceName: svc.Name,
|
||||
ParentResourceUID: string(svc.UID),
|
||||
Hostname: nameForService(svc),
|
||||
Hostname: reconciler.NameForService(svc),
|
||||
Tags: tags,
|
||||
ChildResourceLabels: crl,
|
||||
ProxyClassName: proxyClass,
|
||||
@@ -291,8 +286,8 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
sts.TailnetTargetIP = ip
|
||||
a.managedEgressProxies.Add(svc.UID)
|
||||
gaugeEgressProxies.Set(int64(a.managedEgressProxies.Len()))
|
||||
} else if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]
|
||||
} else if fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]
|
||||
if !strings.HasSuffix(fqdn, ".") {
|
||||
fqdn = fqdn + "."
|
||||
}
|
||||
@@ -310,7 +305,7 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
}
|
||||
|
||||
if sts.TailnetTargetIP != "" || sts.TailnetTargetFQDN != "" { // if an egress proxy
|
||||
clusterDomain := retrieveClusterDomain(a.tsNamespace, logger)
|
||||
clusterDomain := reconciler.ClusterDomain(a.tsNamespace, logger)
|
||||
headlessSvcName := hsvc.Name + "." + hsvc.Namespace + ".svc." + clusterDomain
|
||||
if svc.Spec.ExternalName != headlessSvcName || svc.Spec.Type != corev1.ServiceTypeExternalName {
|
||||
svc.Spec.ExternalName = headlessSvcName
|
||||
@@ -375,40 +370,6 @@ func (a *ServiceReconciler) maybeProvision(ctx context.Context, logger *zap.Suga
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateService(svc *corev1.Service) []string {
|
||||
violations := make([]string, 0)
|
||||
if svc.Spec.ClusterIP == "None" {
|
||||
violations = append(violations, "headless Services are not supported.")
|
||||
}
|
||||
if svc.Annotations[AnnotationTailnetTargetFQDN] != "" && svc.Annotations[AnnotationTailnetTargetIP] != "" {
|
||||
violations = append(violations, fmt.Sprintf("only one of annotations %s and %s can be set", AnnotationTailnetTargetIP, AnnotationTailnetTargetFQDN))
|
||||
}
|
||||
if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
if !isMagicDNSName(fqdn) {
|
||||
violations = append(violations, fmt.Sprintf("invalid value of annotation %s: %q does not appear to be a valid MagicDNS name", AnnotationTailnetTargetFQDN, fqdn))
|
||||
}
|
||||
}
|
||||
if ipStr := svc.Annotations[AnnotationTailnetTargetIP]; ipStr != "" {
|
||||
ip, err := netip.ParseAddr(ipStr)
|
||||
if err != nil {
|
||||
violations = append(violations, fmt.Sprintf("invalid value of annotation %s: %q could not be parsed as a valid IP Address, error: %s", AnnotationTailnetTargetIP, ipStr, err))
|
||||
} else if !ip.IsValid() {
|
||||
violations = append(violations, fmt.Sprintf("parsed IP address in annotation %s: %q is not valid", AnnotationTailnetTargetIP, ipStr))
|
||||
}
|
||||
}
|
||||
|
||||
svcName := nameForService(svc)
|
||||
if err := dnsname.ValidLabel(svcName); err != nil {
|
||||
if _, ok := svc.Annotations[AnnotationHostname]; ok {
|
||||
violations = append(violations, fmt.Sprintf("invalid Tailscale hostname specified %q: %s", svcName, err))
|
||||
} else {
|
||||
violations = append(violations, fmt.Sprintf("invalid Tailscale hostname %q, use %q annotation to override: %s", svcName, AnnotationHostname, err))
|
||||
}
|
||||
}
|
||||
violations = append(violations, tagViolations(svc)...)
|
||||
return violations
|
||||
}
|
||||
|
||||
func shouldExpose(svc *corev1.Service, isDefaultLoadBalancer bool) bool {
|
||||
return shouldExposeClusterIP(svc, isDefaultLoadBalancer) || shouldExposeDNSName(svc)
|
||||
}
|
||||
@@ -445,10 +406,10 @@ func tailnetTargetAnnotation(svc *corev1.Service) string {
|
||||
if svc == nil {
|
||||
return ""
|
||||
}
|
||||
if ip := svc.Annotations[AnnotationTailnetTargetIP]; ip != "" {
|
||||
if ip := svc.Annotations[reconciler.AnnotationTailnetTargetIP]; ip != "" {
|
||||
return ip
|
||||
}
|
||||
return svc.Annotations[annotationTailnetTargetIPOld]
|
||||
return svc.Annotations[reconciler.AnnotationTailnetTargetIPOld]
|
||||
}
|
||||
|
||||
func proxyClassIsReady(ctx context.Context, name string, cl client.Client) (bool, error) {
|
||||
@@ -458,51 +419,3 @@ func proxyClassIsReady(ctx context.Context, name string, cl client.Client) (bool
|
||||
}
|
||||
return tsoperator.ProxyClassIsReady(proxyClass), nil
|
||||
}
|
||||
|
||||
// retrieveClusterDomain determines and retrieves cluster domain i.e
|
||||
// (cluster.local) in which this Pod is running by parsing search domains in
|
||||
// /etc/resolv.conf. If an error is encountered at any point during the process,
|
||||
// defaults cluster domain to 'cluster.local'.
|
||||
func retrieveClusterDomain(namespace string, logger *zap.SugaredLogger) string {
|
||||
logger.Infof("attempting to retrieve cluster domain..")
|
||||
conf, err := resolvconffile.ParseFile(resolvConfPath)
|
||||
if err != nil {
|
||||
// Vast majority of clusters use the cluster.local domain, so it
|
||||
// is probably better to fall back to that than error out.
|
||||
logger.Warn("error parsing /etc/resolv.conf to determine cluster domain, defaulting to 'cluster.local'.")
|
||||
return defaultClusterDomain
|
||||
}
|
||||
return clusterDomainFromResolverConf(conf, namespace, logger)
|
||||
}
|
||||
|
||||
// clusterDomainFromResolverConf attempts to retrieve cluster domain from the provided resolver config.
|
||||
// It expects the first three search domains in the resolver config to be ['<namespace>.svc.<cluster-domain>, svc.<cluster-domain>, <cluster-domain>, ...]
|
||||
// If the first three domains match the expected structure, it returns the third.
|
||||
// If the domains don't match the expected structure or an error is encountered, it defaults to 'cluster.local' domain.
|
||||
func clusterDomainFromResolverConf(conf *resolvconffile.Config, namespace string, logger *zap.SugaredLogger) string {
|
||||
if len(conf.SearchDomains) < 3 {
|
||||
logger.Warnf(" resolver config contains only %d search domains, at least three expected.\nDefaulting cluster domain to 'cluster.local'.", len(conf.SearchDomains))
|
||||
return defaultClusterDomain
|
||||
}
|
||||
first := conf.SearchDomains[0]
|
||||
if !strings.HasPrefix(string(first), namespace+".svc") {
|
||||
logger.Warnf("first search domain in resolver config is %s; expected %s.\nDefaulting cluster domain to 'cluster.local'.", first, namespace+".svc.<cluster-domain>")
|
||||
return defaultClusterDomain
|
||||
}
|
||||
second := conf.SearchDomains[1]
|
||||
if !strings.HasPrefix(string(second), "svc") {
|
||||
logger.Warnf("second search domain in resolver config is %s; expected 'svc.<cluster-domain>'.\nDefaulting cluster domain to 'cluster.local'.", second)
|
||||
return defaultClusterDomain
|
||||
}
|
||||
// Trim the trailing dot for backwards compatibility purposes as the
|
||||
// cluster domain was previously hardcoded to 'cluster.local' without a
|
||||
// trailing dot.
|
||||
probablyClusterDomain := strings.TrimPrefix(second.WithoutTrailingDot(), "svc.")
|
||||
third := conf.SearchDomains[2]
|
||||
if !strings.EqualFold(third.WithoutTrailingDot(), probablyClusterDomain) {
|
||||
logger.Warnf("expected resolver config to contain serch domains <namespace>.svc.<cluster-domain>, svc.<cluster-domain>, <cluster-domain>; got %s %s %s\n. Defaulting cluster domain to 'cluster.local'.", first, second, third)
|
||||
return defaultClusterDomain
|
||||
}
|
||||
logger.Infof("Cluster domain %q extracted from resolver config", probablyClusterDomain)
|
||||
return probablyClusterDomain
|
||||
}
|
||||
@@ -221,97 +221,3 @@ func TestProxyClassHandlerForSvc(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameForService(t *testing.T) {
|
||||
const (
|
||||
longNS = "tailscale-external-services"
|
||||
longName = "harry1027133059-trefknee01-bee-oqggo-kinfe-0-g"
|
||||
)
|
||||
tests := []struct {
|
||||
name string
|
||||
svcName string
|
||||
annotations map[string]string
|
||||
want string
|
||||
wantValid bool
|
||||
}{
|
||||
{
|
||||
name: "egress_fqdn_short_default_unchanged",
|
||||
svcName: "foo",
|
||||
annotations: map[string]string{AnnotationTailnetTargetFQDN: "foo.tailnet.ts.net"},
|
||||
want: longNS + "-foo",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_fqdn_long_default_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{AnnotationTailnetTargetFQDN: longName + ".tailnet.ts.net"},
|
||||
want: "tailscale-external-services-harry1027133059-trefknee01-0908ae76",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_ip_long_default_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{AnnotationTailnetTargetIP: "100.64.0.1"},
|
||||
want: "tailscale-external-services-harry1027133059-trefknee01-0908ae76",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_long_hostname_annotation_not_truncated",
|
||||
annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.tailnet.ts.net",
|
||||
AnnotationHostname: longNS + "-" + longName,
|
||||
},
|
||||
svcName: "foo",
|
||||
want: longNS + "-" + longName,
|
||||
wantValid: false,
|
||||
},
|
||||
{
|
||||
name: "ingress_long_default_not_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{AnnotationExpose: "true"},
|
||||
want: longNS + "-" + longName,
|
||||
wantValid: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tt.svcName,
|
||||
Namespace: longNS,
|
||||
Annotations: tt.annotations,
|
||||
},
|
||||
}
|
||||
got := nameForService(svc)
|
||||
if got != tt.want {
|
||||
t.Errorf("nameForService() = %q, want %q", got, tt.want)
|
||||
}
|
||||
violations := validateService(svc)
|
||||
if valid := len(violations) == 0; valid != tt.wantValid {
|
||||
t.Errorf("validateService() violations = %v, want valid %t", violations, tt.wantValid)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateEgressServiceLongName(t *testing.T) {
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "harry1027133059-trefknee01-bee-oqggo-kinfe-0-g",
|
||||
Namespace: "tailscale-external-services",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "harry1027133059-trefknee01-bee-oqggo-kinfe-0-g.tailnet.ts.net",
|
||||
AnnotationProxyGroup: "egress",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
Type: corev1.ServiceTypeExternalName,
|
||||
ExternalName: "placeholder",
|
||||
Ports: []corev1.ServicePort{{Port: 8080, Protocol: corev1.ProtocolTCP}},
|
||||
},
|
||||
}
|
||||
pg := &tsapi.ProxyGroup{Spec: tsapi.ProxyGroupSpec{Type: tsapi.ProxyGroupTypeEgress}}
|
||||
if violations := validateEgressService(svc, pg); len(violations) > 0 {
|
||||
t.Errorf("validateEgressService() violations = %v, want none", violations)
|
||||
}
|
||||
}
|
||||
@@ -1005,19 +1005,6 @@ func removeResourceReqs(sts *appsv1.StatefulSet) {
|
||||
}
|
||||
}
|
||||
|
||||
func removeTargetPortsFromSvc(svc *corev1.Service) {
|
||||
newPorts := make([]corev1.ServicePort, 0)
|
||||
for _, p := range svc.Spec.Ports {
|
||||
newPorts = append(newPorts, corev1.ServicePort{Protocol: p.Protocol, Port: p.Port, Name: p.Name})
|
||||
}
|
||||
svc.Spec.Ports = newPorts
|
||||
}
|
||||
|
||||
func removeClusterIPsFromSvc(svc *corev1.Service) {
|
||||
svc.Spec.ClusterIP = ""
|
||||
svc.Spec.ClusterIPs = nil
|
||||
}
|
||||
|
||||
func removeAuthKeyIfExistsModifier(t *testing.T) func(s *corev1.Secret) {
|
||||
return func(secret *corev1.Secret) {
|
||||
t.Helper()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
// Package egress provides the reconcilers that expose tailnet targets to cluster workloads through an egress
|
||||
// ProxyGroup.
|
||||
//
|
||||
// A user creates an ExternalName Service that is annotated with a tailnet target and a ProxyGroup. Four reconcilers
|
||||
// then make that target reachable:
|
||||
//
|
||||
// - Reconciler watches the user's ExternalName Service. It allocates a container port for each Service port,
|
||||
// creates a ClusterIP Service and EndpointSlices for those ports, and writes the egress service configuration
|
||||
// that the ProxyGroup proxies read.
|
||||
// - EndpointSliceReconciler keeps the endpoints of those EndpointSlices set to the proxy Pods that can route
|
||||
// traffic to the target.
|
||||
// - ReadinessReconciler sets the EgressSvcReady condition on the user's Service from the number of proxy Pods that
|
||||
// can route traffic to the target.
|
||||
// - PodReconciler sets the egress readiness gate condition on a proxy Pod once the Pod can route traffic to all
|
||||
// egress services of its ProxyGroup.
|
||||
package egress
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"tailscale.com/tstime"
|
||||
)
|
||||
|
||||
// shortRequeue is how long to wait before a reconcile that waits for a proxy Pod, or that hit an update conflict, is
|
||||
// retried.
|
||||
const shortRequeue = 5 * time.Second
|
||||
|
||||
// ReconcilerOptions contains configuration values for the egress reconcilers. All four reconcilers in this package
|
||||
// take the same options.
|
||||
type ReconcilerOptions struct {
|
||||
// Client is used to interact with the Kubernetes API.
|
||||
Client client.Client
|
||||
// Recorder is used to emit Kubernetes events.
|
||||
Recorder record.EventRecorder
|
||||
// TailscaleNamespace is the namespace the operator is installed in. The ClusterIP Services, EndpointSlices and
|
||||
// ProxyGroup resources for egress services are in this namespace.
|
||||
TailscaleNamespace string
|
||||
// Logger is the logger to use for the reconcilers.
|
||||
Logger *zap.SugaredLogger
|
||||
// Clock is used to stamp condition transitions. Defaults to a real clock when unset.
|
||||
Clock tstime.Clock
|
||||
}
|
||||
|
||||
// clockOrDefault returns clock, or a real clock if clock is nil.
|
||||
func clockOrDefault(clock tstime.Clock) tstime.Clock {
|
||||
if clock == nil {
|
||||
return tstime.DefaultClock{}
|
||||
}
|
||||
return clock
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -20,24 +20,54 @@ import (
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/utils/ptr"
|
||||
"sigs.k8s.io/controller-runtime/pkg/builder"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/manager"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/kube/egressservices"
|
||||
)
|
||||
|
||||
// egressEpsReconciler reconciles EndpointSlices for tailnet services exposed to cluster via egress ProxyGroup proxies.
|
||||
type egressEpsReconciler struct {
|
||||
const endpointSliceReconcilerName = "egress-eps-reconciler"
|
||||
|
||||
// EndpointSliceReconciler reconciles EndpointSlices for tailnet services exposed to cluster via egress ProxyGroup proxies.
|
||||
type EndpointSliceReconciler struct {
|
||||
client.Client
|
||||
logger *zap.SugaredLogger
|
||||
tsNamespace string
|
||||
}
|
||||
|
||||
// NewEndpointSliceReconciler returns a new instance of the EndpointSliceReconciler type. It watches the EndpointSlices
|
||||
// for egress services, and the egress Services, ProxyGroup Pods and ProxyGroup state Secrets that decide their
|
||||
// endpoints.
|
||||
func NewEndpointSliceReconciler(options ReconcilerOptions) *EndpointSliceReconciler {
|
||||
return &EndpointSliceReconciler{
|
||||
Client: options.Client,
|
||||
logger: options.Logger.Named(endpointSliceReconcilerName),
|
||||
tsNamespace: options.TailscaleNamespace,
|
||||
}
|
||||
}
|
||||
|
||||
// Register the EndpointSliceReconciler onto the given manager.Manager implementation.
|
||||
func (er *EndpointSliceReconciler) Register(mgr manager.Manager) error {
|
||||
cl := mgr.GetClient()
|
||||
return builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named(endpointSliceReconcilerName).
|
||||
Watches(&discoveryv1.EndpointSlice{}, handler.EnqueueRequestsFromMapFunc(egressEpsHandler)).
|
||||
Watches(&corev1.Pod{}, handler.EnqueueRequestsFromMapFunc(egressEpsFromPGPods(cl, er.tsNamespace))).
|
||||
Watches(&corev1.Secret{}, handler.EnqueueRequestsFromMapFunc(egressEpsFromPGStateSecrets(cl, er.tsNamespace))).
|
||||
Watches(&corev1.Service{}, handler.EnqueueRequestsFromMapFunc(epsFromExternalNameService(cl, er.logger, er.tsNamespace))).
|
||||
Complete(er)
|
||||
}
|
||||
|
||||
// Reconcile reconciles an EndpointSlice for a tailnet service. It updates the EndpointSlice with the endpoints of
|
||||
// those ProxyGroup Pods that are ready to route traffic to the tailnet service.
|
||||
// It compares tailnet service state stored in egress proxy state Secrets by containerboot with the desired
|
||||
// configuration stored in proxy-cfg ConfigMap to determine if the endpoint is ready.
|
||||
func (er *egressEpsReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
func (er *EndpointSliceReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
lg := er.logger.With("Service", req.NamespacedName)
|
||||
lg.Debugf("starting reconcile")
|
||||
defer lg.Debugf("reconcile finished")
|
||||
@@ -60,8 +90,8 @@ func (er *egressEpsReconciler) Reconcile(ctx context.Context, req reconcile.Requ
|
||||
// resources are set up for this tailnet service.
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: eps.Labels[LabelParentName],
|
||||
Namespace: eps.Labels[LabelParentNamespace],
|
||||
Name: eps.Labels[reconciler.LabelParentName],
|
||||
Namespace: eps.Labels[reconciler.LabelParentNamespace],
|
||||
},
|
||||
}
|
||||
err = er.Get(ctx, client.ObjectKeyFromObject(svc), svc)
|
||||
@@ -82,7 +112,7 @@ func (er *egressEpsReconciler) Reconcile(ctx context.Context, req reconcile.Requ
|
||||
lg = lg.With("tailnet-service-name", tailnetSvc)
|
||||
|
||||
// Retrieve the desired tailnet service configuration from the ConfigMap.
|
||||
proxyGroupName := eps.Labels[labelProxyGroup]
|
||||
proxyGroupName := eps.Labels[reconciler.LabelProxyGroup]
|
||||
_, cfgs, err := egressSvcsConfigs(ctx, er.Client, proxyGroupName, er.tsNamespace)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("error retrieving tailnet services configuration: %w", err)
|
||||
@@ -103,7 +133,7 @@ func (er *egressEpsReconciler) Reconcile(ctx context.Context, req reconcile.Requ
|
||||
// Check which Pods in ProxyGroup are ready to route traffic to this
|
||||
// egress service.
|
||||
podList := &corev1.PodList{}
|
||||
if err := er.List(ctx, podList, client.MatchingLabels(pgLabels(proxyGroupName, nil))); err != nil {
|
||||
if err := er.List(ctx, podList, client.MatchingLabels(reconciler.ProxyGroupLabels(proxyGroupName, nil))); err != nil {
|
||||
return res, fmt.Errorf("error listing Pods for ProxyGroup %s: %w", proxyGroupName, err)
|
||||
}
|
||||
newEndpoints := make([]discoveryv1.Endpoint, 0)
|
||||
@@ -169,7 +199,7 @@ func podIPForFamily(pod *corev1.Pod, addrType discoveryv1.AddressType) (string,
|
||||
// podIsReadyToRouteTraffic returns true if it appears that the proxy Pod has configured firewall rules to be able to
|
||||
// route traffic to the given tailnet service. It retrieves the proxy's state Secret and compares the tailnet service
|
||||
// status written there to the desired service configuration.
|
||||
func (er *egressEpsReconciler) podIsReadyToRouteTraffic(ctx context.Context, pod corev1.Pod, cfg *egressservices.Config, tailnetSvcName string, addrType discoveryv1.AddressType, lg *zap.SugaredLogger) (bool, error) {
|
||||
func (er *EndpointSliceReconciler) podIsReadyToRouteTraffic(ctx context.Context, pod corev1.Pod, cfg *egressservices.Config, tailnetSvcName string, addrType discoveryv1.AddressType, lg *zap.SugaredLogger) (bool, error) {
|
||||
lg = lg.With("proxy_pod", pod.Name)
|
||||
lg.Debug("checking whether proxy is ready to route to egress service")
|
||||
if !pod.DeletionTimestamp.IsZero() {
|
||||
+88
-76
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -16,8 +16,11 @@ import (
|
||||
discoveryv1 "k8s.io/api/discovery/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/egress"
|
||||
"tailscale.com/k8s-operator/reconciler/reconcilertest"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/tstest"
|
||||
@@ -32,8 +35,8 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net",
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.bar.ts.net",
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -57,8 +60,7 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
}
|
||||
port := randomPort()
|
||||
cm := configMapForSvc(t, svc, port)
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(svc, cm).
|
||||
WithStatusSubresource(svc).
|
||||
Build()
|
||||
@@ -66,43 +68,43 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
er := &egressEpsReconciler{
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
tsNamespace: "operator-ns",
|
||||
}
|
||||
er := egress.NewEndpointSliceReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
})
|
||||
eps := &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "foo",
|
||||
Namespace: "operator-ns",
|
||||
Labels: map[string]string{
|
||||
LabelParentName: "test",
|
||||
LabelParentNamespace: "default",
|
||||
labelSvcType: typeEgress,
|
||||
labelProxyGroup: "foo"},
|
||||
reconciler.LabelParentName: "test",
|
||||
reconciler.LabelParentNamespace: "default",
|
||||
"tailscale.com/svc-type": "egress",
|
||||
reconciler.LabelProxyGroup: "foo"},
|
||||
},
|
||||
AddressType: discoveryv1.AddressTypeIPv4,
|
||||
}
|
||||
mustCreate(t, fc, eps)
|
||||
reconcilertest.MustCreate(t, fc, eps)
|
||||
|
||||
t.Run("no_proxy_group_resources", func(t *testing.T) {
|
||||
expectReconciled(t, er, "operator-ns", "foo") // should not error
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo") // should not error
|
||||
})
|
||||
|
||||
t.Run("no_pods_ready_to_route_traffic", func(t *testing.T) {
|
||||
pod, stateS := podAndSecretForProxyGroup("foo")
|
||||
mustCreate(t, fc, pod)
|
||||
mustCreate(t, fc, stateS)
|
||||
expectReconciled(t, er, "operator-ns", "foo") // should not error
|
||||
reconcilertest.MustCreate(t, fc, pod)
|
||||
reconcilertest.MustCreate(t, fc, stateS)
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo") // should not error
|
||||
})
|
||||
|
||||
t.Run("pods_are_ready_to_route_traffic", func(t *testing.T) {
|
||||
pod, stateS := podAndSecretForProxyGroup("foo")
|
||||
stBs := serviceStatusForPodIPs(t, svc, pod.Status.PodIPs[0].IP, "", port)
|
||||
mustUpdate(t, fc, "operator-ns", stateS.Name, func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", stateS.Name, func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo")
|
||||
eps.Endpoints = append(eps.Endpoints, discoveryv1.Endpoint{
|
||||
Addresses: []string{"10.0.0.1"},
|
||||
Hostname: new("foo"),
|
||||
@@ -112,17 +114,17 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Terminating: new(false),
|
||||
},
|
||||
})
|
||||
expectEqual(t, fc, eps)
|
||||
reconcilertest.ExpectEqual(t, fc, eps)
|
||||
})
|
||||
t.Run("status_does_not_match_pod_ip", func(t *testing.T) {
|
||||
_, stateS := podAndSecretForProxyGroup("foo") // replica Pod has IP 10.0.0.1
|
||||
stBs := serviceStatusForPodIPs(t, svc, "10.0.0.2", "", port) // status is for a Pod with IP 10.0.0.2
|
||||
mustUpdate(t, fc, "operator-ns", stateS.Name, func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", stateS.Name, func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo")
|
||||
eps.Endpoints = []discoveryv1.Endpoint{}
|
||||
expectEqual(t, fc, eps)
|
||||
reconcilertest.ExpectEqual(t, fc, eps)
|
||||
})
|
||||
|
||||
// Dual-stack.
|
||||
@@ -131,34 +133,34 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Name: "foo-ipv6",
|
||||
Namespace: "operator-ns",
|
||||
Labels: map[string]string{
|
||||
LabelParentName: "test",
|
||||
LabelParentNamespace: "default",
|
||||
labelSvcType: typeEgress,
|
||||
labelProxyGroup: "foo",
|
||||
reconciler.LabelParentName: "test",
|
||||
reconciler.LabelParentNamespace: "default",
|
||||
"tailscale.com/svc-type": "egress",
|
||||
reconciler.LabelProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
AddressType: discoveryv1.AddressTypeIPv6,
|
||||
}
|
||||
mustCreate(t, fc, epsV6)
|
||||
reconcilertest.MustCreate(t, fc, epsV6)
|
||||
t.Run("dual_stack_pod_ready_to_route", func(t *testing.T) {
|
||||
mustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
reconcilertest.MustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
dualPod := &corev1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "foo-0",
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgLabels("foo", nil),
|
||||
Labels: reconciler.ProxyGroupLabels("foo", nil),
|
||||
UID: "foo",
|
||||
},
|
||||
Status: corev1.PodStatus{
|
||||
PodIPs: []corev1.PodIP{{IP: "10.0.0.1"}, {IP: "fd00::1"}},
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, dualPod)
|
||||
reconcilertest.MustCreate(t, fc, dualPod)
|
||||
stBs := serviceStatusForPodIPs(t, svc, "10.0.0.1", "fd00::1", port)
|
||||
mustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo")
|
||||
eps.Endpoints = []discoveryv1.Endpoint{{
|
||||
Addresses: []string{"10.0.0.1"},
|
||||
Hostname: new("foo"),
|
||||
@@ -168,8 +170,8 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Terminating: new(false),
|
||||
},
|
||||
}}
|
||||
expectEqual(t, fc, eps)
|
||||
expectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
reconcilertest.ExpectEqual(t, fc, eps)
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
epsV6.Endpoints = []discoveryv1.Endpoint{{
|
||||
Addresses: []string{"fd00::1"},
|
||||
Hostname: new("foo"),
|
||||
@@ -179,28 +181,28 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Terminating: new(false),
|
||||
},
|
||||
}}
|
||||
expectEqual(t, fc, epsV6)
|
||||
reconcilertest.ExpectEqual(t, fc, epsV6)
|
||||
})
|
||||
|
||||
// IPv6-only.
|
||||
t.Run("ipv4_only_pod_skipped_for_ipv6_slice", func(t *testing.T) {
|
||||
mustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
reconcilertest.MustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
ipv4Pod, _ := podAndSecretForProxyGroup("foo")
|
||||
mustCreate(t, fc, ipv4Pod)
|
||||
reconcilertest.MustCreate(t, fc, ipv4Pod)
|
||||
stBs := serviceStatusForPodIPs(t, svc, "10.0.0.1", "", port)
|
||||
mustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
// IPv4-only pod should not appear in the IPv6 EndpointSlice.
|
||||
epsV6.Endpoints = []discoveryv1.Endpoint{}
|
||||
expectEqual(t, fc, epsV6)
|
||||
reconcilertest.ExpectEqual(t, fc, epsV6)
|
||||
})
|
||||
ipv6Pod := &corev1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "foo-0",
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgLabels("foo", nil),
|
||||
Labels: reconciler.ProxyGroupLabels("foo", nil),
|
||||
UID: "foo",
|
||||
},
|
||||
Status: corev1.PodStatus{
|
||||
@@ -208,22 +210,22 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
},
|
||||
}
|
||||
t.Run("ipv6_status_does_not_match_pod_ip", func(t *testing.T) {
|
||||
mustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
mustCreate(t, fc, ipv6Pod)
|
||||
reconcilertest.MustDeleteAll(t, fc, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo-0", Namespace: "operator-ns"}})
|
||||
reconcilertest.MustCreate(t, fc, ipv6Pod)
|
||||
stBs := serviceStatusForPodIPs(t, svc, "", "fd00::99", port)
|
||||
mustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
epsV6.Endpoints = []discoveryv1.Endpoint{}
|
||||
expectEqual(t, fc, epsV6)
|
||||
reconcilertest.ExpectEqual(t, fc, epsV6)
|
||||
})
|
||||
t.Run("ipv6_pod_ready_to_route", func(t *testing.T) {
|
||||
stBs := serviceStatusForPodIPs(t, svc, "", ipv6Pod.Status.PodIPs[0].IP, port)
|
||||
mustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
reconcilertest.MustUpdate(t, fc, "operator-ns", "foo-0", func(s *corev1.Secret) {
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
})
|
||||
expectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo-ipv6")
|
||||
epsV6.Endpoints = append(epsV6.Endpoints, discoveryv1.Endpoint{
|
||||
Addresses: []string{"fd00::1"},
|
||||
Hostname: new("foo"),
|
||||
@@ -233,7 +235,7 @@ func TestTailscaleEgressEndpointSlices(t *testing.T) {
|
||||
Terminating: new(false),
|
||||
},
|
||||
})
|
||||
expectEqual(t, fc, epsV6)
|
||||
reconcilertest.ExpectEqual(t, fc, epsV6)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -248,8 +250,8 @@ func TestEgressEndpointSliceEndpointsSorted(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net",
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.bar.ts.net",
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -271,16 +273,15 @@ func TestEgressEndpointSliceEndpointsSorted(t *testing.T) {
|
||||
Name: "foo",
|
||||
Namespace: "operator-ns",
|
||||
Labels: map[string]string{
|
||||
LabelParentName: "test",
|
||||
LabelParentNamespace: "default",
|
||||
labelSvcType: typeEgress,
|
||||
labelProxyGroup: "foo",
|
||||
reconciler.LabelParentName: "test",
|
||||
reconciler.LabelParentNamespace: "default",
|
||||
"tailscale.com/svc-type": "egress",
|
||||
reconciler.LabelProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
AddressType: discoveryv1.AddressTypeIPv4,
|
||||
}
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(svc, cm).
|
||||
WithStatusSubresource(svc).
|
||||
Build()
|
||||
@@ -288,8 +289,12 @@ func TestEgressEndpointSliceEndpointsSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
er := &egressEpsReconciler{Client: fc, logger: zl.Sugar(), tsNamespace: "operator-ns"}
|
||||
mustCreate(t, fc, eps)
|
||||
er := egress.NewEndpointSliceReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
})
|
||||
reconcilertest.MustCreate(t, fc, eps)
|
||||
|
||||
// Two ready Pods whose UIDs sort in the opposite order to their creation, so a stable sort is observable.
|
||||
for _, p := range []struct {
|
||||
@@ -300,25 +305,25 @@ func TestEgressEndpointSliceEndpointsSorted(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: p.uid,
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgLabels("foo", nil),
|
||||
Labels: reconciler.ProxyGroupLabels("foo", nil),
|
||||
UID: types.UID(p.uid),
|
||||
},
|
||||
Status: corev1.PodStatus{PodIPs: []corev1.PodIP{{IP: p.ip}}},
|
||||
}
|
||||
mustCreate(t, fc, pod)
|
||||
reconcilertest.MustCreate(t, fc, pod)
|
||||
s := &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: p.uid,
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgSecretLabels("foo", kubetypes.LabelSecretTypeState),
|
||||
Labels: stateSecretLabels("foo"),
|
||||
},
|
||||
}
|
||||
stBs := serviceStatusForPodIPs(t, svc, p.ip, "", port)
|
||||
mak.Set(&s.Data, egressservices.KeyEgressServices, stBs)
|
||||
mustCreate(t, fc, s)
|
||||
reconcilertest.MustCreate(t, fc, s)
|
||||
}
|
||||
|
||||
expectReconciled(t, er, "operator-ns", "foo")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo")
|
||||
got := &discoveryv1.EndpointSlice{}
|
||||
if err := fc.Get(t.Context(), types.NamespacedName{Name: "foo", Namespace: "operator-ns"}, got); err != nil {
|
||||
t.Fatalf("getting EndpointSlice: %v", err)
|
||||
@@ -332,7 +337,7 @@ func TestEgressEndpointSliceEndpointsSorted(t *testing.T) {
|
||||
|
||||
// A second reconcile over the unchanged ready set must not rewrite the slice.
|
||||
rvBefore := got.ResourceVersion
|
||||
expectReconciled(t, er, "operator-ns", "foo")
|
||||
reconcilertest.ExpectReconciled(t, er, "operator-ns", "foo")
|
||||
after := &discoveryv1.EndpointSlice{}
|
||||
if err := fc.Get(t.Context(), types.NamespacedName{Name: "foo", Namespace: "operator-ns"}, after); err != nil {
|
||||
t.Fatalf("getting EndpointSlice: %v", err)
|
||||
@@ -351,10 +356,10 @@ func configMapForSvc(t *testing.T, svc *corev1.Service, p uint16) *corev1.Config
|
||||
cfg := egressservices.Config{
|
||||
Ports: ports,
|
||||
}
|
||||
if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
if fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
cfg.TailnetTarget = egressservices.TailnetTarget{FQDN: fqdn}
|
||||
}
|
||||
if ip := svc.Annotations[AnnotationTailnetTargetIP]; ip != "" {
|
||||
if ip := svc.Annotations[reconciler.AnnotationTailnetTargetIP]; ip != "" {
|
||||
cfg.TailnetTarget = egressservices.TailnetTarget{IP: ip}
|
||||
}
|
||||
name := tailnetSvcName(svc)
|
||||
@@ -365,7 +370,7 @@ func configMapForSvc(t *testing.T, svc *corev1.Service, p uint16) *corev1.Config
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName(svc.Annotations[AnnotationProxyGroup]),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName(svc.Annotations[reconciler.AnnotationProxyGroup]),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
BinaryData: map[string][]byte{egressservices.KeyEgressServices: bs},
|
||||
@@ -380,10 +385,10 @@ func serviceStatusForPodIPs(t *testing.T, svc *corev1.Service, ipv4, ipv6 string
|
||||
ports[egressservices.PortMap{Protocol: string(port.Protocol), MatchPort: p, TargetPort: uint16(port.Port)}] = struct{}{}
|
||||
}
|
||||
svcSt := egressservices.ServiceStatus{Ports: ports}
|
||||
if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
if fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
svcSt.TailnetTarget = egressservices.TailnetTarget{FQDN: fqdn}
|
||||
}
|
||||
if ip := svc.Annotations[AnnotationTailnetTargetIP]; ip != "" {
|
||||
if ip := svc.Annotations[reconciler.AnnotationTailnetTargetIP]; ip != "" {
|
||||
svcSt.TailnetTarget = egressservices.TailnetTarget{IP: ip}
|
||||
}
|
||||
svcName := tailnetSvcName(svc)
|
||||
@@ -404,7 +409,7 @@ func podAndSecretForProxyGroup(pg string) (*corev1.Pod, *corev1.Secret) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: fmt.Sprintf("%s-0", pg),
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgLabels(pg, nil),
|
||||
Labels: reconciler.ProxyGroupLabels(pg, nil),
|
||||
UID: "foo",
|
||||
},
|
||||
Status: corev1.PodStatus{
|
||||
@@ -417,7 +422,7 @@ func podAndSecretForProxyGroup(pg string) (*corev1.Pod, *corev1.Secret) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: fmt.Sprintf("%s-0", pg),
|
||||
Namespace: "operator-ns",
|
||||
Labels: pgSecretLabels(pg, kubetypes.LabelSecretTypeState),
|
||||
Labels: stateSecretLabels(pg),
|
||||
},
|
||||
}
|
||||
return p, s
|
||||
@@ -426,3 +431,10 @@ func podAndSecretForProxyGroup(pg string) (*corev1.Pod, *corev1.Secret) {
|
||||
func randomPort() uint16 {
|
||||
return uint16(rand.Int32N(1000) + 1000)
|
||||
}
|
||||
|
||||
// stateSecretLabels returns the labels that the ProxyGroup reconciler sets on the state Secrets of the named ProxyGroup.
|
||||
func stateSecretLabels(pgName string) map[string]string {
|
||||
return reconciler.ProxyGroupLabels(pgName, map[string]string{
|
||||
kubetypes.LabelSecretType: kubetypes.LabelSecretTypeState,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
discoveryv1 "k8s.io/api/discovery/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
)
|
||||
|
||||
// egressSvcsHandler returns accepts a Kubernetes object and returns a reconcile
|
||||
// request for it , if the object is a Tailscale egress Service meant to be
|
||||
// exposed on a ProxyGroup.
|
||||
func egressSvcsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if !isEgressSvcForProxyGroup(o) {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsHandler returns accepts an EndpointSlice and, if the EndpointSlice
|
||||
// is for an egress service, returns a reconcile request for it.
|
||||
func egressEpsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[labelSvcType]; typ != typeEgress {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func egressPodsHandler(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[reconciler.LabelParentType]; typ != reconciler.ParentTypeProxyGroup {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: o.GetNamespace(),
|
||||
Name: o.GetName(),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsFromEgressPods returns a Pod event handler that checks if Pod is a replica for a ProxyGroup and if it is,
|
||||
// returns reconciler requests for all egress EndpointSlices for that ProxyGroup.
|
||||
func egressEpsFromPGPods(cl client.Client, ns string) handler.MapFunc {
|
||||
return func(_ context.Context, o client.Object) []reconcile.Request {
|
||||
// TODO(irbekrm): for now this is good enough as all ProxyGroups are egress. Add a type check once we
|
||||
// have ingress ProxyGroups.
|
||||
if !reconciler.IsManagedByType(o, reconciler.ParentTypeProxyGroup) {
|
||||
return nil
|
||||
}
|
||||
pg, ok := o.GetLabels()[reconciler.LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return reconcileRequestsForPG(pg, cl, ns)
|
||||
}
|
||||
}
|
||||
|
||||
// egressEpsFromPGStateSecrets returns a Secret event handler that checks if Secret is a state Secret for a ProxyGroup and if it is,
|
||||
// returns reconciler requests for all egress EndpointSlices for that ProxyGroup.
|
||||
func egressEpsFromPGStateSecrets(cl client.Client, ns string) handler.MapFunc {
|
||||
return func(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if !reconciler.IsManagedByType(o, reconciler.ParentTypeProxyGroup) {
|
||||
return nil
|
||||
}
|
||||
if secretType := o.GetLabels()[kubetypes.LabelSecretType]; secretType != kubetypes.LabelSecretTypeState {
|
||||
return nil
|
||||
}
|
||||
pg, ok := o.GetLabels()[reconciler.LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return reconcileRequestsForPG(pg, cl, ns)
|
||||
}
|
||||
}
|
||||
|
||||
func reconcileRequestsForPG(pg string, cl client.Client, ns string) []reconcile.Request {
|
||||
epsList := discoveryv1.EndpointSliceList{}
|
||||
if err := cl.List(context.Background(), &epsList,
|
||||
client.InNamespace(ns),
|
||||
client.MatchingLabels(map[string]string{reconciler.LabelProxyGroup: pg})); err != nil {
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, ep := range epsList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: ep.Namespace,
|
||||
Name: ep.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
|
||||
// egressSvcFromEps is an event handler for EndpointSlices. If an EndpointSlice is for an egress ExternalName Service
|
||||
// meant to be exposed on a ProxyGroup, returns a reconcile request for the Service.
|
||||
func egressSvcFromEps(_ context.Context, o client.Object) []reconcile.Request {
|
||||
if typ := o.GetLabels()[labelSvcType]; typ != typeEgress {
|
||||
return nil
|
||||
}
|
||||
if v, ok := o.GetLabels()[kubetypes.LabelManaged]; !ok || v != "true" {
|
||||
return nil
|
||||
}
|
||||
svcName, ok := o.GetLabels()[reconciler.LabelParentName]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
svcNs, ok := o.GetLabels()[reconciler.LabelParentNamespace]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return []reconcile.Request{
|
||||
{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: svcNs,
|
||||
Name: svcName,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// egressSvcsFromEgressProxyGroup is an event handler for egress ProxyGroups. It returns reconcile requests for all
|
||||
// user-created ExternalName Services that should be exposed on this ProxyGroup.
|
||||
func egressSvcsFromEgressProxyGroup(cl client.Client, logger *zap.SugaredLogger) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
pg, ok := o.(*tsapi.ProxyGroup)
|
||||
if !ok {
|
||||
logger.Warn("ProxyGroup handler triggered for an object that is not a ProxyGroup")
|
||||
return nil
|
||||
}
|
||||
|
||||
if pg.Spec.Type != tsapi.ProxyGroupTypeEgress {
|
||||
return nil
|
||||
}
|
||||
svcList := &corev1.ServiceList{}
|
||||
if err := cl.List(ctx, svcList, client.MatchingFields{indexEgressProxyGroup: pg.Name}); err != nil {
|
||||
logger.Infof("error listing Services: %v, skipping a reconcile for event on ProxyGroup %s", err, pg.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, svc := range svcList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: svc.Namespace,
|
||||
Name: svc.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
// epsFromExternalNameService is an event handler for ExternalName Services that define a Tailscale egress service that
|
||||
// should be exposed on a ProxyGroup. It returns reconcile requests for EndpointSlices created for this Service.
|
||||
func epsFromExternalNameService(cl client.Client, logger *zap.SugaredLogger, ns string) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
svc, ok := o.(*corev1.Service)
|
||||
if !ok {
|
||||
logger.Warn("Service handler triggered for an object that is not a Service")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isEgressSvcForProxyGroup(svc) {
|
||||
return nil
|
||||
}
|
||||
epsList := &discoveryv1.EndpointSliceList{}
|
||||
if err := cl.List(ctx, epsList, client.InNamespace(ns),
|
||||
client.MatchingLabels(egressSvcChildResourceLabels(svc))); err != nil {
|
||||
logger.Infof("error listing EndpointSlices: %v, skipping a reconcile for event on Service %s", err, svc.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, eps := range epsList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: eps.Namespace,
|
||||
Name: eps.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
func podsFromEgressEps(cl client.Client, logger *zap.SugaredLogger, ns string) handler.MapFunc {
|
||||
return func(ctx context.Context, o client.Object) []reconcile.Request {
|
||||
eps, ok := o.(*discoveryv1.EndpointSlice)
|
||||
if !ok {
|
||||
logger.Warn("EndpointSlice handler triggered for an object that is not a EndpointSlice")
|
||||
return nil
|
||||
}
|
||||
|
||||
if eps.Labels[reconciler.LabelProxyGroup] == "" {
|
||||
return nil
|
||||
}
|
||||
if eps.Labels[labelSvcType] != "egress" {
|
||||
return nil
|
||||
}
|
||||
podLabels := reconciler.ProxyGroupLabels(eps.Labels[reconciler.LabelProxyGroup], nil)
|
||||
podList := &corev1.PodList{}
|
||||
if err := cl.List(ctx, podList, client.InNamespace(ns),
|
||||
client.MatchingLabels(podLabels)); err != nil {
|
||||
logger.Infof("error listing EndpointSlices: %v, skipping a reconcile for event on EndpointSlice %s", err, eps.Name)
|
||||
return nil
|
||||
}
|
||||
reqs := make([]reconcile.Request, 0)
|
||||
for _, pod := range podList.Items {
|
||||
reqs = append(reqs, reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{
|
||||
Namespace: pod.Namespace,
|
||||
Name: pod.Name,
|
||||
},
|
||||
})
|
||||
}
|
||||
return reqs
|
||||
}
|
||||
}
|
||||
|
||||
// indexEgressServices adds a local index to cached Tailscale egress Services meant to be exposed on a ProxyGroup. The
|
||||
// index is used a list filter.
|
||||
func indexEgressServices(o client.Object) []string {
|
||||
if !isEgressSvcForProxyGroup(o) {
|
||||
return nil
|
||||
}
|
||||
return []string{o.GetAnnotations()[reconciler.AnnotationProxyGroup]}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -18,32 +18,57 @@ import (
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/builder"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/manager"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/set"
|
||||
)
|
||||
|
||||
const tsEgressReadinessGate = "tailscale.com/egress-services"
|
||||
const podReconcilerName = "egress-pods-readiness-reconciler"
|
||||
|
||||
// egressPodsReconciler is responsible for setting tailscale.com/egress-services condition on egress ProxyGroup Pods.
|
||||
// PodReconciler is responsible for setting tailscale.com/egress-services condition on egress ProxyGroup Pods.
|
||||
// The condition is used as a readiness gate for the Pod, meaning that kubelet will not mark the Pod as ready before the
|
||||
// condition is set. The ProxyGroup StatefulSet updates are rolled out in such a way that no Pod is restarted, before
|
||||
// the previous Pod is marked as ready, so ensuring that the Pod does not get marked as ready when it is not yet able to
|
||||
// route traffic for egress service prevents downtime during restarts caused by no available endpoints left because
|
||||
// every Pod has been recreated and is not yet added to endpoints.
|
||||
// https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate
|
||||
type egressPodsReconciler struct {
|
||||
type PodReconciler struct {
|
||||
client.Client
|
||||
logger *zap.SugaredLogger
|
||||
tsNamespace string
|
||||
clock tstime.Clock
|
||||
}
|
||||
|
||||
// NewPodReconciler returns a new instance of the PodReconciler type. It watches ProxyGroup Pods and the EndpointSlices
|
||||
// for egress services.
|
||||
func NewPodReconciler(options ReconcilerOptions) *PodReconciler {
|
||||
return &PodReconciler{
|
||||
Client: options.Client,
|
||||
logger: options.Logger.Named(podReconcilerName),
|
||||
tsNamespace: options.TailscaleNamespace,
|
||||
clock: clockOrDefault(options.Clock),
|
||||
}
|
||||
}
|
||||
|
||||
// Register the PodReconciler onto the given manager.Manager implementation.
|
||||
func (er *PodReconciler) Register(mgr manager.Manager) error {
|
||||
return builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named(podReconcilerName).
|
||||
Watches(&discoveryv1.EndpointSlice{}, handler.EnqueueRequestsFromMapFunc(podsFromEgressEps(mgr.GetClient(), er.logger, er.tsNamespace))).
|
||||
Watches(&corev1.Pod{}, handler.EnqueueRequestsFromMapFunc(egressPodsHandler)).
|
||||
Complete(er)
|
||||
}
|
||||
|
||||
// Reconcile reconciles an egress ProxyGroup Pods on changes to those Pods and ProxyGroup EndpointSlices. It ensures
|
||||
// that for each Pod who is ready to route traffic to all egress services for the ProxyGroup, the Pod has a
|
||||
// tailscale.com/egress-services condition to set, so that kubelet will mark the Pod as ready.
|
||||
@@ -52,7 +77,7 @@ type egressPodsReconciler struct {
|
||||
// EndpointSlices (egress-eps-reconciler), which only adds a Pod once the Pod's state Secret shows that the proxy has
|
||||
// set up routing for that egress service. So a Pod is ready once, for every egress service for the ProxyGroup, it is
|
||||
// an endpoint in the EndpointSlice of each IP family that the proxy reports an address for in its state Secret.
|
||||
func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
func (er *PodReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
lg := er.logger.With("Pod", req.NamespacedName)
|
||||
lg.Debugf("starting reconcile")
|
||||
defer lg.Debugf("reconcile finished")
|
||||
@@ -70,7 +95,7 @@ func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Req
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if pod.Labels[LabelParentType] != proxyTypeProxyGroup {
|
||||
if pod.Labels[reconciler.LabelParentType] != reconciler.ParentTypeProxyGroup {
|
||||
lg.Warn("reconciler called for a Pod that is not a ProxyGroup Pod")
|
||||
return res, nil
|
||||
}
|
||||
@@ -78,13 +103,13 @@ func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Req
|
||||
// If the Pod does not have the readiness gate set, there is no need to add the readiness condition. In practice
|
||||
// this will happen if the user has configured custom TS_LOCAL_ADDR_PORT, thus disabling the graceful failover.
|
||||
if !slices.ContainsFunc(pod.Spec.ReadinessGates, func(r corev1.PodReadinessGate) bool {
|
||||
return r.ConditionType == tsEgressReadinessGate
|
||||
return r.ConditionType == reconciler.EgressReadinessGate
|
||||
}) {
|
||||
lg.Debug("Pod does not have egress readiness gate set, skipping")
|
||||
return res, nil
|
||||
}
|
||||
|
||||
proxyGroupName := pod.Labels[LabelParentName]
|
||||
proxyGroupName := pod.Labels[reconciler.LabelParentName]
|
||||
pg := new(tsapi.ProxyGroup)
|
||||
if err := er.Get(ctx, types.NamespacedName{Name: proxyGroupName}, pg); err != nil {
|
||||
return res, fmt.Errorf("error getting ProxyGroup %q: %w", proxyGroupName, err)
|
||||
@@ -97,9 +122,9 @@ func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Req
|
||||
|
||||
// Get all ClusterIP Services for all egress targets exposed to cluster via this ProxyGroup.
|
||||
lbls := map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
labelProxyGroup: proxyGroupName,
|
||||
labelSvcType: typeEgress,
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelProxyGroup: proxyGroupName,
|
||||
labelSvcType: typeEgress,
|
||||
}
|
||||
svcs := &corev1.ServiceList{}
|
||||
if err := er.List(ctx, svcs, client.InNamespace(er.tsNamespace), client.MatchingLabels(lbls)); err != nil {
|
||||
@@ -107,7 +132,7 @@ func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Req
|
||||
}
|
||||
|
||||
idx := xslices.IndexFunc(pod.Status.Conditions, func(c corev1.PodCondition) bool {
|
||||
return c.Type == tsEgressReadinessGate
|
||||
return c.Type == reconciler.EgressReadinessGate
|
||||
})
|
||||
if idx != -1 {
|
||||
lg.Debugf("Pod is already ready, do nothing")
|
||||
@@ -159,7 +184,7 @@ func (er *egressPodsReconciler) Reconcile(ctx context.Context, req reconcile.Req
|
||||
|
||||
// reportedFamilies returns the IP families that the proxy reports addresses for in the egress services status in its
|
||||
// state Secret. It returns an empty set if the proxy has not yet written the status.
|
||||
func (er *egressPodsReconciler) reportedFamilies(ctx context.Context, pod *corev1.Pod) (set.Set[discoveryv1.AddressType], error) {
|
||||
func (er *PodReconciler) reportedFamilies(ctx context.Context, pod *corev1.Pod) (set.Set[discoveryv1.AddressType], error) {
|
||||
families := make(set.Set[discoveryv1.AddressType])
|
||||
stateS := &corev1.Secret{}
|
||||
err := er.Get(ctx, types.NamespacedName{Namespace: pod.Namespace, Name: pod.Name}, stateS)
|
||||
@@ -188,15 +213,15 @@ func (er *egressPodsReconciler) reportedFamilies(ctx context.Context, pod *corev
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func (er *egressPodsReconciler) setPodReady(ctx context.Context, pod *corev1.Pod, lg *zap.SugaredLogger) error {
|
||||
func (er *PodReconciler) setPodReady(ctx context.Context, pod *corev1.Pod, lg *zap.SugaredLogger) error {
|
||||
if slices.ContainsFunc(pod.Status.Conditions, func(c corev1.PodCondition) bool {
|
||||
return c.Type == tsEgressReadinessGate
|
||||
return c.Type == reconciler.EgressReadinessGate
|
||||
}) {
|
||||
return nil
|
||||
}
|
||||
lg.Infof("Pod is ready to route traffic to all egress targets")
|
||||
pod.Status.Conditions = append(pod.Status.Conditions, corev1.PodCondition{
|
||||
Type: tsEgressReadinessGate,
|
||||
Type: reconciler.EgressReadinessGate,
|
||||
Status: corev1.ConditionTrue,
|
||||
LastTransitionTime: metav1.Time{Time: er.clock.Now()},
|
||||
})
|
||||
+24
-23
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -16,9 +16,11 @@ import (
|
||||
discoveryv1 "k8s.io/api/discovery/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/egress"
|
||||
"tailscale.com/k8s-operator/reconciler/reconcilertest"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/tstest"
|
||||
@@ -139,13 +141,13 @@ func TestEgressPodReadiness(t *testing.T) {
|
||||
Name: "pod",
|
||||
UID: podUID,
|
||||
Labels: map[string]string{
|
||||
LabelParentType: "proxygroup",
|
||||
LabelParentName: "dev",
|
||||
reconciler.LabelParentType: "proxygroup",
|
||||
reconciler.LabelParentName: "dev",
|
||||
},
|
||||
},
|
||||
Spec: corev1.PodSpec{
|
||||
ReadinessGates: []corev1.PodReadinessGate{{
|
||||
ConditionType: tsEgressReadinessGate,
|
||||
ConditionType: reconciler.EgressReadinessGate,
|
||||
}},
|
||||
},
|
||||
}
|
||||
@@ -161,36 +163,35 @@ func TestEgressPodReadiness(t *testing.T) {
|
||||
}
|
||||
// We need to pass a Pod object to WithStatusSubresource because of some quirks in how the fake client
|
||||
// works. Without this code we would not be able to update Pod's status further down.
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(append(tt.objs, pod, pg, stateS)...).
|
||||
WithStatusSubresource(&corev1.Pod{}).
|
||||
Build()
|
||||
zl, _ := zap.NewDevelopment()
|
||||
cl := tstest.NewClock(tstest.ClockOpts{})
|
||||
rec := &egressPodsReconciler{
|
||||
tsNamespace: "operator-ns",
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: cl,
|
||||
}
|
||||
rec := egress.NewPodReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: cl,
|
||||
})
|
||||
|
||||
if !tt.wantReady {
|
||||
expectRequeue(t, rec, "operator-ns", pod.Name)
|
||||
expectEqual(t, fc, pod)
|
||||
reconcilertest.ExpectRequeue(t, rec, "operator-ns", pod.Name)
|
||||
reconcilertest.ExpectEqual(t, fc, pod)
|
||||
return
|
||||
}
|
||||
expectReconciled(t, rec, "operator-ns", pod.Name)
|
||||
reconcilertest.ExpectReconciled(t, rec, "operator-ns", pod.Name)
|
||||
pod.Status.Conditions = append(pod.Status.Conditions, corev1.PodCondition{
|
||||
Type: tsEgressReadinessGate,
|
||||
Type: reconciler.EgressReadinessGate,
|
||||
Status: corev1.ConditionTrue,
|
||||
LastTransitionTime: metav1.Time{Time: cl.Now().Truncate(time.Second)},
|
||||
})
|
||||
expectEqual(t, fc, pod)
|
||||
reconcilertest.ExpectEqual(t, fc, pod)
|
||||
|
||||
// A subsequent reconcile should not change the Pod.
|
||||
expectReconciled(t, rec, "operator-ns", pod.Name)
|
||||
expectEqual(t, fc, pod)
|
||||
reconcilertest.ExpectReconciled(t, rec, "operator-ns", pod.Name)
|
||||
reconcilertest.ExpectEqual(t, fc, pod)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -232,8 +233,8 @@ func newEps(svcName string, addrType discoveryv1.AddressType, podUIDs ...string)
|
||||
// "dev" ProxyGroup.
|
||||
func egressLabels() map[string]string {
|
||||
return map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
labelProxyGroup: "dev",
|
||||
labelSvcType: typeEgress,
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelProxyGroup: "dev",
|
||||
"tailscale.com/svc-type": "egress",
|
||||
}
|
||||
}
|
||||
+36
-8
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -19,11 +19,15 @@ import (
|
||||
apiequality "k8s.io/apimachinery/pkg/api/equality"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/builder"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/manager"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/set"
|
||||
)
|
||||
@@ -38,18 +42,42 @@ const (
|
||||
msgReadyToRouteTemplate = "%d out of %d replicas are ready to route traffic"
|
||||
)
|
||||
|
||||
type egressSvcsReadinessReconciler struct {
|
||||
const readinessReconcilerName = "egress-svcs-readiness-reconciler"
|
||||
|
||||
// ReadinessReconciler sets the EgressSvcReady condition on egress Services for ProxyGroups.
|
||||
type ReadinessReconciler struct {
|
||||
client.Client
|
||||
logger *zap.SugaredLogger
|
||||
clock tstime.Clock
|
||||
tsNamespace string
|
||||
}
|
||||
|
||||
// NewReadinessReconciler returns a new instance of the ReadinessReconciler type. It watches egress Services for
|
||||
// ProxyGroups and the EndpointSlices created for them.
|
||||
func NewReadinessReconciler(options ReconcilerOptions) *ReadinessReconciler {
|
||||
return &ReadinessReconciler{
|
||||
Client: options.Client,
|
||||
logger: options.Logger.Named(readinessReconcilerName),
|
||||
clock: clockOrDefault(options.Clock),
|
||||
tsNamespace: options.TailscaleNamespace,
|
||||
}
|
||||
}
|
||||
|
||||
// Register the ReadinessReconciler onto the given manager.Manager implementation.
|
||||
func (esrr *ReadinessReconciler) Register(mgr manager.Manager) error {
|
||||
return builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named(readinessReconcilerName).
|
||||
Watches(&corev1.Service{}, handler.EnqueueRequestsFromMapFunc(egressSvcsHandler)).
|
||||
Watches(&discoveryv1.EndpointSlice{}, handler.EnqueueRequestsFromMapFunc(egressSvcFromEps)).
|
||||
Complete(esrr)
|
||||
}
|
||||
|
||||
// Reconcile reconciles an ExternalName Service that defines a tailnet target to be exposed on a ProxyGroup and sets the
|
||||
// EgressSvcReady condition on it. The condition gets set to true if at least one of the proxies is currently ready to
|
||||
// route traffic to the target. It compares proxy Pod IPs with the endpoints set on the EndpointSlice for the egress
|
||||
// service to determine how many replicas are currently able to route traffic.
|
||||
func (esrr *egressSvcsReadinessReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
func (esrr *ReadinessReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
lg := esrr.logger.With("Service", req.NamespacedName)
|
||||
lg.Debugf("starting reconcile")
|
||||
defer lg.Debugf("reconcile finished")
|
||||
@@ -88,7 +116,7 @@ func (esrr *egressSvcsReadinessReconciler) Reconcile(ctx context.Context, req re
|
||||
return res, nil
|
||||
}
|
||||
// If an EndpointSlice for an expected family is missing, we mark the Service as NotReady.
|
||||
clusterIPSvc, err := getSingleObject[corev1.Service](ctx, esrr.Client, esrr.tsNamespace, crl)
|
||||
clusterIPSvc, err := reconciler.GetSingleObject[corev1.Service](ctx, esrr.Client, esrr.tsNamespace, crl)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error retrieving ClusterIP Service: %w", err)
|
||||
reason = reasonReadinessCheckFailed
|
||||
@@ -121,7 +149,7 @@ func (esrr *egressSvcsReadinessReconciler) Reconcile(ctx context.Context, req re
|
||||
}
|
||||
pg := &tsapi.ProxyGroup{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: svc.Annotations[AnnotationProxyGroup],
|
||||
Name: svc.Annotations[reconciler.AnnotationProxyGroup],
|
||||
},
|
||||
}
|
||||
err = esrr.Get(ctx, client.ObjectKeyFromObject(pg), pg)
|
||||
@@ -144,19 +172,19 @@ func (esrr *egressSvcsReadinessReconciler) Reconcile(ctx context.Context, req re
|
||||
return res, nil
|
||||
}
|
||||
|
||||
replicas := pgReplicas(pg)
|
||||
replicas := reconciler.ProxyGroupReplicas(pg)
|
||||
if replicas == 0 {
|
||||
lg.Infof("ProxyGroup replicas set to 0")
|
||||
reason, msg = reasonNoProxies, reasonNoProxies
|
||||
st = metav1.ConditionFalse
|
||||
return res, nil
|
||||
}
|
||||
podLabels := pgLabels(pg.Name, nil)
|
||||
podLabels := reconciler.ProxyGroupLabels(pg.Name, nil)
|
||||
var readyReplicas int32
|
||||
nextReplica:
|
||||
for i := range replicas {
|
||||
podLabels[appsv1.PodIndexLabel] = fmt.Sprintf("%d", i)
|
||||
pod, err := getSingleObject[corev1.Pod](ctx, esrr.Client, esrr.tsNamespace, podLabels)
|
||||
pod, err := reconciler.GetSingleObject[corev1.Pod](ctx, esrr.Client, esrr.tsNamespace, podLabels)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error retrieving ProxyGroup Pod: %w", err)
|
||||
reason = reasonReadinessCheckFailed
|
||||
+108
-108
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -14,9 +14,12 @@ import (
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
discoveryv1 "k8s.io/api/discovery/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/egress"
|
||||
"tailscale.com/k8s-operator/reconciler/reconcilertest"
|
||||
"tailscale.com/tstest"
|
||||
"tailscale.com/tstime"
|
||||
)
|
||||
@@ -24,26 +27,25 @@ import (
|
||||
func TestEgressServiceReadiness(t *testing.T) {
|
||||
// We need to pass a ProxyGroup object to WithStatusSubresource because of some quirks in how the fake client
|
||||
// works. Without this code further down would not be able to update ProxyGroup status.
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithStatusSubresource(&tsapi.ProxyGroup{}).
|
||||
Build()
|
||||
zl, _ := zap.NewDevelopment()
|
||||
cl := tstest.NewClock(tstest.ClockOpts{})
|
||||
rec := &egressSvcsReadinessReconciler{
|
||||
tsNamespace: "operator-ns",
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: cl,
|
||||
}
|
||||
rec := egress.NewReadinessReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: cl,
|
||||
})
|
||||
tailnetFQDN := "my-app.tailnetxyz.ts.net"
|
||||
egressSvc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "dev",
|
||||
Annotations: map[string]string{
|
||||
AnnotationProxyGroup: "dev",
|
||||
AnnotationTailnetTargetFQDN: tailnetFQDN,
|
||||
reconciler.AnnotationProxyGroup: "dev",
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetFQDN,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -51,11 +53,11 @@ func TestEgressServiceReadiness(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "operator-ns",
|
||||
Labels: egressSvcChildResourceLabels(egressSvc),
|
||||
Labels: childResourceLabels(egressSvc),
|
||||
},
|
||||
Spec: corev1.ServiceSpec{ClusterIPs: []string{"10.0.0.1"}},
|
||||
}
|
||||
labels := egressSvcEpsLabels(egressSvc, fakeClusterIPSvc)
|
||||
labels := epsLabels(egressSvc, fakeClusterIPSvc)
|
||||
eps := &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
@@ -69,83 +71,82 @@ func TestEgressServiceReadiness(t *testing.T) {
|
||||
Name: "dev",
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, egressSvc)
|
||||
mustCreate(t, fc, fakeClusterIPSvc)
|
||||
reconcilertest.MustCreate(t, fc, egressSvc)
|
||||
reconcilertest.MustCreate(t, fc, fakeClusterIPSvc)
|
||||
setClusterNotReady(egressSvc, cl, zl.Sugar())
|
||||
t.Run("endpointslice_does_not_exist", func(t *testing.T) {
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc) // not ready
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // not ready
|
||||
})
|
||||
t.Run("proxy_group_does_not_exist", func(t *testing.T) {
|
||||
mustCreate(t, fc, eps)
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc) // still not ready
|
||||
reconcilertest.MustCreate(t, fc, eps)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // still not ready
|
||||
})
|
||||
t.Run("proxy_group_not_ready", func(t *testing.T) {
|
||||
mustCreate(t, fc, pg)
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc) // still not ready
|
||||
reconcilertest.MustCreate(t, fc, pg)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // still not ready
|
||||
})
|
||||
t.Run("no_ready_replicas", func(t *testing.T) {
|
||||
setPGReady(pg, cl, zl.Sugar())
|
||||
mustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
reconcilertest.MustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
p.Status = pg.Status
|
||||
})
|
||||
expectEqual(t, fc, pg)
|
||||
for i := range pgReplicas(pg) {
|
||||
reconcilertest.ExpectEqual(t, fc, pg)
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
p := pod(pg, i)
|
||||
mustCreate(t, fc, p)
|
||||
mustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
reconcilertest.MustCreate(t, fc, p)
|
||||
reconcilertest.MustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
existing.Status.PodIPs = p.Status.PodIPs
|
||||
})
|
||||
}
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg))
|
||||
expectEqual(t, fc, egressSvc) // still not ready
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // still not ready
|
||||
})
|
||||
t.Run("one_ready_replica", func(t *testing.T) {
|
||||
setEndpointForReplica(pg, 0, eps)
|
||||
mustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
reconcilertest.MustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Endpoints = eps.Endpoints
|
||||
})
|
||||
setReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg), 1)
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc) // partially ready
|
||||
setReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg), 1)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // partially ready
|
||||
})
|
||||
t.Run("all_replicas_ready", func(t *testing.T) {
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
setEndpointForReplica(pg, i, eps)
|
||||
}
|
||||
mustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
reconcilertest.MustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Endpoints = eps.Endpoints
|
||||
})
|
||||
setReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg), pgReplicas(pg))
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc) // ready
|
||||
setReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc) // ready
|
||||
})
|
||||
}
|
||||
|
||||
func TestEgressServiceReadinessDualStack(t *testing.T) {
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithStatusSubresource(&tsapi.ProxyGroup{}).
|
||||
Build()
|
||||
zl, _ := zap.NewDevelopment()
|
||||
cl := tstest.NewClock(tstest.ClockOpts{})
|
||||
rec := &egressSvcsReadinessReconciler{
|
||||
tsNamespace: "operator-ns",
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: cl,
|
||||
}
|
||||
rec := egress.NewReadinessReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: cl,
|
||||
})
|
||||
tailnetFQDN := "my-app.tailnetxyz.ts.net"
|
||||
egressSvc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "dev",
|
||||
Annotations: map[string]string{
|
||||
AnnotationProxyGroup: "dev",
|
||||
AnnotationTailnetTargetFQDN: tailnetFQDN,
|
||||
reconciler.AnnotationProxyGroup: "dev",
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetFQDN,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -153,11 +154,11 @@ func TestEgressServiceReadinessDualStack(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "operator-ns",
|
||||
Labels: egressSvcChildResourceLabels(egressSvc),
|
||||
Labels: childResourceLabels(egressSvc),
|
||||
},
|
||||
Spec: corev1.ServiceSpec{ClusterIPs: []string{"10.0.0.1", "fd00::1"}},
|
||||
}
|
||||
labels := egressSvcEpsLabels(egressSvc, fakeClusterIPSvc)
|
||||
labels := epsLabels(egressSvc, fakeClusterIPSvc)
|
||||
epsV4 := &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app-ipv4",
|
||||
@@ -166,7 +167,7 @@ func TestEgressServiceReadinessDualStack(t *testing.T) {
|
||||
},
|
||||
AddressType: discoveryv1.AddressTypeIPv4,
|
||||
}
|
||||
labelsV6 := egressSvcEpsLabels(egressSvc, fakeClusterIPSvc)
|
||||
labelsV6 := epsLabels(egressSvc, fakeClusterIPSvc)
|
||||
epsV6 := &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app-ipv6",
|
||||
@@ -184,41 +185,41 @@ func TestEgressServiceReadinessDualStack(t *testing.T) {
|
||||
Type: tsapi.ProxyGroupTypeEgress,
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, egressSvc)
|
||||
mustCreate(t, fc, fakeClusterIPSvc)
|
||||
mustCreate(t, fc, epsV4)
|
||||
mustCreate(t, fc, epsV6)
|
||||
mustCreate(t, fc, pg)
|
||||
reconcilertest.MustCreate(t, fc, egressSvc)
|
||||
reconcilertest.MustCreate(t, fc, fakeClusterIPSvc)
|
||||
reconcilertest.MustCreate(t, fc, epsV4)
|
||||
reconcilertest.MustCreate(t, fc, epsV6)
|
||||
reconcilertest.MustCreate(t, fc, pg)
|
||||
setPGReady(pg, cl, zl.Sugar())
|
||||
mustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
reconcilertest.MustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
p.Status = pg.Status
|
||||
})
|
||||
|
||||
// Create a dual-stack pod.
|
||||
p := pod(pg, 0)
|
||||
p.Status.PodIPs = append(p.Status.PodIPs, corev1.PodIP{IP: "fd00::0"})
|
||||
mustCreate(t, fc, p)
|
||||
mustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
reconcilertest.MustCreate(t, fc, p)
|
||||
reconcilertest.MustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
existing.Status.PodIPs = p.Status.PodIPs
|
||||
})
|
||||
|
||||
t.Run("not_ready_missing_from_ipv6_slice", func(t *testing.T) {
|
||||
setEndpointForReplicaWithIP("10.0.0.0", epsV4)
|
||||
mustUpdate(t, fc, epsV4.Namespace, epsV4.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
reconcilertest.MustUpdate(t, fc, epsV4.Namespace, epsV4.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Endpoints = epsV4.Endpoints
|
||||
})
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg))
|
||||
expectEqual(t, fc, egressSvc)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc)
|
||||
})
|
||||
t.Run("ready_in_both_slices", func(t *testing.T) {
|
||||
setEndpointForReplicaWithIP("fd00::", epsV6)
|
||||
mustUpdate(t, fc, epsV6.Namespace, epsV6.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
reconcilertest.MustUpdate(t, fc, epsV6.Namespace, epsV6.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Endpoints = epsV6.Endpoints
|
||||
})
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
setReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg), pgReplicas(pg))
|
||||
expectEqual(t, fc, egressSvc)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
setReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc)
|
||||
})
|
||||
t.Run("not_ready_when_ipv6_slice_missing", func(t *testing.T) {
|
||||
// Delete the IPv6 EndpointSlice while the ClusterIP Service still
|
||||
@@ -227,32 +228,31 @@ func TestEgressServiceReadinessDualStack(t *testing.T) {
|
||||
if err := fc.Delete(t.Context(), epsV6); err != nil {
|
||||
t.Fatalf("error deleting IPv6 EndpointSlice: %v", err)
|
||||
}
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
setClusterNotReady(egressSvc, cl, zl.Sugar())
|
||||
expectEqual(t, fc, egressSvc)
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEgressServiceReadinessIPv6Only(t *testing.T) {
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithStatusSubresource(&tsapi.ProxyGroup{}).
|
||||
Build()
|
||||
zl, _ := zap.NewDevelopment()
|
||||
cl := tstest.NewClock(tstest.ClockOpts{})
|
||||
rec := &egressSvcsReadinessReconciler{
|
||||
tsNamespace: "operator-ns",
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: cl,
|
||||
}
|
||||
rec := egress.NewReadinessReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: cl,
|
||||
})
|
||||
egressSvc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "dev",
|
||||
Annotations: map[string]string{
|
||||
AnnotationProxyGroup: "dev",
|
||||
AnnotationTailnetTargetFQDN: "my-app.tailnetxyz.ts.net",
|
||||
reconciler.AnnotationProxyGroup: "dev",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "my-app.tailnetxyz.ts.net",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -260,11 +260,11 @@ func TestEgressServiceReadinessIPv6Only(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app",
|
||||
Namespace: "operator-ns",
|
||||
Labels: egressSvcChildResourceLabels(egressSvc),
|
||||
Labels: childResourceLabels(egressSvc),
|
||||
},
|
||||
Spec: corev1.ServiceSpec{ClusterIPs: []string{"fd00::1"}},
|
||||
}
|
||||
labels := egressSvcEpsLabels(egressSvc, fakeClusterIPSvc)
|
||||
labels := epsLabels(egressSvc, fakeClusterIPSvc)
|
||||
eps := &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "my-app-ipv6",
|
||||
@@ -278,45 +278,45 @@ func TestEgressServiceReadinessIPv6Only(t *testing.T) {
|
||||
Name: "dev",
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, egressSvc)
|
||||
mustCreate(t, fc, fakeClusterIPSvc)
|
||||
mustCreate(t, fc, eps)
|
||||
mustCreate(t, fc, pg)
|
||||
reconcilertest.MustCreate(t, fc, egressSvc)
|
||||
reconcilertest.MustCreate(t, fc, fakeClusterIPSvc)
|
||||
reconcilertest.MustCreate(t, fc, eps)
|
||||
reconcilertest.MustCreate(t, fc, pg)
|
||||
setPGReady(pg, cl, zl.Sugar())
|
||||
mustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
reconcilertest.MustUpdateStatus(t, fc, pg.Namespace, pg.Name, func(p *tsapi.ProxyGroup) {
|
||||
p.Status = pg.Status
|
||||
})
|
||||
|
||||
// Create IPv6-only pods.
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
p := ipv6OnlyPod(pg, i)
|
||||
mustCreate(t, fc, p)
|
||||
mustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
reconcilertest.MustCreate(t, fc, p)
|
||||
reconcilertest.MustUpdateStatus(t, fc, p.Namespace, p.Name, func(existing *corev1.Pod) {
|
||||
existing.Status.PodIPs = p.Status.PodIPs
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("no_ready_replicas", func(t *testing.T) {
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg))
|
||||
expectEqual(t, fc, egressSvc)
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
setNotReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc)
|
||||
})
|
||||
t.Run("all_replicas_ready", func(t *testing.T) {
|
||||
for i := range pgReplicas(pg) {
|
||||
for i := range reconciler.ProxyGroupReplicas(pg) {
|
||||
p := ipv6OnlyPod(pg, i)
|
||||
setEndpointForReplicaWithIP(p.Status.PodIPs[0].IP, eps)
|
||||
}
|
||||
mustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
reconcilertest.MustUpdate(t, fc, eps.Namespace, eps.Name, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Endpoints = eps.Endpoints
|
||||
})
|
||||
setReady(egressSvc, cl, zl.Sugar(), pgReplicas(pg), pgReplicas(pg))
|
||||
expectReconciled(t, rec, "dev", "my-app")
|
||||
expectEqual(t, fc, egressSvc)
|
||||
setReady(egressSvc, cl, zl.Sugar(), reconciler.ProxyGroupReplicas(pg), reconciler.ProxyGroupReplicas(pg))
|
||||
reconcilertest.ExpectReconciled(t, rec, "dev", "my-app")
|
||||
reconcilertest.ExpectEqual(t, fc, egressSvc)
|
||||
})
|
||||
}
|
||||
|
||||
func ipv6OnlyPod(pg *tsapi.ProxyGroup, ordinal int32) *corev1.Pod {
|
||||
labels := pgLabels(pg.Name, nil)
|
||||
labels := reconciler.ProxyGroupLabels(pg.Name, nil)
|
||||
labels[appsv1.PodIndexLabel] = fmt.Sprintf("%d", ordinal)
|
||||
ip := fmt.Sprintf("fd00::%d", ordinal+1) // +1 to avoid fd00::0 normalization issues
|
||||
return &corev1.Pod{
|
||||
@@ -332,20 +332,20 @@ func ipv6OnlyPod(pg *tsapi.ProxyGroup, ordinal int32) *corev1.Pod {
|
||||
}
|
||||
|
||||
func setClusterNotReady(svc *corev1.Service, cl tstime.Clock, lg *zap.SugaredLogger) {
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcReady, metav1.ConditionFalse, reasonClusterResourcesNotReady, reasonClusterResourcesNotReady, cl, lg)
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcReady, metav1.ConditionFalse, "ClusterResourcesNotReady", "ClusterResourcesNotReady", cl, lg)
|
||||
}
|
||||
|
||||
func setNotReady(svc *corev1.Service, cl tstime.Clock, lg *zap.SugaredLogger, replicas int32) {
|
||||
msg := fmt.Sprintf(msgReadyToRouteTemplate, 0, replicas)
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcReady, metav1.ConditionFalse, reasonNotReady, msg, cl, lg)
|
||||
msg := fmt.Sprintf("%d out of %d replicas are ready to route traffic", 0, replicas)
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcReady, metav1.ConditionFalse, "NotReadyToRouteTraffic", msg, cl, lg)
|
||||
}
|
||||
|
||||
func setReady(svc *corev1.Service, cl tstime.Clock, lg *zap.SugaredLogger, replicas, readyReplicas int32) {
|
||||
reason := reasonPartiallyReady
|
||||
reason := "PartiallyReadyToRouteTraffic"
|
||||
if readyReplicas == replicas {
|
||||
reason = reasonReady
|
||||
reason = "ReadyToRouteTraffic"
|
||||
}
|
||||
msg := fmt.Sprintf(msgReadyToRouteTemplate, readyReplicas, replicas)
|
||||
msg := fmt.Sprintf("%d out of %d replicas are ready to route traffic", readyReplicas, replicas)
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcReady, metav1.ConditionTrue, reason, msg, cl, lg)
|
||||
}
|
||||
|
||||
@@ -366,7 +366,7 @@ func setEndpointForReplica(pg *tsapi.ProxyGroup, ordinal int32, eps *discoveryv1
|
||||
}
|
||||
|
||||
func pod(pg *tsapi.ProxyGroup, ordinal int32) *corev1.Pod {
|
||||
labels := pgLabels(pg.Name, nil)
|
||||
labels := reconciler.ProxyGroupLabels(pg.Name, nil)
|
||||
labels[appsv1.PodIndexLabel] = fmt.Sprintf("%d", ordinal)
|
||||
ip := fmt.Sprintf("10.0.0.%d", ordinal)
|
||||
return &corev1.Pod{
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
@@ -29,18 +28,21 @@ import (
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/apiserver/pkg/storage/names"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"sigs.k8s.io/controller-runtime/pkg/builder"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/manager"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/tailscaled"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/clientmetric"
|
||||
"tailscale.com/util/mak"
|
||||
"tailscale.com/util/set"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -49,8 +51,6 @@ const (
|
||||
reasonEgressSvcCreationFailed = "EgressSvcCreationFailed"
|
||||
reasonProxyGroupNotReady = "ProxyGroupNotReady"
|
||||
|
||||
labelProxyGroup = "tailscale.com/proxy-group"
|
||||
|
||||
labelSvcType = "tailscale.com/svc-type" // ingress or egress
|
||||
typeEgress = "egress"
|
||||
// minMatchPort and maxPorts define the range of match ports that can be
|
||||
@@ -73,20 +73,54 @@ const (
|
||||
tsHealthCheckPortName = "tailscale-health-check"
|
||||
)
|
||||
|
||||
const reconcilerName = "egress-svcs-reconciler"
|
||||
|
||||
// gaugeEgressServices tracks the number of egress Services for ProxyGroups that this operator instance manages.
|
||||
var gaugeEgressServices = clientmetric.NewGauge(kubetypes.MetricEgressServiceCount)
|
||||
|
||||
// egressSvcsReconciler reconciles user created ExternalName Services that specify a tailnet
|
||||
// Reconciler reconciles user created ExternalName Services that specify a tailnet
|
||||
// endpoint that should be exposed to cluster workloads and an egress ProxyGroup
|
||||
// on whose proxies it should be exposed.
|
||||
type egressSvcsReconciler struct {
|
||||
type Reconciler struct {
|
||||
client.Client
|
||||
logger *zap.SugaredLogger
|
||||
recorder record.EventRecorder
|
||||
clock tstime.Clock
|
||||
tsNamespace string
|
||||
|
||||
mu sync.Mutex // protects following
|
||||
svcs set.Slice[types.UID] // UIDs of all currently managed egress Services for ProxyGroup
|
||||
tracker *reconciler.ResourceTracker // UIDs of all currently managed egress Services for ProxyGroup
|
||||
}
|
||||
|
||||
// NewReconciler returns a new instance of the Reconciler type. It watches egress Services for ProxyGroups, the
|
||||
// ProxyGroups they reference, and the EndpointSlices created for them.
|
||||
func NewReconciler(options ReconcilerOptions) *Reconciler {
|
||||
return &Reconciler{
|
||||
Client: options.Client,
|
||||
logger: options.Logger.Named(reconcilerName),
|
||||
recorder: options.Recorder,
|
||||
clock: clockOrDefault(options.Clock),
|
||||
tsNamespace: options.TailscaleNamespace,
|
||||
tracker: reconciler.NewResourceTracker(gaugeEgressServices),
|
||||
}
|
||||
}
|
||||
|
||||
// Register the Reconciler onto the given manager.Manager implementation. It also adds the field index that the
|
||||
// ProxyGroup event handler uses to find the egress Services for a ProxyGroup.
|
||||
func (esr *Reconciler) Register(mgr manager.Manager) error {
|
||||
err := builder.
|
||||
ControllerManagedBy(mgr).
|
||||
Named(reconcilerName).
|
||||
Watches(&corev1.Service{}, handler.EnqueueRequestsFromMapFunc(egressSvcsHandler)).
|
||||
Watches(&tsapi.ProxyGroup{}, handler.EnqueueRequestsFromMapFunc(egressSvcsFromEgressProxyGroup(mgr.GetClient(), esr.logger))).
|
||||
Watches(&discoveryv1.EndpointSlice{}, handler.EnqueueRequestsFromMapFunc(egressSvcFromEps)).
|
||||
Complete(esr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mgr.GetFieldIndexer().IndexField(context.Background(), new(corev1.Service), indexEgressProxyGroup, indexEgressServices); err != nil {
|
||||
return fmt.Errorf("failed setting up indexer for egress Services: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reconcile reconciles an ExternalName Service that specifies a tailnet target and a ProxyGroup on whose proxies should
|
||||
@@ -107,7 +141,7 @@ type egressSvcsReconciler struct {
|
||||
//
|
||||
// - updates the egress service config in a ConfigMap mounted to the ProxyGroup proxies with the tailnet target and the
|
||||
// portmappings.
|
||||
func (esr *egressSvcsReconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
func (esr *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (res reconcile.Result, err error) {
|
||||
lg := esr.logger.With("Service", req.NamespacedName)
|
||||
defer lg.Info("reconcile finished")
|
||||
|
||||
@@ -147,18 +181,15 @@ func (esr *egressSvcsReconciler) Reconcile(ctx context.Context, req reconcile.Re
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if !slices.Contains(svc.Finalizers, FinalizerName) {
|
||||
svc.Finalizers = append(svc.Finalizers, FinalizerName)
|
||||
if !slices.Contains(svc.Finalizers, reconciler.Finalizer) {
|
||||
reconciler.SetFinalizer(svc, reconciler.Finalizer)
|
||||
if err := esr.updateSvcSpec(ctx, svc); err != nil {
|
||||
err := fmt.Errorf("failed to add finalizer: %w", err)
|
||||
r := svcConfiguredReason(svc, false, lg)
|
||||
tsoperator.SetServiceCondition(svc, tsapi.EgressSvcConfigured, metav1.ConditionFalse, r, err.Error(), esr.clock, lg)
|
||||
return res, err
|
||||
}
|
||||
esr.mu.Lock()
|
||||
esr.svcs.Add(svc.UID)
|
||||
gaugeEgressServices.Set(int64(esr.svcs.Len()))
|
||||
esr.mu.Unlock()
|
||||
esr.tracker.Add(svc.UID)
|
||||
}
|
||||
|
||||
if err := esr.maybeCleanupProxyGroupConfig(ctx, svc, lg); err != nil {
|
||||
@@ -179,7 +210,7 @@ func (esr *egressSvcsReconciler) Reconcile(ctx context.Context, req reconcile.Re
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) maybeProvision(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) (err error) {
|
||||
func (esr *Reconciler) maybeProvision(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) (err error) {
|
||||
r := svcConfiguredReason(svc, false, lg)
|
||||
st := metav1.ConditionFalse
|
||||
defer func() {
|
||||
@@ -191,7 +222,7 @@ func (esr *egressSvcsReconciler) maybeProvision(ctx context.Context, svc *corev1
|
||||
}()
|
||||
|
||||
crl := egressSvcChildResourceLabels(svc)
|
||||
clusterIPSvc, err := getSingleObject[corev1.Service](ctx, esr.Client, esr.tsNamespace, crl)
|
||||
clusterIPSvc, err := reconciler.GetSingleObject[corev1.Service](ctx, esr.Client, esr.tsNamespace, crl)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error retrieving ClusterIP Service: %w", err)
|
||||
return err
|
||||
@@ -220,7 +251,7 @@ func (esr *egressSvcsReconciler) maybeProvision(ctx context.Context, svc *corev1
|
||||
}
|
||||
provisioned := true
|
||||
if !upToDate {
|
||||
if clusterIPSvc, provisioned, err = esr.provision(ctx, svc.Annotations[AnnotationProxyGroup], svc, clusterIPSvc, lg); err != nil {
|
||||
if clusterIPSvc, provisioned, err = esr.provision(ctx, svc.Annotations[reconciler.AnnotationProxyGroup], svc, clusterIPSvc, lg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -230,7 +261,7 @@ func (esr *egressSvcsReconciler) maybeProvision(ctx context.Context, svc *corev1
|
||||
}
|
||||
|
||||
// Update ExternalName Service to point at the ClusterIP Service.
|
||||
clusterDomain := retrieveClusterDomain(esr.tsNamespace, lg)
|
||||
clusterDomain := reconciler.ClusterDomain(esr.tsNamespace, lg)
|
||||
clusterIPSvcFQDN := fmt.Sprintf("%s.%s.svc.%s", clusterIPSvc.Name, clusterIPSvc.Namespace, clusterDomain)
|
||||
if svc.Spec.ExternalName != clusterIPSvcFQDN {
|
||||
lg.Infof("Configuring ExternalName Service to point to ClusterIP Service %s", clusterIPSvcFQDN)
|
||||
@@ -265,7 +296,7 @@ func addrTypesForClusterIPSvc(clusterIPSvc *corev1.Service) ([]discoveryv1.Addre
|
||||
return addrTypes, nil
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName string, svc, clusterIPSvc *corev1.Service, lg *zap.SugaredLogger) (*corev1.Service, bool, error) {
|
||||
func (esr *Reconciler) provision(ctx context.Context, proxyGroupName string, svc, clusterIPSvc *corev1.Service, lg *zap.SugaredLogger) (*corev1.Service, bool, error) {
|
||||
lg.Infof("updating configuration...")
|
||||
usedPorts, err := esr.usedPortsForPG(ctx, proxyGroupName)
|
||||
if err != nil {
|
||||
@@ -335,7 +366,7 @@ func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName s
|
||||
})
|
||||
}
|
||||
}
|
||||
var healthCheckPort int32 = defaultLocalAddrPort
|
||||
var healthCheckPort int32 = tailscaled.HealthCheckPort
|
||||
|
||||
for {
|
||||
if !slices.ContainsFunc(svc.Spec.Ports, func(p corev1.ServicePort) bool {
|
||||
@@ -351,11 +382,11 @@ func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName s
|
||||
clusterIPSvc.Spec.Ports = append(clusterIPSvc.Spec.Ports, corev1.ServicePort{
|
||||
Name: tsHealthCheckPortName,
|
||||
Port: healthCheckPort,
|
||||
TargetPort: intstr.FromInt(defaultLocalAddrPort),
|
||||
TargetPort: intstr.FromInt(tailscaled.HealthCheckPort),
|
||||
Protocol: "TCP",
|
||||
})
|
||||
if !reflect.DeepEqual(clusterIPSvc, oldClusterIPSvc) {
|
||||
if clusterIPSvc, err = createOrUpdate(ctx, esr.Client, esr.tsNamespace, clusterIPSvc, func(svc *corev1.Service) {
|
||||
if clusterIPSvc, err = reconciler.CreateOrUpdate(ctx, esr.Client, esr.tsNamespace, clusterIPSvc, func(svc *corev1.Service) {
|
||||
svc.Labels = clusterIPSvc.Labels
|
||||
svc.Spec = clusterIPSvc.Spec
|
||||
}); err != nil {
|
||||
@@ -377,7 +408,7 @@ func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName s
|
||||
AddressType: addrType,
|
||||
Ports: epsPortsFromSvc(clusterIPSvc),
|
||||
}
|
||||
if _, err := createOrUpdate(ctx, esr.Client, esr.tsNamespace, eps, func(e *discoveryv1.EndpointSlice) {
|
||||
if _, err := reconciler.CreateOrUpdate(ctx, esr.Client, esr.tsNamespace, eps, func(e *discoveryv1.EndpointSlice) {
|
||||
e.Labels = eps.Labels
|
||||
e.AddressType = eps.AddressType
|
||||
e.Ports = eps.Ports
|
||||
@@ -413,7 +444,7 @@ func (esr *egressSvcsReconciler) provision(ctx context.Context, proxyGroupName s
|
||||
return clusterIPSvc, true, nil
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) maybeCleanup(ctx context.Context, svc *corev1.Service, logger *zap.SugaredLogger) error {
|
||||
func (esr *Reconciler) maybeCleanup(ctx context.Context, svc *corev1.Service, logger *zap.SugaredLogger) error {
|
||||
logger.Info("ensuring that resources created for egress service are deleted")
|
||||
|
||||
// Delete egress service config from the ConfigMap mounted by the proxies.
|
||||
@@ -434,24 +465,16 @@ func (esr *egressSvcsReconciler) maybeCleanup(ctx context.Context, svc *corev1.S
|
||||
}
|
||||
}
|
||||
|
||||
ix := slices.Index(svc.Finalizers, FinalizerName)
|
||||
if ix != -1 {
|
||||
logger.Debug("Removing Tailscale finalizer from Service")
|
||||
svc.Finalizers = append(svc.Finalizers[:ix], svc.Finalizers[ix+1:]...)
|
||||
if err := esr.Update(ctx, svc); err != nil {
|
||||
return fmt.Errorf("failed to remove finalizer: %w", err)
|
||||
}
|
||||
if err := reconciler.ClearFinalizer(ctx, esr.Client, svc, reconciler.Finalizer); err != nil {
|
||||
return fmt.Errorf("failed to remove finalizer: %w", err)
|
||||
}
|
||||
esr.mu.Lock()
|
||||
esr.svcs.Remove(svc.UID)
|
||||
gaugeEgressServices.Set(int64(esr.svcs.Len()))
|
||||
esr.mu.Unlock()
|
||||
esr.tracker.Remove(svc.UID)
|
||||
logger.Info("successfully cleaned up resources for egress Service")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) maybeCleanupProxyGroupConfig(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) error {
|
||||
wantsProxyGroup := svc.Annotations[AnnotationProxyGroup]
|
||||
func (esr *Reconciler) maybeCleanupProxyGroupConfig(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) error {
|
||||
wantsProxyGroup := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
cond := tsoperator.GetServiceCondition(svc, tsapi.EgressSvcConfigured)
|
||||
if cond == nil {
|
||||
return nil
|
||||
@@ -479,9 +502,9 @@ func (esr *egressSvcsReconciler) maybeCleanupProxyGroupConfig(ctx context.Contex
|
||||
// latest ClusterIP Services via the controller cache. It will not work as well
|
||||
// once we split into multiple workers- at that point we probably want to set
|
||||
// used ports on ProxyGroup's status.
|
||||
func (esr *egressSvcsReconciler) usedPortsForPG(ctx context.Context, pg string) (sets.Set[int32], error) {
|
||||
func (esr *Reconciler) usedPortsForPG(ctx context.Context, pg string) (sets.Set[int32], error) {
|
||||
svcList := &corev1.ServiceList{}
|
||||
if err := esr.List(ctx, svcList, client.InNamespace(esr.tsNamespace), client.MatchingLabels(map[string]string{labelProxyGroup: pg})); err != nil {
|
||||
if err := esr.List(ctx, svcList, client.InNamespace(esr.tsNamespace), client.MatchingLabels(map[string]string{reconciler.LabelProxyGroup: pg})); err != nil {
|
||||
return nil, fmt.Errorf("error listing Services: %w", err)
|
||||
}
|
||||
usedPorts := sets.New[int32]()
|
||||
@@ -502,10 +525,10 @@ func (esr *egressSvcsReconciler) usedPortsForPG(ctx context.Context, pg string)
|
||||
// for an egress service exposed on ProxyGroup proxies. The ClusterIP Service
|
||||
// has no selector. Traffic sent to it will be routed to the endpoints defined
|
||||
// by an EndpointSlice created for this egress service.
|
||||
func (esr *egressSvcsReconciler) clusterIPSvcForEgress(crl map[string]string) *corev1.Service {
|
||||
func (esr *Reconciler) clusterIPSvcForEgress(crl map[string]string) *corev1.Service {
|
||||
return &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
GenerateName: svcNameBase(crl[LabelParentName]),
|
||||
GenerateName: svcNameBase(crl[reconciler.LabelParentName]),
|
||||
Namespace: esr.tsNamespace,
|
||||
Labels: crl,
|
||||
},
|
||||
@@ -516,9 +539,9 @@ func (esr *egressSvcsReconciler) clusterIPSvcForEgress(crl map[string]string) *c
|
||||
}
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) ensureEgressSvcCfgDeleted(ctx context.Context, svc *corev1.Service, logger *zap.SugaredLogger) error {
|
||||
func (esr *Reconciler) ensureEgressSvcCfgDeleted(ctx context.Context, svc *corev1.Service, logger *zap.SugaredLogger) error {
|
||||
crl := egressSvcChildResourceLabels(svc)
|
||||
cmName := pgEgressCMName(crl[labelProxyGroup])
|
||||
cmName := reconciler.ProxyGroupEgressConfigMapName(crl[reconciler.LabelProxyGroup])
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: cmName,
|
||||
@@ -559,8 +582,8 @@ func (esr *egressSvcsReconciler) ensureEgressSvcCfgDeleted(ctx context.Context,
|
||||
return esr.Update(ctx, cm)
|
||||
}
|
||||
|
||||
func (esr *egressSvcsReconciler) validateClusterResources(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) (bool, error) {
|
||||
proxyGroupName := svc.Annotations[AnnotationProxyGroup]
|
||||
func (esr *Reconciler) validateClusterResources(ctx context.Context, svc *corev1.Service, lg *zap.SugaredLogger) (bool, error) {
|
||||
proxyGroupName := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
pg := &tsapi.ProxyGroup{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: proxyGroupName,
|
||||
@@ -596,7 +619,7 @@ func (esr *egressSvcsReconciler) validateClusterResources(ctx context.Context, s
|
||||
}
|
||||
|
||||
func egressSvcCfg(externalNameSvc, clusterIPSvc *corev1.Service, ns string, lg *zap.SugaredLogger) egressservices.Config {
|
||||
d := retrieveClusterDomain(ns, lg)
|
||||
d := reconciler.ClusterDomain(ns, lg)
|
||||
tt := tailnetTargetFromSvc(externalNameSvc)
|
||||
hep := healthCheckForSvc(clusterIPSvc, d)
|
||||
cfg := egressservices.Config{
|
||||
@@ -614,11 +637,11 @@ func egressSvcCfg(externalNameSvc, clusterIPSvc *corev1.Service, ns string, lg *
|
||||
}
|
||||
|
||||
func validateEgressService(svc *corev1.Service, pg *tsapi.ProxyGroup) []string {
|
||||
violations := validateService(svc)
|
||||
violations := reconciler.ValidateService(svc)
|
||||
|
||||
// We check that only one of these two is set in the earlier validateService function.
|
||||
if svc.Annotations[AnnotationTailnetTargetFQDN] == "" && svc.Annotations[AnnotationTailnetTargetIP] == "" {
|
||||
violations = append(violations, fmt.Sprintf("egress Service for ProxyGroup must have one of %s, %s annotations set", AnnotationTailnetTargetFQDN, AnnotationTailnetTargetIP))
|
||||
if svc.Annotations[reconciler.AnnotationTailnetTargetFQDN] == "" && svc.Annotations[reconciler.AnnotationTailnetTargetIP] == "" {
|
||||
violations = append(violations, fmt.Sprintf("egress Service for ProxyGroup must have one of %s, %s annotations set", reconciler.AnnotationTailnetTargetFQDN, reconciler.AnnotationTailnetTargetIP))
|
||||
}
|
||||
if len(svc.Spec.Ports) == 0 {
|
||||
violations = append(violations, "egress Service for ProxyGroup must have at least one target Port specified")
|
||||
@@ -672,13 +695,13 @@ func unusedPort(usedPorts sets.Set[int32]) int32 {
|
||||
// Service must contain exactly one of tailscale.com/tailnet-ip,
|
||||
// tailscale.com/tailnet-fqdn annotations.
|
||||
func tailnetTargetFromSvc(svc *corev1.Service) egressservices.TailnetTarget {
|
||||
if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
if fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
return egressservices.TailnetTarget{
|
||||
FQDN: fqdn,
|
||||
}
|
||||
}
|
||||
return egressservices.TailnetTarget{
|
||||
IP: svc.Annotations[AnnotationTailnetTargetIP],
|
||||
IP: svc.Annotations[reconciler.AnnotationTailnetTargetIP],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,13 +720,13 @@ func isEgressSvcForProxyGroup(obj client.Object) bool {
|
||||
return false
|
||||
}
|
||||
annots := s.ObjectMeta.Annotations
|
||||
return annots[AnnotationProxyGroup] != "" && (annots[AnnotationTailnetTargetFQDN] != "" || annots[AnnotationTailnetTargetIP] != "")
|
||||
return annots[reconciler.AnnotationProxyGroup] != "" && (annots[reconciler.AnnotationTailnetTargetFQDN] != "" || annots[reconciler.AnnotationTailnetTargetIP] != "")
|
||||
}
|
||||
|
||||
// egressSvcConfig returns a ConfigMap that contains egress services configuration for the provided ProxyGroup as well
|
||||
// as unmarshalled configuration from the ConfigMap.
|
||||
func egressSvcsConfigs(ctx context.Context, cl client.Client, proxyGroupName, tsNamespace string) (cm *corev1.ConfigMap, cfgs egressservices.Configs, err error) {
|
||||
name := pgEgressCMName(proxyGroupName)
|
||||
name := reconciler.ProxyGroupEgressConfigMapName(proxyGroupName)
|
||||
cm = &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
@@ -733,14 +756,10 @@ func egressSvcsConfigs(ctx context.Context, cl client.Client, proxyGroupName, ts
|
||||
// chars whilst the maximum allowed resource name length is 253 chars, so we
|
||||
// should probably validate and truncate (?) the names is they are too long.
|
||||
func egressSvcChildResourceLabels(svc *corev1.Service) map[string]string {
|
||||
return map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
LabelParentType: "svc",
|
||||
LabelParentName: svc.Name,
|
||||
LabelParentNamespace: svc.Namespace,
|
||||
labelProxyGroup: svc.Annotations[AnnotationProxyGroup],
|
||||
labelSvcType: typeEgress,
|
||||
}
|
||||
labels := reconciler.Labels("svc", svc.Name, svc.Namespace)
|
||||
labels[reconciler.LabelProxyGroup] = svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
labels[labelSvcType] = typeEgress
|
||||
return labels
|
||||
}
|
||||
|
||||
// egressEpsLabels returns labels to be added to an EndpointSlice created for an egress service.
|
||||
@@ -797,12 +816,12 @@ func svcConfiguredReason(svc *corev1.Service, configured bool, lg *zap.SugaredLo
|
||||
} else {
|
||||
r = fmt.Sprintf("ConfigurationFailed:%s", r)
|
||||
}
|
||||
r += fmt.Sprintf("ProxyGroup:%s", svc.Annotations[AnnotationProxyGroup])
|
||||
r += fmt.Sprintf("ProxyGroup:%s", svc.Annotations[reconciler.AnnotationProxyGroup])
|
||||
tt := tailnetTargetFromSvc(svc)
|
||||
s := cfg{
|
||||
Ports: svc.Spec.Ports,
|
||||
TailnetTarget: tt,
|
||||
ProxyGroup: svc.Annotations[AnnotationProxyGroup],
|
||||
ProxyGroup: svc.Annotations[reconciler.AnnotationProxyGroup],
|
||||
}
|
||||
r += fmt.Sprintf(":Config:%s", cfgHash(s, lg))
|
||||
return r
|
||||
@@ -816,7 +835,7 @@ func tailnetSvcName(extNSvc *corev1.Service) string {
|
||||
|
||||
// missingEndpointSliceFamilies reports whether any EndpointSlice expected for the given ClusterIP Service (one per addrType)
|
||||
// does not exist. Slices are looked up by name rather than labels so an orphaned EndpointSlice cannot satisfy the check.
|
||||
func (esr *egressSvcsReconciler) missingEndpointSliceFamilies(ctx context.Context, clusterIPSvc *corev1.Service, addrTypes []discoveryv1.AddressType) (bool, error) {
|
||||
func (esr *Reconciler) missingEndpointSliceFamilies(ctx context.Context, clusterIPSvc *corev1.Service, addrTypes []discoveryv1.AddressType) (bool, error) {
|
||||
for _, addrType := range addrTypes {
|
||||
eps := &discoveryv1.EndpointSlice{}
|
||||
name := fmt.Sprintf("%s-%s", clusterIPSvc.Name, strings.ToLower(string(addrType)))
|
||||
@@ -847,7 +866,7 @@ func epsPortsFromSvc(svc *corev1.Service) (ep []discoveryv1.EndpointPort) {
|
||||
// updateSvcSpec ensures that the given Service's spec is updated in cluster, but the local Service object still retains
|
||||
// the not-yet-applied status.
|
||||
// TODO(irbekrm): once we do SSA for these patch updates, this will no longer be needed.
|
||||
func (esr *egressSvcsReconciler) updateSvcSpec(ctx context.Context, svc *corev1.Service) error {
|
||||
func (esr *Reconciler) updateSvcSpec(ctx context.Context, svc *corev1.Service) error {
|
||||
st := svc.Status.DeepCopy()
|
||||
err := esr.Update(ctx, svc)
|
||||
svc.Status = *st
|
||||
+244
-133
@@ -3,14 +3,16 @@
|
||||
|
||||
//go:build !plan9
|
||||
|
||||
package main
|
||||
package egress_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/AlekSi/pointer"
|
||||
"github.com/google/go-cmp/cmp"
|
||||
@@ -20,16 +22,21 @@ import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/intstr"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/k8s-operator/reconciler"
|
||||
"tailscale.com/k8s-operator/reconciler/egress"
|
||||
"tailscale.com/k8s-operator/reconciler/reconcilertest"
|
||||
"tailscale.com/kube/egressservices"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/tstest"
|
||||
"tailscale.com/tstime"
|
||||
"tailscale.com/util/mak"
|
||||
)
|
||||
|
||||
func TestTailscaleEgressServices(t *testing.T) {
|
||||
@@ -46,12 +53,11 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName("foo"),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName("foo"),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
}
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(pg, cm).
|
||||
WithStatusSubresource(pg).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
@@ -64,12 +70,12 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
}
|
||||
clock := tstest.NewClock(tstest.ClockOpts{})
|
||||
|
||||
esr := &egressSvcsReconciler{
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: clock,
|
||||
tsNamespace: "operator-ns",
|
||||
}
|
||||
esr := egress.NewReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: clock,
|
||||
})
|
||||
tailnetTargetFQDN := "foo.bar.ts.net."
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
@@ -77,8 +83,8 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: tailnetTargetFQDN,
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -95,32 +101,32 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
}
|
||||
|
||||
t.Run("service_one_unnamed_port", func(t *testing.T) {
|
||||
mustCreate(t, fc, svc)
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.MustCreate(t, fc, svc)
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
})
|
||||
t.Run("service_add_two_named_ports", func(t *testing.T) {
|
||||
svc.Spec.Ports = []corev1.ServicePort{{Protocol: "TCP", Port: 80, Name: "http"}, {Protocol: "TCP", Port: 443, Name: "https"}}
|
||||
mustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
reconcilertest.MustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
s.Spec.Ports = svc.Spec.Ports
|
||||
})
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
})
|
||||
t.Run("service_add_udp_port", func(t *testing.T) {
|
||||
svc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{Port: 53, Protocol: "UDP", Name: "dns"})
|
||||
mustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
reconcilertest.MustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
s.Spec.Ports = svc.Spec.Ports
|
||||
})
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
})
|
||||
t.Run("service_change_protocol", func(t *testing.T) {
|
||||
svc.Spec.Ports = []corev1.ServicePort{{Protocol: "TCP", Port: 80, Name: "http"}, {Protocol: "TCP", Port: 443, Name: "https"}, {Port: 53, Protocol: "TCP", Name: "tcp_dns"}}
|
||||
mustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
reconcilertest.MustUpdate(t, fc, "default", "test", func(s *corev1.Service) {
|
||||
s.Spec.Ports = svc.Spec.Ports
|
||||
})
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
})
|
||||
|
||||
@@ -137,7 +143,7 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
if err := fc.Delete(t.Context(), eps); err != nil {
|
||||
t.Fatalf("error deleting EndpointSlice: %v", err)
|
||||
}
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
})
|
||||
|
||||
@@ -146,26 +152,26 @@ func TestTailscaleEgressServices(t *testing.T) {
|
||||
if err := fc.Delete(context.Background(), svc); err != nil {
|
||||
t.Fatalf("error deleting ExternalName Service: %v", err)
|
||||
}
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
// Verify that ClusterIP Service and EndpointSlice have been deleted.
|
||||
expectMissing[corev1.Service](t, fc, "operator-ns", name)
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv4", name))
|
||||
reconcilertest.ExpectMissing[corev1.Service](t, fc, "operator-ns", name)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv4", name))
|
||||
// Verify that service config has been deleted from the ConfigMap.
|
||||
mustNotHaveConfigForSvc(t, fc, svc, cm)
|
||||
})
|
||||
}
|
||||
|
||||
func validateReadyService(t *testing.T, fc client.WithWatch, esr *egressSvcsReconciler, svc *corev1.Service, clock *tstest.Clock, zl *zap.Logger, cm *corev1.ConfigMap) {
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
func validateReadyService(t *testing.T, fc client.WithWatch, esr *egress.Reconciler, svc *corev1.Service, clock *tstest.Clock, zl *zap.Logger, cm *corev1.ConfigMap) {
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
// Verify that a ClusterIP Service has been created.
|
||||
name := findGenNameForEgressSvcResources(t, fc, svc)
|
||||
expectEqual(t, fc, clusterIPSvc(name, svc), removeTargetPortsFromSvc, removeClusterIPsFromSvc)
|
||||
reconcilertest.ExpectEqual(t, fc, clusterIPSvc(name, svc), removeTargetPortsFromSvc, removeClusterIPsFromSvc)
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
// Verify that an EndpointSlice has been created.
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
// Verify that ConfigMap contains configuration for the new egress service.
|
||||
mustHaveConfigForSvc(t, fc, svc, clusterSvc, cm, zl)
|
||||
r := svcConfiguredReason(svc, true, zl.Sugar())
|
||||
r := configuredReason(t, svc)
|
||||
// Verify that the user-created ExternalName Service has Configured set to true and ExternalName pointing to the
|
||||
// CluterIP Service.
|
||||
svc.Status.Conditions = []metav1.Condition{
|
||||
@@ -174,7 +180,7 @@ func validateReadyService(t *testing.T, fc client.WithWatch, esr *egressSvcsReco
|
||||
}
|
||||
svc.ObjectMeta.Finalizers = []string{"tailscale.com/finalizer"}
|
||||
svc.Spec.ExternalName = fmt.Sprintf("%s.operator-ns.svc.cluster.local", name)
|
||||
expectEqual(t, fc, svc)
|
||||
reconcilertest.ExpectEqual(t, fc, svc)
|
||||
|
||||
}
|
||||
|
||||
@@ -182,7 +188,7 @@ func condition(typ tsapi.ConditionType, st metav1.ConditionStatus, r, msg string
|
||||
return metav1.Condition{
|
||||
Type: string(typ),
|
||||
Status: st,
|
||||
LastTransitionTime: conditionTime(clock),
|
||||
LastTransitionTime: metav1.NewTime(clock.Now().Truncate(time.Second)),
|
||||
Reason: r,
|
||||
Message: msg,
|
||||
}
|
||||
@@ -190,8 +196,8 @@ func condition(typ tsapi.ConditionType, st metav1.ConditionStatus, r, msg string
|
||||
|
||||
func findGenNameForEgressSvcResources(t *testing.T, client client.Client, svc *corev1.Service) string {
|
||||
t.Helper()
|
||||
labels := egressSvcChildResourceLabels(svc)
|
||||
s, err := getSingleObject[corev1.Service](context.Background(), client, "operator-ns", labels)
|
||||
labels := childResourceLabels(svc)
|
||||
s, err := reconciler.GetSingleObject[corev1.Service](context.Background(), client, "operator-ns", labels)
|
||||
if err != nil {
|
||||
t.Fatalf("finding ClusterIP Service for ExternalName Service %s: %v", svc.Name, err)
|
||||
}
|
||||
@@ -202,7 +208,7 @@ func findGenNameForEgressSvcResources(t *testing.T, client client.Client, svc *c
|
||||
}
|
||||
|
||||
func clusterIPSvc(name string, extNSvc *corev1.Service) *corev1.Service {
|
||||
labels := egressSvcChildResourceLabels(extNSvc)
|
||||
labels := childResourceLabels(extNSvc)
|
||||
ports := make([]corev1.ServicePort, len(extNSvc.Spec.Ports))
|
||||
for i, port := range extNSvc.Spec.Ports {
|
||||
ports[i] = corev1.ServicePort{ // Copy the port to avoid modifying the original.
|
||||
@@ -249,7 +255,7 @@ func mustGetClusterIPSvc(t *testing.T, cl client.Client, name string) *corev1.Se
|
||||
}
|
||||
|
||||
func endpointSlice(name string, extNSvc, clusterIPSvc *corev1.Service, addrType discoveryv1.AddressType) *discoveryv1.EndpointSlice {
|
||||
labels := egressSvcChildResourceLabels(extNSvc)
|
||||
labels := childResourceLabels(extNSvc)
|
||||
labels[discoveryv1.LabelManagedBy] = "tailscale.com"
|
||||
labels[discoveryv1.LabelServiceName] = name
|
||||
suffix := "ipv4"
|
||||
@@ -281,7 +287,7 @@ func portsForEndpointSlice(svc *corev1.Service) []discoveryv1.EndpointPort {
|
||||
|
||||
func mustHaveConfigForSvc(t *testing.T, cl client.Client, extNSvc, clusterIPSvc *corev1.Service, cm *corev1.ConfigMap, lg *zap.Logger) {
|
||||
t.Helper()
|
||||
wantsCfg := egressSvcCfg(extNSvc, clusterIPSvc, clusterIPSvc.Namespace, lg.Sugar())
|
||||
wantsCfg := egressConfig(extNSvc, clusterIPSvc)
|
||||
if err := cl.Get(context.Background(), client.ObjectKeyFromObject(cm), cm); err != nil {
|
||||
t.Fatalf("Error retrieving ConfigMap: %v", err)
|
||||
}
|
||||
@@ -338,12 +344,11 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName("foo"),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName("foo"),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
}
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(pg, cm).
|
||||
WithStatusSubresource(pg).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
@@ -356,20 +361,20 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
}
|
||||
clock := tstest.NewClock(tstest.ClockOpts{})
|
||||
|
||||
esr := &egressSvcsReconciler{
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: clock,
|
||||
tsNamespace: "operator-ns",
|
||||
}
|
||||
esr := egress.NewReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: clock,
|
||||
})
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "test",
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -386,13 +391,13 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
}
|
||||
|
||||
t.Run("dual_stack_creates_both_endpoint_slices", func(t *testing.T) {
|
||||
mustCreate(t, fc, svc)
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.MustCreate(t, fc, svc)
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
// Also verify the IPv6 EndpointSlice was created.
|
||||
name := findGenNameForEgressSvcResources(t, fc, svc)
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
})
|
||||
|
||||
t.Run("dual_stack_endpointslice_deletion_recovery", func(t *testing.T) {
|
||||
@@ -409,12 +414,12 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
if err := fc.Delete(t.Context(), eps); err != nil {
|
||||
t.Fatalf("error deleting EndpointSlice %s: %v", epsName, err)
|
||||
}
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
}
|
||||
// Reconcile should recreate both.
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
})
|
||||
|
||||
t.Run("dual_stack_single_endpointslice_deletion_recovery", func(t *testing.T) {
|
||||
@@ -430,13 +435,13 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
if err := fc.Delete(t.Context(), eps); err != nil {
|
||||
t.Fatalf("error deleting EndpointSlice %s: %v", epsName, err)
|
||||
}
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", epsName)
|
||||
// Reconcile should recreate the missing IPv6 EndpointSlice while leaving
|
||||
// the IPv4 one untouched.
|
||||
validateReadyService(t, fc, esr, svc, clock, zl, cm)
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv6))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
})
|
||||
|
||||
t.Run("delete_dual_stack_service", func(t *testing.T) {
|
||||
@@ -444,10 +449,10 @@ func TestTailscaleEgressServicesDualStack(t *testing.T) {
|
||||
if err := fc.Delete(context.Background(), svc); err != nil {
|
||||
t.Fatalf("error deleting ExternalName Service: %v", err)
|
||||
}
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
expectMissing[corev1.Service](t, fc, "operator-ns", name)
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv4", name))
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv6", name))
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectMissing[corev1.Service](t, fc, "operator-ns", name)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv4", name))
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", fmt.Sprintf("%s-ipv6", name))
|
||||
mustNotHaveConfigForSvc(t, fc, svc, cm)
|
||||
})
|
||||
}
|
||||
@@ -470,7 +475,7 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName("foo"),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName("foo"),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
}
|
||||
@@ -483,8 +488,7 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
// the EgressSvcConfigured condition.
|
||||
tsoperator.SetProxyGroupCondition(pg, tsapi.ProxyGroupAvailable, metav1.ConditionTrue, "foo", "foo", pg.Generation, clock, zl.Sugar())
|
||||
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(pg, cm).
|
||||
WithStatusSubresource(pg, &corev1.Service{}).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
@@ -492,20 +496,20 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
}).
|
||||
Build()
|
||||
|
||||
esr := &egressSvcsReconciler{
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: clock,
|
||||
tsNamespace: "operator-ns",
|
||||
}
|
||||
esr := egress.NewReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: clock,
|
||||
})
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "test",
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -516,15 +520,15 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
},
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, svc)
|
||||
reconcilertest.MustCreate(t, fc, svc)
|
||||
|
||||
// First reconcile: provisions the single-stack (IPv4) EndpointSlice and sets
|
||||
// EgressSvcConfigured=True.
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
name := findGenNameForEgressSvcResources(t, fc, svc)
|
||||
v4Name := fmt.Sprintf("%s-ipv4", name)
|
||||
v6Name := fmt.Sprintf("%s-ipv6", name)
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", v6Name)
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", v6Name)
|
||||
gotSvc := &corev1.Service{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: "default", Name: "test"}, gotSvc); err != nil {
|
||||
t.Fatalf("getting Service: %v", err)
|
||||
@@ -536,7 +540,7 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
// Second reconcile: the service is up to date (same single family), so the
|
||||
// gate must skip provision and not rewrite the IPv4 EndpointSlice.
|
||||
v4Before := mustGetEndpointSlice(t, fc, v4Name)
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
v4After := mustGetEndpointSlice(t, fc, v4Name)
|
||||
if v4Before.ResourceVersion != v4After.ResourceVersion {
|
||||
t.Errorf("IPv4 EndpointSlice was rewritten on a no-op reconcile: resourceVersion %s -> %s", v4Before.ResourceVersion, v4After.ResourceVersion)
|
||||
@@ -544,17 +548,20 @@ func TestEgressServiceGatedProvision(t *testing.T) {
|
||||
|
||||
// If an expected EndpointSlice is missing while the config is up to date, the
|
||||
// missingEndpointSliceFamilies check must flip the gate false so provision reruns
|
||||
// and recreates the slice, without reshuffling the ClusterIP Service ports.
|
||||
// and recreates the slice, without reshuffling the ClusterIP Service ports. The
|
||||
// check looks slices up by name, so an orphaned slice with the same labels must
|
||||
// not satisfy it.
|
||||
clusterPortsBefore := mustGetClusterIPSvc(t, fc, name).Spec.Ports
|
||||
reconcilertest.MustCreate(t, fc, endpointSlice("ts-foo-orphan", svc, mustGetClusterIPSvc(t, fc, name), discoveryv1.AddressTypeIPv4))
|
||||
if err := fc.Delete(t.Context(), &discoveryv1.EndpointSlice{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: v4Name, Namespace: "operator-ns"},
|
||||
}); err != nil {
|
||||
t.Fatalf("deleting EndpointSlice: %v", err)
|
||||
}
|
||||
expectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", v4Name)
|
||||
expectReconciled(t, esr, "default", "test")
|
||||
reconcilertest.ExpectMissing[discoveryv1.EndpointSlice](t, fc, "operator-ns", v4Name)
|
||||
reconcilertest.ExpectReconciled(t, esr, "default", "test")
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
expectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
reconcilertest.ExpectEqual(t, fc, endpointSlice(name, svc, clusterSvc, discoveryv1.AddressTypeIPv4))
|
||||
if diff := cmp.Diff(clusterSvc.Spec.Ports, clusterPortsBefore); diff != "" {
|
||||
t.Errorf("ClusterIP Service ports changed after reprovision (-got +want):\n%s", diff)
|
||||
}
|
||||
@@ -583,46 +590,29 @@ func clusterIPInterceptor(clusterIPs ...string) func(ctx context.Context, c clie
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingEndpointSliceFamilies verifies that the check reports an expected IP family's
|
||||
// EndpointSlice as missing until a slice named for the current ClusterIP Service exists.
|
||||
func TestMissingEndpointSliceFamilies(t *testing.T) {
|
||||
zl, err := zap.NewDevelopment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
func removeTargetPortsFromSvc(svc *corev1.Service) {
|
||||
newPorts := make([]corev1.ServicePort, 0)
|
||||
for _, p := range svc.Spec.Ports {
|
||||
newPorts = append(newPorts, corev1.ServicePort{Protocol: p.Protocol, Port: p.Port, Name: p.Name})
|
||||
}
|
||||
extNSvc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "test",
|
||||
Namespace: "default",
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
}
|
||||
current := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "ts-foo-current", Namespace: "operator-ns"}}
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
Build()
|
||||
esr := &egressSvcsReconciler{Client: fc, logger: zl.Sugar(), tsNamespace: "operator-ns"}
|
||||
svc.Spec.Ports = newPorts
|
||||
}
|
||||
|
||||
// No slice exists for the current ClusterIP Service yet.
|
||||
missing, err := esr.missingEndpointSliceFamilies(t.Context(), current, []discoveryv1.AddressType{discoveryv1.AddressTypeIPv4})
|
||||
if err != nil {
|
||||
t.Fatalf("missingEndpointSliceFamilies: %v", err)
|
||||
}
|
||||
if !missing {
|
||||
t.Error("expected missing=true when no EndpointSlice exists for the current ClusterIP Service")
|
||||
}
|
||||
func removeClusterIPsFromSvc(svc *corev1.Service) {
|
||||
svc.Spec.ClusterIP = ""
|
||||
svc.Spec.ClusterIPs = nil
|
||||
}
|
||||
|
||||
// Should not be mising once the EndpointSlice exists.
|
||||
mustCreate(t, fc, endpointSlice("ts-foo-current", extNSvc, current, discoveryv1.AddressTypeIPv4))
|
||||
missing, err = esr.missingEndpointSliceFamilies(t.Context(), current, []discoveryv1.AddressType{discoveryv1.AddressTypeIPv4})
|
||||
if err != nil {
|
||||
t.Fatalf("missingEndpointSliceFamilies: %v", err)
|
||||
}
|
||||
if missing {
|
||||
t.Error("expected missing=false once the current ClusterIP Service's IPv4 slice exists")
|
||||
// childResourceLabels returns the labels that the Reconciler sets on the ClusterIP Service and EndpointSlices that it
|
||||
// creates for the egress Service svc.
|
||||
func childResourceLabels(svc *corev1.Service) map[string]string {
|
||||
return map[string]string{
|
||||
kubetypes.LabelManaged: "true",
|
||||
reconciler.LabelParentType: "svc",
|
||||
reconciler.LabelParentName: svc.Name,
|
||||
reconciler.LabelParentNamespace: svc.Namespace,
|
||||
reconciler.LabelProxyGroup: svc.Annotations[reconciler.AnnotationProxyGroup],
|
||||
"tailscale.com/svc-type": "egress",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,6 +620,11 @@ func TestMissingEndpointSliceFamilies(t *testing.T) {
|
||||
// ports until the ProxyGroup uses maxPorts of them, and that the health check
|
||||
// port does not count towards the limit.
|
||||
func TestEgressServicePortAllocation(t *testing.T) {
|
||||
// The Reconciler allocates match ports in [minMatchPort, minMatchPort+maxPorts).
|
||||
const (
|
||||
minMatchPort = 10000
|
||||
maxPorts = 20000
|
||||
)
|
||||
tests := []struct {
|
||||
name string
|
||||
usedPorts int
|
||||
@@ -647,7 +642,7 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pgEgressCMName("foo"),
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName("foo"),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
}
|
||||
@@ -657,7 +652,7 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "existing",
|
||||
Namespace: "operator-ns",
|
||||
Labels: map[string]string{labelProxyGroup: "foo"},
|
||||
Labels: map[string]string{reconciler.LabelProxyGroup: "foo"},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{Type: corev1.ServiceTypeClusterIP},
|
||||
}
|
||||
@@ -670,13 +665,12 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
})
|
||||
}
|
||||
existing.Spec.Ports = append(existing.Spec.Ports, corev1.ServicePort{
|
||||
Name: tsHealthCheckPortName,
|
||||
Name: "tailscale-health-check",
|
||||
Protocol: "TCP",
|
||||
Port: defaultLocalAddrPort,
|
||||
TargetPort: intstr.FromInt(defaultLocalAddrPort),
|
||||
Port: 9002,
|
||||
TargetPort: intstr.FromInt(9002),
|
||||
})
|
||||
fc := fake.NewClientBuilder().
|
||||
WithScheme(tsapi.GlobalScheme).
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(pg, cm, existing).
|
||||
WithStatusSubresource(pg).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
@@ -687,20 +681,20 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
esr := &egressSvcsReconciler{
|
||||
Client: fc,
|
||||
logger: zl.Sugar(),
|
||||
clock: tstest.NewClock(tstest.ClockOpts{}),
|
||||
tsNamespace: "operator-ns",
|
||||
}
|
||||
esr := egress.NewReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: tstest.NewClock(tstest.ClockOpts{}),
|
||||
})
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "test",
|
||||
Namespace: "default",
|
||||
UID: types.UID("1234-UID"),
|
||||
Annotations: map[string]string{
|
||||
AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
AnnotationProxyGroup: "foo",
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.bar.ts.net.",
|
||||
reconciler.AnnotationProxyGroup: "foo",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
@@ -709,7 +703,7 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
Ports: []corev1.ServicePort{{Protocol: "TCP", Port: 80}},
|
||||
},
|
||||
}
|
||||
mustCreate(t, fc, svc)
|
||||
reconcilertest.MustCreate(t, fc, svc)
|
||||
|
||||
_, err = esr.Reconcile(t.Context(), reconcile.Request{
|
||||
NamespacedName: types.NamespacedName{Namespace: "default", Name: "test"},
|
||||
@@ -726,7 +720,7 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
name := findGenNameForEgressSvcResources(t, fc, svc)
|
||||
clusterSvc := mustGetClusterIPSvc(t, fc, name)
|
||||
for _, p := range clusterSvc.Spec.Ports {
|
||||
if p.Name == tsHealthCheckPortName {
|
||||
if p.Name == "tailscale-health-check" {
|
||||
continue
|
||||
}
|
||||
if got := p.TargetPort.IntVal; got < minMatchPort+int32(tt.usedPorts) || got >= minMatchPort+maxPorts {
|
||||
@@ -736,3 +730,120 @@ func TestEgressServicePortAllocation(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateEgressServiceLongName verifies that an egress Service whose
|
||||
// default hostname (<namespace>-<name>) is longer than a DNS label is valid.
|
||||
func TestValidateEgressServiceLongName(t *testing.T) {
|
||||
const (
|
||||
ns = "tailscale-external-services"
|
||||
name = "harry1027133059-trefknee01-bee-oqggo-kinfe-0-g"
|
||||
)
|
||||
pg := &tsapi.ProxyGroup{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "egress"},
|
||||
Spec: tsapi.ProxyGroupSpec{Type: tsapi.ProxyGroupTypeEgress},
|
||||
}
|
||||
cm := &corev1.ConfigMap{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: reconciler.ProxyGroupEgressConfigMapName("egress"),
|
||||
Namespace: "operator-ns",
|
||||
},
|
||||
}
|
||||
fc := reconcilertest.NewClientBuilder().
|
||||
WithObjects(pg, cm).
|
||||
WithStatusSubresource(pg, &corev1.Service{}).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
Create: clusterIPInterceptor("10.96.0.1"),
|
||||
}).
|
||||
Build()
|
||||
zl, err := zap.NewDevelopment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
esr := egress.NewReconciler(egress.ReconcilerOptions{
|
||||
Client: fc,
|
||||
Recorder: record.NewFakeRecorder(10),
|
||||
TailscaleNamespace: "operator-ns",
|
||||
Logger: zl.Sugar(),
|
||||
Clock: tstest.NewClock(tstest.ClockOpts{}),
|
||||
})
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: ns,
|
||||
Annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: name + ".tailnet.ts.net",
|
||||
reconciler.AnnotationProxyGroup: "egress",
|
||||
},
|
||||
},
|
||||
Spec: corev1.ServiceSpec{
|
||||
Type: corev1.ServiceTypeExternalName,
|
||||
ExternalName: "placeholder",
|
||||
Ports: []corev1.ServicePort{{Port: 8080, Protocol: corev1.ProtocolTCP}},
|
||||
},
|
||||
}
|
||||
reconcilertest.MustCreate(t, fc, svc)
|
||||
|
||||
reconcilertest.ExpectReconciled(t, esr, ns, name)
|
||||
got := &corev1.Service{}
|
||||
if err := fc.Get(t.Context(), client.ObjectKey{Namespace: ns, Name: name}, got); err != nil {
|
||||
t.Fatalf("getting Service: %v", err)
|
||||
}
|
||||
if cond := tsoperator.GetServiceCondition(got, tsapi.EgressSvcValid); cond == nil || cond.Status != metav1.ConditionTrue {
|
||||
t.Errorf("EgressSvcValid condition = %+v, want status True", cond)
|
||||
}
|
||||
}
|
||||
|
||||
// epsLabels returns the labels that the Reconciler sets on the EndpointSlices that it creates for the egress Service
|
||||
// extNSvc and its ClusterIP Service.
|
||||
func epsLabels(extNSvc, clusterIPSvc *corev1.Service) map[string]string {
|
||||
labels := childResourceLabels(extNSvc)
|
||||
labels[discoveryv1.LabelServiceName] = clusterIPSvc.Name
|
||||
labels[discoveryv1.LabelManagedBy] = "tailscale.com"
|
||||
return labels
|
||||
}
|
||||
|
||||
// tailnetSvcName returns the key of the egress service config for svc in the egress ConfigMap.
|
||||
func tailnetSvcName(svc *corev1.Service) string {
|
||||
return fmt.Sprintf("%s-%s", svc.Namespace, svc.Name)
|
||||
}
|
||||
|
||||
// tailnetTarget returns the tailnet target that the annotations of svc define.
|
||||
func tailnetTarget(svc *corev1.Service) egressservices.TailnetTarget {
|
||||
if fqdn := svc.Annotations[reconciler.AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
return egressservices.TailnetTarget{FQDN: fqdn}
|
||||
}
|
||||
return egressservices.TailnetTarget{IP: svc.Annotations[reconciler.AnnotationTailnetTargetIP]}
|
||||
}
|
||||
|
||||
// configuredReason returns the reason of the EgressSvcConfigured condition once the Reconciler has configured svc. The
|
||||
// reason holds a SHA-256 hash of the configuration, so a change to the ports, the target or the ProxyGroup changes it.
|
||||
func configuredReason(t *testing.T, svc *corev1.Service) string {
|
||||
t.Helper()
|
||||
pg := svc.Annotations[reconciler.AnnotationProxyGroup]
|
||||
bs, err := json.Marshal(struct {
|
||||
Ports []corev1.ServicePort `json:"ports"`
|
||||
TailnetTarget egressservices.TailnetTarget `json:"tailnetTarget"`
|
||||
ProxyGroup string `json:"proxyGroup"`
|
||||
}{svc.Spec.Ports, tailnetTarget(svc), pg})
|
||||
if err != nil {
|
||||
t.Fatalf("marshalling config: %v", err)
|
||||
}
|
||||
return fmt.Sprintf("ConfiguredFor:ProxyGroup:%s:Config:%x", pg, sha256.Sum256(bs))
|
||||
}
|
||||
|
||||
// egressConfig returns the egress service config that the Reconciler writes for extNSvc and its ClusterIP Service.
|
||||
func egressConfig(extNSvc, clusterIPSvc *corev1.Service) egressservices.Config {
|
||||
cfg := egressservices.Config{TailnetTarget: tailnetTarget(extNSvc)}
|
||||
for _, p := range clusterIPSvc.Spec.Ports {
|
||||
if p.Name == "tailscale-health-check" {
|
||||
cfg.HealthCheckEndpoint = fmt.Sprintf("http://%s.%s.svc.cluster.local:%d/healthz", clusterIPSvc.Name, clusterIPSvc.Namespace, p.Port)
|
||||
continue
|
||||
}
|
||||
mak.Set(&cfg.Ports, egressservices.PortMap{
|
||||
Protocol: string(p.Protocol),
|
||||
MatchPort: uint16(p.TargetPort.IntVal),
|
||||
TargetPort: uint16(p.Port),
|
||||
}, struct{}{})
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
@@ -10,10 +10,15 @@ package reconciler
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
@@ -21,8 +26,13 @@ import (
|
||||
"sigs.k8s.io/controller-runtime/pkg/handler"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
tsoperator "tailscale.com/k8s-operator"
|
||||
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
|
||||
"tailscale.com/kube/kubetypes"
|
||||
"tailscale.com/net/dns/resolvconffile"
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/util/clientmetric"
|
||||
"tailscale.com/util/dnsname"
|
||||
"tailscale.com/util/set"
|
||||
)
|
||||
|
||||
@@ -48,6 +58,48 @@ const (
|
||||
optimisticLockErrorMsg = "the object has been modified; please apply your changes to the latest version and try again"
|
||||
)
|
||||
|
||||
// Annotations that users can set on Services (and, for some of them, Ingresses) to configure how the operator exposes
|
||||
// them.
|
||||
const (
|
||||
// AnnotationTailnetTargetIP is the tailnet IP address that cluster traffic sent to the Service is forwarded to.
|
||||
AnnotationTailnetTargetIP = "tailscale.com/tailnet-ip"
|
||||
|
||||
// AnnotationTailnetTargetIPOld is the deprecated form of AnnotationTailnetTargetIP. It is still read if
|
||||
// AnnotationTailnetTargetIP is not set.
|
||||
AnnotationTailnetTargetIPOld = "tailscale.com/ts-tailnet-target-ip"
|
||||
|
||||
// AnnotationTailnetTargetFQDN is the MagicDNS name of the tailnet node that cluster traffic sent to the Service is
|
||||
// forwarded to.
|
||||
AnnotationTailnetTargetFQDN = "tailscale.com/tailnet-fqdn"
|
||||
|
||||
// AnnotationProxyGroup is the name of the ProxyGroup whose proxies expose the annotated resource.
|
||||
AnnotationProxyGroup = "tailscale.com/proxy-group"
|
||||
|
||||
// AnnotationHostname is the tailnet hostname for the proxy of the annotated resource.
|
||||
AnnotationHostname = "tailscale.com/hostname"
|
||||
|
||||
// AnnotationTags is a comma-separated list of tags for the proxy of the annotated resource.
|
||||
AnnotationTags = "tailscale.com/tags"
|
||||
)
|
||||
|
||||
// LabelProxyGroup is set on resources that the operator creates for a Service or Ingress exposed on a ProxyGroup. Its
|
||||
// value is the name of the ProxyGroup.
|
||||
const LabelProxyGroup = "tailscale.com/proxy-group"
|
||||
|
||||
const (
|
||||
// ParentTypeProxyGroup is the LabelParentType value on resources that the operator creates for a ProxyGroup.
|
||||
ParentTypeProxyGroup = "proxygroup"
|
||||
|
||||
// EgressReadinessGate is the Pod readiness gate on egress ProxyGroup Pods. The egress Pod reconciler sets the
|
||||
// condition once the Pod can route traffic to all egress services of its ProxyGroup.
|
||||
EgressReadinessGate = "tailscale.com/egress-services"
|
||||
)
|
||||
|
||||
const (
|
||||
resolvConfPath = "/etc/resolv.conf"
|
||||
defaultClusterDomain = "cluster.local"
|
||||
)
|
||||
|
||||
// IsOptimisticLockError reports whether err was caused by an optimistic locking conflict, i.e. the object being
|
||||
// updated was modified after the reconciler read it. Such an error is transient: the reconciler should requeue and
|
||||
// retry against a freshly read object rather than surface the error.
|
||||
@@ -301,3 +353,182 @@ func GetSingleObject[T any, O PtrObject[T]](ctx context.Context, c client.Client
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// ValidateService returns the problems with the Tailscale configuration of svc. It checks the tailnet target
|
||||
// annotations, the tailnet hostname, and the tags. It returns an empty slice if svc is valid.
|
||||
func ValidateService(svc *corev1.Service) []string {
|
||||
violations := make([]string, 0)
|
||||
if svc.Spec.ClusterIP == "None" {
|
||||
violations = append(violations, "headless Services are not supported.")
|
||||
}
|
||||
if svc.Annotations[AnnotationTailnetTargetFQDN] != "" && svc.Annotations[AnnotationTailnetTargetIP] != "" {
|
||||
violations = append(violations, fmt.Sprintf("only one of annotations %s and %s can be set", AnnotationTailnetTargetIP, AnnotationTailnetTargetFQDN))
|
||||
}
|
||||
if fqdn := svc.Annotations[AnnotationTailnetTargetFQDN]; fqdn != "" {
|
||||
if !isMagicDNSName(fqdn) {
|
||||
violations = append(violations, fmt.Sprintf("invalid value of annotation %s: %q does not appear to be a valid MagicDNS name", AnnotationTailnetTargetFQDN, fqdn))
|
||||
}
|
||||
}
|
||||
if ipStr := svc.Annotations[AnnotationTailnetTargetIP]; ipStr != "" {
|
||||
ip, err := netip.ParseAddr(ipStr)
|
||||
if err != nil {
|
||||
violations = append(violations, fmt.Sprintf("invalid value of annotation %s: %q could not be parsed as a valid IP Address, error: %s", AnnotationTailnetTargetIP, ipStr, err))
|
||||
} else if !ip.IsValid() {
|
||||
violations = append(violations, fmt.Sprintf("parsed IP address in annotation %s: %q is not valid", AnnotationTailnetTargetIP, ipStr))
|
||||
}
|
||||
}
|
||||
|
||||
svcName := NameForService(svc)
|
||||
if err := dnsname.ValidLabel(svcName); err != nil {
|
||||
if _, ok := svc.Annotations[AnnotationHostname]; ok {
|
||||
violations = append(violations, fmt.Sprintf("invalid Tailscale hostname specified %q: %s", svcName, err))
|
||||
} else {
|
||||
violations = append(violations, fmt.Sprintf("invalid Tailscale hostname %q, use %q annotation to override: %s", svcName, AnnotationHostname, err))
|
||||
}
|
||||
}
|
||||
violations = append(violations, TagViolations(svc)...)
|
||||
return violations
|
||||
}
|
||||
|
||||
// NameForService returns the tailnet hostname for the proxy of svc. It is the value of AnnotationHostname if set, or
|
||||
// <namespace>-<name> otherwise. For an egress Service, a default that is longer than a DNS label allows is shortened
|
||||
// with a hash suffix.
|
||||
func NameForService(svc *corev1.Service) string {
|
||||
if h, ok := svc.Annotations[AnnotationHostname]; ok {
|
||||
return h
|
||||
}
|
||||
name := svc.Namespace + "-" + svc.Name
|
||||
if isEgressService(svc) {
|
||||
// The hostname of an egress proxy is not user facing, so instead of
|
||||
// failing validation, shorten a default that is longer than a DNS
|
||||
// label allows. Defaults that already fit are unchanged.
|
||||
return tsoperator.TruncateWithHash(name)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// isEgressService reports whether svc exposes a tailnet target to the cluster.
|
||||
func isEgressService(svc *corev1.Service) bool {
|
||||
return svc.Annotations[AnnotationTailnetTargetIP] != "" ||
|
||||
svc.Annotations[AnnotationTailnetTargetIPOld] != "" ||
|
||||
svc.Annotations[AnnotationTailnetTargetFQDN] != ""
|
||||
}
|
||||
|
||||
// TagViolations returns a problem for each tag in the AnnotationTags annotation of obj that is not a valid tag. It
|
||||
// returns nil if obj is nil or does not have the annotation.
|
||||
func TagViolations(obj client.Object) []string {
|
||||
var violations []string
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
tags, ok := obj.GetAnnotations()[AnnotationTags]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for tag := range strings.SplitSeq(tags, ",") {
|
||||
tag = strings.TrimSpace(tag)
|
||||
if err := tailcfg.CheckTag(tag); err != nil {
|
||||
violations = append(violations, fmt.Sprintf("invalid tag %q: %v", tag, err))
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// isMagicDNSName reports whether name is a full tailnet node FQDN (with or
|
||||
// without final dot).
|
||||
func isMagicDNSName(name string) bool {
|
||||
validMagicDNSName := regexp.MustCompile(`^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.ts\.net\.?$`)
|
||||
return validMagicDNSName.MatchString(name)
|
||||
}
|
||||
|
||||
// ClusterDomainOption configures ClusterDomain.
|
||||
type ClusterDomainOption func(*clusterDomainOptions)
|
||||
|
||||
type clusterDomainOptions struct {
|
||||
resolvConfPath string
|
||||
}
|
||||
|
||||
// WithResolvConfPath sets the resolver config file that ClusterDomain parses. Only tests need it. The operator uses
|
||||
// the resolver config of its own Pod.
|
||||
func WithResolvConfPath(path string) ClusterDomainOption {
|
||||
return func(o *clusterDomainOptions) { o.resolvConfPath = path }
|
||||
}
|
||||
|
||||
// ClusterDomain determines and retrieves cluster domain i.e
|
||||
// (cluster.local) in which this Pod is running by parsing search domains in
|
||||
// /etc/resolv.conf. If an error is encountered at any point during the process,
|
||||
// defaults cluster domain to 'cluster.local'.
|
||||
func ClusterDomain(namespace string, logger *zap.SugaredLogger, opts ...ClusterDomainOption) string {
|
||||
o := clusterDomainOptions{resolvConfPath: resolvConfPath}
|
||||
for _, opt := range opts {
|
||||
opt(&o)
|
||||
}
|
||||
|
||||
logger.Infof("attempting to retrieve cluster domain..")
|
||||
conf, err := resolvconffile.ParseFile(o.resolvConfPath)
|
||||
if err != nil {
|
||||
// Vast majority of clusters use the cluster.local domain, so it
|
||||
// is probably better to fall back to that than error out.
|
||||
logger.Warn("error parsing /etc/resolv.conf to determine cluster domain, defaulting to 'cluster.local'.")
|
||||
return defaultClusterDomain
|
||||
}
|
||||
return clusterDomainFromResolverConf(conf, namespace, logger)
|
||||
}
|
||||
|
||||
// clusterDomainFromResolverConf attempts to retrieve cluster domain from the provided resolver config.
|
||||
// It expects the first three search domains in the resolver config to be ['<namespace>.svc.<cluster-domain>, svc.<cluster-domain>, <cluster-domain>, ...]
|
||||
// If the first three domains match the expected structure, it returns the third.
|
||||
// If the domains don't match the expected structure or an error is encountered, it defaults to 'cluster.local' domain.
|
||||
func clusterDomainFromResolverConf(conf *resolvconffile.Config, namespace string, logger *zap.SugaredLogger) string {
|
||||
if len(conf.SearchDomains) < 3 {
|
||||
logger.Warnf(" resolver config contains only %d search domains, at least three expected.\nDefaulting cluster domain to 'cluster.local'.", len(conf.SearchDomains))
|
||||
return defaultClusterDomain
|
||||
}
|
||||
first := conf.SearchDomains[0]
|
||||
if !strings.HasPrefix(string(first), namespace+".svc") {
|
||||
logger.Warnf("first search domain in resolver config is %s; expected %s.\nDefaulting cluster domain to 'cluster.local'.", first, namespace+".svc.<cluster-domain>")
|
||||
return defaultClusterDomain
|
||||
}
|
||||
second := conf.SearchDomains[1]
|
||||
if !strings.HasPrefix(string(second), "svc") {
|
||||
logger.Warnf("second search domain in resolver config is %s; expected 'svc.<cluster-domain>'.\nDefaulting cluster domain to 'cluster.local'.", second)
|
||||
return defaultClusterDomain
|
||||
}
|
||||
// Trim the trailing dot for backwards compatibility purposes as the
|
||||
// cluster domain was previously hardcoded to 'cluster.local' without a
|
||||
// trailing dot.
|
||||
probablyClusterDomain := strings.TrimPrefix(second.WithoutTrailingDot(), "svc.")
|
||||
third := conf.SearchDomains[2]
|
||||
if !strings.EqualFold(third.WithoutTrailingDot(), probablyClusterDomain) {
|
||||
logger.Warnf("expected resolver config to contain serch domains <namespace>.svc.<cluster-domain>, svc.<cluster-domain>, <cluster-domain>; got %s %s %s\n. Defaulting cluster domain to 'cluster.local'.", first, second, third)
|
||||
return defaultClusterDomain
|
||||
}
|
||||
logger.Infof("Cluster domain %q extracted from resolver config", probablyClusterDomain)
|
||||
return probablyClusterDomain
|
||||
}
|
||||
|
||||
// ProxyGroupLabels returns the labels for a resource that the operator creates for the named ProxyGroup. The result
|
||||
// holds customLabels plus the standard labels for a managed child of the ProxyGroup. The standard labels take
|
||||
// precedence.
|
||||
func ProxyGroupLabels(pgName string, customLabels map[string]string) map[string]string {
|
||||
labels := make(map[string]string, len(customLabels)+3)
|
||||
maps.Copy(labels, customLabels)
|
||||
maps.Copy(labels, Labels(ParentTypeProxyGroup, pgName, ""))
|
||||
return labels
|
||||
}
|
||||
|
||||
// ProxyGroupReplicas returns the number of replicas for pg. It is 2 if pg does not set the replicas.
|
||||
func ProxyGroupReplicas(pg *tsapi.ProxyGroup) int32 {
|
||||
if pg.Spec.Replicas != nil {
|
||||
return *pg.Spec.Replicas
|
||||
}
|
||||
|
||||
return 2
|
||||
}
|
||||
|
||||
// ProxyGroupEgressConfigMapName returns the name of the ConfigMap that holds the egress service configuration for the
|
||||
// named egress ProxyGroup.
|
||||
func ProxyGroupEgressConfigMapName(pgName string) string {
|
||||
return fmt.Sprintf("%s-egress-config", pgName)
|
||||
}
|
||||
@@ -9,9 +9,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"go.uber.org/zap"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
@@ -294,3 +297,238 @@ func TestEnsureAndClearFinalizer(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestValidateService(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
annotations map[string]string
|
||||
clusterIP string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "valid-magicdns-name",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.tail4567.ts.net",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid-magicdns-name-with-trailing-dot",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.tail4567.ts.net.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid-magicdns-name",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.tail4567",
|
||||
},
|
||||
want: []string{`invalid value of annotation tailscale.com/tailnet-fqdn: "foo.tail4567" does not appear to be a valid MagicDNS name`},
|
||||
},
|
||||
{
|
||||
name: "both-tailnet-targets",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.tail4567.ts.net",
|
||||
reconciler.AnnotationTailnetTargetIP: "100.64.0.1",
|
||||
},
|
||||
want: []string{"only one of annotations tailscale.com/tailnet-ip and tailscale.com/tailnet-fqdn can be set"},
|
||||
},
|
||||
{
|
||||
name: "invalid-tailnet-ip",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetIP: "not-an-ip",
|
||||
},
|
||||
want: []string{`invalid value of annotation tailscale.com/tailnet-ip: "not-an-ip" could not be parsed as a valid IP Address, error: ParseAddr("not-an-ip"): unable to parse IP`},
|
||||
},
|
||||
{
|
||||
name: "headless",
|
||||
clusterIP: "None",
|
||||
want: []string{"headless Services are not supported."},
|
||||
},
|
||||
{
|
||||
name: "invalid-hostname",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationHostname: "foo.bar",
|
||||
},
|
||||
want: []string{`invalid Tailscale hostname specified "foo.bar": "foo.bar" is not a valid DNS label: contains invalid character '.'`},
|
||||
},
|
||||
{
|
||||
name: "invalid-tag",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTags: "tag:ok,notatag",
|
||||
},
|
||||
want: []string{`invalid tag "notatag": tags must start with 'tag:'`},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "test",
|
||||
Namespace: "default",
|
||||
Annotations: tc.annotations,
|
||||
},
|
||||
Spec: corev1.ServiceSpec{ClusterIP: tc.clusterIP},
|
||||
}
|
||||
got := reconciler.ValidateService(svc)
|
||||
if len(got) == 0 && len(tc.want) == 0 {
|
||||
return
|
||||
}
|
||||
if !slices.Equal(got, tc.want) {
|
||||
t.Errorf("ValidateService() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameForService(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
longNS = "tailscale-external-services"
|
||||
longName = "harry1027133059-trefknee01-bee-oqggo-kinfe-0-g"
|
||||
)
|
||||
tests := []struct {
|
||||
name string
|
||||
svcName string
|
||||
annotations map[string]string
|
||||
want string
|
||||
wantValid bool
|
||||
}{
|
||||
{
|
||||
name: "egress_fqdn_short_default_unchanged",
|
||||
svcName: "foo",
|
||||
annotations: map[string]string{reconciler.AnnotationTailnetTargetFQDN: "foo.tailnet.ts.net"},
|
||||
want: longNS + "-foo",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_fqdn_long_default_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{reconciler.AnnotationTailnetTargetFQDN: longName + ".tailnet.ts.net"},
|
||||
want: "tailscale-external-services-harry1027133059-trefknee01-0908ae76",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_ip_long_default_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{reconciler.AnnotationTailnetTargetIP: "100.64.0.1"},
|
||||
want: "tailscale-external-services-harry1027133059-trefknee01-0908ae76",
|
||||
wantValid: true,
|
||||
},
|
||||
{
|
||||
name: "egress_long_hostname_annotation_not_truncated",
|
||||
annotations: map[string]string{
|
||||
reconciler.AnnotationTailnetTargetFQDN: "foo.tailnet.ts.net",
|
||||
reconciler.AnnotationHostname: longNS + "-" + longName,
|
||||
},
|
||||
svcName: "foo",
|
||||
want: longNS + "-" + longName,
|
||||
wantValid: false,
|
||||
},
|
||||
{
|
||||
name: "ingress_long_default_not_truncated",
|
||||
svcName: longName,
|
||||
annotations: map[string]string{"tailscale.com/expose": "true"},
|
||||
want: longNS + "-" + longName,
|
||||
wantValid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &corev1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tc.svcName,
|
||||
Namespace: longNS,
|
||||
Annotations: tc.annotations,
|
||||
},
|
||||
}
|
||||
got := reconciler.NameForService(svc)
|
||||
if got != tc.want {
|
||||
t.Errorf("NameForService() = %q, want %q", got, tc.want)
|
||||
}
|
||||
violations := reconciler.ValidateService(svc)
|
||||
if valid := len(violations) == 0; valid != tc.wantValid {
|
||||
t.Errorf("ValidateService() violations = %v, want valid %t", violations, tc.wantValid)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClusterDomain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// resolvConf is the content of the file that ClusterDomain parses. Empty means that the file does not exist.
|
||||
resolvConf string
|
||||
namespace string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "success-custom-domain",
|
||||
resolvConf: "search foo.svc.department.org.io svc.department.org.io department.org.io\n",
|
||||
namespace: "foo",
|
||||
want: "department.org.io",
|
||||
},
|
||||
{
|
||||
name: "success-default-domain",
|
||||
resolvConf: "search foo.svc.cluster.local. svc.cluster.local. cluster.local.\n",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "only-two-search-domains",
|
||||
resolvConf: "search svc.department.org.io department.org.io\n",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "first-search-domain-mismatch",
|
||||
resolvConf: "search foo.bar.department.org.io svc.department.org.io some.other.fqdn\n",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "second-search-domain-mismatch",
|
||||
resolvConf: "search foo.svc.department.org.io foo.department.org.io some.other.fqdn\n",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "third-search-domain-mismatch",
|
||||
resolvConf: "search foo.svc.department.org.io svc.department.org.io some.other.fqdn\n",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
{
|
||||
name: "missing-resolv-conf",
|
||||
namespace: "foo",
|
||||
want: "cluster.local",
|
||||
},
|
||||
}
|
||||
|
||||
logger := zap.Must(zap.NewDevelopment()).Sugar()
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
path := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
if tc.resolvConf != "" {
|
||||
if err := os.WriteFile(path, []byte(tc.resolvConf), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := reconciler.ClusterDomain(tc.namespace, logger, reconciler.WithResolvConfPath(path)); got != tc.want {
|
||||
t.Errorf("ClusterDomain() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -176,6 +176,19 @@ func ExpectReconciled(t *testing.T, r reconcile.Reconciler, ns, name string) {
|
||||
}
|
||||
}
|
||||
|
||||
// ExpectRequeue runs a single reconcile for ns/name and asserts it succeeded and asked to be requeued after a delay,
|
||||
// i.e. the reconciler is waiting for something it does not control.
|
||||
func ExpectRequeue(t *testing.T, r reconcile.Reconciler, ns, name string) {
|
||||
t.Helper()
|
||||
res, err := r.Reconcile(t.Context(), request(ns, name))
|
||||
if err != nil {
|
||||
t.Fatalf("Reconcile: unexpected error: %v", err)
|
||||
}
|
||||
if res.RequeueAfter == 0 {
|
||||
t.Fatalf("expected timed requeue, got success")
|
||||
}
|
||||
}
|
||||
|
||||
func request(ns, name string) reconcile.Request {
|
||||
return reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: name}}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user