Skip to content

Commit 0816696

Browse files
committed
add leader election support for external snapshotter
Signed-off-by: Andrew Sy Kim <[email protected]>
1 parent 68a0ecd commit 0816696

File tree

1 file changed

+33
-12
lines changed

1 file changed

+33
-12
lines changed

cmd/csi-snapshotter/main.go

+33-12
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"k8s.io/client-go/tools/clientcmd"
3131
"k8s.io/klog"
3232

33+
"github.com/kubernetes-csi/csi-lib-utils/leaderelection"
3334
"github.com/kubernetes-csi/external-snapshotter/pkg/connection"
3435
"github.com/kubernetes-csi/external-snapshotter/pkg/controller"
3536

@@ -60,10 +61,14 @@ var (
6061
snapshotNamePrefix = flag.String("snapshot-name-prefix", "snapshot", "Prefix to apply to the name of a created snapshot")
6162
snapshotNameUUIDLength = flag.Int("snapshot-name-uuid-length", -1, "Length in characters for the generated uuid of a created snapshot. Defaults behavior is to NOT truncate.")
6263
showVersion = flag.Bool("version", false, "Show version.")
64+
65+
leaderElection = flag.Bool("leader-election", false, "enables leader election")
66+
leaderElectionNamespace = flag.String("leader-election-namespace", "", "the namespace where the leader election lock exists, should be the same namespace attacher runs")
6367
)
6468

6569
var (
66-
version = "unknown"
70+
version = "unknown"
71+
leaderElectionLockName = "external-snapshotter-leader-election"
6772
)
6873

6974
func main() {
@@ -183,17 +188,33 @@ func main() {
183188
*snapshotNameUUIDLength,
184189
)
185190

186-
// run...
187-
stopCh := make(chan struct{})
188-
factory.Start(stopCh)
189-
coreFactory.Start(stopCh)
190-
go ctrl.Run(threads, stopCh)
191-
192-
// ...until SIGINT
193-
c := make(chan os.Signal, 1)
194-
signal.Notify(c, os.Interrupt)
195-
<-c
196-
close(stopCh)
191+
run := func(context.Context) {
192+
// run...
193+
stopCh := make(chan struct{})
194+
factory.Start(stopCh)
195+
coreFactory.Start(stopCh)
196+
go ctrl.Run(threads, stopCh)
197+
198+
// ...until SIGINT
199+
c := make(chan os.Signal, 1)
200+
signal.Notify(c, os.Interrupt)
201+
<-c
202+
close(stopCh)
203+
}
204+
205+
if !*leaderElection {
206+
run(context.TODO())
207+
} else {
208+
if *leaderElectionNamespace == "" {
209+
klog.Error("--leader-election-namespace is required")
210+
os.Exit(1)
211+
}
212+
213+
le := leaderelection.NewLeaderElection(kubeClient, leaderElectionLockName, *leaderElectionNamespace, run)
214+
if err := le.Run(); err != nil {
215+
klog.Fatalf("failed to initialze leader election: %v", err)
216+
}
217+
}
197218
}
198219

199220
func buildConfig(kubeconfig string) (*rest.Config, error) {

0 commit comments

Comments
 (0)