~egtann/up

ref: e0094c2d396c40d9b217e16605545b83ed0985b4 up/cmd/up/main.go -rw-r--r-- 16.8 KiB
e0094c2d — Evan Tann update license to openbsd isc 7 months ago
                                                                                
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
// up ensures a project's servers are deployed successfully in one command.
package main

import (
	"bufio"
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"os/exec"
	"strings"
	"time"

	"egt.run/up"
)

type flags struct {
	// Upfile allows you to specify a different Upfile name. This is
	// helpful when running across multiple operating systems or shells.
	// For example, you may have Upfile.windows.toml and Upfile.linux.toml,
	// or Upfile.bash.toml and Upfile.fish.toml.
	Upfile string

	// Inventory allows you specify a different inventory name.
	Inventory string

	// Command to run. Like `make`, an empty Command defaults to the first
	// command in the Upfile.
	Command up.CmdName

	// Tags limits the changed services to those enumerated if the flag is
	// provided. This holds the tags that will be used.
	Tags map[string]struct{}

	// Serial determines how many servers of the same type will be operated
	// on at any one time. This defaults to 1. Use 0 to specify all of
	// them.
	Serial int

	// Vars passed into `up` at runtime to be used in start commands.
	Vars map[string]string

	// Stdin instructs `up` to read from stdin, achieved with `up -`.
	Stdin bool

	// Verbose will log full commands, even when they're very log. By
	// default `up` truncates commands to 80 characters when logging,
	// except in the case of a failure where the full command is displayed.
	Verbose bool

	// Prompt instructs `up` to wait for input before moving onto the next
	// batch.
	Prompt bool
}

type batch map[string][][]string

type result struct {
	server string
	err    error
}

func main() {
	log.SetFlags(0)
	rand.Seed(time.Now().UnixNano())

	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	log.Println("success")
}

