~egtann/up

ref: 1ab0f861d8d69becf312b45bf8acdec04f8c9667 up/cmd/up/main.go -rw-r--r-- 10.0 KiB
1ab0f861 — Evan Tann simplify tool 4 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
// up ensures a project's servers are deployed successfully in one command.
package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os"
	"os/exec"
	"sort"
	"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

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

	// targets are the servers (typically IP addresses) upon which up will
	// run commands.
	targets []string

	// 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 in parallel.
	serial int

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

	// verbose will log full commands, even when they're very long. 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 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))
	}

	upFi, err := os.Open(flgs.upfile)
	if err != nil {
		return fmt.Errorf("open upfile: %w", err)
	}
	defer upFi.Close()
	conf, err := up.ParseUpfile(upFi)
	if err != nil {
		return fmt.Errorf("parse upfile: %w", err)
	}

	if flgs.command == "" {
		flgs.command = conf.DefaultCommand
		if _, exist := conf.Commands[conf.DefaultCommand]; !exist {
			return fmt.Errorf("undefined command: %s",
				conf.DefaultCommand)
		}
	}
	cmds := conf.Commands[flgs.command]
	if len(cmds) == 0 {
		return fmt.Errorf("%s has no commands", flgs.command)
	}

	for k, v := range conf.Vars {
		if _, ok := flgs.vars[k]; !ok {
			flgs.vars[k] = v
		}
	}
	for i := range cmds {
		cmds, err = substituteVariables(flgs.vars, cmds, cmds[i])
		if err != nil {
			return fmt.Errorf("substitute vars: %w", err)
		}
	}

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

	for _, batch := range batches {
		job := job{ips: batch, cmds: cmds}
		ipErrs := make(chan error)
		for _, ip := range job.ips {
			go ipWorker(ip, job.cmds, ipErrs, flgs.verbose)
		}
		for range job.ips {
			if err := <-ipErrs; err != nil {
				return err
			}
		}
	}
	return nil
}

type job struct {
	ips  []string
	cmds []string
}

func ipWorker(ip string, cmds []string, ipErrs chan<- error, verbose bool) {
	for _, cmd := range cmds {
		cmd = strings.ReplaceAll(cmd, "$server", ip)
		logLine := fmt.Sprintf("[%s] %s", ip, 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 {
			ipErrs <- err
			return
		}
	}
	ipErrs <- 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)
	}
}

// parseFlags and validate them.
func parseFlags() (*flags, error) {
	f := &flags{vars: map[string]string{}}
	flag.StringVar(&f.upfile, "f", "Upfile", "path to upfile")
	flag.IntVar(&f.serial, "n", 1, "how many servers to operate on at a time")
	flag.BoolVar(&f.prompt, "p", false, "prompt before moving to the next batch")
	flag.BoolVar(&f.verbose, "v", false, "verbose logs full commands")
	targets := flag.String("t", "", "comma-separated targets (required)")
	flag.Parse()

	args := flag.Args()
	switch len(args) {
	case 0: // Do nothing
	case 1:
		f.command = args[0]
	default:
		return nil, errors.New("unknown extra args")
	}
	if *targets == "" {
		return nil, errors.New("-t targets is required")
	}
	f.targets = strings.Split(*targets, ",")
	rand.Shuffle(len(f.targets), func(i, j int) {
		f.targets[i], f.targets[j] = f.targets[j], f.targets[i]
	})
	for _, pair := range os.Environ() {
		if len(pair) == 0 {
			continue
		}
		pair = strings.TrimSpace(pair)
		vals := strings.Split(pair, "=")
		if len(vals) != 2 {
			continue
		}
		f.vars[vals[0]] = vals[1]
	}
	return f, nil
}

func makeBatches(
	targets []string,
	max int,
) ([][]string, error) {
	if max == 0 {
		return [][]string{targets}, nil
	}

	batchesLen := len(targets) / max
	if len(targets)%max != 0 {
		// Always round up
		batchesLen++
	}
	var (
		batches = make([][]string, 0, batchesLen)
		batch   = make([]string, 0, max)
	)
	for _, t := range targets {
		if i := len(batch); i < max {
			batch = append(batch, t)
			continue
		}
		batches = append(batches, batch)
		batch = make([]string, 0, max)
		batch = append(batch, t)
	}
	if len(batch) > 0 {
		batches = append(batches, batch)
	}
	if len(batches) == 0 {
		return nil, errors.New("empty batches, nothing to do")
	}
	return batches, nil
}

// substituteVariables recursively up to 50 times. After 50 substitutions, this
// function reports an error in lieu of proper cycle detection.
func substituteVariables(
	vars map[string]string,
	cmds []string,
	cmd string,
) ([]string, error) {
	// Arrange variables biggest to smallest, so $abc is substituted before
	// $a.
	bigToSmall := make([]string, 0, len(vars))
	for v := range vars {
		bigToSmall = append(bigToSmall, v)
	}
	sort.Slice(bigToSmall, func(i, j int) bool {
		return len(bigToSmall[j]) < len(bigToSmall[i])
	})
	var lastReplaced string
	for i := 0; i < 50; i++ {
		var replaced bool
		for i := range cmds {
			orig := cmds[i]
			for _, v := range bigToSmall {
				cmds[i] = strings.ReplaceAll(cmds[i], "$"+v, vars[v])
				lastReplaced = v
			}
			if cmds[i] != orig {
				replaced = true
			}
		}
		if !replaced {
			return cmds, nil
		}
	}
	return nil, fmt.Errorf("possible cycle detected on %s", lastReplaced)
}

// 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"
	[-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
}