| 1 |
/* |
| 2 |
Copyright 2018 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package main |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"flag" |
| 22 |
"os" |
| 23 |
"os/signal" |
| 24 |
"sync/atomic" |
| 25 |
"syscall" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/google/uuid" |
| 29 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 30 |
clientset "k8s.io/client-go/kubernetes" |
| 31 |
"k8s.io/client-go/rest" |
| 32 |
"k8s.io/client-go/tools/clientcmd" |
| 33 |
"k8s.io/client-go/tools/leaderelection" |
| 34 |
"k8s.io/client-go/tools/leaderelection/resourcelock" |
| 35 |
"k8s.io/klog/v2" |
| 36 |
) |
| 37 |
|
| 38 |
func buildConfig(kubeconfig string) (*rest.Config, error) { |
| 39 |
if kubeconfig != "" { |
| 40 |
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
return cfg, nil |
| 45 |
} |
| 46 |
|
| 47 |
cfg, err := rest.InClusterConfig() |
| 48 |
if err != nil { |
| 49 |
return nil, err |
| 50 |
} |
| 51 |
return cfg, nil |
| 52 |
} |
| 53 |
|
| 54 |
func main() { |
| 55 |
klog.InitFlags(nil) |
| 56 |
|
| 57 |
var kubeconfig string |
| 58 |
var leaseLockName string |
| 59 |
var leaseLockNamespace string |
| 60 |
var id string |
| 61 |
var startedLeading atomic.Bool |
| 62 |
|
| 63 |
flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file") |
| 64 |
flag.StringVar(&id, "id", uuid.New().String(), "the holder identity name") |
| 65 |
flag.StringVar(&leaseLockName, "lease-lock-name", "", "the lease lock resource name") |
| 66 |
flag.StringVar(&leaseLockNamespace, "lease-lock-namespace", "", "the lease lock resource namespace") |
| 67 |
flag.Parse() |
| 68 |
|
| 69 |
if leaseLockName == "" { |
| 70 |
klog.Fatal("unable to get lease lock resource name (missing lease-lock-name flag).") |
| 71 |
} |
| 72 |
if leaseLockNamespace == "" { |
| 73 |
klog.Fatal("unable to get lease lock resource namespace (missing lease-lock-namespace flag).") |
| 74 |
} |
| 75 |
|
| 76 |
// leader election uses the Kubernetes API by writing to a |
| 77 |
// lock object, which can be a LeaseLock object (preferred), |
| 78 |
// a ConfigMap, or an Endpoints (deprecated) object. |
| 79 |
// Conflicting writes are detected and each client handles those actions |
| 80 |
// independently. |
| 81 |
config, err := buildConfig(kubeconfig) |
| 82 |
if err != nil { |
| 83 |
klog.Fatal(err) |
| 84 |
} |
| 85 |
client := clientset.NewForConfigOrDie(config) |
| 86 |
|
| 87 |
run := func(ctx context.Context) { |
| 88 |
// complete your controller loop here |
| 89 |
klog.Info("Controller loop...") |
| 90 |
|
| 91 |
select {} |
| 92 |
} |
| 93 |
|
| 94 |
// use a Go context so we can tell the leaderelection code when we |
| 95 |
// want to step down |
| 96 |
ctx, cancel := context.WithCancel(context.Background()) |
| 97 |
defer cancel() |
| 98 |
|
| 99 |
// listen for interrupts or the Linux SIGTERM signal and cancel |
| 100 |
// our context, which the leader election code will observe and |
| 101 |
// step down |
| 102 |
ch := make(chan os.Signal, 1) |
| 103 |
signal.Notify(ch, os.Interrupt, syscall.SIGTERM) |
| 104 |
go func() { |
| 105 |
<-ch |
| 106 |
klog.Info("Received termination, signaling shutdown") |
| 107 |
cancel() |
| 108 |
}() |
| 109 |
|
| 110 |
// we use the Lease lock type since edits to Leases are less common |
| 111 |
// and fewer objects in the cluster watch "all Leases". |
| 112 |
lock := &resourcelock.LeaseLock{ |
| 113 |
LeaseMeta: metav1.ObjectMeta{ |
| 114 |
Name: leaseLockName, |
| 115 |
Namespace: leaseLockNamespace, |
| 116 |
}, |
| 117 |
Client: client.CoordinationV1(), |
| 118 |
LockConfig: resourcelock.ResourceLockConfig{ |
| 119 |
Identity: id, |
| 120 |
}, |
| 121 |
} |
| 122 |
|
| 123 |
// start the leader election code loop |
| 124 |
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{ |
| 125 |
Lock: lock, |
| 126 |
// IMPORTANT: you MUST ensure that any code you have that |
| 127 |
// is protected by the lease must terminate **before** |
| 128 |
// you call cancel. Otherwise, you could have a background |
| 129 |
// loop still running and another process could |
| 130 |
// get elected before your background loop finished, violating |
| 131 |
// the stated goal of the lease. |
| 132 |
ReleaseOnCancel: true, |
| 133 |
LeaseDuration: 60 * time.Second, |
| 134 |
RenewDeadline: 15 * time.Second, |
| 135 |
RetryPeriod: 5 * time.Second, |
| 136 |
Callbacks: leaderelection.LeaderCallbacks{ |
| 137 |
OnStartedLeading: func(ctx context.Context) { |
| 138 |
// we're notified when we start - this is where you would |
| 139 |
// usually put your code |
| 140 |
startedLeading.Store(true) |
| 141 |
run(ctx) |
| 142 |
}, |
| 143 |
OnStoppedLeading: func() { |
| 144 |
// we can do cleanup here, but note that this callback is always called |
| 145 |
// when the LeaderElector exits, even if it did not start leading. |
| 146 |
// Therefore, we should check if we actually started leading before |
| 147 |
// performing any cleanup operations to avoid unexpected behavior. |
| 148 |
klog.Infof("leader lost: %s", id) |
| 149 |
|
| 150 |
// Example check to ensure we only perform cleanup if we actually started leading |
| 151 |
if startedLeading.Load() { |
| 152 |
// Perform cleanup operations here |
| 153 |
// For example, releasing resources, closing connections, etc. |
| 154 |
klog.Info("Performing cleanup operations...") |
| 155 |
} else { |
| 156 |
klog.Info("No cleanup needed as we never started leading.") |
| 157 |
} |
| 158 |
os.Exit(0) |
| 159 |
}, |
| 160 |
OnNewLeader: func(identity string) { |
| 161 |
// we're notified when new leader elected |
| 162 |
if identity == id { |
| 163 |
// I just got the lock |
| 164 |
return |
| 165 |
} |
| 166 |
klog.Infof("new leader elected: %s", identity) |
| 167 |
}, |
| 168 |
}, |
| 169 |
}) |
| 170 |
} |