func run() error {
	flgs, err := parseFlags()
	if err != nil {
		return usage(fmt.Errorf("parse flags: %w", err))
	}

	var upFi io.ReadCloser
	if flgs.Stdin {
		// Read until we see a NUL byte, which is an indication that we
		// are done. We can't use ReadAll or similar because we need to
		// still accept Stdin on commands for things like doas/sudo
		// prompts when Up is running.
		byt, err := bufio.NewReader(os.Stdin).ReadBytes(0)
		if err != nil && err != io.EOF {
			return fmt.Errorf("read bytes: %w", err)
		}
		// Remove the NUL byte delimiter 0
		if len(byt) >= 1 && byt[len(byt)-1] == byte(0) {
			byt = byt[:len(byt)-1]
		}
		upFi = ioutil.NopCloser(bytes.NewReader(byt))
	} else {
		upFi, err = os.Open(flgs.Upfile)
		if err != nil {
			return fmt.Errorf("open upfile: %w", err)
		}
	}
	conf, err := up.ParseUpfile(upFi)
	if err != nil {
		return fmt.Errorf("parse upfile: %w", err)
	}
	if err = upFi.Close(); err != nil {
		return fmt.Errorf("close: %w", err)
	}

	// Open and parse the inventory file
	invFi, err := os.Open(flgs.Inventory)
	if err != nil {
		return fmt.Errorf("open inventory: %w", err)
	}
	defer invFi.Close()
	inventory, err := up.ParseInventory(invFi)
	if err != nil {
		return fmt.Errorf("parse inventory: %w", err)
	}

	if flgs.Command != "" && flgs.Upfile != "-" {
		conf.DefaultCommand = flgs.Command
		if _, exist := conf.Commands[conf.DefaultCommand]; !exist {
			return fmt.Errorf("undefined command: %s", conf.DefaultCommand)
		}
	}
	lims := []string{}
	for lim := range flgs.Tags {
		lims = append(lims, string(lim))
	}
	tmp := strings.Join(lims, ", ")
	if tmp == "" {
		tmp = string(conf.DefaultCommand)
	}

	if _, exist := inventory["all"]; exist {
		return errors.New("reserved keyword 'all' cannot be inventory name")
	}

	// Default the tags equal to the command name, which makes the
	// following work: `cup -f my_app.json | up -`
	if len(flgs.Tags) == 0 {
		flgs.Tags[string(conf.DefaultCommand)] = struct{}{}
	}

	// Remove any unnecessary inventory. All remaining defined inventory
	// will be used.
	if _, exist := flgs.Tags["all"]; exist {
		for ip, tags := range inventory {
			inventory[ip] = append(tags, "all")
		}
	} else {
		for ip, tags := range inventory {
			var found bool
			for _, t := range tags {
				if _, exist := flgs.Tags[t]; exist {
					found = true
					break
				}
			}
			if !found {
				delete(inventory, ip)
			}
		}
	}

	// Remove any tags which are not in the provided flags, as we'll be
	// ignoring those
	for ip, tags := range inventory {
		var newTags []string
		for _, t := range tags {
			if _, exist := flgs.Tags[t]; !exist {
				continue
			}
			newTags = append(newTags, t)
		}
		inventory[ip] = newTags
	}

	// Validate all tags are defined in inventory (i.e. no silent failure
	// on typos).
	if len(inventory) == 0 {
		msg := fmt.Sprintf("tags not defined in inventory: ")
		for l := range flgs.Tags {
			msg += fmt.Sprintf("%s, ", l)
		}
		return errors.New(strings.TrimSuffix(msg, ", "))
	}

	log.Printf("running %s on %s\n", conf.DefaultCommand, tmp)

	// Split into batches limited in size by the provided Serial flag.
	batches, err := makeBatches(conf, inventory, flgs.Serial)
	if err != nil {
		return fmt.Errorf("make batches: %w", err)
	}
	log.Printf("got batches: %v\n", batches)

	// For each batch, run the ExecIfs and run Execs if necessary.
	done := make(chan struct{}, len(batches))
	crash := make(chan error)
	defer close(crash)
	for _, srvBatch := range batches {
		// Schedule our next batch to run
		go func(srvBatch [][]string) {
			for i, srvGroup := range srvBatch {
				ch := make(chan result, len(srvGroup))
				srvGroup = randomizeOrder(srvGroup)
				cmd := conf.Commands[conf.DefaultCommand]
				runExecIfs(ch, flgs.Vars, conf.Commands, cmd,
					"", srvGroup, flgs.Verbose)
				for j := 0; j < len(srvGroup); j++ {
					res := <-ch
					if res.err != nil {
						crash <- res.err
						return
					}
				}

				// We want to prompt to continue unless it's
				// the last batch
				if flgs.Prompt && i != len(srvBatch)-1 {
					if err := confirmPrompt(srvGroup); err != nil {
						crash <- err
						return
					}
				}
			}
			done <- struct{}{}
		}(srvBatch)
	}
	for i := 0; i < len(batches); i++ {
		select {
		case <-done:
			// Keep going
		case err := <-crash:
			return err
		}
	}
	return nil
}

// confirmPrompt prompts the user and asks if up should continue.
func confirmPrompt(ips []string) error {
	var shouldContinue string
	fmt.Println("done with", ips)
	fmt.Printf("do you want to continue? [Y/n] ")

	rdr := bufio.NewReader(os.Stdin)
	shouldContinue, err := rdr.ReadString('\n')
	if err != nil {
		return fmt.Errorf("failed to read: %w", err)
	}
	shouldContinue = strings.TrimSuffix(shouldContinue, "\n")
	switch strings.ToLower(shouldContinue) {
	case "y", "yes", "":
		return nil
	case "n", "no":
		return errors.New("stopping up")
	default:
		fmt.Printf("unknown input: %s\n", shouldContinue)
		return confirmPrompt(ips)
	}
}

