forked from UKHomeOffice/kd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
392 lines (353 loc) · 10.1 KB
/
main.go
File metadata and controls
392 lines (353 loc) · 10.1 KB
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
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"text/template"
"time"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
)
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
)
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)
logDebug = log.New(os.Stderr, "[DEBUG] ", log.Ldate|log.Ltime|log.Lshortfile)
}
func main() {
app := cli.NewApp()
app.Name = "kd"
app.Author = "Vaidas Jablonskis <jablonskis@gmail.com>"
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: "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: "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: "certificate-authority",
Usage: "the path to a file containing the CA for kubernetes API `PATH`",
EnvVar: "KUBE_CERTIFICATE_AUTHORITY,PLUGIN_KUBE_CERTIFICATE_AUHORITY",
},
cli.StringFlag{
Name: "certificate-authority-data",
Usage: "the certificate authority data for the kubernetes API `PATH`",
EnvVar: "KUBE_CERTIFICATE_AUTHORITY_DATA,PLUGIN_KUBE_CERTIFICATE_AUHORITY_DATA",
},
cli.StringFlag{
Name: "certificate-authority-file",
Usage: "the path to file the certificate authority file from certifacte-authority-data option",
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.Action = func(cx *cli.Context) error {
if err := run(cx); err != nil {
logError.Print(err)
return cli.NewExitError("", 1)
}
return nil
}
if err := app.Run(os.Args); err != nil {
logError.Fatal(err)
}
}
func run(c *cli.Context) error {
// Check we have some files to process
if len(c.StringSlice("file")) == 0 {
return errors.New("no kubernetes resource files specified")
}
// Check if all files exist first - fail early on building up a list of files
var files []string
for _, fn := range c.StringSlice("file") {
stat, err := os.Stat(fn)
if err != nil {
return err
}
switch stat.IsDir() {
case true:
files, err := listDirectory(fn)
if err != nil {
return err
}
files = append(files, files...)
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 {
data, err := ioutil.ReadFile(fn)
if err != nil {
return err
}
rendered, err := render(string(data), envToMap())
if err != nil {
return err
}
for _, d := range splitYamlDocs(rendered) {
r := ObjectResource{FileName: fn, Template: []byte(d)}
resources = append(resources, &r)
}
}
for _, r := range resources {
if err := yaml.Unmarshal(r.Template, &r); err != nil {
return err
}
if err := deploy(c, r); err != nil {
return err
}
}
return nil
}
func render(tmpl string, vars map[string]string) (string, error) {
t := template.Must(template.New("template").Parse(tmpl))
t.Option("missingkey=error")
var b bytes.Buffer
if err := t.Execute(&b, vars); err != nil {
return b.String(), err
}
return b.String(), nil
}
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
}
// 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 {
args := []string{"apply", "-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
if _, err := stdin.Write(r.Template); err != nil {
return err
}
if err := stdin.Close(); err != nil {
return err
}
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.Kind != "Deployment" {
return nil
}
if c.Bool("debug") {
logDebug.Printf("sleeping 3 seconds before checking deployment status for the first time")
}
time.Sleep(3 * time.Second)
if err := updateDeploymentStatus(c, r); err != nil {
return err
}
ticker := time.NewTicker(c.Duration("check-interval"))
timeout := time.After(c.Duration("timeout"))
og := r.DeploymentStatus.ObservedGeneration
for {
select {
case <-timeout:
return fmt.Errorf("deployment %q timed out after %s", r.Name, c.Duration("timeout").String())
case <-ticker.C:
r.DeploymentStatus = DeploymentStatus{}
// @TODO should a one-off error (perhaps network issue) cause us to completly fail?
if err := updateDeploymentStatus(c, r); err != nil {
return err
}
if c.Bool("debug") {
logDebug.Printf("fetching deployment status: %+v", r.DeploymentStatus)
}
if (r.DeploymentStatus.UnavailableReplicas == 0 && r.DeploymentStatus.AvailableReplicas == r.DeploymentStatus.Replicas) &&
r.DeploymentStatus.Replicas == r.DeploymentStatus.UpdatedReplicas {
logInfo.Printf("deployment %q is complete. Available replicas: %d\n",
r.Name, r.DeploymentStatus.AvailableReplicas)
return nil
}
logInfo.Printf("deployment %q in progress. Unavailable replicas: %d.\n",
r.Name, r.DeploymentStatus.UnavailableReplicas)
// Fail the deployment in case another deployment has started
if og != r.DeploymentStatus.ObservedGeneration && c.Bool("fail-superseded") {
return fmt.Errorf("deployment failed. It has been superseded by another deployment")
}
}
}
}
func updateDeploymentStatus(c *cli.Context, r *ObjectResource) error {
args := []string{"get", "deployment/" + 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 newKubeCmd(c *cli.Context, args []string) (*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...)
}
if c.IsSet("certificate-authority-data") {
if err := createCertificateAuthority(c.String("certificate-authority-file"), c.String("certificate-authority-data")); err != nil {
return nil, err
}
args = append([]string{"--certificate-authority=" + c.String("certificate-authority-file")}, args...)
}
if c.IsSet("certificate-authority") {
args = append([]string{"--certificate-authority=" + c.String("certificate-authority")}, 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...)
}
return exec.Command(kube, 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
}
// fileExists 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
}