From e8fce5026aebecb45133ffb32963ef6575c1df0a Mon Sep 17 00:00:00 2001 From: chaosinthecrd Date: Mon, 26 Oct 2026 06:41:08 +0000 Subject: [PATCH] cmd/{k8s-proxy,k8s-operator},k8s-operator: serve k8s-proxy /livez and /readyz k8s-proxy did not serve /livez or /readyz, so the operator skipped the probes for the kube-apiserver ProxyGroup even when a ProxyClass set them. This adds both to k8s-proxy (/livez passes while the LocalAPI answers, /readyz once the node has its tailnet IPs) and drops the exception from the operator. k8s-proxy takes its port from the config file that the operator writes, so its probes always use port 9002 and ignore TS_LOCAL_ADDR_PORT and TS_ENABLE_HEALTH_CHECK. The local server now starts before Up, so /livez answers while Up runs and while waiting for a reissued auth key. Updates tailscale/corp#38175 Signed-off-by: chaosinthecrd --- .../crds/tailscale.com_proxyclasses.yaml | 6 +- .../deploy/manifests/operator.yaml | 6 +- cmd/k8s-operator/proxygroup.go | 8 +- cmd/k8s-operator/proxygroup_test.go | 2 +- cmd/k8s-operator/sts.go | 23 ++-- cmd/k8s-operator/sts_test.go | 2 +- cmd/k8s-proxy/health.go | 55 ++++++++++ cmd/k8s-proxy/k8s-proxy.go | 102 ++++++++++-------- k8s-operator/api.md | 2 +- .../apis/v1alpha1/types_proxyclass.go | 3 +- 10 files changed, 139 insertions(+), 70 deletions(-) create mode 100644 cmd/k8s-proxy/health.go diff --git a/cmd/k8s-operator/deploy/crds/tailscale.com_proxyclasses.yaml b/cmd/k8s-operator/deploy/crds/tailscale.com_proxyclasses.yaml index 2febaa6fa..bc1bac1e4 100644 --- a/cmd/k8s-operator/deploy/crds/tailscale.com_proxyclasses.yaml +++ b/cmd/k8s-operator/deploy/crds/tailscale.com_proxyclasses.yaml @@ -1499,7 +1499,8 @@ spec: Services, has applied its serve config and has a TLS cert for each HTTPS-only Tailscale Service. Off unless set; {} runs it with the default timing. Older proxy images don't serve /readyz and fail the probe. - Only used by ProxyGroups. + Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits + for the tailnet IP address. type: object properties: failureThreshold: @@ -1913,7 +1914,8 @@ spec: Services, has applied its serve config and has a TLS cert for each HTTPS-only Tailscale Service. Off unless set; {} runs it with the default timing. Older proxy images don't serve /readyz and fail the probe. - Only used by ProxyGroups. + Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits + for the tailnet IP address. type: object properties: failureThreshold: diff --git a/cmd/k8s-operator/deploy/manifests/operator.yaml b/cmd/k8s-operator/deploy/manifests/operator.yaml index a71fb6ea7..4ffe82984 100644 --- a/cmd/k8s-operator/deploy/manifests/operator.yaml +++ b/cmd/k8s-operator/deploy/manifests/operator.yaml @@ -3302,7 +3302,8 @@ spec: Services, has applied its serve config and has a TLS cert for each HTTPS-only Tailscale Service. Off unless set; {} runs it with the default timing. Older proxy images don't serve /readyz and fail the probe. - Only used by ProxyGroups. + Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits + for the tailnet IP address. properties: failureThreshold: default: 3 @@ -3716,7 +3717,8 @@ spec: Services, has applied its serve config and has a TLS cert for each HTTPS-only Tailscale Service. Off unless set; {} runs it with the default timing. Older proxy images don't serve /readyz and fail the probe. - Only used by ProxyGroups. + Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits + for the tailnet IP address. properties: failureThreshold: default: 3 diff --git a/cmd/k8s-operator/proxygroup.go b/cmd/k8s-operator/proxygroup.go index b1acea67a..1513d48a7 100644 --- a/cmd/k8s-operator/proxygroup.go +++ b/cmd/k8s-operator/proxygroup.go @@ -459,11 +459,7 @@ func (r *ProxyGroupReconciler) maybeProvision(ctx context.Context, tsClient tscl proxyType: string(pg.Spec.Type), } ss = applyProxyClassToStatefulSet(proxyClass, ss, cfg, logger) - - // TODO(ChaosInTheCRD): temporary check, remove when probes are added for kube-apiserver ProxyGroups. - if pg.Spec.Type != tsapi.ProxyGroupTypeKubernetesAPIServer { - applyHealthzProbes(proxyClass, ss) - } + applyHealthzProbes(proxyClass, ss, pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer) if replaced, err := r.maybeReplaceStatefulSet(ctx, ss, logger); err != nil { return r.notReadyErrf(pg, logger, "failed to replace StatefulSet: %w", err) @@ -797,7 +793,7 @@ func (r *ProxyGroupReconciler) ensureConfigSecretsCreated( // as containerboot does for ingress-pg-reconciler. IssueCerts: opt.NewBool(i == 0), }, - LocalPort: new(uint16(9002)), + LocalPort: new(uint16(defaultLocalAddrPort)), HealthCheckEnabled: opt.NewBool(true), }, } diff --git a/cmd/k8s-operator/proxygroup_test.go b/cmd/k8s-operator/proxygroup_test.go index 9bd8871e3..31f44bce1 100644 --- a/cmd/k8s-operator/proxygroup_test.go +++ b/cmd/k8s-operator/proxygroup_test.go @@ -2356,7 +2356,7 @@ func expectProxyGroupResources(t *testing.T, fc client.WithWatch, pg *tsapi.Prox } statefulSet.Annotations = defaultProxyClassAnnotations if pg.Spec.Type != tsapi.ProxyGroupTypeKubernetesAPIServer { - applyHealthzProbes(proxyClass, statefulSet) + applyHealthzProbes(proxyClass, statefulSet, false) } if shouldExist { diff --git a/cmd/k8s-operator/sts.go b/cmd/k8s-operator/sts.go index c660f5239..7c4025d8b 100644 --- a/cmd/k8s-operator/sts.go +++ b/cmd/k8s-operator/sts.go @@ -1267,8 +1267,10 @@ func isMainContainer(c *corev1.Container) bool { // /livez and /readyz endpoints to the main container, and enables those // endpoints via TS_ENABLE_HEALTH_CHECK. Each probe is off unless the ProxyClass // 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]. -func applyHealthzProbes(pc *tsapi.ProxyClass, ss *appsv1.StatefulSet) { +// 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. +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 { liveness = pc.Spec.StatefulSet.Pod.TailscaleContainer.LivenessProbe @@ -1282,13 +1284,16 @@ func applyHealthzProbes(pc *tsapi.ProxyClass, ss *appsv1.StatefulSet) { if !isMainContainer(&c) { continue } - port, ok := healthzPort(c.Env) - if !ok { - return - } - if _, ok := lookupEnv(c.Env, "TS_ENABLE_HEALTH_CHECK"); !ok { - ss.Spec.Template.Spec.Containers[i].Env = append(ss.Spec.Template.Spec.Containers[i].Env, - corev1.EnvVar{Name: "TS_ENABLE_HEALTH_CHECK", Value: "true"}) + port := defaultLocalAddrPort + if !k8sProxy { + var ok bool + if port, ok = healthzPort(c.Env); !ok { + return + } + if _, ok := lookupEnv(c.Env, "TS_ENABLE_HEALTH_CHECK"); !ok { + ss.Spec.Template.Spec.Containers[i].Env = append(ss.Spec.Template.Spec.Containers[i].Env, + corev1.EnvVar{Name: "TS_ENABLE_HEALTH_CHECK", Value: "true"}) + } } if liveness != nil { // Longer than for readiness, as a restart drops the traffic a slow tailscaled still carries. diff --git a/cmd/k8s-operator/sts_test.go b/cmd/k8s-operator/sts_test.go index 8b5409caf..d22417c58 100644 --- a/cmd/k8s-operator/sts_test.go +++ b/cmd/k8s-operator/sts_test.go @@ -354,7 +354,7 @@ func Test_applyHealthzProbes(t *testing.T) { t.Fatalf("unmarshaling proxy template: %v", err) } ss.Spec.Template.Spec.Containers[0].Env = append(ss.Spec.Template.Spec.Containers[0].Env, tt.env...) - applyHealthzProbes(tt.pc, &ss) + applyHealthzProbes(tt.pc, &ss, false) c := ss.Spec.Template.Spec.Containers[0] if got := c.LivenessProbe != nil; got != tt.wantLiveness { diff --git a/cmd/k8s-proxy/health.go b/cmd/k8s-proxy/health.go new file mode 100644 index 000000000..bc2066180 --- /dev/null +++ b/cmd/k8s-proxy/health.go @@ -0,0 +1,55 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !plan9 + +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + + "tailscale.com/ipn/ipnstate" + healthz "tailscale.com/kube/health" + "tailscale.com/types/logger" +) + +// healthLocalClient is the subset of [local.Client] used by the health checks. +type healthLocalClient interface { + StatusWithoutPeers(context.Context) (*ipnstate.Status, error) +} + +// registerHealthChecks registers the /livez and /readyz probes and their +// checks on mux. It must be called before mux is served. +func registerHealthChecks(mux *http.ServeMux, lc healthLocalClient, logf logger.Logf) { + healthz.RegisterLivezHandlers(mux, logf).AddCheck("localapi", localAPIResponding(lc)) + healthz.RegisterReadyzHandlers(mux, logf).AddCheck("netmap", hasTailnetIPs(lc)) +} + +// localAPIResponding returns a check that passes while the LocalAPI answers a +// cheap request. +func localAPIResponding(lc healthLocalClient) func(context.Context) error { + return func(ctx context.Context) error { + if _, err := lc.StatusWithoutPeers(ctx); err != nil { + return fmt.Errorf("failed to get status: %w", err) + } + return nil + } +} + +// hasTailnetIPs returns a check that passes once the node has received a +// netmap with its tailnet IPs. +func hasTailnetIPs(lc healthLocalClient) func(context.Context) error { + return func(ctx context.Context) error { + st, err := lc.StatusWithoutPeers(ctx) + if err != nil { + return fmt.Errorf("failed to get status: %w", err) + } + if st.Self == nil || len(st.Self.TailscaleIPs) == 0 { + return errors.New("no netmap with tailnet IPs received yet") + } + return nil + } +} diff --git a/cmd/k8s-proxy/k8s-proxy.go b/cmd/k8s-proxy/k8s-proxy.go index d82c9badc..bf7427486 100644 --- a/cmd/k8s-proxy/k8s-proxy.go +++ b/cmd/k8s-proxy/k8s-proxy.go @@ -233,6 +233,48 @@ func run(logger *zap.SugaredLogger) error { return fmt.Errorf("error getting local client: %w", err) } + // Serve the local endpoints before Up, so /livez answers while Up runs and + // while waiting for a reissued auth key. + var mux *http.ServeMux + if cfg.Parsed.HealthCheckEnabled.EqualBool(true) || cfg.Parsed.MetricsEnabled.EqualBool(true) { + addr := podIP + if addr == "" { + addr = cfg.GetLocalAddr() + } + + addrPort := getLocalAddrPort(addr, cfg.GetLocalPort()) + mux = http.NewServeMux() + localSrv := &http.Server{Addr: addrPort, Handler: mux} + + if cfg.Parsed.MetricsEnabled.EqualBool(true) { + logger.Infof("Running metrics endpoint at %s/metrics", addrPort) + metrics.RegisterMetricsHandlers(mux, lc, "") + } + + if cfg.Parsed.HealthCheckEnabled.EqualBool(true) { + registerHealthChecks(mux, lc, logger.Infof) + } + + group.Go(func() error { + errChan := make(chan error) + go func() { + if err := localSrv.ListenAndServe(); err != nil { + errChan <- err + } + close(errChan) + }() + + select { + case <-ctx.Done(): + sCtx, scancel := context.WithTimeout(serveCtx, 10*time.Second) + defer scancel() + return localSrv.Shutdown(sCtx) + case err := <-errChan: + return err + } + }) + } + // Make sure we crash loop if Up doesn't complete in reasonable time. upCtx, upCancel := context.WithTimeout(ctx, 30*time.Second) defer upCancel() @@ -293,57 +335,23 @@ func run(logger *zap.SugaredLogger) error { } } - if cfg.Parsed.HealthCheckEnabled.EqualBool(true) || cfg.Parsed.MetricsEnabled.EqualBool(true) { - addr := podIP - if addr == "" { - addr = cfg.GetLocalAddr() + // /healthz reports the node's tailnet IPs, so it can only be registered after Up. + if cfg.Parsed.HealthCheckEnabled.EqualBool(true) { + ipV4, ipV6 := ts.TailscaleIPs() + var v4, v6 string + if ipV4.IsValid() { + v4 = ipV4.String() } - - addrPort := getLocalAddrPort(addr, cfg.GetLocalPort()) - mux := http.NewServeMux() - localSrv := &http.Server{Addr: addrPort, Handler: mux} - - if cfg.Parsed.MetricsEnabled.EqualBool(true) { - logger.Infof("Running metrics endpoint at %s/metrics", addrPort) - metrics.RegisterMetricsHandlers(mux, lc, "") + if ipV6.IsValid() { + v6 = ipV6.String() } - - if cfg.Parsed.HealthCheckEnabled.EqualBool(true) { - ipV4, ipV6 := ts.TailscaleIPs() - var v4, v6 string - if ipV4.IsValid() { - v4 = ipV4.String() - } - if ipV6.IsValid() { - v6 = ipV6.String() - } - hz := healthz.RegisterHealthHandlers(mux, v4, v6, logger.Infof) - group.Go(func() error { - err := hz.MonitorHealth(ctx, lc) - if errors.Is(err, context.Canceled) { - return nil - } - return err - }) - } - + hz := healthz.RegisterHealthHandlers(mux, v4, v6, logger.Infof) group.Go(func() error { - errChan := make(chan error) - go func() { - if err := localSrv.ListenAndServe(); err != nil { - errChan <- err - } - close(errChan) - }() - - select { - case <-ctx.Done(): - sCtx, scancel := context.WithTimeout(serveCtx, 10*time.Second) - defer scancel() - return localSrv.Shutdown(sCtx) - case err := <-errChan: - return err + err := hz.MonitorHealth(ctx, lc) + if errors.Is(err, context.Canceled) { + return nil } + return err }) } diff --git a/k8s-operator/api.md b/k8s-operator/api.md index 3c869029f..fea28d034 100644 --- a/k8s-operator/api.md +++ b/k8s-operator/api.md @@ -196,7 +196,7 @@ _Appears in:_ | `securityContext` _[SecurityContext](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.3/#securitycontext-v1-core)_ | Container security context.
Security context specified here will override the security context set by the operator.
By default the operator sets the Tailscale container and the Tailscale init container to privileged
for proxies created for Tailscale ingress and egress Service, Connector and ProxyGroup.
You can reduce the permissions of the Tailscale container to cap NET_ADMIN by
installing device plugin in your cluster and configuring the proxies tun device to be created
by the device plugin, see https://github.com/tailscale/tailscale/issues/10814#issuecomment-2479977752
https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#security-context | | Optional: \{\}
| | `debug` _[Debug](#debug)_ | Configuration for enabling extra debug information in the container.
Not recommended for production use. | | Optional: \{\}
| | `livenessProbe` _[Probe](#probe)_ | Liveness probe against the proxy's /livez endpoint, which fails only when
tailscaled stops responding, not when the tailnet is unreachable. Off
unless set; \{\} runs it with the default timing. Older proxy images don't
serve /livez and fail the probe. Only used by ProxyGroups. | | Optional: \{\}
| -| `readinessProbe` _[Probe](#probe)_ | Readiness probe against the proxy's /readyz endpoint, which passes once
the proxy has a tailnet IP address and, for proxies that serve Tailscale
Services, has applied its serve config and has a TLS cert for each
HTTPS-only Tailscale Service. Off unless set; \{\} runs it with the default
timing. Older proxy images don't serve /readyz and fail the probe.
Only used by ProxyGroups. | | Optional: \{\}
| +| `readinessProbe` _[Probe](#probe)_ | Readiness probe against the proxy's /readyz endpoint, which passes once
the proxy has a tailnet IP address and, for proxies that serve Tailscale
Services, has applied its serve config and has a TLS cert for each
HTTPS-only Tailscale Service. Off unless set; \{\} runs it with the default
timing. Older proxy images don't serve /readyz and fail the probe.
Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits
for the tailnet IP address. | | Optional: \{\}
| #### DNSConfig diff --git a/k8s-operator/apis/v1alpha1/types_proxyclass.go b/k8s-operator/apis/v1alpha1/types_proxyclass.go index 0167e3734..ff9600ea0 100644 --- a/k8s-operator/apis/v1alpha1/types_proxyclass.go +++ b/k8s-operator/apis/v1alpha1/types_proxyclass.go @@ -437,7 +437,8 @@ type Container struct { // Services, has applied its serve config and has a TLS cert for each // HTTPS-only Tailscale Service. Off unless set; {} runs it with the default // timing. Older proxy images don't serve /readyz and fail the probe. - // Only used by ProxyGroups. + // Only used by ProxyGroups. On kube-apiserver ProxyGroups it only waits + // for the tailnet IP address. // +optional ReadinessProbe *Probe `json:"readinessProbe,omitempty"` }