func runExecIfs(
	ch chan result,
	vars map[string]string,
	cmds map[up.CmdName]*up.Cmd,
	cmd *up.Cmd,
	chk string,
	servers []string,
	verbose bool,
) {
	send := func(ch chan<- result, err error, servers []string) {
		for _, srv := range servers {
			ch <- result{server: srv, err: err}
		}
	}
	var needToRun bool
	for _, execIf := range cmd.ExecIfs {
		// TODO should this also enforce ExecIfs? Probably...
		// TODO this should handle errors correctly through the channel
		cmds := copyCommands(cmds)
		steps := cmds[execIf].Execs
		for _, step := range steps {
			ok, err := runExec(vars, cmds, step, chk, servers,
				true, verbose)
			if err != nil {
				send(ch, err, servers)
				return
			}
			if !ok {
				needToRun = true
			}
		}
	}
	if !needToRun && len(cmd.ExecIfs) > 0 {
		for _, srv := range servers {
			ch <- result{server: srv}
		}
		return
	}
	for _, cmdLine := range cmd.Execs {
		cmdLine, err := substituteVariables(vars, cmds, cmdLine)
		if err != nil {
			send(ch, err, servers)
			return
		}

		// We may have substituted a variable with a multi-line command
		cmdLines := strings.SplitN(cmdLine, "\n", -1)
		for _, cmdLine := range cmdLines {
			_, err = runExec(vars, cmds, cmdLine, chk, servers,
				false, verbose)
			if err != nil {
				send(ch, err, servers)
				return
			}
		}
	}
	send(ch, nil, servers)
}

// runExec reports whether all execIfs passed and an error if any.
func runExec(
	vars map[string]string,
	cmds map[up.CmdName]*up.Cmd,
	cmd, chk string,
	servers []string,
	execIf, verbose bool,
) (bool, error) {
	cmds = copyCommands(cmds)
	ch := make(chan runResult, len(servers))
	for _, server := range servers {
		go runCmd(ch, vars, cmds, cmd, chk, server, execIf, verbose)
	}
	var err error
	pass := true
	for i := 0; i < len(servers); i++ {
		res := <-ch
		pass = pass && res.pass
		if res.error != nil {
			err = res.error
		}
	}
	return pass, err
}

type runResult struct {
	pass  bool
	error error
}

func runCmd(
	ch chan<- runResult,
	vars map[string]string,
	cmds map[up.CmdName]*up.Cmd,
	cmd, chk, server string,
	execIf, verbose bool,
) {
	// TODO ensure that no cycles are present with depth-first
	// search

	// Now substitute any variables designated by a '$'
	cmds = copyCommands(cmds)
	cmds["server"] = &up.Cmd{Execs: []string{server}}
	cmd, err := substituteVariables(vars, cmds, cmd)
	if err != nil {
		err = fmt.Errorf("substitute: %w", err)
		ch <- runResult{pass: false, error: err}
		return
	}

	logLine := fmt.Sprintf("[%s] %s", server, cmd)
	if !verbose && len(logLine) > 90 {
		logLine = logLine[:87] + "..."
	}
	log.Printf("%s\n", logLine)

	c := exec.Command("sh", "-c", cmd)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	c.Stdin = os.Stdin
	if err = c.Run(); err != nil {
		if execIf {
			// TODO log if verbose
			ch <- runResult{pass: false}
			return
		}

		fmt.Println("error running command:", cmd)
		ch <- runResult{pass: false, error: err}
		return
	}
	ch <- runResult{pass: true}
}

