-
Notifications
You must be signed in to change notification settings - Fork 2k
/
command.go
1712 lines (1456 loc) · 55.1 KB
/
command.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: BUSL-1.1
package agent
import (
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"syscall"
"time"
metrics "github.com/armon/go-metrics"
"github.com/armon/go-metrics/circonus"
"github.com/armon/go-metrics/datadog"
"github.com/armon/go-metrics/prometheus"
checkpoint "github.com/hashicorp/go-checkpoint"
discover "github.com/hashicorp/go-discover"
hclog "github.com/hashicorp/go-hclog"
gsyslog "github.com/hashicorp/go-syslog"
"github.com/hashicorp/logutils"
"github.com/hashicorp/nomad/helper"
flaghelper "github.com/hashicorp/nomad/helper/flags"
gatedwriter "github.com/hashicorp/nomad/helper/gated-writer"
"github.com/hashicorp/nomad/helper/logging"
"github.com/hashicorp/nomad/helper/winsvc"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/hashicorp/nomad/version"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
// gracefulTimeout controls how long we wait before forcefully terminating
const gracefulTimeout = 5 * time.Second
// Command is a Command implementation that runs a Nomad agent.
// The command will not end unless a shutdown message is sent on the
// ShutdownCh. If two messages are sent on the ShutdownCh it will forcibly
// exit.
type Command struct {
Version *version.VersionInfo
Ui cli.Ui
ShutdownCh <-chan struct{}
args []string
agent *Agent
httpServers []*HTTPServer
logFilter *logutils.LevelFilter
logOutput io.Writer
retryJoinErrCh chan struct{}
}
func (c *Command) readConfig() *Config {
var configPath []string
var servers string
var meta []string
// Make a new, empty config.
cmdConfig := &Config{
Client: &ClientConfig{},
Consuls: []*config.ConsulConfig{{Name: structs.ConsulDefaultCluster}},
Ports: &Ports{},
Server: &ServerConfig{
ServerJoin: &ServerJoin{},
},
Vaults: []*config.VaultConfig{{Name: structs.VaultDefaultCluster}},
ACL: &ACLConfig{},
Audit: &config.AuditConfig{},
Reporting: &config.ReportingConfig{},
}
flags := flag.NewFlagSet("agent", flag.ContinueOnError)
flags.Usage = func() { c.Ui.Error(c.Help()) }
// Role options
var devMode bool
var devConnectMode bool
var devConsulMode bool
var devVaultMode bool
flags.BoolVar(&devMode, "dev", false, "")
flags.BoolVar(&devConnectMode, "dev-connect", false, "")
flags.BoolVar(&devConsulMode, "dev-consul", false, "")
flags.BoolVar(&devVaultMode, "dev-vault", false, "")
flags.BoolVar(&cmdConfig.Server.Enabled, "server", false, "")
flags.BoolVar(&cmdConfig.Client.Enabled, "client", false, "")
// Server-only options
flags.IntVar(&cmdConfig.Server.BootstrapExpect, "bootstrap-expect", 0, "")
flags.StringVar(&cmdConfig.Server.EncryptKey, "encrypt", "", "gossip encryption key")
flags.IntVar(&cmdConfig.Server.RaftProtocol, "raft-protocol", 0, "")
flags.BoolVar(&cmdConfig.Server.RejoinAfterLeave, "rejoin", false, "")
flags.Var((*flaghelper.StringFlag)(&cmdConfig.Server.ServerJoin.StartJoin), "join", "")
flags.Var((*flaghelper.StringFlag)(&cmdConfig.Server.ServerJoin.RetryJoin), "retry-join", "")
flags.IntVar(&cmdConfig.Server.ServerJoin.RetryMaxAttempts, "retry-max", 0, "")
flags.Var((flaghelper.FuncDurationVar)(func(d time.Duration) error {
cmdConfig.Server.ServerJoin.RetryInterval = d
return nil
}), "retry-interval", "")
// Client-only options
flags.StringVar(&cmdConfig.Client.StateDir, "state-dir", "", "")
flags.StringVar(&cmdConfig.Client.AllocDir, "alloc-dir", "", "")
flags.StringVar(&cmdConfig.Client.AllocMountsDir, "alloc-mounts-dir", "", "")
flags.StringVar(&cmdConfig.Client.NodeClass, "node-class", "", "")
flags.StringVar(&cmdConfig.Client.NodePool, "node-pool", "", "")
flags.StringVar(&servers, "servers", "", "")
flags.Var((*flaghelper.StringFlag)(&meta), "meta", "")
flags.StringVar(&cmdConfig.Client.NetworkInterface, "network-interface", "", "")
flags.StringVar((*string)(&cmdConfig.Client.PreferredAddressFamily), "preferred-address-family", "", "ipv4 or ipv6")
flags.IntVar(&cmdConfig.Client.NetworkSpeed, "network-speed", 0, "")
// General options
flags.Var((*flaghelper.StringFlag)(&configPath), "config", "config")
flags.StringVar(&cmdConfig.BindAddr, "bind", "", "")
flags.StringVar(&cmdConfig.Region, "region", "", "")
flags.StringVar(&cmdConfig.DataDir, "data-dir", "", "")
flags.StringVar(&cmdConfig.PluginDir, "plugin-dir", "", "")
flags.StringVar(&cmdConfig.Datacenter, "dc", "", "")
flags.StringVar(&cmdConfig.LogLevel, "log-level", "", "")
flags.BoolVar(&cmdConfig.LogJson, "log-json", false, "")
flags.BoolVar(&cmdConfig.LogIncludeLocation, "log-include-location", false, "")
flags.StringVar(&cmdConfig.NodeName, "node", "", "")
// Consul options
defaultConsul := cmdConfig.defaultConsul()
flags.StringVar(&defaultConsul.Auth, "consul-auth", "", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.AutoAdvertise = &b
return nil
}), "consul-auto-advertise", "")
flags.StringVar(&defaultConsul.CAFile, "consul-ca-file", "", "")
flags.StringVar(&defaultConsul.CertFile, "consul-cert-file", "", "")
flags.StringVar(&defaultConsul.KeyFile, "consul-key-file", "", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.ChecksUseAdvertise = &b
return nil
}), "consul-checks-use-advertise", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.ClientAutoJoin = &b
return nil
}), "consul-client-auto-join", "")
flags.StringVar(&defaultConsul.ClientServiceName, "consul-client-service-name", "", "")
flags.StringVar(&defaultConsul.ClientHTTPCheckName, "consul-client-http-check-name", "", "")
flags.IntVar(&defaultConsul.ClientFailuresBeforeCritical, "consul-client-failures-before-critical", 0, "")
flags.IntVar(&defaultConsul.ClientFailuresBeforeWarning, "consul-client-failures-before-warning", 0, "")
flags.StringVar(&defaultConsul.ServerServiceName, "consul-server-service-name", "", "")
flags.StringVar(&defaultConsul.ServerHTTPCheckName, "consul-server-http-check-name", "", "")
flags.StringVar(&defaultConsul.ServerSerfCheckName, "consul-server-serf-check-name", "", "")
flags.StringVar(&defaultConsul.ServerRPCCheckName, "consul-server-rpc-check-name", "", "")
flags.IntVar(&defaultConsul.ServerFailuresBeforeCritical, "consul-server-failures-before-critical", 0, "")
flags.IntVar(&defaultConsul.ServerFailuresBeforeWarning, "consul-server-failures-before-warning", 0, "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.ServerAutoJoin = &b
return nil
}), "consul-server-auto-join", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.EnableSSL = &b
return nil
}), "consul-ssl", "")
flags.StringVar(&defaultConsul.Token, "consul-token", "", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.VerifySSL = &b
return nil
}), "consul-verify-ssl", "")
flags.StringVar(&defaultConsul.Addr, "consul-address", "", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultConsul.AllowUnauthenticated = &b
return nil
}), "consul-allow-unauthenticated", "")
// Vault options
defaultVault := cmdConfig.defaultVault()
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultVault.Enabled = &b
return nil
}), "vault-enabled", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultVault.AllowUnauthenticated = &b
return nil
}), "vault-allow-unauthenticated", "")
flags.StringVar(&defaultVault.Token, "vault-token", "", "")
flags.StringVar(&defaultVault.Addr, "vault-address", "", "")
flags.StringVar(&defaultVault.Namespace, "vault-namespace", "", "")
flags.StringVar(&defaultVault.Role, "vault-create-from-role", "", "")
flags.StringVar(&defaultVault.TLSCaFile, "vault-ca-file", "", "")
flags.StringVar(&defaultVault.TLSCaPath, "vault-ca-path", "", "")
flags.StringVar(&defaultVault.TLSCertFile, "vault-cert-file", "", "")
flags.StringVar(&defaultVault.TLSKeyFile, "vault-key-file", "", "")
flags.Var((flaghelper.FuncBoolVar)(func(b bool) error {
defaultVault.TLSSkipVerify = &b
return nil
}), "vault-tls-skip-verify", "")
flags.StringVar(&defaultVault.TLSServerName, "vault-tls-server-name", "", "")
// ACL options
flags.BoolVar(&cmdConfig.ACL.Enabled, "acl-enabled", false, "")
flags.StringVar(&cmdConfig.ACL.ReplicationToken, "acl-replication-token", "", "")
if err := flags.Parse(c.args); err != nil {
return nil
}
// Split the servers.
if servers != "" {
cmdConfig.Client.Servers = strings.Split(servers, ",")
}
// Parse the meta flags.
metaLength := len(meta)
if metaLength != 0 {
cmdConfig.Client.Meta = make(map[string]string, metaLength)
for _, kv := range meta {
parts := strings.SplitN(kv, "=", 2)
if len(parts) != 2 {
c.Ui.Error(fmt.Sprintf("Error parsing Client.Meta value: %v", kv))
return nil
}
cmdConfig.Client.Meta[parts[0]] = parts[1]
}
}
// Load the configuration
var config *Config
devConfig := &devModeConfig{
defaultMode: devMode,
connectMode: devConnectMode,
consulMode: devConsulMode,
vaultMode: devVaultMode,
}
if devConfig.enabled() {
err := devConfig.validate()
if err != nil {
c.Ui.Error(err.Error())
return nil
}
err = devConfig.networkConfig()
if err != nil {
c.Ui.Error(err.Error())
return nil
}
config = DevConfig(devConfig)
} else {
config = DefaultConfig()
}
// Merge in the enterprise overlay
config = config.Merge(DefaultEntConfig())
for _, path := range configPath {
current, err := LoadConfig(path)
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error loading configuration from %s: %s", path, err))
return nil
}
// The user asked us to load some config here but we didn't find any,
// so we'll complain but continue.
if current == nil || reflect.DeepEqual(current, &Config{}) {
c.Ui.Warn(fmt.Sprintf("No configuration loaded from %s", path))
}
if config == nil {
config = current
} else {
config = config.Merge(current)
}
}
// Ensure the sub-structs at least exist
if config.Client == nil {
config.Client = &ClientConfig{}
}
if config.Server == nil {
config.Server = &ServerConfig{}
}
// Merge any CLI options over config file options
config = config.Merge(cmdConfig)
// Set the version info
config.Version = c.Version
// Normalize binds, ports, addresses, and advertise
if err := config.normalizeAddrs(); err != nil {
c.Ui.Error(err.Error())
return nil
}
// Read Vault configuration for the default cluster again after all
// configuration sources have been merged.
defaultVault = config.defaultVault()
// Check to see if we should read the Vault token from the environment
if defaultVault.Token == "" {
defaultVault.Token = os.Getenv("VAULT_TOKEN")
}
// Check to see if we should read the Vault namespace from the environment
if defaultVault.Namespace == "" {
defaultVault.Namespace = os.Getenv("VAULT_NAMESPACE")
}
// Default the plugin directory to be under that of the data directory if it
// isn't explicitly specified.
if config.PluginDir == "" && config.DataDir != "" {
config.PluginDir = filepath.Join(config.DataDir, "plugins")
}
// License configuration options
config.Server.LicenseEnv = os.Getenv("NOMAD_LICENSE")
if config.Server.LicensePath == "" {
config.Server.LicensePath = os.Getenv("NOMAD_LICENSE_PATH")
}
config.Server.DefaultSchedulerConfig.Canonicalize()
if !c.IsValidConfig(config, cmdConfig) {
return nil
}
return config
}
func (c *Command) IsValidConfig(config, cmdConfig *Config) bool {
// Check that the server is running in at least one mode.
if !(config.Server.Enabled || config.Client.Enabled) {
c.Ui.Error("Must specify either server, client or dev mode for the agent.")
return false
}
// Check that the region does not contain invalid characters
if strings.ContainsAny(config.Region, "\000") {
c.Ui.Error("Region contains invalid characters")
return false
}
// Check that the datacenter name does not contain invalid characters
if strings.ContainsAny(config.Datacenter, "\000*") {
c.Ui.Error("Datacenter contains invalid characters (null or '*')")
return false
}
if err := config.Telemetry.Validate(); err != nil {
c.Ui.Error(fmt.Sprintf("telemetry block invalid: %v", err))
return false
}
// Set up the TLS configuration properly if we have one.
// XXX chelseakomlo: set up a TLSConfig New method which would wrap
// constructor-type actions like this.
if config.TLSConfig != nil && !config.TLSConfig.IsEmpty() {
if err := config.TLSConfig.SetChecksum(); err != nil {
c.Ui.Error(fmt.Sprintf("WARNING: Error when parsing TLS configuration: %v", err))
}
}
if !config.DevMode && (config.TLSConfig == nil ||
!config.TLSConfig.EnableHTTP || !config.TLSConfig.EnableRPC) {
c.Ui.Error("WARNING: mTLS is not configured - Nomad is not secure without mTLS!")
}
if config.Server.EncryptKey != "" {
if _, err := config.Server.EncryptBytes(); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid encryption key: %s", err))
return false
}
keyfile := filepath.Join(config.DataDir, serfKeyring)
if _, err := os.Stat(keyfile); err == nil {
c.Ui.Warn("WARNING: keyring exists but -encrypt given, using keyring")
}
}
// Verify the paths are absolute.
dirs := map[string]string{
"data-dir": config.DataDir,
"plugin-dir": config.PluginDir,
"alloc-dir": config.Client.AllocDir,
"alloc-mounts-dir": config.Client.AllocMountsDir,
"state-dir": config.Client.StateDir,
}
for k, dir := range dirs {
if dir == "" {
continue
}
if !filepath.IsAbs(dir) {
c.Ui.Error(fmt.Sprintf("%s must be given as an absolute path: got %v", k, dir))
return false
}
}
if config.Client.Enabled {
for k := range config.Client.Meta {
if !helper.IsValidInterpVariable(k) {
c.Ui.Error(fmt.Sprintf("Invalid Client.Meta key: %v", k))
return false
}
}
}
if err := config.Server.DefaultSchedulerConfig.Validate(); err != nil {
c.Ui.Error(err.Error())
return false
}
// Validate node pool name early to prevent agent from starting but the
// client failing to register.
if pool := config.Client.NodePool; pool != "" {
if err := structs.ValidateNodePoolName(pool); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid node pool: %v", err))
return false
}
if pool == structs.NodePoolAll {
c.Ui.Error(fmt.Sprintf("Invalid node pool: node is not allowed to register in node pool %q", structs.NodePoolAll))
return false
}
}
for _, consul := range config.Consuls {
if err := structs.ValidateConsulClusterName(consul.Name); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid Consul configuration: %v", err))
}
}
for _, vault := range config.Vaults {
if err := structs.ValidateVaultClusterName(vault.Name); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid Vault configuration: %v", err))
}
}
for _, volumeConfig := range config.Client.HostVolumes {
if volumeConfig.Path == "" {
c.Ui.Error("Missing path in host_volume config")
return false
}
}
if config.Client.MinDynamicPort < 0 || config.Client.MinDynamicPort > structs.MaxValidPort {
c.Ui.Error(fmt.Sprintf("Invalid dynamic port range: min_dynamic_port=%d", config.Client.MinDynamicPort))
return false
}
if config.Client.MaxDynamicPort < 0 || config.Client.MaxDynamicPort > structs.MaxValidPort {
c.Ui.Error(fmt.Sprintf("Invalid dynamic port range: max_dynamic_port=%d", config.Client.MaxDynamicPort))
return false
}
if config.Client.MinDynamicPort > config.Client.MaxDynamicPort {
c.Ui.Error(fmt.Sprintf("Invalid dynamic port range: min_dynamic_port=%d and max_dynamic_port=%d", config.Client.MinDynamicPort, config.Client.MaxDynamicPort))
return false
}
if config.Client.Reserved == nil {
// Coding error; should always be set by DefaultConfig()
c.Ui.Error("client.reserved must be initialized. Please report a bug.")
return false
}
if ports := config.Client.Reserved.ReservedPorts; ports != "" {
if _, err := structs.ParsePortRanges(ports); err != nil {
c.Ui.Error(fmt.Sprintf("reserved.reserved_ports %q invalid: %v", ports, err))
return false
}
}
for _, hn := range config.Client.HostNetworks {
// Ensure port range is valid
if _, err := structs.ParsePortRanges(hn.ReservedPorts); err != nil {
c.Ui.Error(fmt.Sprintf("host_network[%q].reserved_ports %q invalid: %v",
hn.Name, hn.ReservedPorts, err))
return false
}
}
if err := config.Client.Artifact.Validate(); err != nil {
c.Ui.Error(fmt.Sprintf("client.artifact block invalid: %v", err))
return false
}
if err := config.Client.PreferredAddressFamily.Validate(); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid preferred-address-family value: %s (valid values: %s, %s)",
config.Client.PreferredAddressFamily,
structs.NodeNetworkAF_IPv4, structs.NodeNetworkAF_IPv6),
)
return false
}
if !config.DevMode {
// Ensure that we have the directories we need to run.
if config.Server.Enabled && config.DataDir == "" {
c.Ui.Error(`Must specify "data_dir" config option or "data-dir" CLI flag`)
return false
}
// The config is valid if the top-level data-dir is set or if both
// alloc-dir and state-dir are set.
if config.Client.Enabled && config.DataDir == "" {
missing := config.Client.AllocDir == "" ||
config.Client.AllocMountsDir == "" ||
config.Client.StateDir == "" ||
config.PluginDir == ""
if missing {
c.Ui.Error("Must specify the state, alloc-dir, alloc-mounts-dir and plugin-dir if data-dir is omitted.")
return false
}
}
// Check the bootstrap flags
if !config.Server.Enabled && cmdConfig.Server.BootstrapExpect > 0 {
// report an error if BootstrapExpect is set in CLI but server is disabled
c.Ui.Error("Bootstrap requires server mode to be enabled")
return false
}
if config.Server.Enabled && config.Server.BootstrapExpect == 1 {
c.Ui.Error("WARNING: Bootstrap mode enabled! Potentially unsafe operation.")
}
if config.Server.Enabled && config.Server.BootstrapExpect%2 == 0 {
c.Ui.Error("WARNING: Number of bootstrap servers should ideally be set to an odd number.")
}
// Check OIDC Issuer if set
if config.Server.Enabled && config.Server.OIDCIssuer != "" {
issuerURL, err := url.Parse(config.Server.OIDCIssuer)
if err != nil {
c.Ui.Error(fmt.Sprintf(`Error using server.oidc_issuer = "%s" as a base URL: %s`, config.Server.OIDCIssuer, err))
return false
}
if issuerURL.Scheme != "https" {
c.Ui.Warn(fmt.Sprintf(`server.oidc_issuer = "%s" is not using https. Many OIDC implementations require https.`, config.Server.OIDCIssuer))
}
}
}
// ProtocolVersion has never been used. Warn if it is set as someone
// has probably made a mistake.
if config.Server.ProtocolVersion != 0 {
c.Ui.Warn("Please remove deprecated protocol_version field from config.")
}
return true
}
// SetupLoggers is used to set up the logGate, and our logOutput
func SetupLoggers(ui cli.Ui, config *Config) (*logutils.LevelFilter, *gatedwriter.Writer, io.Writer) {
// Setup logging. First create the gated log writer, which will
// store logs until we're ready to show them. Then create the level
// filter, filtering logs of the specified level.
logGate := &gatedwriter.Writer{
Writer: &cli.UiWriter{Ui: ui},
}
logFilter := LevelFilter()
logFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.LogLevel))
logFilter.Writer = logGate
if !ValidateLevelFilter(logFilter.MinLevel, logFilter) {
ui.Error(fmt.Sprintf(
"Invalid log level: %s. Valid log levels are: %v",
logFilter.MinLevel, logFilter.Levels))
return nil, nil, nil
}
// Create a log writer, and wrap a logOutput around it
writers := []io.Writer{logFilter}
logLevel := strings.ToUpper(config.LogLevel)
logLevelMap := map[string]gsyslog.Priority{
"ERROR": gsyslog.LOG_ERR,
"WARN": gsyslog.LOG_WARNING,
"INFO": gsyslog.LOG_INFO,
"DEBUG": gsyslog.LOG_DEBUG,
"TRACE": gsyslog.LOG_DEBUG,
}
if logLevel == "OFF" {
config.EnableSyslog = false
}
// Check if syslog is enabled
if config.EnableSyslog {
ui.Output(fmt.Sprintf("Config enable_syslog is `true` with log_level=%v", config.LogLevel))
l, err := gsyslog.NewLogger(logLevelMap[logLevel], config.SyslogFacility, "nomad")
if err != nil {
ui.Error(fmt.Sprintf("Syslog setup failed: %v", err))
return nil, nil, nil
}
writers = append(writers, &SyslogWrapper{l, logFilter})
}
// Check if file logging is enabled
if config.LogFile != "" {
dir, fileName := filepath.Split(config.LogFile)
// if a path is provided, but has no filename, then a default is used.
if fileName == "" {
fileName = "nomad.log"
}
// Try to enter the user specified log rotation duration first
var logRotateDuration time.Duration
if config.LogRotateDuration != "" {
duration, err := time.ParseDuration(config.LogRotateDuration)
if err != nil {
ui.Error(fmt.Sprintf("Failed to parse log rotation duration: %v", err))
return nil, nil, nil
}
logRotateDuration = duration
} else {
// Default to 24 hrs if no rotation period is specified
logRotateDuration = 24 * time.Hour
}
logFile := &logFile{
logFilter: logFilter,
fileName: fileName,
logPath: dir,
duration: logRotateDuration,
MaxBytes: config.LogRotateBytes,
MaxFiles: config.LogRotateMaxFiles,
}
writers = append(writers, logFile)
}
logOutput := io.MultiWriter(writers...)
return logFilter, logGate, logOutput
}
// setupAgent is used to start the agent and various interfaces
func (c *Command) setupAgent(config *Config, logger hclog.InterceptLogger, logOutput io.Writer, inmem *metrics.InmemSink) error {
c.Ui.Output("Starting Nomad agent...")
agent, err := NewAgent(config, logger, logOutput, inmem)
if err != nil {
// log the error as well, so it appears at the end
logger.Error("error starting agent", "error", err)
c.Ui.Error(fmt.Sprintf("Error starting agent: %s", err))
return err
}
c.agent = agent
// Setup the HTTP server
httpServers, err := NewHTTPServers(agent, config)
if err != nil {
agent.Shutdown()
c.Ui.Error(fmt.Sprintf("Error starting http server: %s", err))
return err
}
c.httpServers = httpServers
for _, vault := range config.Vaults {
if vault.Token != "" {
logger.Warn("Setting a Vault token in the agent configuration is deprecated and will be removed in Nomad 1.9. Migrate your Vault configuration to use workload identity.", "cluster", vault.Name)
}
}
// If DisableUpdateCheck is not enabled, set up update checking
// (DisableUpdateCheck is false by default)
if config.DisableUpdateCheck != nil && !*config.DisableUpdateCheck {
version := config.Version.Version
if config.Version.VersionPrerelease != "" {
version += fmt.Sprintf("-%s", config.Version.VersionPrerelease)
}
updateParams := &checkpoint.CheckParams{
Product: "nomad",
Version: version,
}
if !config.DisableAnonymousSignature {
updateParams.SignatureFile = filepath.Join(config.DataDir, "checkpoint-signature")
}
// Schedule a periodic check with expected interval of 24 hours
checkpoint.CheckInterval(updateParams, 24*time.Hour, c.checkpointResults)
// Do an immediate check within the next 30 seconds
go func() {
time.Sleep(helper.RandomStagger(30 * time.Second))
c.checkpointResults(checkpoint.Check(updateParams))
}()
}
return nil
}
// checkpointResults is used to handler periodic results from our update checker
func (c *Command) checkpointResults(results *checkpoint.CheckResponse, err error) {
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to check for updates: %v", err))
return
}
if results.Outdated {
c.Ui.Error(fmt.Sprintf("Newer Nomad version available: %s (currently running: %s)", results.CurrentVersion, c.Version.VersionNumber()))
}
for _, alert := range results.Alerts {
switch alert.Level {
case "info":
c.Ui.Info(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
default:
c.Ui.Error(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
}
}
}
func (c *Command) AutocompleteFlags() complete.Flags {
configFilePredictor := complete.PredictOr(
complete.PredictFiles("*.json"),
complete.PredictFiles("*.hcl"))
return map[string]complete.Predictor{
"-dev": complete.PredictNothing,
"-dev-connect": complete.PredictNothing,
"-server": complete.PredictNothing,
"-client": complete.PredictNothing,
"-bootstrap-expect": complete.PredictAnything,
"-encrypt": complete.PredictAnything,
"-raft-protocol": complete.PredictAnything,
"-rejoin": complete.PredictNothing,
"-join": complete.PredictAnything,
"-retry-join": complete.PredictAnything,
"-retry-max": complete.PredictAnything,
"-state-dir": complete.PredictDirs("*"),
"-alloc-dir": complete.PredictDirs("*"),
"-node-class": complete.PredictAnything,
"-node-pool": complete.PredictAnything,
"-servers": complete.PredictAnything,
"-meta": complete.PredictAnything,
"-config": configFilePredictor,
"-bind": complete.PredictAnything,
"-region": complete.PredictAnything,
"-data-dir": complete.PredictDirs("*"),
"-plugin-dir": complete.PredictDirs("*"),
"-dc": complete.PredictAnything,
"-log-level": complete.PredictAnything,
"-json-logs": complete.PredictNothing,
"-node": complete.PredictAnything,
"-consul-auth": complete.PredictAnything,
"-consul-auto-advertise": complete.PredictNothing,
"-consul-ca-file": complete.PredictAnything,
"-consul-cert-file": complete.PredictAnything,
"-consul-key-file": complete.PredictAnything,
"-consul-checks-use-advertise": complete.PredictNothing,
"-consul-client-auto-join": complete.PredictNothing,
"-consul-client-service-name": complete.PredictAnything,
"-consul-client-failures-before-critical": complete.PredictAnything,
"-consul-client-failures-before-warning": complete.PredictAnything,
"-consul-client-http-check-name": complete.PredictAnything,
"-consul-server-service-name": complete.PredictAnything,
"-consul-server-http-check-name": complete.PredictAnything,
"-consul-server-serf-check-name": complete.PredictAnything,
"-consul-server-rpc-check-name": complete.PredictAnything,
"-consul-server-auto-join": complete.PredictNothing,
"-consul-server-failures-before-critical": complete.PredictAnything,
"-consul-server-failures-before-warning": complete.PredictAnything,
"-consul-ssl": complete.PredictNothing,
"-consul-verify-ssl": complete.PredictNothing,
"-consul-address": complete.PredictAnything,
"-consul-token": complete.PredictAnything,
"-vault-enabled": complete.PredictNothing,
"-vault-allow-unauthenticated": complete.PredictNothing,
"-vault-token": complete.PredictAnything,
"-vault-address": complete.PredictAnything,
"-vault-create-from-role": complete.PredictAnything,
"-vault-ca-file": complete.PredictAnything,
"-vault-ca-path": complete.PredictAnything,
"-vault-cert-file": complete.PredictAnything,
"-vault-key-file": complete.PredictAnything,
"-vault-tls-skip-verify": complete.PredictNothing,
"-vault-tls-server-name": complete.PredictAnything,
"-acl-enabled": complete.PredictNothing,
"-acl-replication-token": complete.PredictAnything,
}
}
func (c *Command) AutocompleteArgs() complete.Predictor {
return nil
}
func (c *Command) Run(args []string) int {
c.Ui = &cli.PrefixedUi{
OutputPrefix: "==> ",
InfoPrefix: " ",
ErrorPrefix: "==> ",
Ui: c.Ui,
}
// Parse our configs
c.args = args
config := c.readConfig()
if config == nil {
return 1
}
// reset UI to prevent prefixed json output
if config.LogJson {
c.Ui = &cli.BasicUi{
Reader: os.Stdin,
Writer: os.Stdout,
ErrorWriter: os.Stderr,
}
}
// Setup the log outputs
logFilter, logGate, logOutput := SetupLoggers(c.Ui, config)
c.logFilter = logFilter
c.logOutput = logOutput
if logGate == nil {
return 1
}
// Create logger
logger := hclog.NewInterceptLogger(&hclog.LoggerOptions{
Name: "agent",
Level: hclog.LevelFromString(config.LogLevel),
Output: logOutput,
JSONFormat: config.LogJson,
IncludeLocation: config.LogIncludeLocation,
})
// Wrap log messages emitted with the 'log' package.
// These usually come from external dependencies.
log.SetOutput(logger.StandardWriter(&hclog.StandardLoggerOptions{
InferLevels: true,
InferLevelsWithTimestamp: true,
}))
log.SetPrefix("")
log.SetFlags(0)
// Swap out UI implementation if json logging is enabled
if config.LogJson {
c.Ui = &logging.HcLogUI{Log: logger}
// Don't buffer json logs because they aren't reordered anyway.
logGate.Flush()
}
// Log config files
if len(config.Files) > 0 {
c.Ui.Output(fmt.Sprintf("Loaded configuration from %s", strings.Join(config.Files, ", ")))
} else {
c.Ui.Output("No configuration files loaded")
}
// Initialize the telemetry
inmem, err := c.setupTelemetry(config)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing telemetry: %s", err))
return 1
}
// Create the agent
if err := c.setupAgent(config, logger, logOutput, inmem); err != nil {
logGate.Flush()
return 1
}
defer func() {
c.agent.Shutdown()
// Shutdown the http server at the end, to ease debugging if
// the agent takes long to shutdown
if len(c.httpServers) > 0 {
for _, srv := range c.httpServers {
srv.Shutdown()
}
}
}()
// Join startup nodes if specified
if err := c.startupJoin(config); err != nil {
c.Ui.Error(err.Error())
return 1
}
// Compile agent information for output later
info := make(map[string]string)
info["version"] = config.Version.VersionNumber()
info["client"] = strconv.FormatBool(config.Client.Enabled)
info["log level"] = config.LogLevel
info["server"] = strconv.FormatBool(config.Server.Enabled)
info["region"] = fmt.Sprintf("%s (DC: %s)", config.Region, config.Datacenter)
info["bind addrs"] = c.getBindAddrSynopsis()
info["advertise addrs"] = c.getAdvertiseAddrSynopsis()
if config.Server.Enabled {
serverConfig, err := c.agent.serverConfig()
if err == nil {
info["node id"] = serverConfig.NodeID
}
}
// Sort the keys for output
infoKeys := make([]string, 0, len(info))
for key := range info {
infoKeys = append(infoKeys, key)
}
sort.Strings(infoKeys)
// Agent configuration output
padding := 18
c.Ui.Output("Nomad agent configuration:\n")
for _, k := range infoKeys {
c.Ui.Info(fmt.Sprintf(
"%s%s: %s",
strings.Repeat(" ", padding-len(k)),
strings.Title(k),
info[k]))
}
c.Ui.Output("")
// Output the header that the server has started
c.Ui.Output("Nomad agent started! Log data will stream in below:\n")
// Enable log streaming
logGate.Flush()
// Start retry join process
if err := c.handleRetryJoin(config); err != nil {
c.Ui.Error(err.Error())
return 1
}
// Wait for exit
return c.handleSignals()
}
// handleRetryJoin is used to start retry joining if it is configured.
func (c *Command) handleRetryJoin(config *Config) error {
c.retryJoinErrCh = make(chan struct{})
if config.Server.Enabled && len(config.Server.RetryJoin) != 0 {
joiner := retryJoiner{
autoDiscover: autoDiscover{goDiscover: &discover.Discover{}, netAddrs: &netAddrs{}},
errCh: c.retryJoinErrCh,
logger: c.agent.logger.Named("joiner"),
serverJoin: c.agent.server.Join,
serverEnabled: true,
}
if err := joiner.Validate(config); err != nil {
return err
}
// Remove the duplicate fields
if len(config.Server.RetryJoin) != 0 {
config.Server.ServerJoin.RetryJoin = config.Server.RetryJoin
config.Server.RetryJoin = nil
}
if config.Server.RetryMaxAttempts != 0 {
config.Server.ServerJoin.RetryMaxAttempts = config.Server.RetryMaxAttempts
config.Server.RetryMaxAttempts = 0
}
if config.Server.RetryInterval != 0 {
config.Server.ServerJoin.RetryInterval = config.Server.RetryInterval
config.Server.RetryInterval = 0
}
c.agent.logger.Warn("using deprecated retry_join fields. Upgrade configuration to use server_join")
}
if config.Server.Enabled &&
config.Server.ServerJoin != nil &&
len(config.Server.ServerJoin.RetryJoin) != 0 {
joiner := retryJoiner{
autoDiscover: autoDiscover{goDiscover: &discover.Discover{}, netAddrs: &netAddrs{}},
errCh: c.retryJoinErrCh,
logger: c.agent.logger.Named("joiner"),
serverJoin: c.agent.server.Join,
serverEnabled: true,
}
if err := joiner.Validate(config); err != nil {
return err
}
go joiner.RetryJoin(config.Server.ServerJoin)
}
if config.Client.Enabled &&
config.Client.ServerJoin != nil &&
len(config.Client.ServerJoin.RetryJoin) != 0 {
joiner := retryJoiner{
autoDiscover: autoDiscover{goDiscover: &discover.Discover{}, netAddrs: &netAddrs{}},
errCh: c.retryJoinErrCh,
logger: c.agent.logger.Named("joiner"),
clientJoin: c.agent.client.SetServers,
clientEnabled: true,
}
if err := joiner.Validate(config); err != nil {
return err
}
go joiner.RetryJoin(config.Client.ServerJoin)
}