forked from DBCDK/morph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
morph.go
669 lines (570 loc) · 17.3 KB
/
morph.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/dbcdk/kingpin"
"github.com/dbcdk/morph/assets"
"github.com/dbcdk/morph/filter"
"github.com/dbcdk/morph/healthchecks"
"github.com/dbcdk/morph/nix"
"github.com/dbcdk/morph/secrets"
"github.com/dbcdk/morph/ssh"
"github.com/dbcdk/morph/utils"
"os"
"path/filepath"
"strings"
)
// This is set at build time via -ldflags magic
var version string
var switchActions = []string{"dry-activate", "test", "switch", "boot"}
var (
app = kingpin.New("morph", "NixOS host manager").Version(version)
dryRun = app.Flag("dry-run", "Don't do anything, just eval and print changes").Default("False").Bool()
selectGlob string
selectTags string
selectEvery int
selectSkip int
selectLimit int
orderingTags string
deployment string
timeout int
askForSudoPasswd bool
nixBuildArg []string
nixBuildTarget string
nixBuildTargetFile string
build = buildCmd(app.Command("build", "Evaluate and build deployment configuration to the local Nix store"))
push = pushCmd(app.Command("push", "Build and transfer items from the local Nix store to target machines"))
deploy = deployCmd(app.Command("deploy", "Build, push and activate new configuration on machines according to switch-action"))
deploySwitchAction string
deployUploadSecrets bool
deployReboot bool
skipHealthChecks bool
showTrace bool
healthCheck = healthCheckCmd(app.Command("check-health", "Run health checks"))
uploadSecrets = uploadSecretsCmd(app.Command("upload-secrets", "Upload secrets"))
listSecrets = listSecretsCmd(app.Command("list-secrets", "List secrets"))
asJson bool
execute = executeCmd(app.Command("exec", "Execute arbitrary commands on machines"))
executeCommand []string
keepGCRoot = app.Flag("keep-result", "Keep latest build in .gcroots to prevent it from being garbage collected").Default("False").Bool()
allowBuildShell = app.Flag("allow-build-shell", "Allow using `network.buildShell` to build in a nix-shell which can execute arbitrary commands on the local system").Default("False").Bool()
assetRoot string
)
func deploymentArg(cmd *kingpin.CmdClause) {
cmd.Arg("deployment", "File containing the nix deployment expression").
HintFiles("nix").
Required().
ExistingFileVar(&deployment)
}
func timeoutFlag(cmd *kingpin.CmdClause) {
cmd.Flag("timeout", "Seconds to wait for commands/healthchecks on a host to complete").
Default("0").
IntVar(&timeout)
}
func askForSudoPasswdFlag(cmd *kingpin.CmdClause) {
cmd.
Flag("passwd", "Whether to ask interactively for remote sudo password when needed").
Default("False").
BoolVar(&askForSudoPasswd)
}
func selectorFlags(cmd *kingpin.CmdClause) {
cmd.Flag("on", "Glob for selecting servers in the deployment").
Default("*").
StringVar(&selectGlob)
cmd.Flag("tagged", "Select hosts with these tags").
Default("").
StringVar(&selectTags)
cmd.Flag("every", "Select every n hosts").
Default("1").
IntVar(&selectEvery)
cmd.Flag("skip", "Skip first n hosts").
Default("0").
IntVar(&selectSkip)
cmd.Flag("limit", "Select at most n hosts").
IntVar(&selectLimit)
cmd.Flag("order-by-tags", "Order hosts by tags (comma separated list)").
Default("").
StringVar(&orderingTags)
}
func nixBuildArgFlag(cmd *kingpin.CmdClause) {
cmd.Flag("build-arg", "Extra argument to pass on to nix-build command. **DEPRECATED**").
StringsVar(&nixBuildArg)
}
func nixBuildTargetFlag(cmd *kingpin.CmdClause) {
cmd.Flag("target", "A Nix lambda defining the build target to use instead of the default").
StringVar(&nixBuildTarget)
}
func nixBuildTargetFileFlag(cmd *kingpin.CmdClause) {
cmd.Flag("target-file", "File containing a Nix attribute set, defining build targets to use instead of the default").
HintFiles("nix").
ExistingFileVar(&nixBuildTargetFile)
}
func skipHealthChecksFlag(cmd *kingpin.CmdClause) {
cmd.
Flag("skip-health-checks", "Whether to skip all health checks").
Default("False").
BoolVar(&skipHealthChecks)
}
func showTraceFlag(cmd *kingpin.CmdClause) {
cmd.
Flag("show-trace", "Whether to pass --show-trace to all nix commands").
Default("False").
BoolVar(&showTrace)
}
func asJsonFlag(cmd *kingpin.CmdClause) {
cmd.
Flag("json", "Whether to format the output as JSON instead of plaintext").
Default("False").
BoolVar(&asJson)
}
func buildCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
nixBuildArgFlag(cmd)
nixBuildTargetFlag(cmd)
nixBuildTargetFileFlag(cmd)
deploymentArg(cmd)
return cmd
}
func pushCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
deploymentArg(cmd)
return cmd
}
func executeCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
askForSudoPasswdFlag(cmd)
timeoutFlag(cmd)
deploymentArg(cmd)
cmd.
Arg("command", "Command to execute").
Required().
StringsVar(&executeCommand)
cmd.NoInterspersed = true
return cmd
}
func deployCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
nixBuildArgFlag(cmd)
deploymentArg(cmd)
timeoutFlag(cmd)
askForSudoPasswdFlag(cmd)
skipHealthChecksFlag(cmd)
cmd.
Flag("upload-secrets", "Upload secrets as part of the host deployment").
Default("False").
BoolVar(&deployUploadSecrets)
cmd.
Flag("reboot", "Reboots the host after system activation, but before healthchecks has executed.").
Default("False").
BoolVar(&deployReboot)
cmd.
Arg("switch-action", "Either of "+strings.Join(switchActions, "|")).
Required().
HintOptions(switchActions...).
EnumVar(&deploySwitchAction, switchActions...)
return cmd
}
func healthCheckCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
deploymentArg(cmd)
timeoutFlag(cmd)
return cmd
}
func uploadSecretsCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
askForSudoPasswdFlag(cmd)
skipHealthChecksFlag(cmd)
deploymentArg(cmd)
return cmd
}
func listSecretsCmd(cmd *kingpin.CmdClause) *kingpin.CmdClause {
selectorFlags(cmd)
showTraceFlag(cmd)
deploymentArg(cmd)
asJsonFlag(cmd)
return cmd
}
func setup() {
utils.ValidateEnvironment("nix")
utils.AddFinalizer(func() {
assets.Teardown(assetRoot)
})
utils.SignalHandler()
var assetErr error
assetRoot, assetErr = assets.Setup()
handleError(assetErr)
}
func main() {
clause := kingpin.MustParse(app.Parse(os.Args[1:]))
//TODO: Remove deprecation warning when removing --build-arg flag
if len(nixBuildArg) > 0 {
fmt.Fprintln(os.Stderr, "Deprecation: The --build-arg flag will be removed in a future release.")
}
defer utils.RunFinalizers()
setup()
hosts, err := getHosts(deployment)
handleError(err)
switch clause {
case build.FullCommand():
_, err = execBuild(hosts)
case push.FullCommand():
_, err = execPush(hosts)
case deploy.FullCommand():
_, err = execDeploy(hosts)
case healthCheck.FullCommand():
err = execHealthCheck(hosts)
case uploadSecrets.FullCommand():
err = execUploadSecrets(createSSHContext(), hosts)
case listSecrets.FullCommand():
if asJson {
err = execListSecretsAsJson(hosts)
} else {
execListSecrets(hosts)
}
case execute.FullCommand():
err = execExecute(hosts)
}
handleError(err)
}
func handleError(err error) {
//Stupid handling of catch-all errors for now
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
utils.Exit(1)
}
}
func execExecute(hosts []nix.Host) error {
sshContext := createSSHContext()
for _, host := range hosts {
if host.BuildOnly {
fmt.Fprintf(os.Stderr, "Exec is disabled for build-only host: %s\n", host.Name)
continue
}
fmt.Fprintln(os.Stderr, "** "+host.Name)
sshContext.CmdInteractive(&host, timeout, executeCommand...)
fmt.Fprintln(os.Stderr)
}
return nil
}
func execBuild(hosts []nix.Host) (string, error) {
resultPath, err := buildHosts(hosts)
if err != nil {
return "", err
}
return resultPath, nil
}
func execPush(hosts []nix.Host) (string, error) {
resultPath, err := execBuild(hosts)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr)
return resultPath, pushPaths(createSSHContext(), hosts, resultPath)
}
func execDeploy(hosts []nix.Host) (string, error) {
doPush := false
doUploadSecrets := false
doActivate := false
if !*dryRun {
switch deploySwitchAction {
case "dry-activate":
doPush = true
doActivate = true
case "test":
fallthrough
case "switch":
fallthrough
case "boot":
doPush = true
doUploadSecrets = deployUploadSecrets
doActivate = true
}
}
resultPath, err := buildHosts(hosts)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr)
sshContext := createSSHContext()
for _, host := range hosts {
if host.BuildOnly {
fmt.Fprintf(os.Stderr, "Deployment steps are disabled for build-only host: %s\n", host.Name)
continue
}
singleHostInList := []nix.Host{host}
if doPush {
err = pushPaths(sshContext, singleHostInList, resultPath)
if err != nil {
return "", err
}
}
fmt.Fprintln(os.Stderr)
if doUploadSecrets {
err = execUploadSecrets(sshContext, singleHostInList)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr)
}
if doActivate {
err = activateConfiguration(sshContext, singleHostInList, resultPath)
if err != nil {
return "", err
}
}
if deployReboot {
err = host.Reboot(sshContext)
if err != nil {
fmt.Fprintln(os.Stderr, "Reboot failed")
return "", err
}
}
if !skipHealthChecks {
err := healthchecks.Perform(sshContext, &host, timeout)
if err != nil {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Not deploying to additional hosts, since a host health check failed.")
utils.Exit(1)
}
}
fmt.Fprintln(os.Stderr, "Done:", host.Name)
}
return resultPath, nil
}
func createSSHContext() *ssh.SSHContext {
return &ssh.SSHContext{
AskForSudoPassword: askForSudoPasswd,
IdentityFile: os.Getenv("SSH_IDENTITY_FILE"),
DefaultUsername: os.Getenv("SSH_USER"),
SkipHostKeyCheck: os.Getenv("SSH_SKIP_HOST_KEY_CHECK") != "",
ConfigFile: os.Getenv("SSH_CONFIG_FILE"),
}
}
func execHealthCheck(hosts []nix.Host) error {
sshContext := createSSHContext()
var err error
for _, host := range hosts {
if host.BuildOnly {
fmt.Fprintf(os.Stderr, "Healthchecks are disabled for build-only host: %s\n", host.Name)
continue
}
err = healthchecks.Perform(sshContext, &host, timeout)
}
if err != nil {
err = errors.New("One or more errors occurred during host healthchecks")
}
return err
}
func execUploadSecrets(sshContext *ssh.SSHContext, hosts []nix.Host) error {
for _, host := range hosts {
if host.BuildOnly {
fmt.Fprintf(os.Stderr, "Secret upload is disabled for build-only host: %s\n", host.Name)
continue
}
singleHostInList := []nix.Host{host}
err := secretsUpload(sshContext, singleHostInList)
if err != nil {
return err
}
if !skipHealthChecks {
err = healthchecks.Perform(sshContext, &host, timeout)
if err != nil {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Not uploading to additional hosts, since a host health check failed.")
return err
}
}
}
return nil
}
func execListSecrets(hosts []nix.Host) {
for _, host := range hosts {
singleHostInList := []nix.Host{host}
for _, host := range singleHostInList {
fmt.Fprintf(os.Stdout, "Secrets for host %s:\n", host.Name)
for name, secret := range host.Secrets {
fmt.Fprintf(os.Stdout, "%s:\n- %v\n", name, &secret)
}
fmt.Fprintf(os.Stdout, "\n")
}
}
}
func execListSecretsAsJson(hosts []nix.Host) error {
deploymentDir, err := filepath.Abs(filepath.Dir(deployment))
if err != nil {
return err
}
secretsByHost := make(map[string](map[string]secrets.Secret))
for _, host := range hosts {
singleHostInList := []nix.Host{host}
for _, host := range singleHostInList {
canonicalSecrets := make(map[string]secrets.Secret)
for name, secret := range host.Secrets {
sourcePath := utils.GetAbsPathRelativeTo(secret.Source, deploymentDir)
secret.Source = sourcePath
canonicalSecrets[name] = secret
}
secretsByHost[host.Name] = canonicalSecrets
}
}
jsonSecrets, err := json.MarshalIndent(secretsByHost, "", " ")
if err != nil {
return err
}
fmt.Fprintf(os.Stdout, "%s\n", jsonSecrets)
return nil
}
func getHosts(deploymentPath string) (hosts []nix.Host, err error) {
deploymentFile, err := os.Open(deploymentPath)
if err != nil {
return hosts, err
}
deploymentAbsPath, err := filepath.Abs(deploymentFile.Name())
if err != nil {
return hosts, err
}
ctx := getNixContext()
deployment, err := ctx.GetMachines(deploymentAbsPath)
if err != nil {
return hosts, err
}
matchingHosts, err := filter.MatchHosts(deployment.Hosts, selectGlob)
if err != nil {
return hosts, err
}
var selectedTags []string
if selectTags != "" {
selectedTags = strings.Split(selectTags, ",")
}
matchingHosts2 := filter.FilterHostsTags(matchingHosts, selectedTags)
ordering := deployment.Meta.Ordering
if orderingTags != "" {
ordering = nix.HostOrdering{Tags: strings.Split(orderingTags, ",")}
}
sortedHosts := filter.SortHosts(matchingHosts2, ordering)
filteredHosts := filter.FilterHosts(sortedHosts, selectSkip, selectEvery, selectLimit)
fmt.Fprintf(os.Stderr, "Selected %v/%v hosts (name filter:-%v, limits:-%v):\n", len(filteredHosts), len(deployment.Hosts), len(deployment.Hosts)-len(matchingHosts), len(matchingHosts)-len(filteredHosts))
for index, host := range filteredHosts {
fmt.Fprintf(os.Stderr, "\t%3d: %s (secrets: %d, health checks: %d, tags: %s)\n", index, host.Name, len(host.Secrets), len(host.HealthChecks.Cmd)+len(host.HealthChecks.Http), strings.Join(host.GetTags(), ","))
}
fmt.Fprintln(os.Stderr)
return filteredHosts, nil
}
func getNixContext() *nix.NixContext {
return &nix.NixContext{
EvalMachines: filepath.Join(assetRoot, assets.Friendly, "eval-machines.nix"),
ShowTrace: showTrace,
KeepGCRoot: *keepGCRoot,
AllowBuildShell: *allowBuildShell,
}
}
func buildHosts(hosts []nix.Host) (resultPath string, err error) {
if len(hosts) == 0 {
err = errors.New("No hosts selected")
return
}
deploymentPath, err := filepath.Abs(deployment)
if err != nil {
return
}
nixBuildTargets := ""
if nixBuildTargetFile != "" {
if path, err := filepath.Abs(nixBuildTargetFile); err == nil {
nixBuildTargets = fmt.Sprintf("import \"%s\"", path)
}
} else if nixBuildTarget != "" {
nixBuildTargets = fmt.Sprintf("{ \"out\" = %s; }", nixBuildTarget)
}
ctx := getNixContext()
resultPath, err = ctx.BuildMachines(deploymentPath, hosts, nixBuildArg, nixBuildTargets)
if err != nil {
return
}
fmt.Fprintln(os.Stderr, "nix result path: ")
fmt.Println(resultPath)
return
}
func pushPaths(sshContext *ssh.SSHContext, filteredHosts []nix.Host, resultPath string) error {
for _, host := range filteredHosts {
if host.BuildOnly {
fmt.Fprintf(os.Stderr, "Push is disabled for build-only host: %s\n", host.Name)
continue
}
paths, err := nix.GetPathsToPush(host, resultPath)
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Pushing paths to %v (%v@%v):\n", host.Name, host.TargetUser, host.TargetHost)
for _, path := range paths {
fmt.Fprintf(os.Stderr, "\t* %s\n", path)
}
err = nix.Push(sshContext, host, paths...)
if err != nil {
return err
}
}
return nil
}
func secretsUpload(ctx ssh.Context, filteredHosts []nix.Host) error {
// upload secrets
// relative paths are resolved relative to the deployment file (!)
deploymentDir := filepath.Dir(deployment)
for _, host := range filteredHosts {
fmt.Fprintf(os.Stderr, "Uploading secrets to %s (%s):\n", host.Name, host.TargetHost)
postUploadActions := make(map[string][]string, 0)
for secretName, secret := range host.Secrets {
secretSize, err := secrets.GetSecretSize(secret, deploymentDir)
if err != nil {
return err
}
secretErr := secrets.UploadSecret(ctx, &host, secret, deploymentDir)
fmt.Fprintf(os.Stderr, "\t* %s (%d bytes).. ", secretName, secretSize)
if secretErr != nil {
if secretErr.Fatal {
fmt.Fprintln(os.Stderr, "Failed")
return secretErr
} else {
fmt.Fprintln(os.Stderr, "Partial")
fmt.Fprint(os.Stderr, secretErr.Error())
}
} else {
fmt.Fprintln(os.Stderr, "OK")
}
if len(secret.Action) > 0 {
// ensure each action is only run once
postUploadActions[strings.Join(secret.Action, " ")] = secret.Action
}
}
// Execute post-upload secret actions one-by-one after all secrets have been uploaded
for _, action := range postUploadActions {
fmt.Fprintf(os.Stderr, "\t- executing post-upload command: "+strings.Join(action, " ")+"\n")
// Errors from secret actions will be printed on screen, but we won't stop the flow if they fail
ctx.CmdInteractive(&host, timeout, action...)
}
}
return nil
}
func activateConfiguration(ctx ssh.Context, filteredHosts []nix.Host, resultPath string) error {
fmt.Fprintln(os.Stderr, "Executing '"+deploySwitchAction+"' on matched hosts:")
fmt.Fprintln(os.Stderr)
for _, host := range filteredHosts {
fmt.Fprintln(os.Stderr, "** "+host.Name)
configuration, err := nix.GetNixSystemPath(host, resultPath)
if err != nil {
return err
}
err = ctx.ActivateConfiguration(&host, configuration, deploySwitchAction)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr)
}
return nil
}