// parseFlags and validate them.
func parseFlags() (flags, error) {
	var (
		upfile    = flag.String("f", "Upfile", "path to upfile")
		inventory = flag.String("i", "inventory.json", "path to inventory")
		command   = flag.String("c", "", "command to run in upfile (use - to read from stdin)")
		tags      = flag.String("t", "", "tags from inventory to run (defaults to the name of the command)")
		serial    = flag.Int("n", 1, "how many of each type of server to operate on at a time")
		prompt    = flag.Bool("p", false, "prompt before moving to the next batch (default false)")
		verbose   = flag.Bool("v", false, "verbose logs full commands (default false)")
	)
	flag.Parse()

	if *command == "" && *upfile != "-" {
		return flags{}, errors.New("command is required")
	}

	lim := map[string]struct{}{}
	if *tags != "" {
		lims := strings.Split(*tags, ",")
		if len(lims) > 0 {
			all := false
			for _, service := range lims {
				if service == "all" {
					lim["all"] = struct{}{}
					all = true
				}
			}
			if all && len(lims) > 1 {
				return flags{}, errors.New("cannot use 'all' tag alongside others")
			}
			for _, service := range lims {
				lim[service] = struct{}{}
			}
		}
	}
	extraVars := map[string]string{}
	for _, pair := range os.Environ() {
		if len(pair) == 0 {
			continue
		}
		pair = strings.TrimSpace(pair)
		vals := strings.Split(pair, "=")
		if len(vals) != 2 {
			continue
		}
		extraVars[vals[0]] = vals[1]
	}
	flgs := flags{
		Tags:      lim,
		Upfile:    *upfile,
		Inventory: *inventory,
		Serial:    *serial,
		Command:   up.CmdName(*command),
		Vars:      extraVars,
		Stdin:     *upfile == "-",
		Verbose:   *verbose,
		Prompt:    *prompt,
	}
	return flgs, nil
}

func makeBatches(
	conf *up.Config,
	inventory up.Inventory,
	max int,
) (batch, error) {
	batches := batch{}

	// Organize by tags, rather than IPs for efficiency in this next
	// operation
	invMap := map[string][]string{}
	for ip, tags := range inventory {
		for _, tag := range tags {
			if _, exist := invMap[tag]; !exist {
				invMap[tag] = []string{}
			}
			invMap[tag] = append(invMap[tag], ip)
		}
	}

	// Now create batches for each tag
	for tag, ips := range invMap {
		if max == 0 {
			batches[tag] = [][]string{ips}
			continue
		}
		b := [][]string{}
		for _, ip := range ips {
			b = appendToBatch(b, ip, max)
		}
		batches[tag] = b
	}
	if len(batches) == 0 {
		return nil, errors.New("empty batches, nothing to do")
	}
	return batches, nil
}

// appendToBatch adds to the existing last batch if smaller than the max size.
// Otherwise it creates and appends a new batch to the end.
func appendToBatch(b [][]string, srv string, max int) [][]string {
	if len(b) == 0 {
		return [][]string{{srv}}
	}
	last := b[len(b)-1]
	if len(last) >= max {
		return append(b, []string{srv})
	}
	b[len(b)-1] = append(last, srv)
	return b
}

func randomizeOrder(ss []string) []string {
	out := make([]string, len(ss))
	perm := rand.Perm(len(ss))
	for i, p := range perm {
		out[i] = ss[p]
	}
	return out
}

// substituteVariables recursively up to 10 times. After 10 substitutions, this
// function reports an error.
func substituteVariables(
	vars map[string]string,
	cmds map[up.CmdName]*up.Cmd,
	cmd string,
) (string, error) {
	replacements := []string{}
	for cmdName, cmd := range cmds {
		if len(cmd.ExecIfs) > 0 {
			continue
		}
		replacements = append(replacements, "$"+string(cmdName))
		rep := ""
		for _, c := range cmd.Execs {
			rep += c + "\n"
		}
		rep = strings.TrimSpace(rep)
		replacements = append(replacements, rep)
	}
	for name, val := range vars {
		replacements = append(replacements, "$"+name)
		replacements = append(replacements, val)
	}
	r := strings.NewReplacer(replacements...)
	for i := 0; i < 10; i++ {
		tmp := r.Replace(cmd)
		if cmd == tmp {
			// We're done
			return cmd, nil
		}
		cmd = tmp
	}
	return "", errors.New("possible cycle detected")
}

