Skip to content

Commit a9d0e53

Browse files
committed
refactor: use common sidecar flags functionality
1 parent 20bb89a commit a9d0e53

File tree

1 file changed

+21
-67
lines changed

1 file changed

+21
-67
lines changed

cmd/csi-snapshotter/main.go

Lines changed: 21 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@ import (
3838
"k8s.io/client-go/kubernetes"
3939
"k8s.io/client-go/kubernetes/scheme"
4040
"k8s.io/client-go/rest"
41-
"k8s.io/client-go/tools/clientcmd"
4241
"k8s.io/client-go/util/workqueue"
4342
klog "k8s.io/klog/v2"
4443

4544
"github.com/container-storage-interface/spec/lib/go/csi"
4645
"github.com/kubernetes-csi/csi-lib-utils/connection"
46+
libconfig "github.com/kubernetes-csi/csi-lib-utils/config"
4747
"github.com/kubernetes-csi/csi-lib-utils/leaderelection"
4848
"github.com/kubernetes-csi/csi-lib-utils/metrics"
4949
csirpc "github.com/kubernetes-csi/csi-lib-utils/rpc"
@@ -74,28 +74,13 @@ const (
7474

7575
// Command line flags
7676
var (
77-
kubeconfig = flag.String("kubeconfig", "", "Absolute path to the kubeconfig file. Required only when running out of cluster.")
78-
csiAddress = flag.String("csi-address", "/run/csi/socket", "Address of the CSI driver socket.")
7977
resyncPeriod = flag.Duration("resync-period", 15*time.Minute, "Resync interval of the controller. Default is 15 minutes")
8078
snapshotNamePrefix = flag.String("snapshot-name-prefix", "snapshot", "Prefix to apply to the name of a created snapshot")
8179
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.")
82-
showVersion = flag.Bool("version", false, "Show version.")
8380
threads = flag.Int("worker-threads", 10, "Number of worker threads.")
8481
csiTimeout = flag.Duration("timeout", defaultCSITimeout, "The timeout for any RPCs to the CSI driver. Default is 1 minute.")
8582
extraCreateMetadata = flag.Bool("extra-create-metadata", false, "If set, add snapshot metadata to plugin snapshot requests as parameters.")
8683

87-
leaderElection = flag.Bool("leader-election", false, "Enables leader election.")
88-
leaderElectionNamespace = flag.String("leader-election-namespace", "", "The namespace where the leader election resource exists. Defaults to the pod namespace if not set.")
89-
leaderElectionLeaseDuration = flag.Duration("leader-election-lease-duration", 15*time.Second, "Duration, in seconds, that non-leader candidates will wait to force acquire leadership. Defaults to 15 seconds.")
90-
leaderElectionRenewDeadline = flag.Duration("leader-election-renew-deadline", 10*time.Second, "Duration, in seconds, that the acting leader will retry refreshing leadership before giving up. Defaults to 10 seconds.")
91-
leaderElectionRetryPeriod = flag.Duration("leader-election-retry-period", 5*time.Second, "Duration, in seconds, the LeaderElector clients should wait between tries of actions. Defaults to 5 seconds.")
92-
93-
kubeAPIQPS = flag.Float64("kube-api-qps", 5, "QPS to use while communicating with the kubernetes apiserver. Defaults to 5.0.")
94-
kubeAPIBurst = flag.Int("kube-api-burst", 10, "Burst to use while communicating with the kubernetes apiserver. Defaults to 10.")
95-
96-
metricsAddress = flag.String("metrics-address", "", "(deprecated) The TCP network address where the prometheus metrics endpoint will listen (example: `:8080`). The default is empty string, which means metrics endpoint is disabled. Only one of `--metrics-address` and `--http-endpoint` can be set.")
97-
httpEndpoint = flag.String("http-endpoint", "", "The TCP network address where the HTTP server for diagnostics, including metrics and leader election health check, will listen (example: `:8080`). The default is empty string, which means the server is disabled. Only one of `--metrics-address` and `--http-endpoint` can be set.")
98-
metricsPath = flag.String("metrics-path", "/metrics", "The HTTP path where prometheus metrics will be exposed. Default is `/metrics`.")
9984
retryIntervalStart = flag.Duration("retry-interval-start", time.Second, "Initial retry interval of failed volume snapshot creation or deletion. It doubles with each failure, up to retry-interval-max. Default is 1 second.")
10085
retryIntervalMax = flag.Duration("retry-interval-max", 5*time.Minute, "Maximum retry interval of failed volume snapshot creation or deletion. Default is 5 minutes.")
10186
enableNodeDeployment = flag.Bool("node-deployment", false, "Enables deploying the sidecar controller together with a CSI driver on nodes to manage snapshots for node-local volumes.")
@@ -118,6 +103,7 @@ func main() {
118103
c := logsapi.NewLoggingConfiguration()
119104
logsapi.AddGoFlags(c, flag.CommandLine)
120105
logs.InitLogs()
106+
standardflags.RegisterCommonFlags(flag.CommandLine)
121107
standardflags.AddAutomaxprocs(klog.Infof)
122108
flag.Parse()
123109
if err := logsapi.ValidateAndApply(c, fg); err != nil {
@@ -129,28 +115,25 @@ func main() {
129115
klog.Fatal("Error while parsing feature gates: ", err)
130116
}
131117

132-
if *showVersion {
118+
if standardflags.Configuration.ShowVersion {
133119
fmt.Println(os.Args[0], version)
134120
os.Exit(0)
135121
}
136122
klog.InfoS("Version", "version", version)
137123

138124
// If distributed snapshotting is enabled and leaderElection is also set to true, return
139-
if *enableNodeDeployment && *leaderElection {
125+
if *enableNodeDeployment && standardflags.Configuration.LeaderElection {
140126
klog.Error("Leader election cannot happen when node-deployment is set to true")
141127
os.Exit(1)
142128
}
143129

144130
// Create the client config. Use kubeconfig if given, otherwise assume in-cluster.
145-
config, err := buildConfig(*kubeconfig)
131+
config, err := libconfig.BuildConfig(standardflags.Configuration.KubeConfig, standardflags.Configuration)
146132
if err != nil {
147133
klog.Error(err.Error())
148134
os.Exit(1)
149135
}
150136

151-
config.QPS = (float32)(*kubeAPIQPS)
152-
config.Burst = *kubeAPIBurst
153-
154137
coreConfig := rest.CopyConfig(config)
155138
coreConfig.ContentType = runtime.ContentTypeProtobuf
156139
kubeClient, err := kubernetes.NewForConfig(coreConfig)
@@ -184,21 +167,21 @@ func main() {
184167
// Add Snapshot types to the default Kubernetes so events can be logged for them
185168
snapshotscheme.AddToScheme(scheme.Scheme)
186169

187-
if *metricsAddress != "" && *httpEndpoint != "" {
170+
if standardflags.Configuration.MetricsAddress != "" && standardflags.Configuration.HttpEndpoint != "" {
188171
klog.Error("only one of `--metrics-address` and `--http-endpoint` can be set.")
189172
os.Exit(1)
190173
}
191-
addr := *metricsAddress
174+
addr := standardflags.Configuration.MetricsAddress
192175
if addr == "" {
193-
addr = *httpEndpoint
176+
addr = standardflags.Configuration.HttpEndpoint
194177
}
195178

196179
// Connect to CSI.
197180
metricsManager := metrics.NewCSIMetricsManager("" /* driverName */)
198181
ctx := context.Background()
199182
csiConn, err := connection.Connect(
200183
ctx,
201-
*csiAddress,
184+
standardflags.Configuration.CSIAddress,
202185
metricsManager,
203186
connection.OnConnectionLoss(connection.ExitOnConnectionLoss()))
204187
if err != nil {
@@ -226,13 +209,13 @@ func main() {
226209
// Prepare http endpoint for metrics + leader election healthz
227210
mux := http.NewServeMux()
228211
if addr != "" {
229-
metricsManager.RegisterToServer(mux, *metricsPath)
212+
metricsManager.RegisterToServer(mux, standardflags.Configuration.MetricsPath)
230213
metricsManager.SetDriverName(driverName)
231214
go func() {
232215
klog.Infof("ServeMux listening at %q", addr)
233216
err := http.ListenAndServe(addr, mux)
234217
if err != nil {
235-
klog.Fatalf("Failed to start HTTP server at specified address (%q) and metrics path (%q): %s", addr, *metricsPath, err)
218+
klog.Fatalf("Failed to start HTTP server at specified address (%q) and metrics path (%q): %s", addr, standardflags.Configuration.MetricsPath, err)
236219
}
237220
}()
238221
}
@@ -261,7 +244,7 @@ func main() {
261244
os.Exit(1)
262245
}
263246

264-
klog.V(2).Infof("Start NewCSISnapshotSideCarController with snapshotter [%s] kubeconfig [%s] csiTimeout [%+v] csiAddress [%s] resyncPeriod [%+v] snapshotNamePrefix [%s] snapshotNameUUIDLength [%d]", driverName, *kubeconfig, *csiTimeout, *csiAddress, *resyncPeriod, *snapshotNamePrefix, snapshotNameUUIDLength)
247+
klog.V(2).Infof("Start NewCSISnapshotSideCarController with snapshotter [%s] kubeconfig [%s] csiTimeout [%+v] csiAddress [%s] resyncPeriod [%+v] snapshotNamePrefix [%s] snapshotNameUUIDLength [%d]", driverName, standardflags.Configuration.KubeConfig, *csiTimeout, standardflags.Configuration.CSIAddress, *resyncPeriod, *snapshotNamePrefix, snapshotNameUUIDLength)
265248

266249
snapShotter := snapshotter.NewSnapshotter(csiConn)
267250
var groupSnapshotter group_snapshotter.GroupSnapshotter
@@ -354,44 +337,15 @@ func main() {
354337
}
355338
}
356339

357-
if !*leaderElection {
358-
run(context.TODO())
359-
} else {
360-
lockName := fmt.Sprintf("%s-%s", prefix, strings.Replace(driverName, "/", "-", -1))
361-
// Create a new clientset for leader election to prevent throttling
362-
// due to snapshot sidecar
363-
leClientset, err := kubernetes.NewForConfig(config)
364-
if err != nil {
365-
klog.Fatalf("failed to create leaderelection client: %v", err)
366-
}
367-
le := leaderelection.NewLeaderElection(leClientset, lockName, run)
368-
if *httpEndpoint != "" {
369-
le.PrepareHealthCheck(mux, leaderelection.DefaultHealthCheckTimeout)
370-
}
371-
372-
if *leaderElectionNamespace != "" {
373-
le.WithNamespace(*leaderElectionNamespace)
374-
}
375-
376-
le.WithLeaseDuration(*leaderElectionLeaseDuration)
377-
le.WithRenewDeadline(*leaderElectionRenewDeadline)
378-
le.WithRetryPeriod(*leaderElectionRetryPeriod)
379-
if utilfeature.DefaultFeatureGate.Enabled(features.ReleaseLeaderElectionOnExit) {
380-
le.WithReleaseOnCancel(true)
381-
le.WithContext(ctx)
382-
}
383-
384-
if err := le.Run(); err != nil {
385-
klog.Fatalf("failed to initialize leader election: %v", err)
386-
}
387-
}
388-
}
389-
390-
func buildConfig(kubeconfig string) (*rest.Config, error) {
391-
if kubeconfig != "" {
392-
return clientcmd.BuildConfigFromFlags("", kubeconfig)
393-
}
394-
return rest.InClusterConfig()
340+
leaderelection.RunWithLeaderElection(
341+
ctx,
342+
config,
343+
standardflags.Configuration,
344+
run,
345+
fmt.Sprintf("%s-%s", prefix, strings.Replace(driverName, "/", "-", -1)),
346+
mux,
347+
utilfeature.DefaultFeatureGate.Enabled(features.ReleaseLeaderElectionOnExit),
348+
)
395349
}
396350

397351
func supportsControllerCreateSnapshot(ctx context.Context, conn *grpc.ClientConn) (bool, error) {

0 commit comments

Comments
 (0)