forked from rancher/local-path-provisioner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
311 lines (281 loc) · 9.33 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main
import (
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/Sirupsen/logrus"
"github.com/pkg/errors"
"github.com/urfave/cli"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
pvController "sigs.k8s.io/sig-storage-lib-external-provisioner/controller"
)
var (
VERSION = "0.0.1"
FlagConfigFile = "config"
FlagProvisionerName = "provisioner-name"
EnvProvisionerName = "PROVISIONER_NAME"
DefaultProvisionerName = "rancher.io/local-path"
FlagNamespace = "namespace"
EnvNamespace = "POD_NAMESPACE"
DefaultNamespace = "local-path-storage"
FlagHelperImage = "helper-image"
EnvHelperImage = "HELPER_IMAGE"
DefaultHelperImage = "rancher/library-busybox:1.32.1"
FlagServiceAccountName = "service-account-name"
DefaultServiceAccount = "local-path-provisioner-service-account"
EnvServiceAccountName = "SERVICE_ACCOUNT_NAME"
FlagKubeconfig = "kubeconfig"
DefaultConfigFileKey = "config.json"
DefaultConfigMapName = "local-path-config"
FlagConfigMapName = "configmap-name"
FlagHelperPodFile = "helper-pod-file"
DefaultHelperPodFile = "helperPod.yaml"
FlagWorkerThreads = "worker-threads"
DefaultWorkerThreads = pvController.DefaultThreadiness
FlagProvisioningRetryCount = "provisioning-retry-count"
DefaultProvisioningRetryCount = pvController.DefaultFailedProvisionThreshold
FlagDeletionRetryCount = "deletion-retry-count"
DefaultDeletionRetryCount = pvController.DefaultFailedDeleteThreshold
)
func cmdNotFound(c *cli.Context, command string) {
panic(fmt.Errorf("Unrecognized command: %s", command))
}
func onUsageError(c *cli.Context, err error, isSubcommand bool) error {
panic(fmt.Errorf("Usage error, please check your command"))
}
func RegisterShutdownChannel(done chan struct{}) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
logrus.Infof("Receive %v to exit", sig)
close(done)
}()
}
func StartCmd() cli.Command {
return cli.Command{
Name: "start",
Flags: []cli.Flag{
cli.StringFlag{
Name: FlagConfigFile,
Usage: "Required. Provisioner configuration file.",
Value: "",
},
cli.StringFlag{
Name: FlagProvisionerName,
Usage: "Required. Specify Provisioner name.",
EnvVar: EnvProvisionerName,
Value: DefaultProvisionerName,
},
cli.StringFlag{
Name: FlagNamespace,
Usage: "Required. The namespace that Provisioner is running in",
EnvVar: EnvNamespace,
Value: DefaultNamespace,
},
cli.StringFlag{
Name: FlagHelperImage,
Usage: "Required. The helper image used for create/delete directories on the host",
EnvVar: EnvHelperImage,
Value: DefaultHelperImage,
},
cli.StringFlag{
Name: FlagKubeconfig,
Usage: "Paths to a kubeconfig. Only required when it is out-of-cluster.",
Value: "",
},
cli.StringFlag{
Name: FlagConfigMapName,
Usage: "Required. Specify configmap name.",
Value: DefaultConfigMapName,
},
cli.StringFlag{
Name: FlagServiceAccountName,
Usage: "Required. The ServiceAccountName for deployment",
EnvVar: EnvServiceAccountName,
Value: DefaultServiceAccount,
},
cli.StringFlag{
Name: FlagHelperPodFile,
Usage: "Paths to the Helper pod yaml file",
Value: "",
},
cli.IntFlag{
Name: FlagWorkerThreads,
Usage: "Number of provisioner worker threads.",
Value: DefaultWorkerThreads,
},
cli.IntFlag{
Name: FlagProvisioningRetryCount,
Usage: "Number of retries of failed volume provisioning. 0 means retry indefinitely.",
Value: DefaultProvisioningRetryCount,
},
cli.IntFlag{
Name: FlagDeletionRetryCount,
Usage: "Number of retries of failed volume deletion. 0 means retry indefinitely.",
Value: DefaultDeletionRetryCount,
},
},
Action: func(c *cli.Context) {
if err := startDaemon(c); err != nil {
logrus.Fatalf("Error starting daemon: %v", err)
}
},
}
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func loadConfig(kubeconfig string) (*rest.Config, error) {
if len(kubeconfig) > 0 {
return clientcmd.BuildConfigFromFlags("", kubeconfig)
}
kubeconfigPath := os.Getenv(clientcmd.RecommendedConfigPathEnvVar)
if len(kubeconfigPath) > 0 {
envVarFiles := filepath.SplitList(kubeconfigPath)
for _, f := range envVarFiles {
if _, err := os.Stat(f); err == nil {
return clientcmd.BuildConfigFromFlags("", f)
}
}
}
if c, err := rest.InClusterConfig(); err == nil {
return c, nil
}
kubeconfig = filepath.Join(homeDir(), clientcmd.RecommendedHomeDir, clientcmd.RecommendedFileName)
return clientcmd.BuildConfigFromFlags("", kubeconfig)
}
func findConfigFileFromConfigMap(kubeClient clientset.Interface, namespace, configMapName, key string) (string, error) {
cm, err := kubeClient.CoreV1().ConfigMaps(namespace).Get(configMapName, metav1.GetOptions{})
if err != nil {
return "", err
}
value, ok := cm.Data[key]
if !ok {
return "", fmt.Errorf("%v is not exist in local-path-config ConfigMap", key)
}
return value, nil
}
func startDaemon(c *cli.Context) error {
stopCh := make(chan struct{})
RegisterShutdownChannel(stopCh)
config, err := loadConfig(c.String(FlagKubeconfig))
if err != nil {
return errors.Wrap(err, "unable to get client config")
}
kubeClient, err := clientset.NewForConfig(config)
if err != nil {
return errors.Wrap(err, "unable to get k8s client")
}
serverVersion, err := kubeClient.Discovery().ServerVersion()
if err != nil {
return errors.Wrap(err, "Cannot start Provisioner: failed to get Kubernetes server version")
}
provisionerName := c.String(FlagProvisionerName)
if provisionerName == "" {
return fmt.Errorf("invalid empty flag %v", FlagProvisionerName)
}
namespace := c.String(FlagNamespace)
if namespace == "" {
return fmt.Errorf("invalid empty flag %v", FlagNamespace)
}
configMapName := c.String(FlagConfigMapName)
if configMapName == "" {
return fmt.Errorf("invalid empty flag %v", FlagConfigMapName)
}
configFile := c.String(FlagConfigFile)
if configFile == "" {
configFile, err = findConfigFileFromConfigMap(kubeClient, namespace, configMapName, DefaultConfigFileKey)
if err != nil {
return fmt.Errorf("invalid empty flag %v and it also does not exist at ConfigMap %v/%v with err: %v", FlagConfigFile, namespace, configMapName, err)
}
}
helperImage := c.String(FlagHelperImage)
if helperImage == "" {
return fmt.Errorf("invalid empty flag %v", FlagHelperImage)
}
serviceAccountName := c.String(FlagServiceAccountName)
if serviceAccountName == "" {
return fmt.Errorf("invalid empty flag %v", FlagServiceAccountName)
}
// if helper pod file is not specified, then find the helper pod by configmap with key = helperPod.yaml
// if helper pod file is specified with flag FlagHelperPodFile, then load the file
helperPodFile := c.String(FlagHelperPodFile)
helperPodYaml := ""
if helperPodFile == "" {
helperPodYaml, err = findConfigFileFromConfigMap(kubeClient, namespace, configMapName, DefaultHelperPodFile)
if err != nil {
return fmt.Errorf("invalid empty flag %v and it also does not exist at ConfigMap %v/%v with err: %v", FlagHelperPodFile, namespace, configMapName, err)
}
} else {
helperPodYaml, err = loadFile(helperPodFile)
if err != nil {
return fmt.Errorf("could not open file %v with err: %v", helperPodFile, err)
}
}
provisioningRetryCount := c.Int(FlagProvisioningRetryCount)
if provisioningRetryCount < 0 {
return fmt.Errorf("invalid negative integer flag %v", FlagProvisioningRetryCount)
}
deletionRetryCount := c.Int(FlagDeletionRetryCount)
if deletionRetryCount < 0 {
return fmt.Errorf("invalid negative integer flag %v", FlagDeletionRetryCount)
}
workerThreads := c.Int(FlagWorkerThreads)
if workerThreads <= 0 {
return fmt.Errorf("invalid zero or negative integer flag %v", FlagWorkerThreads)
}
provisioner, err := NewProvisioner(stopCh, kubeClient, configFile, namespace, helperImage, configMapName, serviceAccountName, helperPodYaml)
if err != nil {
return err
}
pc := pvController.NewProvisionController(
kubeClient,
provisionerName,
provisioner,
serverVersion.GitVersion,
pvController.LeaderElection(false),
pvController.FailedProvisionThreshold(provisioningRetryCount),
pvController.FailedDeleteThreshold(deletionRetryCount),
pvController.Threadiness(workerThreads),
)
logrus.Debug("Provisioner started")
pc.Run(stopCh)
logrus.Debug("Provisioner stopped")
return nil
}
func main() {
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
a := cli.NewApp()
a.Version = VERSION
a.Usage = "Local Path Provisioner"
a.Before = func(c *cli.Context) error {
if c.GlobalBool("debug") {
logrus.SetLevel(logrus.DebugLevel)
}
return nil
}
a.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, d",
Usage: "enable debug logging level",
EnvVar: "RANCHER_DEBUG",
},
}
a.Commands = []cli.Command{
StartCmd(),
}
a.CommandNotFound = cmdNotFound
a.OnUsageError = onUsageError
if err := a.Run(os.Args); err != nil {
logrus.Fatalf("Critical error: %v", err)
}
}