func copyCommands(m1 map[up.CmdName]*up.Cmd) map[up.CmdName]*up.Cmd {
	m2 := map[up.CmdName]*up.Cmd{}
	for k, v := range m1 {
		m2[k] = v
	}
	return m2
}

// usage prints usage instructions. It passes through any error to be sent to
// Stderr by main().
func usage(err error) error {
	fmt.Println(`USAGE
	up -c <cmd> [options...]
	up -f -     [options...]

OPTIONS
	[-c] command to run in upfile
	[-f] path to Upfile, default "Upfile" or use "-" to read from stdin
	[-h] short-form help with flags
	[-i] path to inventory, default "inventory.json"
	[-n] number of servers to execute in parallel, default 1
	[-p] prompt before moving to next batch, default false
	[-t] comma-separated tags from inventory to execute, default is your command
	[-v] verbose output, default false

UPFILE
	Upfiles define the steps to be run for each server using a syntax
	similar to Makefiles.

	There are 4 parts to Upfiles:

	1. Command name: This is passed into up using "-c"
	2. Conditionals: Before running commands, up will execute
	   space-separated conditionals in order. It will proceed to run
	   commands for the server if and only if any of the conditionals
	   return a non-zero exit code. Conditionals are optional.
	3. Commands: One or more commands to be run if all conditionals pass.
	4. Variables: Variables can be substituted within commands by prefixing
	   the name with "$". Variable substitution values may be a single
	   value or an entire series of commands.

	These parts are generally arranged as follows:

	CMD_NAME_1 CONDITIONAL_1 CONDITIONAL_2
		CMD_1
		CMD_2

	CMD_NAME_2
		CMD_3
		$VARIABLE_1

	CONDITIONAL_1
		CMD_4

	VARIABLE_1
		SUBSTITUTION_VALUE

INVENTORY
	The inventory is a JSON file which maps IP addresses to arbitrary tags.
	It has the following format:

	{
		"IP_1": ["TAG_1", "TAG_2"],
		"IP_2": ["TAG_1"]
	}

	Because this is a simple JSON file, your inventory can be dynamically
	generated if you wish based on the state of your architecture at a
	given moment, or you can commit the single into source code alongside
	your Upfile.

EXIT STATUS
	up exits with 0 on success or 1 on any failure.

EXAMPLES
	In the following example Upfile, "deploy_dashboard" is the command.
	Before running the script indented underneath the command, up will
	first execute any space-separated commands to the right. In this
	example, up will only execute the deploy_dashboard commands if
	check_version returns a non-zero exit code.

	All steps are executed locally, so to run commands on the server we use
	the reserved variable "$server" to get the IP and execute commands
	through ssh.

	$ cat Upfile
	deploy_dashboard check_version
		rsync -a dashboard $remote:
		ssh $remote 'sudo service dashboard restart'
		sleep 1 && $check_health

	check_version
		expr $CHECKSUM == "$(curl --max-time 1 $server/version)"

	remote
		$UP_USER@$server

	$ cat inventory.json
	{
		"10.0.0.1": ["dashboard", "redis", "openbsd"],
		"10.0.0.2": ["dashboard", "openbsd"],
		"10.0.0.3": ["dashboard_staging"],
		"10.0.0.4": ["postgres", "debian"],
		"10.0.0.5": ["reverse_proxy"]
	}

	Good inventory tags generally include the type of services running on
	the box and the operating system (for easily updating groups of
	machines with the same OS).

	In this example, running:

	$ up -c deploy_dashboard -t dashboard

	would execute deploy_dashboard on 10.0.0.1 and 10.0.0.2. Since we
	didn't pass in "-n 2", up will deploy on the first server before
	continuing to the next.

AUTHORS
	up was written by Evan Tann <up@evantann.com>.

ERRORS`)
	fmt.Printf("\t")

	return err
}