Skip to content

Commit f3cbc7f

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

File tree

1 file changed

+31
-12
lines changed

1 file changed

+31
-12
lines changed

cmd/csi-snapshotter/main.go

+31-12
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434

3535
"github.com/container-storage-interface/spec/lib/go/csi"
3636
"github.com/kubernetes-csi/csi-lib-utils/connection"
37+
"github.com/kubernetes-csi/csi-lib-utils/leaderelection"
3738
csirpc "github.com/kubernetes-csi/csi-lib-utils/rpc"
3839
"github.com/kubernetes-csi/external-snapshotter/pkg/controller"
3940
"github.com/kubernetes-csi/external-snapshotter/pkg/snapshotter"
@@ -65,10 +66,14 @@ var (
6566
snapshotNamePrefix = flag.String("snapshot-name-prefix", "snapshot", "Prefix to apply to the name of a created snapshot")
6667
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.")
6768
showVersion = flag.Bool("version", false, "Show version.")
69+
70+
leaderElection = flag.Bool("leader-election", false, "Enables leader election.")
71+
leaderElectionNamespace = flag.String("leader-election-namespace", "", "The namespace where the leader election resource exists. It should be the same namespace where the attacher runs.")
6872
)
6973

7074
var (
71-
version = "unknown"
75+
version = "unknown"
76+
leaderElectionLockName = "external-snapshotter-leader-election"
7277
)
7378

7479
func main() {
@@ -192,17 +197,31 @@ func main() {
192197
*snapshotNameUUIDLength,
193198
)
194199

195-
// run...
196-
stopCh := make(chan struct{})
197-
factory.Start(stopCh)
198-
coreFactory.Start(stopCh)
199-
go ctrl.Run(threads, stopCh)
200-
201-
// ...until SIGINT
202-
c := make(chan os.Signal, 1)
203-
signal.Notify(c, os.Interrupt)
204-
<-c
205-
close(stopCh)
200+
run := func(context.Context) {
201+
// run...
202+
stopCh := make(chan struct{})
203+
factory.Start(stopCh)
204+
coreFactory.Start(stopCh)
205+
go ctrl.Run(threads, stopCh)
206+
207+
// ...until SIGINT
208+
c := make(chan os.Signal, 1)
209+
signal.Notify(c, os.Interrupt)
210+
<-c
211+
close(stopCh)
212+
}
213+
214+
if !*leaderElection {
215+
run(context.TODO())
216+
} else {
217+
le := leaderelection.NewLeaderElection(kubeClient, leaderElectionLockName, run)
218+
if *leaderElectionNamespace != "" {
219+
le.WithNamespace(*leaderElectionNamespace)
220+
}
221+
if err := le.Run(); err != nil {
222+
klog.Fatalf("failed to initialize leader election: %v", err)
223+
}
224+
}
206225
}
207226

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

0 commit comments

Comments
 (0)