~egtann/up

ref: 8be49268b697bb00d8244f7127d8ab80bc21f281 up/cmd/up/main.go -rw-r--r-- 8.5 KiB
8be49268 — Evan Tann update usage text a month 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
// 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 longest to shortest, so the more specific $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 [options...] <cmd>

OPTIONS
	[-f] path to Upfile, default "Upfile"
	[-h] short-form help with flags
	[-n] number of servers to execute in parallel, default 1
	[-p] prompt before moving to next batch, default false
	[-t] comma-separated target ips, used for $server value
	[-v] verbose output, default false

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

	There are 3 parts to Upfiles:

	1. Command name
	2. Commands: One or more commands to be run, separated by newlines.
	3. 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:

	VARIABLE_1=SUBSTITUTION_VALUE

	CMD_NAME_1:
		CMD_1
		CMD_2
		$VARIABLE_1

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

EXAMPLES
	In the following example Upfile, "deploy_dashboard" is the command.

	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
	remote=$UP_USER@$server
	check_health=curl --max-time 1 $server/version

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

	In this example, running:

	$ up -t 10.0.0.1,10.0.0.2 deploy_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
}