From b015021747faeac6cad6d4488717e8f2c2dab35e Mon Sep 17 00:00:00 2001 From: Irbe Krumina Date: Tue, 14 Nov 2023 07:23:50 +0100 Subject: [PATCH] cmd/k8s-operator: use c/r leader election Signed-off-by: Irbe Krumina --- .../deploy/chart/templates/operator-rbac.yaml | 28 +++++++++++++++++++ cmd/k8s-operator/operator.go | 12 +++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/cmd/k8s-operator/deploy/chart/templates/operator-rbac.yaml b/cmd/k8s-operator/deploy/chart/templates/operator-rbac.yaml index 5fc7ad203..d631a1053 100644 --- a/cmd/k8s-operator/deploy/chart/templates/operator-rbac.yaml +++ b/cmd/k8s-operator/deploy/chart/templates/operator-rbac.yaml @@ -58,3 +58,31 @@ roleRef: kind: Role name: operator apiGroup: rbac.authorization.k8s.io +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: tailscale-operator-leaderelection + namespace: kube-system +rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + resourceNames: ["tailscale-operator"] + verbs: ["get", "update", "patch"] + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: tailscale-operator-leaderelection + namespace: kube-system +subjects: +- kind: ServiceAccount + name: operator + namespace: {{ .Release.Namespace }} +roleRef: + kind: Role + name: tailscale-operator-leaderelection + apiGroup: rbac.authorization.k8s.io diff --git a/cmd/k8s-operator/operator.go b/cmd/k8s-operator/operator.go index 79d70778a..7f8617ebc 100644 --- a/cmd/k8s-operator/operator.go +++ b/cmd/k8s-operator/operator.go @@ -41,6 +41,12 @@ import ( "tailscale.com/version" ) +const ( + leaderElectionLock = "tailscale-operator" +) + +type tsSetupFunc func() tsSetup + func main() { // Required to use our client API. We're fine with the instability since the // client lives in the same repo as this code. @@ -203,7 +209,11 @@ func runReconcilers(zlog *zap.SugaredLogger, s *tsnet.Server, tsNamespace string nsFilter := cache.ByObject{ Field: client.InNamespace(tsNamespace).AsSelector(), } - mgr, err := manager.New(restConfig, manager.Options{ + mgr, err := manager.New(c.restConfig, manager.Options{ + LeaderElectionNamespace: "kube-system", + LeaderElection: true, + LeaderElectionReleaseOnCancel: true, + LeaderElectionID: leaderElectionLock, Cache: cache.Options{ ByObject: map[client.Object]cache.ByObject{ &corev1.Secret{}: nsFilter,