forked from hashicorp/envconsul
/
cli.go
385 lines (323 loc) · 10.2 KB
/
cli.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
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
dep "github.com/hashicorp/consul-template/dependency"
"github.com/hashicorp/consul-template/logging"
"github.com/hashicorp/consul-template/watch"
)
// Exit codes are int valuse that represent an exit code for a particular error.
// Sub-systems may check this unique error to determine the cause of an error
// without parsing the output or help text.
const (
ExitCodeOK int = 0
// Errors start at 10
ExitCodeError = 10 + iota
ExitCodeInterrupt
ExitCodeLoggingError
ExitCodeParseFlagsError
ExitCodeRunnerError
ExitCodeConfigError
ExitCodeUsageError
)
var (
// Error returned when no command is specified.
ErrMissingCommand = fmt.Errorf("No command given")
)
/// ------------------------- ///
// CLI is the main entry point for envconsul.
type CLI struct {
sync.Mutex
// outSteam and errStream are the standard out and standard error streams to
// write messages from the CLI.
outStream, errStream io.Writer
// stopCh is an internal channel used to trigger a shutdown of the CLI.
stopCh chan struct{}
stopped bool
}
func NewCLI(out, err io.Writer) *CLI {
return &CLI{
outStream: out,
errStream: err,
stopCh: make(chan struct{}),
}
}
// Run accepts a slice of arguments and returns an int representing the exit
// status from the command.
func (cli *CLI) Run(args []string) int {
// Parse the flags and args
config, command, once, version, err := cli.parseFlags(args[1:])
if err != nil {
return cli.handleError(err, ExitCodeParseFlagsError)
}
// If a path was given, load the config from file
if config.Path != "" {
newConfig, err := ConfigFromPath(config.Path)
if err != nil {
return cli.handleError(err, ExitCodeConfigError)
}
// Merge ensuring that the CLI options still take precedence
newConfig.Merge(config)
config = newConfig
}
// Setup the logging
if err := logging.Setup(&logging.Config{
Name: Name,
Level: config.LogLevel,
Syslog: config.Syslog.Enabled,
SyslogFacility: config.Syslog.Facility,
Writer: cli.errStream,
}); err != nil {
return cli.handleError(err, ExitCodeLoggingError)
}
// Return an error if no command was given
if len(command) == 0 && !version {
return cli.handleError(ErrMissingCommand, ExitCodeUsageError)
}
// Print version information for debugging
log.Printf("[INFO] envconsul v%s", Version)
// If the version was requested, return an "error" containing the version
// information. This might sound weird, but most *nix applications actually
// print their version on stderr anyway.
if version {
log.Printf("[DEBUG] (cli) version flag was given, exiting now")
fmt.Fprintf(cli.errStream, "%s v%s\n", Name, Version)
return ExitCodeOK
}
// Initial runner
runner, err := NewRunner(config, command, once)
if err != nil {
return cli.handleError(err, ExitCodeRunnerError)
}
go runner.Start()
// Listen for signals
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, Signals...)
for {
select {
case err := <-runner.ErrCh:
return cli.handleError(err, ExitCodeRunnerError)
case <-runner.DoneCh:
return ExitCodeOK
case code := <-runner.ExitCh:
log.Printf("[INFO] (cli) subprocess exited")
runner.Stop()
if code == ExitCodeOK {
return ExitCodeOK
} else {
err := fmt.Errorf("unexpected exit from subprocess (%d)", code)
return cli.handleError(err, code)
}
case s := <-signalCh:
// Propogate the signal to the child process
runner.Signal(s)
switch s {
case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
fmt.Fprintf(cli.errStream, "Received interrupt, cleaning up...\n")
runner.Stop()
return ExitCodeInterrupt
}
case <-cli.stopCh:
return ExitCodeOK
}
}
}
// stop is used internally to shutdown a running CLI
func (cli *CLI) stop() {
cli.Lock()
defer cli.Unlock()
if cli.stopped {
return
}
close(cli.stopCh)
cli.stopped = true
}
// parseFlags is a helper function for parsing command line flags using Go's
// Flag library. This is extracted into a helper to keep the main function
// small, but it also makes writing tests for parsing command line arguments
// much easier and cleaner.
func (cli *CLI) parseFlags(args []string) (*Config, []string, bool, bool, error) {
var once, version bool
var config = DefaultConfig()
// Parse the flags and options
flags := flag.NewFlagSet(Name, flag.ContinueOnError)
flags.SetOutput(cli.errStream)
flags.Usage = func() { fmt.Fprintf(cli.errStream, usage, Name) }
flags.Var((funcVar)(func(s string) error {
config.Consul = s
config.set("consul")
return nil
}), "consul", "")
flags.Var((funcVar)(func(s string) error {
config.Token = s
config.set("token")
return nil
}), "token", "")
flags.Var((funcVar)(func(s string) error {
s = strings.TrimPrefix(s, "/")
p, err := dep.ParseStoreKeyPrefix(s)
if err != nil {
return err
}
if config.Prefixes == nil {
config.Prefixes = make([]*dep.StoreKeyPrefix, 0, 1)
}
config.Prefixes = append(config.Prefixes, p)
return nil
}), "prefix", "")
flags.Var((funcVar)(func(s string) error {
config.Auth.Enabled = true
config.set("auth.enabled")
if strings.Contains(s, ":") {
split := strings.SplitN(s, ":", 2)
config.Auth.Username = split[0]
config.set("auth.username")
config.Auth.Password = split[1]
config.set("auth.password")
} else {
config.Auth.Username = s
config.set("auth.username")
}
return nil
}), "auth", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.SSL.Enabled = b
config.set("ssl")
config.set("ssl.enabled")
return nil
}), "ssl", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.SSL.Verify = b
config.set("ssl.verify")
return nil
}), "ssl-verify", "")
flags.Var((funcVar)(func(s string) error {
config.SSL.Cert = s
config.set("ssl.cert")
return nil
}), "ssl-cert", "")
flags.Var((funcVar)(func(s string) error {
config.SSL.CaCert = s
config.set("ssl.ca_cert")
return nil
}), "ssl-ca-cert", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
config.MaxStale = d
config.set("max_stale")
return nil
}), "max-stale", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.Syslog.Enabled = b
config.set("syslog.enabled")
return nil
}), "syslog", "")
flags.Var((funcVar)(func(s string) error {
config.Syslog.Facility = s
config.set("syslog.facility")
return nil
}), "syslog-facility", "")
flags.Var((funcVar)(func(s string) error {
w, err := watch.ParseWait(s)
if err != nil {
return err
}
config.Wait.Min = w.Min
config.Wait.Max = w.Max
config.set("wait")
return nil
}), "wait", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
config.Retry = d
config.set("retry")
return nil
}), "retry", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.Sanitize = b
config.set("sanitize")
return nil
}), "sanitize", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.Upcase = b
config.set("upcase")
return nil
}), "upcase", "")
flags.Var((funcVar)(func(s string) error {
config.Path = s
config.set("path")
return nil
}), "config", "")
flags.Var((funcVar)(func(s string) error {
config.KillSignal = s
config.set("kill_signal")
return nil
}), "kill-signal", "")
flags.Var((funcVar)(func(s string) error {
config.LogLevel = s
config.set("log_level")
return nil
}), "log-level", "")
flags.Var((funcBoolVar)(func(b bool) error {
config.Pristine = b
config.set("pristine")
return nil
}), "pristine", "")
flags.BoolVar(&once, "once", false, "")
flags.BoolVar(&version, "v", false, "")
flags.BoolVar(&version, "version", false, "")
// If there was a parser error, stop
if err := flags.Parse(args); err != nil {
return nil, nil, false, false, err
}
return config, flags.Args(), once, version, nil
}
// handleError outputs the given error's Error() to the errStream and returns
// the given exit status.
func (cli *CLI) handleError(err error, status int) int {
log.Printf("[ERR] %s", err.Error())
return status
}
const usage = `
Usage: %s [options] <command>
Watches values from Consul's K/V store and sets environment variables when
Consul values are changed.
Options:
-auth=<user[:pass]> Set the basic authentication username (and password)
-consul=<address> Sets the address of the Consul instance
-max-stale=<duration> Set the maximum staleness and allow stale queries to
Consul which will distribute work among all servers
instead of just the leader
-ssl Use SSL when connecting to Consul
-ssl-verify Verify certificates when connecting via SSL
-token=<token> Sets the Consul API token
-syslog Send the output to syslog instead of standard error
and standard out. The syslog facility defaults to
LOCAL0 and can be changed using a configuration file
-syslog-facility=<f> Set the facility where syslog should log. If this
attribute is supplied, the -syslog flag must also be
supplied.
-wait=<duration> Sets the 'minumum(:maximum)' amount of time to wait
before writing a triggering a restart
-retry=<duration> The amount of time to wait if Consul returns an
error when communicating with the API
-prefix A prefix to watch, multiple prefixes are merged from
left to right, with the right-most result taking
precedence
-sanitize Replace invalid characters in keys to underscores
-upcase Convert all environment variable keys to uppercase
-kill-signal The signal to send to kill the process
-config=<path> Sets the path to a configuration file on disk
-log-level=<level> Set the logging level - valid values are "debug",
"info", "warn" (default), and "err"
-pristine Only use variables retrieved from consul, do not inherit
existing environment variables
-once Do not run the process as a daemon
-version Print the version of this daemon
`