Skip to content

Commit 536ffeb

Browse files
committed
Use common flags within csi-lib-utils
1 parent c85e076 commit 536ffeb

File tree

1 file changed

+21
-58
lines changed

1 file changed

+21
-58
lines changed

cmd/csi-snapshotter/main.go

Lines changed: 21 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import (
4242
"k8s.io/client-go/util/workqueue"
4343
klog "k8s.io/klog/v2"
4444

45+
libconfig "github.com/kubernetes-csi/csi-lib-utils/config"
4546
"github.com/container-storage-interface/spec/lib/go/csi"
4647
"github.com/kubernetes-csi/csi-lib-utils/connection"
4748
"github.com/kubernetes-csi/csi-lib-utils/leaderelection"
@@ -74,28 +75,13 @@ const (
7475

7576
// Command line flags
7677
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.")
7978
resyncPeriod = flag.Duration("resync-period", 15*time.Minute, "Resync interval of the controller. Default is 15 minutes")
8079
snapshotNamePrefix = flag.String("snapshot-name-prefix", "snapshot", "Prefix to apply to the name of a created snapshot")
8180
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.")
8381
threads = flag.Int("worker-threads", 10, "Number of worker threads.")
8482
csiTimeout = flag.Duration("timeout", defaultCSITimeout, "The timeout for any RPCs to the CSI driver. Default is 1 minute.")
8583
extraCreateMetadata = flag.Bool("extra-create-metadata", false, "If set, add snapshot metadata to plugin snapshot requests as parameters.")
8684

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`.")
9985
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.")
10086
retryIntervalMax = flag.Duration("retry-interval-max", 5*time.Minute, "Maximum retry interval of failed volume snapshot creation or deletion. Default is 5 minutes.")
10187
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.")
@@ -119,6 +105,7 @@ func main() {
119105
logsapi.AddGoFlags(c, flag.CommandLine)
120106
logs.InitLogs()
121107
standardflags.AddAutomaxprocs(klog.Infof)
108+
standardflags.RegisterCommonFlags(flag.CommandLine)
122109
flag.Parse()
123110
if err := logsapi.ValidateAndApply(c, fg); err != nil {
124111
klog.ErrorS(err, "LoggingConfiguration is invalid")
@@ -129,28 +116,25 @@ func main() {
129116
klog.Fatal("Error while parsing feature gates: ", err)
130117
}
131118

132-
if *showVersion {
119+
if standardflags.Configuration.ShowVersion {
133120
fmt.Println(os.Args[0], version)
134121
os.Exit(0)
135122
}
136123
klog.InfoS("Version", "version", version)
137124

138125
// If distributed snapshotting is enabled and leaderElection is also set to true, return
139-
if *enableNodeDeployment && *leaderElection {
126+
if *enableNodeDeployment && standardflags.Configuration.LeaderElection {
140127
klog.Error("Leader election cannot happen when node-deployment is set to true")
141128
os.Exit(1)
142129
}
143130

144131
// Create the client config. Use kubeconfig if given, otherwise assume in-cluster.
145-
config, err := buildConfig(*kubeconfig)
132+
config, err := libconfig.BuildConfig(standardflags.Configuration.KubeConfig, standardflags.Configuration)
146133
if err != nil {
147134
klog.Error(err.Error())
148135
os.Exit(1)
149136
}
150137

151-
config.QPS = (float32)(*kubeAPIQPS)
152-
config.Burst = *kubeAPIBurst
153-
154138
coreConfig := rest.CopyConfig(config)
155139
coreConfig.ContentType = runtime.ContentTypeProtobuf
156140
kubeClient, err := kubernetes.NewForConfig(coreConfig)
@@ -184,21 +168,21 @@ func main() {
184168
// Add Snapshot types to the default Kubernetes so events can be logged for them
185169
snapshotscheme.AddToScheme(scheme.Scheme)
186170

187-
if *metricsAddress != "" && *httpEndpoint != "" {
171+
if standardflags.Configuration.MetricsAddress != "" && standardflags.Configuration.HttpEndpoint != "" {
188172
klog.Error("only one of `--metrics-address` and `--http-endpoint` can be set.")
189173
os.Exit(1)
190174
}
191-
addr := *metricsAddress
175+
addr := standardflags.Configuration.MetricsAddress
192176
if addr == "" {
193-
addr = *httpEndpoint
177+
addr = standardflags.Configuration.HttpEndpoint
194178
}
195179

196180
// Connect to CSI.
197181
metricsManager := metrics.NewCSIMetricsManager("" /* driverName */)
198182
ctx := context.Background()
199183
csiConn, err := connection.Connect(
200184
ctx,
201-
*csiAddress,
185+
standardflags.Configuration.CSIAddress,
202186
metricsManager,
203187
connection.OnConnectionLoss(connection.ExitOnConnectionLoss()))
204188
if err != nil {
@@ -226,13 +210,13 @@ func main() {
226210
// Prepare http endpoint for metrics + leader election healthz
227211
mux := http.NewServeMux()
228212
if addr != "" {
229-
metricsManager.RegisterToServer(mux, *metricsPath)
213+
metricsManager.RegisterToServer(mux, standardflags.Configuration.MetricsPath)
230214
metricsManager.SetDriverName(driverName)
231215
go func() {
232216
klog.Infof("ServeMux listening at %q", addr)
233217
err := http.ListenAndServe(addr, mux)
234218
if err != nil {
235-
klog.Fatalf("Failed to start HTTP server at specified address (%q) and metrics path (%q): %s", addr, *metricsPath, err)
219+
klog.Fatalf("Failed to start HTTP server at specified address (%q) and metrics path (%q): %s", addr, standardflags.Configuration.MetricsPath, err)
236220
}
237221
}()
238222
}
@@ -261,7 +245,7 @@ func main() {
261245
os.Exit(1)
262246
}
263247

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)
248+
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)
265249

266250
snapShotter := snapshotter.NewSnapshotter(csiConn)
267251
var groupSnapshotter group_snapshotter.GroupSnapshotter
@@ -354,37 +338,16 @@ func main() {
354338
}
355339
}
356340

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-
}
341+
leaderelection.RunWithLeaderElection(
342+
ctx,
343+
config,
344+
standardflags.Configuration,
345+
run,
346+
fmt.Sprintf("%s-%s", prefix, strings.Replace(driverName, "/", "-", -1)),
347+
mux,
348+
utilfeature.DefaultFeatureGate.Enabled(features.ReleaseLeaderElectionOnExit),
349+
)
383350

384-
if err := le.Run(); err != nil {
385-
klog.Fatalf("failed to initialize leader election: %v", err)
386-
}
387-
}
388351
}
389352

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

0 commit comments

Comments
 (0)