-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
781 lines (708 loc) · 20.8 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/cavaliercoder/grab"
"github.com/joho/godotenv"
"github.com/urfave/cli"
yaml "gopkg.in/yaml.v2"
)
const (
// DeployDelaySeconds - delay between deployments
DeployDelaySeconds = 3
// MaxHealthcheckRetries - Amount of times to retry checking of resource after deployment
MaxHealthcheckRetries = 3
// HealthCheckSleepDuration - the amount of time to sleep (seconds) between healthcehck retries
HealthCheckSleepDuration = time.Duration(int64(2)) * time.Second
// FlagCreateOnlyResources is the flag syntax to specify create only for only
// the specified resource
FlagCreateOnlyResources = "create-only-resource"
// FlagCreateOnly is the flag syntax to specify create only for all resources
FlagCreateOnly = "create-only"
// FlagCa specifies the synatx for specifying a CA to trust
FlagCa = "certificate-authority"
// FlagCaData is the flag to specify that a PEM encoded CA is being specified
FlagCaData = "certificate-authority-data"
// FlagCaFile is the sytax to specify a CA file when FlagCa specifies a URL or
// when FlagCaData is set
FlagCaFile = "certificate-authority-file"
)
var (
// Version is set at compile time, passing -ldflags "-X main.Version=<build version>"
Version string
logInfo *log.Logger
logError *log.Logger
logDebug *log.Logger
logDebugIf *log.Logger
// dryRun Defaults to false
dryRun bool
// Files to delete on exit
tmpDir string = ""
// caFile
caFile string = ""
)
func init() {
logInfo = log.New(os.Stdout, "[INFO] ", log.Ldate|log.Ltime|log.Lshortfile)
logError = log.New(os.Stderr, "[ERROR] ", log.Ldate|log.Ltime|log.Lshortfile)
logDebugIf = log.New(os.Stderr, "[DEBUG] ", log.Ldate|log.Ltime|log.Lshortfile)
logDebug = log.New(ioutil.Discard, "", log.Lshortfile)
}
func main() {
app := cli.NewApp()
app.Name = "kd"
app.Author = "Vaidas Jablonskis <[email protected]>"
app.Version = Version
app.Usage = "simple kubernetes resources deployment tool"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug",
Usage: "debug output",
EnvVar: "DEBUG,PLUGIN_DEBUG",
},
cli.BoolFlag{
Name: "debug-templates",
Usage: "debug template output",
EnvVar: "DEBUG_TEMPLATES,PLUGIN_DEBUG_TEMPLATES",
},
cli.BoolFlag{
Name: "dryrun",
Usage: "if true, kd will exit prior to deployment",
EnvVar: "DRY_RUN",
Destination: &dryRun,
},
cli.BoolFlag{
Name: "insecure-skip-tls-verify",
Usage: "if true, the server's certificate will not be checked for validity",
EnvVar: "INSECURE_SKIP_TLS_VERIFY,PLUGIN_INSECURE_SKIP_TLS_VERIFY",
},
cli.StringFlag{
Name: "kube-server, s",
Usage: "kubernetes api server `URL`",
EnvVar: "KUBE_SERVER,PLUGIN_KUBE_SERVER",
},
cli.StringFlag{
Name: "kube-token, t",
Usage: "kubernetes auth `TOKEN`",
EnvVar: "KUBE_TOKEN,PLUGIN_KUBE_TOKEN",
},
cli.StringFlag{
Name: "kube-username, u",
Usage: "kubernetes auth `USERNAME`",
EnvVar: "KUBE_USERNAME,PLUGIN_KUBE_USERNAME",
},
cli.StringFlag{
Name: "kube-password, p",
Usage: "kubernetes auth `PASSWORD`",
EnvVar: "KUBE_PASSWORD,PLUGIN_KUBE_PASSWORD",
},
cli.StringFlag{
Name: "config",
Usage: "Env file location",
EnvVar: "CONFIG_FILE,PLUGIN_CONFIG_FILE",
},
cli.BoolFlag{
Name: FlagCreateOnly,
Usage: "only create resources (do not update, skip if exists).",
EnvVar: "CREATE_ONLY,PLUGIN_CREATE_ONLY",
},
cli.StringSliceFlag{
Name: FlagCreateOnlyResources,
Usage: "only create specified resources e.g. 'kind/name' (do not update, skip if exists).",
EnvVar: "CREATE_ONLY_RESOURCES,PLUGIN_CREATE_ONLY_RESOURCES",
Value: nil,
},
cli.StringFlag{
Name: "context, c",
Usage: "kube config `CONTEXT`",
EnvVar: "KUBE_CONTEXT,PLUGIN_CONTEXT",
},
cli.StringFlag{
Name: "namespace, n",
Usage: "kubernetes `NAMESPACE`",
EnvVar: "KUBE_NAMESPACE,PLUGIN_KUBE_NAMESPACE",
},
cli.BoolFlag{
Name: "fail-superseded",
Usage: "fail deployment if it has been superseded by another deployment. WARNING: there are some bugs in kubernetes.",
EnvVar: "FAIL_SUPERSEDED,PLUGIN_FAIL_SUPERSEDED",
},
cli.StringFlag{
Name: FlagCa,
Usage: "the path (or URL) to a file containing the CA for kubernetes API `PATH`",
EnvVar: "KUBE_CERTIFICATE_AUTHORITY,PLUGIN_KUBE_CERTIFICATE_AUHORITY",
},
cli.StringFlag{
Name: FlagCaData,
Usage: "the certificate authority data for the kubernetes API `PATH`",
EnvVar: "KUBE_CERTIFICATE_AUTHORITY_DATA,PLUGIN_KUBE_CERTIFICATE_AUHORITY_DATA",
},
cli.StringFlag{
Name: FlagCaFile,
Usage: "the path to save certificate authority data when data or a URL is specified",
Value: "/tmp/kube-ca.pem",
},
cli.StringSliceFlag{
Name: "file, f",
Usage: "the path to a file or directory containing kubernetes resource/s `PATH`",
EnvVar: "FILES,PLUGIN_FILES",
},
cli.DurationFlag{
Name: "timeout, T",
Usage: "the amount of time to wait for a successful deployment `TIMEOUT`",
EnvVar: "TIMEOUT,PLUGIN_TIMEOUT",
Value: time.Duration(3) * time.Minute,
},
cli.DurationFlag{
Name: "check-interval",
Usage: "deployment status check interval `INTERVAL`",
EnvVar: "CHECK_INTERVAL,PLUGIN_CHECK_INTERVAL",
Value: time.Duration(1000) * time.Millisecond,
},
}
app.Commands = []cli.Command{
{
Action: runKubectl,
Name: "run",
Usage: "run [kubectl args] - runs kubectl supporting kd flags / environment options",
Description: "runs kubectl whist supporting the kd global flags",
UsageText: "run [kubectl args] - will run kubectl with all the parameters supplied",
SkipFlagParsing: true,
OnUsageError: nil,
},
}
app.Action = func(cx *cli.Context) error {
if err := run(cx); err != nil {
logError.Print(err)
return cli.NewExitError("", 1)
}
return nil
}
defer cleanup()
if err := app.Run(os.Args); err != nil {
logError.Fatal(err)
}
}
// Delete any temparay files
func cleanup() {
if len(tmpDir) > 0 {
logDebug.Printf("cleaning up %s", tmpDir)
os.RemoveAll(tmpDir)
}
}
func runKubectl(c *cli.Context) error {
if c.Parent().Bool("debug") {
logDebug = logDebugIf
}
if c.Parent().IsSet(FlagCreateOnlyResources) {
if len(c.Parent().StringSlice(FlagCreateOnlyResources)) > 1 {
return fmt.Errorf("can only specify a single resource when using run")
}
resString := c.Parent().StringSlice(FlagCreateOnlyResources)[0]
resParts := strings.Split(resString, "/")
if len(resParts) != 2 {
return fmt.Errorf(
"invalid resource type %s, expecting kind/name", resString)
}
name := resParts[1]
kind := resParts[0]
exists, err := checkResourceExist(c.Parent(), &ObjectResource{
Kind: kind,
ObjectMeta: ObjectMeta{
Name: name,
},
})
if err != nil {
return fmt.Errorf(
"problem checking if resource %s/%s exists", name, kind)
}
if exists {
log.Printf(
"resource marked as 'create only', skipping app for %s", resString)
return nil
}
}
// Allow the lib to render args and then create array
cmd, err := newKubeCmdSub(c.Parent(), c.Args(), true)
if err != nil {
return err
}
logDebug.Printf("About to run %s", cmd.Args)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return fmt.Errorf(
"error running '%s %s' (use debug to see sensitive params):%s",
cmd.Args[0],
strings.Join(c.Args(), " "),
err)
}
return nil
}
func run(c *cli.Context) error {
if c.Bool("debug") {
logDebug = logDebugIf
}
// Check we have some files to process
if len(c.StringSlice("file")) == 0 {
return errors.New("no kubernetes resource files specified")
}
// Load Environment file overrides into the OS Environment Scope
if c.IsSet("config") {
err := godotenv.Load(c.String("config"))
if err != nil {
return errors.New("Error loading .env file")
}
}
// Check if all files exist first - fail early on building up a list of files
var files []string
for _, fn := range c.StringSlice("file") {
logDebug.Printf("about to open file:%s\n", fn)
stat, err := os.Stat(fn)
if err != nil {
return err
}
switch stat.IsDir() {
case true:
fileList, err := ListDirectory(fn)
if err != nil {
return err
}
files = append(files, fileList...)
default:
files = append(files, fn)
}
}
// Iterate the list of files and add rendered templates to resources list - fail early.
resources := []*ObjectResource{}
for _, fn := range files {
logDebug.Printf("parsing file:%s\n", fn)
data, err := ioutil.ReadFile(fn)
if err != nil {
return err
}
for _, d := range splitYamlDocs(string(data)) {
rendered, genSecret, err := Render(string(d), EnvToMap())
if err != nil {
return err
}
r := &ObjectResource{
FileName: fn,
Template: []byte(rendered),
CreateOnly: genSecret,
}
resources = append(resources, r)
}
}
for _, r := range resources {
if c.Bool("debug-templates") {
logInfo.Printf("Template:\n" + string(r.Template[:]))
}
if err := yaml.Unmarshal(r.Template, &r); err != nil {
return err
}
// Add any flag specific settings for resources
updateResFromFlags(c, r)
// Only perform deploy if dry-run is not set to true
if !dryRun {
if err := deploy(c, r); err != nil {
return err
}
}
}
return nil
}
// EnvToMap - creates a map of all environment variables
func EnvToMap() map[string]string {
m := map[string]string{}
for _, n := range os.Environ() {
parts := strings.SplitN(n, "=", 2)
m[parts[0]] = parts[1]
}
return m
}
// updateResFromFlags will inspect a resource and apply any flag specific args
func updateResFromFlags(c *cli.Context, r *ObjectResource) error {
// Add create only option where applicable
if c.IsSet(FlagCreateOnly) {
r.CreateOnly = true
return nil
}
// Supports specifying kind/names
if c.IsSet(FlagCreateOnlyResources) {
if len(c.StringSlice(FlagCreateOnlyResources)) > 0 {
for _, resString := range c.StringSlice(FlagCreateOnlyResources) {
resParts := strings.Split(resString, "/")
if len(resParts) != 2 {
return fmt.Errorf(
"invalid resource type %s, expecting kind/name", resString)
}
// Is this the resource we are looking for?
if strings.ToLower(r.Kind) == strings.ToLower(resParts[0]) &&
strings.ToLower(r.Name) == strings.ToLower(resParts[1]) {
r.CreateOnly = true
}
}
}
}
return nil
}
// splitYamlDocs splits a yaml string into separate yaml documents.
func splitYamlDocs(data string) []string {
r := regexp.MustCompile(`(?m)^---\n`)
s := r.Split(data, -1)
for i, item := range s {
if item == "" {
s = append(s[:i], s[i+1:]...)
}
}
return s
}
func deploy(c *cli.Context, r *ObjectResource) error {
if r.CreateOnly {
exists, err := checkResourceExist(c, r)
if err != nil {
return fmt.Errorf(
"problem checking if resource %s/%s exists", r.Kind, r.Name)
}
if exists {
log.Printf(
"skipping deploy for resource (%s/%s) marked as create only.",
r.Kind,
r.Name)
return nil
}
}
name := r.Name
command := "apply"
if r.GenerateName != "" {
name = r.GenerateName
command = "create"
}
logDebug.Printf("about to deploy resource %s/%s (from file:%q)", r.Kind, name, r.FileName)
args := []string{command, "-f", "-"}
cmd, err := newKubeCmd(c, args)
if err != nil {
return err
}
if c.Bool("debug") {
logDebug.Printf("kubectl arguments: %q", strings.Join(cmd.Args, " "))
}
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
go func() {
defer stdin.Close()
stdin.Write(r.Template)
}()
logInfo.Printf("deploying %s/%s", strings.ToLower(r.Kind), r.Name)
if err = cmd.Run(); err != nil {
if errbuf.Len() > 0 {
return fmt.Errorf(errbuf.String())
}
return err
}
logInfo.Print(outbuf.String())
if r.GenerateName != "" {
//This gets the generated resource name from the output
resourceName := strings.TrimSuffix(outbuf.String(), " created\n")
r.Name = strings.Split(resourceName, "/")[1]
}
if isWatchableResouce(r) {
return watchResource(c, r)
}
return nil
}
func isWatchableResouce(r *ObjectResource) bool {
included := false
watchable := []string{"Deployment", "StatefulSet", "DaemonSet", "Job"}
for _, item := range watchable {
if item == r.Kind {
included = true
break
}
}
return included
}
func watchResource(c *cli.Context, r *ObjectResource) error {
if c.Bool("debug") {
logDebug.Printf("sleeping %d seconds before checking %s status for the first time", DeployDelaySeconds, r.Kind)
}
time.Sleep(DeployDelaySeconds * time.Second)
if err := updateResourceStatus(c, r); err != nil {
return err
}
if r.Kind == "StatefulSet" || r.Kind == "DaemonSet" {
if r.ObjectSpec.UpdateStrategy.Type != "RollingUpdate" {
if c.Bool("debug") {
logDebug.Printf("Only %s with type of RollingUpdate will be watched for completion", r.Kind)
}
return nil
}
}
ticker := time.NewTicker(c.Duration("check-interval"))
timeout := time.After(c.Duration("timeout"))
og := r.DeploymentStatus.ObservedGeneration
ready := false
var availableResourceCount int32
var unavailableResourceCount int32
for {
select {
case <-timeout:
return fmt.Errorf("%s rolling update %q timed out after %s", r.Kind, r.Name, c.Duration("timeout").String())
case <-ticker.C:
r.DeploymentStatus = DeploymentStatus{}
// Retry on error until max retries is met
for attempt := 0; attempt < MaxHealthcheckRetries; attempt++ {
if err := updateResourceStatus(c, r); err != nil {
// Return error on final try
if attempt == (MaxHealthcheckRetries - 1) {
return err
}
// Sleep between retries
time.Sleep(HealthCheckSleepDuration)
} else {
break
}
}
if c.Bool("debug") {
logDebug.Printf("fetching %s %q status: %+v", r.Kind, r.Name, r.DeploymentStatus)
}
ready = false
switch r.Kind {
case "Deployment":
if (r.DeploymentStatus.UnavailableReplicas == 0 && r.DeploymentStatus.AvailableReplicas == r.DeploymentStatus.Replicas) &&
r.DeploymentStatus.Replicas == r.DeploymentStatus.UpdatedReplicas {
ready = true
}
availableResourceCount = r.DeploymentStatus.AvailableReplicas
unavailableResourceCount = r.DeploymentStatus.UnavailableReplicas
case "StatefulSet":
if (r.DeploymentStatus.ReadyReplicas == r.ObjectSpec.Replicas) &&
r.DeploymentStatus.CurrentRevision == r.DeploymentStatus.UpdateRevision {
ready = true
}
availableResourceCount = r.DeploymentStatus.ReadyReplicas
unavailableResourceCount = r.ObjectSpec.Replicas - r.DeploymentStatus.ReadyReplicas
case "DaemonSet":
if (r.DeploymentStatus.DesiredNumberScheduled == r.DeploymentStatus.NumberAvailable) &&
(r.DeploymentStatus.UpdatedNumberScheduled == r.DeploymentStatus.DesiredNumberScheduled) {
ready = true
}
availableResourceCount = r.DeploymentStatus.NumberAvailable
unavailableResourceCount = r.DeploymentStatus.DesiredNumberScheduled - r.DeploymentStatus.UpdatedNumberScheduled
case "Job":
if r.DeploymentStatus.Succeeded == 1 {
availableResourceCount = 1
ready = true
}
unavailableResourceCount = 1
}
if ready {
logInfo.Printf("%s %q is complete. Available objects: %d\n", r.Kind, r.Name, availableResourceCount)
return nil
}
logInfo.Printf("%s %q update in progress. Waiting for %d objects.\n", r.Kind, r.Name, unavailableResourceCount)
// Fail the deployment in case another deployment has started
if og != r.DeploymentStatus.ObservedGeneration && c.Bool("fail-superseded") {
return fmt.Errorf("%s %q update failed. It has been superseded by another update", r.Kind, r.Name)
}
}
}
}
func updateResourceStatus(c *cli.Context, r *ObjectResource) error {
args := []string{"get", r.Kind + "/" + r.Name, "-o", "yaml"}
cmd, err := newKubeCmd(c, args)
if err != nil {
return err
}
cmd.Stderr = os.Stderr
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
return err
}
data, _ := ioutil.ReadAll(stdout)
if err := yaml.Unmarshal(data, r); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return err
}
return nil
}
func checkResourceExist(c *cli.Context, r *ObjectResource) (bool, error) {
args := []string{"get", r.Kind + "/" + r.Name, "-o", "custom-columns=:.metadata.name", "--no-headers"}
cmd, err := newKubeCmd(c, args)
if err != nil {
return false, err
}
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
logDebug.Printf("error starting kubectl: %s", err)
return false, err
}
data, _ := ioutil.ReadAll(stdout)
if err := cmd.Wait(); err != nil {
logDebug.Printf("error with kubectl: %s", err)
errData, _ := ioutil.ReadAll(stderr)
if strings.Contains("NotFound", string(errData[:])) {
return false, nil
}
return false, err
}
if strings.TrimSpace(string(data[:])) == r.Name {
return true, nil
} else {
return false, nil
}
}
func newKubeCmd(c *cli.Context, args []string) (*exec.Cmd, error) {
return newKubeCmdSub(c, args, false)
}
func newKubeCmdSub(c *cli.Context, args []string, subCommand bool) (*exec.Cmd, error) {
kube := "kubectl"
if c.IsSet("namespace") {
args = append([]string{"--namespace=" + c.String("namespace")}, args...)
}
if c.IsSet("context") {
args = append([]string{"--context=" + c.String("context")}, args...)
}
if c.IsSet("kube-token") {
args = append([]string{"--token=" + c.String("kube-token")}, args...)
} else {
if c.IsSet("kube-username") {
args = append([]string{"--username=" + c.String("kube-username")}, args...)
}
if c.IsSet("kube-password") {
args = append([]string{"--password=" + c.String("kube-password")}, args...)
}
}
if c.IsSet(FlagCaData) {
if err := createCertificateAuthority(c.String(FlagCaFile), c.String(FlagCaData)); err != nil {
return nil, err
}
args = append([]string{"--certificate-authority=" + c.String(FlagCaFile)}, args...)
}
if c.IsSet(FlagCa) {
caFile, err := getCaFileAndDownloadIfRequired(c)
if err != nil {
return nil, err
}
args = append([]string{"--certificate-authority=" + caFile}, args...)
}
if c.IsSet("insecure-skip-tls-verify") {
args = append([]string{"--insecure-skip-tls-verify"}, args...)
}
if c.IsSet("kube-server") {
args = append([]string{"--server=" + c.String("kube-server")}, args...)
}
flags, err := extraFlags(c, subCommand)
if err != nil {
return nil, err
}
args = append(args, flags...)
return exec.Command(kube, args...), nil
}
// getCaFileAndDownloadIfRequired will obtain a CA file on disk - if required
func getCaFileAndDownloadIfRequired(c *cli.Context) (string, error) {
// have we done this already?
if len(caFile) > 0 {
return caFile, nil
}
ca := c.String(FlagCa)
// Detect if using a URL scheme
if uri, _ := url.ParseRequestURI(ca); uri != nil {
if uri.Scheme == "" {
// Not a URL, get out of here
return ca, nil
}
}
// Where should we save the ca?
if c.IsSet(FlagCaFile) {
caFile = c.String(FlagCaFile)
} else {
// This is used by cleanup
tmpDir, _ = ioutil.TempDir("", "kd")
caFile = filepath.Join(tmpDir, "kube-ca.pem")
}
logDebug.Printf("ca file specified as %s, to download from %s", caFile, ca)
// download the ca...
resp, err := grab.Get(caFile, ca)
if err != nil {
return "", fmt.Errorf(
"problem downloading ca from %s:%s", resp.Filename, err)
}
return caFile, nil
}
// extraFlags will parse out the -- args portion
func extraFlags(c *cli.Context, subCommand bool) ([]string, error) {
var a []string
if c.NArg() < 1 {
return a, nil
}
if c.Args()[0] == "--" {
return c.Args()[1:], nil
}
// When we are called from a sub command we don't want the sub command bits
if subCommand {
return a, nil
}
return c.Args(), nil
}
// ListDirectory returns a recursive list of all files under a directory, or an error
func ListDirectory(path string) ([]string, error) {
var list []string
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
// We only support yaml at the moment, so we might well filter on it
switch filepath.Ext(path) {
case ".yaml":
fallthrough
case ".yml":
list = append(list, path)
}
}
return nil
})
return list, err
}
// createCertificateAuthority creates if required a certificate-authority file
func createCertificateAuthority(path, content string) error {
// This hardcoded certificate authority
if found, err := FilesExists(path); err != nil {
return err
} else if found {
return nil
}
// Write the file to disk
if err := ioutil.WriteFile(path, []byte(content), 0444); err != nil {
return err
}
return nil
}
// FilesExists checks if a file exists already
func FilesExists(path string) (bool, error) {
stat, err := os.Stat(path)
if err != nil {
if err != nil && os.IsNotExist(err) {
return false, nil
}
return false, err
}
return !stat.IsDir(), nil
}