-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathcli.go
1068 lines (873 loc) · 30 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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/hashicorp/consul-template/config"
"github.com/hashicorp/consul-template/manager"
"github.com/hashicorp/consul-template/signals"
"github.com/hashicorp/envconsul/version"
"github.com/hashicorp/go-hclog"
gsyslog "github.com/hashicorp/go-syslog"
)
// Exit codes are int values 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
ExitCodeError = 10 + iota
ExitCodeInterrupt
ExitCodeParseFlagsError
ExitCodeRunnerError
ExitCodeConfigError
)
// ErrMissingCommand is returned when no command is specified.
var (
ErrMissingCommand = fmt.Errorf("No command given")
)
// get a new named logger, should log as 'envconsul.[name]'
func namedLogger(name string) hclog.Logger {
return hclog.Default().Named(name)
}
// 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
// signalCh is the channel where the cli receives signals.
signalCh chan os.Signal
// stopCh is an internal channel used to trigger a shutdown of the CLI.
stopCh chan struct{}
stopped bool
}
// NewCLI creates a new command line interface with the given streams.
func NewCLI(out, err io.Writer) *CLI {
return &CLI{
outStream: out,
errStream: err,
signalCh: make(chan os.Signal, 1),
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
cfg, paths, once, isVersion, err := cli.ParseFlags(args[1:])
if err != nil {
if err == flag.ErrHelp {
fmt.Fprintf(cli.outStream, usage, version.Name)
return 0
}
fmt.Fprintln(cli.errStream, err.Error())
return ExitCodeParseFlagsError
}
// Save original config (defaults + parsed flags) for handling reloads
cliConfig := cfg.Copy()
// Load configuration paths, with CLI taking precendence
cfg, err = loadConfigs(paths, cliConfig)
if err != nil {
return logError(err, ExitCodeConfigError)
}
cfg.Finalize()
// Setup the config and logging
err = cli.setupLogger(cfg)
if err != nil {
return logError(err, ExitCodeConfigError)
}
logger := namedLogger("cli")
// 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 isVersion {
logger.Debug("version flag was given, exiting now")
fmt.Fprintf(cli.outStream, "%s\n", version.HumanVersion)
return ExitCodeOK
}
// Return an error if no command was given
if cfg.Exec.Command.Empty() {
return logError(ErrMissingCommand, ExitCodeConfigError)
}
// Print version information for debugging
logger.Info(version.HumanVersion)
// Initial runner
runner, err := NewRunner(cfg, once)
if err != nil {
return logError(err, ExitCodeRunnerError)
}
go runner.Start()
// Listen for signals
signal.Notify(cli.signalCh)
for {
select {
case err := <-runner.ErrCh:
// Check if the runner's error returned a specific exit status, and return
// that value. If no value was given, return a generic exit status.
code := ExitCodeRunnerError
if typed, ok := err.(manager.ErrExitable); ok {
code = typed.ExitStatus()
}
return logError(err, code)
case <-runner.DoneCh:
return ExitCodeOK
case code := <-runner.ExitCh:
logger.Info("subprocess exited")
runner.Stop()
if code == ExitCodeOK {
return ExitCodeOK
} else {
err := fmt.Errorf("unexpected exit from subprocess (%d)", code)
return logError(err, code)
}
case s := <-cli.signalCh:
switch s {
case RuntimeSig:
default: // filter out RuntimeSig, as it is used by the scheduler and noisy
logger.Debug("receiving signal", "signal", s)
}
switch s {
case *cfg.ReloadSignal:
fmt.Fprintf(cli.errStream, "Reloading configuration...\n")
runner.Stop()
// Re-parse any configuration files or paths
cfg, err = loadConfigs(paths, cliConfig)
if err != nil {
return logError(err, ExitCodeConfigError)
}
cfg.Finalize()
// Load the new configuration from disk
err = cli.setupLogger(cfg)
if err != nil {
return logError(err, ExitCodeConfigError)
}
runner, err = NewRunner(cfg, once)
if err != nil {
return logError(err, ExitCodeRunnerError)
}
go runner.Start()
case *cfg.KillSignal:
fmt.Fprintf(cli.errStream, "Cleaning up...\n")
runner.Stop()
return ExitCodeInterrupt
case signals.SignalLookup["SIGCHLD"]:
// The SIGCHLD signal is sent to the parent of a child process when it
// exits, is interrupted, or resumes after being interrupted. We ignore
// this signal because the child process is monitored on its own.
//
// Also, the reason we do a lookup instead of a direct syscall.SIGCHLD
// is because that isn't defined on Windows.
case RuntimeSig:
// ignore these as the runtime uses them with the scheduler
default:
// Propogate the signal to the child process
runner.Signal(s)
}
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) {
logger := namedLogger("cli")
var once, isVersion bool
var no_prefix *bool
c := DefaultConfig()
// configPaths stores the list of configuration paths on disk
configPaths := make([]string, 0, 6)
// Parse the flags and options
flags := flag.NewFlagSet(version.Name, flag.ContinueOnError)
flags.SetOutput(ioutil.Discard)
flags.Usage = func() {}
flags.Var((funcVar)(func(s string) error {
configPaths = append(configPaths, s)
return nil
}), "config", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.Address = config.String(s)
return nil
}), "consul-addr", "")
flags.Var((funcVar)(func(s string) error {
a, err := config.ParseAuthConfig(s)
if err != nil {
return err
}
c.Consul.Auth = a
return nil
}), "consul-auth", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Consul.Retry.Enabled = config.Bool(b)
return nil
}), "consul-retry", "")
flags.Var((funcIntVar)(func(i int) error {
c.Consul.Retry.Attempts = config.Int(i)
return nil
}), "consul-retry-attempts", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Consul.Retry.Backoff = config.TimeDuration(d)
return nil
}), "consul-retry-backoff", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Consul.Retry.MaxBackoff = config.TimeDuration(d)
return nil
}), "consul-retry-max-backoff", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Consul.SSL.Enabled = config.Bool(b)
return nil
}), "consul-ssl", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.SSL.CaCert = config.String(s)
return nil
}), "consul-ssl-ca-cert", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.SSL.CaPath = config.String(s)
return nil
}), "consul-ssl-ca-path", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.SSL.Cert = config.String(s)
return nil
}), "consul-ssl-cert", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.SSL.Key = config.String(s)
return nil
}), "consul-ssl-key", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.SSL.ServerName = config.String(s)
return nil
}), "consul-ssl-server-name", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Consul.SSL.Verify = config.Bool(b)
return nil
}), "consul-ssl-verify", "")
flags.Var((funcVar)(func(s string) error {
c.Consul.Token = config.String(s)
return nil
}), "consul-token", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Consul.Transport.DialKeepAlive = config.TimeDuration(d)
return nil
}), "consul-transport-dial-keep-alive", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Consul.Transport.DialTimeout = config.TimeDuration(d)
return nil
}), "consul-transport-dial-timeout", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Consul.Transport.DisableKeepAlives = config.Bool(b)
return nil
}), "consul-transport-disable-keep-alives", "")
flags.Var((funcIntVar)(func(i int) error {
c.Consul.Transport.MaxIdleConnsPerHost = config.Int(i)
return nil
}), "consul-transport-max-idle-conns-per-host", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Consul.Transport.TLSHandshakeTimeout = config.TimeDuration(d)
return nil
}), "consul-transport-tls-handshake-timeout", "")
flags.Var((funcVar)(func(s string) error {
c.Exec.Enabled = config.Bool(true)
c.Exec.Command = []string{s}
return nil
}), "exec", "")
flags.Var((funcVar)(func(s string) error {
sig, err := signals.Parse(s)
if err != nil {
return err
}
c.Exec.KillSignal = config.Signal(sig)
return nil
}), "exec-kill-signal", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Exec.KillTimeout = config.TimeDuration(d)
return nil
}), "exec-kill-timeout", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Exec.Splay = config.TimeDuration(d)
return nil
}), "exec-splay", "")
flags.Var((funcVar)(func(s string) error {
sig, err := signals.Parse(s)
if err != nil {
return err
}
c.KillSignal = config.Signal(sig)
return nil
}), "kill-signal", "")
flags.Var((funcVar)(func(s string) error {
c.LogLevel = config.String(s)
return nil
}), "log-level", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.MaxStale = config.TimeDuration(d)
return nil
}), "max-stale", "")
// requires post processing (see below) as it depends on -prefix
flags.Var((funcBoolVar)(func(b bool) error {
no_prefix = config.Bool(b)
return nil
}), "no-prefix", "")
flags.BoolVar(&once, "once", false, "")
flags.Var((funcVar)(func(s string) error {
c.PidFile = config.String(s)
return nil
}), "pid-file", "")
flags.Var((funcVar)(func(s string) error {
p, err := ParsePrefixConfig(s)
if err != nil {
return err
}
*c.Prefixes = append(*c.Prefixes, p)
return nil
}), "prefix", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Pristine = config.Bool(b)
return nil
}), "pristine", "")
flags.Var((funcVar)(func(s string) error {
sig, err := signals.Parse(s)
if err != nil {
return err
}
c.ReloadSignal = config.Signal(sig)
return nil
}), "reload-signal", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Sanitize = config.Bool(b)
return nil
}), "sanitize", "")
flags.Var((funcVar)(func(s string) error {
p, err := ParsePrefixConfig(s)
if err != nil {
return err
}
*c.Secrets = append(*c.Secrets, p)
return nil
}), "secret", "")
flags.Var((funcVar)(func(s string) error {
p, err := ParseServiceConfig(s)
if err != nil {
return err
}
*c.Services = append(*c.Services, p)
return nil
}), "service-query", "")
flags.Var((funcVar)(func(s string) error {
serviceConfig := c.Services.LastSeviceConfig()
if serviceConfig == nil {
return fmt.Errorf("format must be specified before query")
}
serviceConfig.FormatId = config.String(s)
return nil
}), "service-format-id", "")
flags.Var((funcVar)(func(s string) error {
serviceConfig := c.Services.LastSeviceConfig()
if serviceConfig == nil {
return fmt.Errorf("format must be specified before query")
}
serviceConfig.FormatName = config.String(s)
return nil
}), "service-format-name", "")
flags.Var((funcVar)(func(s string) error {
serviceConfig := c.Services.LastSeviceConfig()
if serviceConfig == nil {
return fmt.Errorf("format must be specified before query")
}
serviceConfig.FormatAddress = config.String(s)
return nil
}), "service-format-address", "")
flags.Var((funcVar)(func(s string) error {
serviceConfig := c.Services.LastSeviceConfig()
if serviceConfig == nil {
return fmt.Errorf("format must be specified before query")
}
serviceConfig.FormatTag = config.String(s)
return nil
}), "service-format-tag", "")
flags.Var((funcVar)(func(s string) error {
serviceConfig := c.Services.LastSeviceConfig()
if serviceConfig == nil {
return fmt.Errorf("format must be specified before query")
}
serviceConfig.FormatPort = config.String(s)
return nil
}), "service-format-port", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Syslog.Enabled = config.Bool(b)
return nil
}), "syslog", "")
flags.Var((funcVar)(func(s string) error {
c.Syslog.Facility = config.String(s)
return nil
}), "syslog-facility", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Upcase = config.Bool(b)
return nil
}), "upcase", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.Address = config.String(s)
return nil
}), "vault-addr", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.Namespace = config.String(s)
return nil
}), "vault-namespace", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.RenewToken = config.Bool(b)
return nil
}), "vault-renew-token", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.Retry.Enabled = config.Bool(b)
return nil
}), "vault-retry", "")
flags.Var((funcIntVar)(func(i int) error {
c.Vault.Retry.Attempts = config.Int(i)
return nil
}), "vault-retry-attempts", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Vault.Retry.Backoff = config.TimeDuration(d)
return nil
}), "vault-retry-backoff", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Vault.Retry.MaxBackoff = config.TimeDuration(d)
return nil
}), "vault-retry-max-backoff", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.SSL.Enabled = config.Bool(b)
return nil
}), "vault-ssl", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.SSL.CaCert = config.String(s)
return nil
}), "vault-ssl-ca-cert", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.SSL.CaPath = config.String(s)
return nil
}), "vault-ssl-ca-path", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.SSL.Cert = config.String(s)
return nil
}), "vault-ssl-cert", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.SSL.Key = config.String(s)
return nil
}), "vault-ssl-key", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.SSL.ServerName = config.String(s)
return nil
}), "vault-ssl-server-name", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.SSL.Verify = config.Bool(b)
return nil
}), "vault-ssl-verify", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Vault.Transport.DialKeepAlive = config.TimeDuration(d)
return nil
}), "vault-transport-dial-keep-alive", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Vault.Transport.DialTimeout = config.TimeDuration(d)
return nil
}), "vault-transport-dial-timeout", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.Transport.DisableKeepAlives = config.Bool(b)
return nil
}), "vault-transport-disable-keep-alives", "")
flags.Var((funcIntVar)(func(i int) error {
c.Vault.Transport.MaxIdleConnsPerHost = config.Int(i)
return nil
}), "vault-transport-max-idle-conns-per-host", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
c.Vault.Transport.TLSHandshakeTimeout = config.TimeDuration(d)
return nil
}), "vault-transport-tls-handshake-timeout", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.Token = config.String(s)
return nil
}), "vault-token", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.VaultAgentTokenFile = config.String(s)
return nil
}), "vault-agent-token-file", "")
flags.Var((funcBoolVar)(func(b bool) error {
c.Vault.UnwrapToken = config.Bool(b)
return nil
}), "vault-unwrap-token", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.K8SAuthRoleName = config.String(s)
return nil
}), "vault-k8s-auth-role-name", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.K8SServiceAccountToken = config.String(s)
return nil
}), "vault-k8s-service-account-token", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.K8SServiceAccountTokenPath = config.String(s)
return nil
}), "vault-k8s-service-account-token-path", "")
flags.Var((funcVar)(func(s string) error {
c.Vault.K8SServiceMountPath = config.String(s)
return nil
}), "vault-k8s-service-mount-path", "")
flags.Var((funcVar)(func(s string) error {
w, err := config.ParseWaitConfig(s)
if err != nil {
return err
}
c.Wait = w
return nil
}), "wait", "")
flags.BoolVar(&isVersion, "v", false, "")
flags.BoolVar(&isVersion, "version", false, "")
// Deprecations
// TODO remove in 0.8.0
flags.Var((funcVar)(func(s string) error {
logger.Warn("-auth is now -consul-auth")
a, err := config.ParseAuthConfig(s)
if err != nil {
return err
}
c.Consul.Auth = a
return nil
}), "auth", "")
flags.Var((funcVar)(func(s string) error {
logger.Warn("-consul is now -consul-addr")
c.Consul.Address = config.String(s)
return nil
}), "consul", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
logger.Warn("-retry is now -consul-retry-* and -vault-retry-*")
c.Consul.Retry.Backoff = config.TimeDuration(d)
c.Consul.Retry.MaxBackoff = config.TimeDuration(d)
c.Vault.Retry.Backoff = config.TimeDuration(d)
c.Vault.Retry.MaxBackoff = config.TimeDuration(d)
return nil
}), "retry", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
logger.Warn("-splay is now -exec-splay")
c.Exec.Splay = config.TimeDuration(d)
return nil
}), "splay", "")
flags.Var((funcBoolVar)(func(b bool) error {
logger.Warn("-ssl is now -consul-ssl-* and -vault-ssl-*")
c.Consul.SSL.Enabled = config.Bool(b)
c.Vault.SSL.Enabled = config.Bool(b)
return nil
}), "ssl", "")
flags.Var((funcBoolVar)(func(b bool) error {
logger.Warn("-ssl-verify is now -consul-ssl-verify and -vault-ssl-verify")
c.Consul.SSL.Verify = config.Bool(b)
c.Vault.SSL.Verify = config.Bool(b)
return nil
}), "ssl-verify", "")
flags.Var((funcVar)(func(s string) error {
logger.Warn("-ssl-ca-cert is now -consul-ssl-ca-cert and -vault-ssl-ca-cert")
c.Consul.SSL.CaCert = config.String(s)
c.Vault.SSL.CaCert = config.String(s)
return nil
}), "ssl-ca-cert", "")
flags.Var((funcVar)(func(s string) error {
logger.Warn("-ssl-cert is now -consul-ssl-cert and -vault-ssl-cert")
c.Consul.SSL.Cert = config.String(s)
c.Vault.SSL.Cert = config.String(s)
return nil
}), "ssl-cert", "")
flags.Var((funcDurationVar)(func(d time.Duration) error {
logger.Warn("-timeout is now -exec-timeout")
c.Exec.Timeout = config.TimeDuration(d)
return nil
}), "timeout", "")
flags.Var((funcVar)(func(s string) error {
logger.Warn("-token is now -consul-token")
c.Consul.Token = config.String(s)
return nil
}), "token", "")
// End deprecations
// TODO remove in 0.8.0
// If there was a parser error, stop
if err := flags.Parse(args); err != nil {
return nil, nil, false, false, err
}
// Post-processing of no-prefix option
if no_prefix != nil {
for _, p := range *c.Prefixes {
p.NoPrefix = no_prefix
}
for _, s := range *c.Secrets {
s.NoPrefix = no_prefix
}
}
// Convert any arguments given after to the command, but a command specified
// via the flag takes precedence.
if c.Exec.Command == nil {
if command := strings.Join(flags.Args(), " "); command != "" {
c.Exec.Enabled = config.Bool(true)
c.Exec.Command = []string{command}
}
}
return c, configPaths, once, isVersion, nil
}
// loadConfigs loads the configuration from the list of paths. The optional
// configuration is the list of overrides to apply at the very end, taking
// precendence over any configurations that were loaded from the paths. If any
// errors occur when reading or parsing those sub-configs, it is returned.
func loadConfigs(paths []string, o *Config) (*Config, error) {
finalC := DefaultConfig()
for _, path := range paths {
c, err := FromPath(path)
if err != nil {
return nil, err
}
finalC = finalC.Merge(c)
}
finalC = finalC.Merge(o)
finalC.Finalize()
return finalC, nil
}
// logError logs an error message and then returns the given status.
func logError(err error, status int) int {
hclog.Default().Error(err.Error())
return status
}
func (cli *CLI) setupLogger(conf *Config) error {
// Validate the log level
logLevel := strings.ToUpper(valueFrom(conf.LogLevel))
levels := map[string]bool{
"TRACE": true, "DEBUG": true, "INFO": true, "WARN": true, "ERROR": true,
}
switch {
case logLevel == "ERR": // old ERROR notation
logLevel = "ERROR"
case !levels[logLevel]:
return fmt.Errorf("invalid log level: %s", logLevel)
}
var logOutput io.Writer
if valueFrom(conf.Syslog.Enabled) {
syslog, err := gsyslog.NewLogger(
gsyslog.LOG_NOTICE, valueFrom(conf.Syslog.Facility), version.Name)
if err != nil {
return fmt.Errorf("error setting up syslog logger: %s", err)
}
logOutput = io.MultiWriter(cli.errStream, syslog)
} else {
logOutput = cli.errStream
}
logger := hclog.New(&hclog.LoggerOptions{
Name: "envconsul",
Level: hclog.LevelFromString(logLevel),
Output: logOutput,
TimeFormat: hclog.TimeFormat,
})
hclog.SetDefault(logger)
// XXX consul-template still uses 'log' package
// XXX this gets 'log' playing mostly nice with hclog
// XXX remove after consul-template uses hclog??
log.SetFlags(0) // only log the message
log.SetOutput(logger.StandardWriter( // send message to hclog
&hclog.StandardLoggerOptions{InferLevels: true}))
return nil
}
// use generics (woo!) simplify getting values from pointers
func valueFrom[T any](p *T) T {
if p == nil {
return *new(T) // zero value of type T
}
return *p
}
const usage = `Usage: %s [options] <command>
Watches values from Consul's K/V store and Vault secrets to set environment
variables when the values are changed. It spawns a child process populated
with the environment variables.
Options:
-config=<path>
Sets the path to a configuration file or folder on disk. This can be
specified multiple times to load multiple files or folders. If multiple
values are given, they are merged left-to-right, and CLI arguments take
the top-most precedence.
-consul-addr=<address>
Sets the address of the Consul instance
-consul-auth=<username[:password]>
Set the basic authentication username and password for communicating
with Consul.
-consul-retry
Use retry logic when communication with Consul fails
-consul-retry-attempts=<int>
The number of attempts to use when retrying failed communications
-consul-retry-backoff=<duration>
The base amount to use for the backoff duration. This number will be
increased exponentially for each retry attempt.
-consul-retry-max-backoff=<duration>
The maximum limit of the retry backoff duration. Default is one minute.
0 means infinite. The backoff will increase exponentially until given value.
-consul-ssl
Use SSL when connecting to Consul
-consul-ssl-ca-cert=<string>
Validate server certificate against this CA certificate file list
-consul-ssl-ca-path=<string>
Sets the path to the CA to use for TLS verification
-consul-ssl-cert=<string>
SSL client certificate to send to server
-consul-ssl-key=<string>
SSL/TLS private key for use in client authentication key exchange
-consul-ssl-server-name=<string>
Sets the name of the server to use when validating TLS.
-consul-ssl-verify
Verify certificates when connecting via SSL
-consul-token=<token>
Sets the Consul API token
-consul-transport-dial-keep-alive=<duration>
Sets the amount of time to use for keep-alives
-consul-transport-dial-timeout=<duration>
Sets the amount of time to wait to establish a connection
-consul-transport-disable-keep-alives
Disables keep-alives (this will impact performance)
-consul-transport-max-idle-conns-per-host=<int>
Sets the maximum number of idle connections to permit per host
-consul-transport-tls-handshake-timeout=<duration>
Sets the handshake timeout
-exec=<command>
Enable exec mode to run as a supervisor-like process - the given command
will receive all signals provided to the parent process and will receive a
signal when templates change
-exec-kill-signal=<signal>
Signal to send when gracefully killing the process
-exec-kill-timeout=<duration>
Amount of time to wait before force-killing the child
-exec-splay=<duration>
Amount of time to wait before sending signals
-kill-signal=<signal>
Signal to listen to gracefully terminate the process
-log-level=<level>
Set the logging level - values are "trace", "debug", "info", "warn",
and "error"
-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
-no-prefix[=<bool>]
Tells Envconsul to not prefix the keys with their parent "folder".
-once
Do not run as a daemon. Fetch the data, run the process once and exit.
-pid-file=<path>
Path on disk to write the PID of the process
-prefix=<prefix>
Add a prefix to watch (to the right of configured prefixes), multiple
prefixes are merged from left to right, with the right-most result taking
precedence, including any values specified with -secret (secrets
overrides prefixes)
-pristine
Only use values retrieved from prefixes and secrets, do not inherit the
existing environment variables
-reload-signal=<signal>
Signal to listen to reload configuration
-sanitize
Replace invalid characters in keys to underscores
-secret=<prefix>
Add a secret path to watch in Vault (to the right of configured secrets),
multiple prefixes are merged from left to right, with the right-most
result taking precedence, including any values specified with -prefix
(secrets overrides prefixes)
-service-query=<service-name>
A query to watch in Consul service parameters
-service-format-id=<{{service}}/{{key}}>
Format key environment for service id.
-service-format-name=<{{service}}/{{key}}>
Format key environment for service name.
-service-format-address=<{{service}}/{{key}}>
Format key environment for service address.
-service-format-tag=<{{service}}/{{key}}>
Format key environment for service tag.
-service-format-port=<{{service}}/{{key}}>
Format key environment for service port.
-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=<facility>
Set the facility where syslog should log - if this attribute is supplied,
the -syslog flag must also be supplied
-upcase
Convert all environment variable keys to uppercase
-vault-addr=<address>
Sets the address of the Vault server
-vault-namespace=<namespace>
Sets the Vault namespace
-vault-renew-token
Periodically renew the provided Vault API token - this defaults to "true"
and will renew the token at half of the lease duration (unless
vault-agent-token-file is set, then it defaults to false as it is
presumed the vault-agent will take care of renewing)
-vault-retry
Use retry logic when communication with Vault fails
-vault-retry-attempts=<int>
The number of attempts to use when retrying failed communications
-vault-retry-backoff=<duration>
The base amount to use for the backoff duration. This number will be
increased exponentially for each retry attempt.
-vault-retry-max-backoff=<duration>