/
builder.go
2866 lines (2539 loc) · 103 KB
/
builder.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 config
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/armon/go-metrics/prometheus"
"github.com/hashicorp/go-bexpr"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-sockaddr/template"
"github.com/hashicorp/memberlist"
"golang.org/x/time/rate"
"github.com/hashicorp/consul/agent/cache"
"github.com/hashicorp/consul/agent/checks"
"github.com/hashicorp/consul/agent/connect/ca"
"github.com/hashicorp/consul/agent/consul"
"github.com/hashicorp/consul/agent/consul/authmethod/ssoauth"
consulrate "github.com/hashicorp/consul/agent/consul/rate"
hcpconfig "github.com/hashicorp/consul/agent/hcp/config"
"github.com/hashicorp/consul/agent/rpc/middleware"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/agent/token"
"github.com/hashicorp/consul/internal/dnsutil"
"github.com/hashicorp/consul/ipaddr"
"github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/lib/stringslice"
libtempl "github.com/hashicorp/consul/lib/template"
"github.com/hashicorp/consul/logging"
"github.com/hashicorp/consul/tlsutil"
"github.com/hashicorp/consul/types"
)
type FlagValuesTarget = decodeTarget
// LoadOpts used by Load to construct and validate a RuntimeConfig.
type LoadOpts struct {
// FlagValues contains the command line arguments that can also be set
// in a config file.
FlagValues FlagValuesTarget
// ConfigFiles is a slice of paths to config files and directories that will
// be loaded.
//
// It is an error for any config files to have an extension other than `hcl`
// or `json`, unless ConfigFormat is also set. However, non-HCL/JSON files in
// a config directory are merely skipped, with a warning.
ConfigFiles []string
// ConfigFormat forces all config files to be interpreted as this format
// independent of their extension. Value may be `hcl` or `json`.
ConfigFormat string
// DevMode indicates whether the agent should be started in development
// mode. This cannot be configured in a config file.
DevMode *bool
// HCL is a slice of config data in hcl format. Each one will be loaded as
// if it were the source of a config file. Values from HCL will override
// values from ConfigFiles and FlagValues.
HCL []string
// DefaultConfig is an optional source that is applied after other defaults
// but before ConfigFiles and all other user specified config.
DefaultConfig Source
// Overrides are optional config sources that are applied as the very last
// config source so they can override any previous values.
Overrides []Source
// hostname is a shim for testing, allowing tests to specify a replacement
// for os.Hostname.
hostname func() (string, error)
// getPrivateIPv4 and getPublicIPv6 are shims for testing, allowing tests to
// specify a replacement for ipaddr.GetPrivateIPv4 and ipaddr.GetPublicIPv6.
getPrivateIPv4 func() ([]*net.IPAddr, error)
getPublicIPv6 func() ([]*net.IPAddr, error)
// sources is a shim for testing. Many test cases used explicit sources instead
// paths to config files. This shim allows us to preserve those test cases
// while using Load as the entrypoint.
sources []Source
}
// Load will build the configuration including the config source injected
// after all other defaults but before any user supplied configuration and the overrides
// source injected as the final source in the configuration parsing chain.
//
// The caller is responsible for handling any warnings in LoadResult.Warnings.
func Load(opts LoadOpts) (LoadResult, error) {
r := LoadResult{}
b, err := newBuilder(opts)
if err != nil {
return r, err
}
cfg, err := b.build()
if err != nil {
return r, err
}
if err := b.validate(cfg); err != nil {
return r, err
}
watcherFiles := stringslice.CloneStringSlice(opts.ConfigFiles)
return LoadResult{RuntimeConfig: &cfg, Warnings: b.Warnings, WatchedFiles: watcherFiles}, nil
}
// LoadResult is the result returned from Load. The caller is responsible for
// handling any warnings.
type LoadResult struct {
RuntimeConfig *RuntimeConfig
Warnings []string
WatchedFiles []string
}
// builder constructs and validates a runtime configuration from multiple
// configuration sources.
//
// The sources are merged in the following order:
//
// - default configuration
// - config files in alphabetical order
// - command line arguments
// - overrides
//
// The config sources are merged sequentially and later values overwrite
// previously set values. Slice values are merged by concatenating the two slices.
// Map values are merged by over-laying the later maps on top of earlier ones.
type builder struct {
opts LoadOpts
// Head, Sources, and Tail are used to manage the order of the
// config sources, as described in the comments above.
Head []Source
Sources []Source
Tail []Source
// Warnings contains the warnings encountered when
// parsing the configuration.
Warnings []string
// err contains the first error that occurred during
// building the runtime configuration.
err error
}
// newBuilder returns a new configuration Builder from the LoadOpts.
func newBuilder(opts LoadOpts) (*builder, error) {
configFormat := opts.ConfigFormat
if configFormat != "" && configFormat != "json" && configFormat != "hcl" {
return nil, fmt.Errorf("config: -config-format must be either 'hcl' or 'json'")
}
b := &builder{
opts: opts,
Head: []Source{DefaultSource(), DefaultEnterpriseSource()},
}
if boolVal(opts.DevMode) {
b.Head = append(b.Head, DevSource())
}
cfg, warns := applyDeprecatedFlags(&opts.FlagValues)
b.Warnings = append(b.Warnings, warns...)
// Since the merge logic is to overwrite all fields with later
// values except slices which are merged by appending later values
// we need to merge all slice values defined in flags before we
// merge the config files since the flag values for slices are
// otherwise appended instead of prepended.
slices, values := splitSlicesAndValues(cfg)
b.Head = append(b.Head, LiteralSource{Name: "flags.slices", Config: slices})
if opts.DefaultConfig != nil {
b.Head = append(b.Head, opts.DefaultConfig)
}
b.Sources = opts.sources
for _, path := range opts.ConfigFiles {
sources, err := b.sourcesFromPath(path, opts.ConfigFormat)
if err != nil {
return nil, err
}
b.Sources = append(b.Sources, sources...)
}
b.Tail = append(b.Tail, LiteralSource{Name: "flags.values", Config: values})
for i, s := range opts.HCL {
b.Tail = append(b.Tail, FileSource{
Name: fmt.Sprintf("flags-%d.hcl", i),
Format: "hcl",
Data: s,
})
}
b.Tail = append(b.Tail, NonUserSource(), DefaultConsulSource(), OverrideEnterpriseSource(), defaultVersionSource())
if boolVal(opts.DevMode) {
b.Tail = append(b.Tail, DevConsulSource())
}
if len(opts.Overrides) != 0 {
b.Tail = append(b.Tail, opts.Overrides...)
}
return b, nil
}
// sourcesFromPath reads a single config file or all files in a directory (but
// not its sub-directories) and returns Sources created from the
// files.
func (b *builder) sourcesFromPath(path string, format string) ([]Source, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("config: Open failed on %s. %s", path, err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, fmt.Errorf("config: Stat failed on %s. %s", path, err)
}
if !fi.IsDir() {
if !shouldParseFile(path, format) {
return nil, fmt.Errorf("file %v has unknown extension; must be .hcl or .json, or config format must be set", path)
}
src, err := newSourceFromFile(path, format)
if err != nil {
return nil, err
}
return []Source{src}, nil
}
fis, err := f.Readdir(-1)
if err != nil {
return nil, fmt.Errorf("config: Readdir failed on %s. %s", path, err)
}
// sort files by name
sort.Sort(byName(fis))
var sources []Source
for _, fi := range fis {
fp := filepath.Join(path, fi.Name())
// check for a symlink and resolve the path
if fi.Mode()&os.ModeSymlink > 0 {
var err error
fp, err = filepath.EvalSymlinks(fp)
if err != nil {
return nil, err
}
fi, err = os.Stat(fp)
if err != nil {
return nil, err
}
}
// do not recurse into sub dirs
if fi.IsDir() {
continue
}
if !shouldParseFile(fp, format) {
b.warn("skipping file %v, extension must be .hcl or .json, or config format must be set", fp)
continue
}
src, err := newSourceFromFile(fp, format)
if err != nil {
return nil, err
}
sources = append(sources, src)
}
return sources, nil
}
// newSourceFromFile creates a Source from the contents of the file at path.
func newSourceFromFile(path string, format string) (Source, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: failed to read %s: %s", path, err)
}
if format == "" {
format = formatFromFileExtension(path)
}
return FileSource{Name: path, Data: string(data), Format: format}, nil
}
// shouldParse file determines whether the file to be read is of a supported extension
func shouldParseFile(path string, configFormat string) bool {
srcFormat := formatFromFileExtension(path)
return configFormat != "" || srcFormat == "hcl" || srcFormat == "json"
}
func formatFromFileExtension(name string) string {
switch {
case strings.HasSuffix(name, ".json"):
return "json"
case strings.HasSuffix(name, ".hcl"):
return "hcl"
default:
return ""
}
}
type byName []os.FileInfo
func (a byName) Len() int { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
// build constructs the runtime configuration from the config sources
// and the command line flags. The config sources are processed in the
// order they were added with the flags being processed last to give
// precedence over the other sources. If the error is nil then
// warnings can still contain deprecation or format warnings that should
// be presented to the user.
func (b *builder) build() (rt RuntimeConfig, err error) {
srcs := make([]Source, 0, len(b.Head)+len(b.Sources)+len(b.Tail))
srcs = append(srcs, b.Head...)
srcs = append(srcs, b.Sources...)
srcs = append(srcs, b.Tail...)
// parse the config sources into a configuration
var c Config
for _, s := range srcs {
c2, md, err := s.Parse()
switch {
case err == ErrNoData:
continue
case err != nil:
return RuntimeConfig{}, fmt.Errorf("failed to parse %v: %w", s.Source(), err)
}
var unusedErr error
for _, k := range md.Unused {
switch {
case k == "acl_enforce_version_8":
b.warn("config key %q is deprecated and should be removed", k)
case strings.HasPrefix(k, "audit.sink[") && strings.HasSuffix(k, "].name"):
b.warn("config key audit.sink[].name is deprecated and should be removed")
default:
unusedErr = multierror.Append(unusedErr, fmt.Errorf("invalid config key %s", k))
}
}
if unusedErr != nil {
return RuntimeConfig{}, fmt.Errorf("failed to parse %v: %s", s.Source(), unusedErr)
}
for _, err := range validateEnterpriseConfigKeys(&c2) {
b.warn("%s", err)
}
b.Warnings = append(b.Warnings, md.Warnings...)
// if we have a single 'check' or 'service' we need to add them to the
// list of checks and services first since we cannot merge them
// generically and later values would clobber earlier ones.
// TODO: move to applyDeprecatedConfig
if c2.Check != nil {
c2.Checks = append(c2.Checks, *c2.Check)
c2.Check = nil
}
if c2.Service != nil {
c2.Services = append(c2.Services, *c2.Service)
c2.Service = nil
}
c = Merge(c, c2)
}
// ----------------------------------------------------------------
// process/merge some complex values
//
dnsServiceTTL := map[string]time.Duration{}
for k, v := range c.DNS.ServiceTTL {
dnsServiceTTL[k] = b.durationVal(fmt.Sprintf("dns_config.service_ttl[%q]", k), &v)
}
soa := RuntimeSOAConfig{Refresh: 3600, Retry: 600, Expire: 86400, Minttl: 0}
if c.DNS.SOA != nil {
if c.DNS.SOA.Expire != nil {
soa.Expire = *c.DNS.SOA.Expire
}
if c.DNS.SOA.Minttl != nil {
soa.Minttl = *c.DNS.SOA.Minttl
}
if c.DNS.SOA.Refresh != nil {
soa.Refresh = *c.DNS.SOA.Refresh
}
if c.DNS.SOA.Retry != nil {
soa.Retry = *c.DNS.SOA.Retry
}
}
leaveOnTerm := !boolVal(c.ServerMode)
if c.LeaveOnTerm != nil {
leaveOnTerm = boolVal(c.LeaveOnTerm)
}
skipLeaveOnInt := boolVal(c.ServerMode)
if c.SkipLeaveOnInt != nil {
skipLeaveOnInt = boolVal(c.SkipLeaveOnInt)
}
// ----------------------------------------------------------------
// checks and services
//
var checks []*structs.CheckDefinition
if c.Check != nil {
checks = append(checks, b.checkVal(c.Check))
}
for _, check := range c.Checks {
checks = append(checks, b.checkVal(&check))
}
var services []*structs.ServiceDefinition
for _, service := range c.Services {
services = append(services, b.serviceVal(&service))
}
if c.Service != nil {
services = append(services, b.serviceVal(c.Service))
}
// ----------------------------------------------------------------
// addresses
//
// determine port values and replace values <= 0 and > 65535 with -1
dnsPort := b.portVal("ports.dns", c.Ports.DNS)
httpPort := b.portVal("ports.http", c.Ports.HTTP)
httpsPort := b.portVal("ports.https", c.Ports.HTTPS)
serverPort := b.portVal("ports.server", c.Ports.Server)
grpcPort := b.portVal("ports.grpc", c.Ports.GRPC)
grpcTlsPort := b.portVal("ports.grpc_tls", c.Ports.GRPCTLS)
// default gRPC TLS port for servers is 8503
if c.Ports.GRPCTLS == nil && boolVal(c.ServerMode) {
grpcTlsPort = 8503
}
serfPortLAN := b.portVal("ports.serf_lan", c.Ports.SerfLAN)
serfPortWAN := b.portVal("ports.serf_wan", c.Ports.SerfWAN)
proxyMinPort := b.portVal("ports.proxy_min_port", c.Ports.ProxyMinPort)
proxyMaxPort := b.portVal("ports.proxy_max_port", c.Ports.ProxyMaxPort)
sidecarMinPort := b.portVal("ports.sidecar_min_port", c.Ports.SidecarMinPort)
sidecarMaxPort := b.portVal("ports.sidecar_max_port", c.Ports.SidecarMaxPort)
exposeMinPort := b.portVal("ports.expose_min_port", c.Ports.ExposeMinPort)
exposeMaxPort := b.portVal("ports.expose_max_port", c.Ports.ExposeMaxPort)
if serverPort <= 0 {
return RuntimeConfig{}, fmt.Errorf(
"server-port must be greater than zero")
}
if serfPortLAN <= 0 {
return RuntimeConfig{}, fmt.Errorf(
"serf-lan-port must be greater than zero")
}
if proxyMaxPort < proxyMinPort {
return RuntimeConfig{}, fmt.Errorf(
"proxy_min_port must be less than proxy_max_port. To disable, set both to zero.")
}
if sidecarMaxPort < sidecarMinPort {
return RuntimeConfig{}, fmt.Errorf(
"sidecar_min_port must be less than sidecar_max_port. To disable, set both to zero.")
}
if exposeMaxPort < exposeMinPort {
return RuntimeConfig{}, fmt.Errorf(
"expose_min_port must be less than expose_max_port. To disable, set both to zero.")
}
// determine the default bind and advertise address
//
// First check whether the user provided an ANY address or whether
// the expanded template results in an ANY address. In that case we
// derive an advertise address from the current network
// configuration since we can listen on an ANY address for incoming
// traffic but cannot advertise it as the address on which the
// server can be reached.
bindAddrs := b.expandAddrs("bind_addr", c.BindAddr)
if len(bindAddrs) == 0 {
return RuntimeConfig{}, fmt.Errorf("bind_addr cannot be empty")
}
if len(bindAddrs) > 1 {
return RuntimeConfig{}, fmt.Errorf("bind_addr cannot contain multiple addresses. Use 'addresses.{dns,http,https}' instead.")
}
if isUnixAddr(bindAddrs[0]) {
return RuntimeConfig{}, fmt.Errorf("bind_addr cannot be a unix socket")
}
if !isIPAddr(bindAddrs[0]) {
return RuntimeConfig{}, fmt.Errorf("bind_addr must be an ip address")
}
if ipaddr.IsAny(stringVal(c.AdvertiseAddrLAN)) {
return RuntimeConfig{}, fmt.Errorf("Advertise address cannot be 0.0.0.0, :: or [::]")
}
if ipaddr.IsAny(stringVal(c.AdvertiseAddrWAN)) {
return RuntimeConfig{}, fmt.Errorf("Advertise WAN address cannot be 0.0.0.0, :: or [::]")
}
bindAddr := bindAddrs[0].(*net.IPAddr)
advertiseAddr := makeIPAddr(b.expandFirstIP("advertise_addr", c.AdvertiseAddrLAN), bindAddr)
if ipaddr.IsAny(advertiseAddr) {
addrtyp, detect := advertiseAddrFunc(b.opts, advertiseAddr)
advertiseAddrs, err := detect()
if err != nil {
return RuntimeConfig{}, fmt.Errorf("Error detecting %s address: %s", addrtyp, err)
}
if len(advertiseAddrs) == 0 {
return RuntimeConfig{}, fmt.Errorf("No %s address found", addrtyp)
}
if len(advertiseAddrs) > 1 {
return RuntimeConfig{}, fmt.Errorf("Multiple %s addresses found. Please configure one with 'bind' and/or 'advertise'.", addrtyp)
}
advertiseAddr = advertiseAddrs[0]
}
// derive other bind addresses from the bindAddr
rpcBindAddr := b.makeTCPAddr(bindAddr, nil, serverPort)
serfBindAddrLAN := b.makeTCPAddr(b.expandFirstIP("serf_lan", c.SerfBindAddrLAN), bindAddr, serfPortLAN)
// Only initialize serf WAN bind address when its enabled
var serfBindAddrWAN *net.TCPAddr
if serfPortWAN >= 0 {
serfBindAddrWAN = b.makeTCPAddr(b.expandFirstIP("serf_wan", c.SerfBindAddrWAN), bindAddr, serfPortWAN)
}
// derive other advertise addresses from the advertise address
advertiseAddrLAN := makeIPAddr(b.expandFirstIP("advertise_addr", c.AdvertiseAddrLAN), advertiseAddr)
advertiseAddrIsV6 := advertiseAddr.IP.To4() == nil
var advertiseAddrV4, advertiseAddrV6 *net.IPAddr
if !advertiseAddrIsV6 {
advertiseAddrV4 = advertiseAddr
} else {
advertiseAddrV6 = advertiseAddr
}
advertiseAddrLANIPv4 := makeIPAddr(b.expandFirstIP("advertise_addr_ipv4", c.AdvertiseAddrLANIPv4), advertiseAddrV4)
if advertiseAddrLANIPv4 != nil && advertiseAddrLANIPv4.IP.To4() == nil {
return RuntimeConfig{}, fmt.Errorf("advertise_addr_ipv4 must be an ipv4 address")
}
advertiseAddrLANIPv6 := makeIPAddr(b.expandFirstIP("advertise_addr_ipv6", c.AdvertiseAddrLANIPv6), advertiseAddrV6)
if advertiseAddrLANIPv6 != nil && advertiseAddrLANIPv6.IP.To4() != nil {
return RuntimeConfig{}, fmt.Errorf("advertise_addr_ipv6 must be an ipv6 address")
}
advertiseAddrWAN := makeIPAddr(b.expandFirstIP("advertise_addr_wan", c.AdvertiseAddrWAN), advertiseAddrLAN)
advertiseAddrWANIsV6 := advertiseAddrWAN.IP.To4() == nil
var advertiseAddrWANv4, advertiseAddrWANv6 *net.IPAddr
if !advertiseAddrWANIsV6 {
advertiseAddrWANv4 = advertiseAddrWAN
} else {
advertiseAddrWANv6 = advertiseAddrWAN
}
advertiseAddrWANIPv4 := makeIPAddr(b.expandFirstIP("advertise_addr_wan_ipv4", c.AdvertiseAddrWANIPv4), advertiseAddrWANv4)
if advertiseAddrWANIPv4 != nil && advertiseAddrWANIPv4.IP.To4() == nil {
return RuntimeConfig{}, fmt.Errorf("advertise_addr_wan_ipv4 must be an ipv4 address")
}
advertiseAddrWANIPv6 := makeIPAddr(b.expandFirstIP("advertise_addr_wan_ipv6", c.AdvertiseAddrWANIPv6), advertiseAddrWANv6)
if advertiseAddrWANIPv6 != nil && advertiseAddrWANIPv6.IP.To4() != nil {
return RuntimeConfig{}, fmt.Errorf("advertise_addr_wan_ipv6 must be an ipv6 address")
}
rpcAdvertiseAddr := &net.TCPAddr{IP: advertiseAddrLAN.IP, Port: serverPort}
serfAdvertiseAddrLAN := &net.TCPAddr{IP: advertiseAddrLAN.IP, Port: serfPortLAN}
// Only initialize serf WAN advertise address when its enabled
var serfAdvertiseAddrWAN *net.TCPAddr
if serfPortWAN >= 0 {
serfAdvertiseAddrWAN = &net.TCPAddr{IP: advertiseAddrWAN.IP, Port: serfPortWAN}
}
// determine client addresses
clientAddrs := b.expandIPs("client_addr", c.ClientAddr)
if len(clientAddrs) == 0 {
b.warn("client_addr is empty, client services (DNS, HTTP, HTTPS, GRPC) will not be listening for connections")
}
dnsAddrs := b.makeAddrs(b.expandAddrs("addresses.dns", c.Addresses.DNS), clientAddrs, dnsPort)
httpAddrs := b.makeAddrs(b.expandAddrs("addresses.http", c.Addresses.HTTP), clientAddrs, httpPort)
httpsAddrs := b.makeAddrs(b.expandAddrs("addresses.https", c.Addresses.HTTPS), clientAddrs, httpsPort)
grpcAddrs := b.makeAddrs(b.expandAddrs("addresses.grpc", c.Addresses.GRPC), clientAddrs, grpcPort)
grpcTlsAddrs := b.makeAddrs(b.expandAddrs("addresses.grpc_tls", c.Addresses.GRPCTLS), clientAddrs, grpcTlsPort)
for _, a := range dnsAddrs {
if x, ok := a.(*net.TCPAddr); ok {
dnsAddrs = append(dnsAddrs, &net.UDPAddr{IP: x.IP, Port: x.Port})
}
}
// expand dns recursors
uniq := map[string]bool{}
dnsRecursors := []string{}
for _, r := range c.DNSRecursors {
x, err := template.Parse(r)
if err != nil {
return RuntimeConfig{}, fmt.Errorf("Invalid DNS recursor template %q: %s", r, err)
}
for _, addr := range strings.Fields(x) {
if strings.HasPrefix(addr, "unix://") {
return RuntimeConfig{}, fmt.Errorf("DNS Recursors cannot be unix sockets: %s", addr)
}
if uniq[addr] {
continue
}
uniq[addr] = true
dnsRecursors = append(dnsRecursors, addr)
}
}
datacenter := strings.ToLower(stringVal(c.Datacenter))
altDomain := stringVal(c.DNSAltDomain)
// Create the default set of tagged addresses.
if c.TaggedAddresses == nil {
c.TaggedAddresses = make(map[string]string)
}
c.TaggedAddresses[structs.TaggedAddressLAN] = advertiseAddrLAN.IP.String()
if advertiseAddrLANIPv4 != nil {
c.TaggedAddresses[structs.TaggedAddressLANIPv4] = advertiseAddrLANIPv4.IP.String()
}
if advertiseAddrLANIPv6 != nil {
c.TaggedAddresses[structs.TaggedAddressLANIPv6] = advertiseAddrLANIPv6.IP.String()
}
c.TaggedAddresses[structs.TaggedAddressWAN] = advertiseAddrWAN.IP.String()
if advertiseAddrWANIPv4 != nil {
c.TaggedAddresses[structs.TaggedAddressWANIPv4] = advertiseAddrWANIPv4.IP.String()
}
if advertiseAddrWANIPv6 != nil {
c.TaggedAddresses[structs.TaggedAddressWANIPv6] = advertiseAddrWANIPv6.IP.String()
}
// segments
var segments []structs.NetworkSegment
for _, s := range c.Segments {
name := stringVal(s.Name)
port := b.portVal(fmt.Sprintf("segments[%s].port", name), s.Port)
if port <= 0 {
return RuntimeConfig{}, fmt.Errorf("Port for segment %q cannot be <= 0", name)
}
bind := b.makeTCPAddr(
b.expandFirstIP(fmt.Sprintf("segments[%s].bind", name), s.Bind),
bindAddr,
port,
)
advertise := b.makeTCPAddr(
b.expandFirstIP(fmt.Sprintf("segments[%s].advertise", name), s.Advertise),
advertiseAddrLAN,
port,
)
segments = append(segments, structs.NetworkSegment{
Name: name,
Bind: bind,
Advertise: advertise,
RPCListener: boolVal(s.RPCListener),
})
}
// Parse the metric filters
telemetryAllowedPrefixes, telemetryBlockedPrefixes := b.parsePrefixFilter(&c.Telemetry)
// raft performance scaling
performanceRaftMultiplier := intVal(c.Performance.RaftMultiplier)
if performanceRaftMultiplier < 1 || uint(performanceRaftMultiplier) > consul.MaxRaftMultiplier {
return RuntimeConfig{}, fmt.Errorf("performance.raft_multiplier cannot be %d. Must be between 1 and %d", performanceRaftMultiplier, consul.MaxRaftMultiplier)
}
consulRaftElectionTimeout := b.durationVal("consul.raft.election_timeout", c.Consul.Raft.ElectionTimeout) * time.Duration(performanceRaftMultiplier)
consulRaftHeartbeatTimeout := b.durationVal("consul.raft.heartbeat_timeout", c.Consul.Raft.HeartbeatTimeout) * time.Duration(performanceRaftMultiplier)
consulRaftLeaderLeaseTimeout := b.durationVal("consul.raft.leader_lease_timeout", c.Consul.Raft.LeaderLeaseTimeout) * time.Duration(performanceRaftMultiplier)
// Connect
connectEnabled := boolVal(c.Connect.Enabled)
connectCAProvider := stringVal(c.Connect.CAProvider)
connectCAConfig := c.Connect.CAConfig
// autoEncrypt and autoConfig implicitly turns on connect which is why
// they need to be above other settings that rely on connect.
autoEncryptDNSSAN := []string{}
for _, d := range c.AutoEncrypt.DNSSAN {
autoEncryptDNSSAN = append(autoEncryptDNSSAN, d)
}
autoEncryptIPSAN := []net.IP{}
for _, i := range c.AutoEncrypt.IPSAN {
ip := net.ParseIP(i)
if ip == nil {
b.warn(fmt.Sprintf("Cannot parse ip %q from AutoEncrypt.IPSAN", i))
continue
}
autoEncryptIPSAN = append(autoEncryptIPSAN, ip)
}
autoEncryptAllowTLS := boolVal(c.AutoEncrypt.AllowTLS)
autoConfig := b.autoConfigVal(c.AutoConfig, stringVal(c.Partition))
if autoEncryptAllowTLS || autoConfig.Enabled {
connectEnabled = true
}
// Connect proxy defaults
connectMeshGatewayWANFederationEnabled := boolVal(c.Connect.MeshGatewayWANFederationEnabled)
if connectMeshGatewayWANFederationEnabled && !connectEnabled {
return RuntimeConfig{}, fmt.Errorf("'connect.enable_mesh_gateway_wan_federation=true' requires 'connect.enabled=true'")
}
if connectCAConfig != nil {
// nolint: staticcheck // CA config should be changed to use HookTranslateKeys
lib.TranslateKeys(connectCAConfig, map[string]string{
// Consul CA config
"private_key": "PrivateKey",
"root_cert": "RootCert",
"intermediate_cert_ttl": "IntermediateCertTTL",
// Vault CA config
"address": "Address",
"token": "Token",
"root_pki_path": "RootPKIPath",
"root_pki_namespace": "RootPKINamespace",
"intermediate_pki_path": "IntermediatePKIPath",
"intermediate_pki_namespace": "IntermediatePKINamespace",
"ca_file": "CAFile",
"ca_path": "CAPath",
"cert_file": "CertFile",
"key_file": "KeyFile",
"tls_server_name": "TLSServerName",
"tls_skip_verify": "TLSSkipVerify",
// AWS CA config
"existing_arn": "ExistingARN",
"delete_on_exit": "DeleteOnExit",
// Common CA config
"leaf_cert_ttl": "LeafCertTTL",
"csr_max_per_second": "CSRMaxPerSecond",
"csr_max_concurrent": "CSRMaxConcurrent",
"private_key_type": "PrivateKeyType",
"private_key_bits": "PrivateKeyBits",
"root_cert_ttl": "RootCertTTL",
})
}
aclsEnabled := false
primaryDatacenter := strings.ToLower(stringVal(c.PrimaryDatacenter))
if c.ACL.Enabled != nil {
aclsEnabled = boolVal(c.ACL.Enabled)
}
// Set the primary DC if it wasn't set.
if primaryDatacenter == "" {
primaryDatacenter = datacenter
}
enableRemoteScriptChecks := boolVal(c.EnableScriptChecks)
enableLocalScriptChecks := boolValWithDefault(c.EnableLocalScriptChecks, enableRemoteScriptChecks)
var configEntries []structs.ConfigEntry
if len(c.ConfigEntries.Bootstrap) > 0 {
for i, rawEntry := range c.ConfigEntries.Bootstrap {
entry, err := structs.DecodeConfigEntry(rawEntry)
if err != nil {
return RuntimeConfig{}, fmt.Errorf("config_entries.bootstrap[%d]: %s", i, err)
}
if err := entry.Normalize(); err != nil {
return RuntimeConfig{}, fmt.Errorf("config_entries.bootstrap[%d]: %s", i, err)
}
if err := entry.Validate(); err != nil {
return RuntimeConfig{}, fmt.Errorf("config_entries.bootstrap[%d]: %w", i, err)
}
configEntries = append(configEntries, entry)
}
}
serfAllowedCIDRSLAN, err := memberlist.ParseCIDRs(c.SerfAllowedCIDRsLAN)
if err != nil {
return RuntimeConfig{}, fmt.Errorf("serf_lan_allowed_cidrs: %s", err)
}
serfAllowedCIDRSWAN, err := memberlist.ParseCIDRs(c.SerfAllowedCIDRsWAN)
if err != nil {
return RuntimeConfig{}, fmt.Errorf("serf_wan_allowed_cidrs: %s", err)
}
// Handle Deprecated UI config fields
if c.UI != nil {
b.warn("The 'ui' field is deprecated. Use the 'ui_config.enabled' field instead.")
if c.UIConfig.Enabled == nil {
c.UIConfig.Enabled = c.UI
}
}
if c.UIDir != nil {
b.warn("The 'ui_dir' field is deprecated. Use the 'ui_config.dir' field instead.")
if c.UIConfig.Dir == nil {
c.UIConfig.Dir = c.UIDir
}
}
if c.UIContentPath != nil {
b.warn("The 'ui_content_path' field is deprecated. Use the 'ui_config.content_path' field instead.")
if c.UIConfig.ContentPath == nil {
c.UIConfig.ContentPath = c.UIContentPath
}
}
serverMode := boolVal(c.ServerMode)
// ----------------------------------------------------------------
// build runtime config
//
dataDir := stringVal(c.DataDir)
rt = RuntimeConfig{
// non-user configurable values
AEInterval: b.durationVal("ae_interval", c.AEInterval),
CheckDeregisterIntervalMin: b.durationVal("check_deregister_interval_min", c.CheckDeregisterIntervalMin),
CheckReapInterval: b.durationVal("check_reap_interval", c.CheckReapInterval),
Revision: stringVal(c.Revision),
SegmentNameLimit: intVal(c.SegmentNameLimit),
SyncCoordinateIntervalMin: b.durationVal("sync_coordinate_interval_min", c.SyncCoordinateIntervalMin),
SyncCoordinateRateTarget: float64Val(c.SyncCoordinateRateTarget),
Version: stringVal(c.Version),
VersionPrerelease: stringVal(c.VersionPrerelease),
VersionMetadata: stringVal(c.VersionMetadata),
Experiments: c.Experiments,
// What is a sensible default for BuildDate?
BuildDate: timeValWithDefault(c.BuildDate, time.Date(1970, 1, 00, 00, 00, 01, 0, time.UTC)),
// consul configuration
ConsulCoordinateUpdateBatchSize: intVal(c.Consul.Coordinate.UpdateBatchSize),
ConsulCoordinateUpdateMaxBatches: intVal(c.Consul.Coordinate.UpdateMaxBatches),
ConsulCoordinateUpdatePeriod: b.durationVal("consul.coordinate.update_period", c.Consul.Coordinate.UpdatePeriod),
ConsulRaftElectionTimeout: consulRaftElectionTimeout,
ConsulRaftHeartbeatTimeout: consulRaftHeartbeatTimeout,
ConsulRaftLeaderLeaseTimeout: consulRaftLeaderLeaseTimeout,
ConsulServerHealthInterval: b.durationVal("consul.server.health_interval", c.Consul.Server.HealthInterval),
// gossip configuration
GossipLANGossipInterval: b.durationVal("gossip_lan..gossip_interval", c.GossipLAN.GossipInterval),
GossipLANGossipNodes: intVal(c.GossipLAN.GossipNodes),
Locality: c.Locality,
GossipLANProbeInterval: b.durationVal("gossip_lan..probe_interval", c.GossipLAN.ProbeInterval),
GossipLANProbeTimeout: b.durationVal("gossip_lan..probe_timeout", c.GossipLAN.ProbeTimeout),
GossipLANSuspicionMult: intVal(c.GossipLAN.SuspicionMult),
GossipLANRetransmitMult: intVal(c.GossipLAN.RetransmitMult),
GossipWANGossipInterval: b.durationVal("gossip_wan..gossip_interval", c.GossipWAN.GossipInterval),
GossipWANGossipNodes: intVal(c.GossipWAN.GossipNodes),
GossipWANProbeInterval: b.durationVal("gossip_wan..probe_interval", c.GossipWAN.ProbeInterval),
GossipWANProbeTimeout: b.durationVal("gossip_wan..probe_timeout", c.GossipWAN.ProbeTimeout),
GossipWANSuspicionMult: intVal(c.GossipWAN.SuspicionMult),
GossipWANRetransmitMult: intVal(c.GossipWAN.RetransmitMult),
// ACL
ACLsEnabled: aclsEnabled,
ACLResolverSettings: consul.ACLResolverSettings{
ACLsEnabled: aclsEnabled,
Datacenter: datacenter,
NodeName: b.nodeName(c.NodeName),
ACLPolicyTTL: b.durationVal("acl.policy_ttl", c.ACL.PolicyTTL),
ACLTokenTTL: b.durationVal("acl.token_ttl", c.ACL.TokenTTL),
ACLRoleTTL: b.durationVal("acl.role_ttl", c.ACL.RoleTTL),
ACLDownPolicy: stringVal(c.ACL.DownPolicy),
ACLDefaultPolicy: stringVal(c.ACL.DefaultPolicy),
},
ACLEnableKeyListPolicy: boolVal(c.ACL.EnableKeyListPolicy),
ACLInitialManagementToken: stringVal(c.ACL.Tokens.InitialManagement),
ACLTokenReplication: boolVal(c.ACL.TokenReplication),
ACLTokens: token.Config{
DataDir: dataDir,
EnablePersistence: boolValWithDefault(c.ACL.EnableTokenPersistence, false),
ACLDefaultToken: stringVal(c.ACL.Tokens.Default),
ACLAgentToken: stringVal(c.ACL.Tokens.Agent),
ACLAgentRecoveryToken: stringVal(c.ACL.Tokens.AgentRecovery),
ACLReplicationToken: stringVal(c.ACL.Tokens.Replication),
ACLConfigFileRegistrationToken: stringVal(c.ACL.Tokens.ConfigFileRegistration),
ACLDNSToken: stringVal(c.ACL.Tokens.DNS),
},
// Autopilot
AutopilotCleanupDeadServers: boolVal(c.Autopilot.CleanupDeadServers),
AutopilotDisableUpgradeMigration: boolVal(c.Autopilot.DisableUpgradeMigration),
AutopilotLastContactThreshold: b.durationVal("autopilot.last_contact_threshold", c.Autopilot.LastContactThreshold),
AutopilotMaxTrailingLogs: intVal(c.Autopilot.MaxTrailingLogs),
AutopilotMinQuorum: uintVal(c.Autopilot.MinQuorum),
AutopilotRedundancyZoneTag: stringVal(c.Autopilot.RedundancyZoneTag),
AutopilotServerStabilizationTime: b.durationVal("autopilot.server_stabilization_time", c.Autopilot.ServerStabilizationTime),
AutopilotUpgradeVersionTag: stringVal(c.Autopilot.UpgradeVersionTag),
// DNS
DNSAddrs: dnsAddrs,
DNSAllowStale: boolVal(c.DNS.AllowStale),
DNSARecordLimit: intVal(c.DNS.ARecordLimit),
DNSDisableCompression: boolVal(c.DNS.DisableCompression),
DNSDomain: stringVal(c.DNSDomain),
DNSAltDomain: altDomain,
DNSEnableTruncate: boolVal(c.DNS.EnableTruncate),
DNSMaxStale: b.durationVal("dns_config.max_stale", c.DNS.MaxStale),
DNSNodeTTL: b.durationVal("dns_config.node_ttl", c.DNS.NodeTTL),
DNSOnlyPassing: boolVal(c.DNS.OnlyPassing),
DNSPort: dnsPort,
DNSRecursorStrategy: b.dnsRecursorStrategyVal(stringVal(c.DNS.RecursorStrategy)),
DNSRecursorTimeout: b.durationVal("recursor_timeout", c.DNS.RecursorTimeout),
DNSRecursors: dnsRecursors,
DNSServiceTTL: dnsServiceTTL,
DNSSOA: soa,
DNSUDPAnswerLimit: intVal(c.DNS.UDPAnswerLimit),
DNSNodeMetaTXT: boolValWithDefault(c.DNS.NodeMetaTXT, true),
DNSUseCache: boolVal(c.DNS.UseCache),
DNSCacheMaxAge: b.durationVal("dns_config.cache_max_age", c.DNS.CacheMaxAge),
// HTTP
HTTPPort: httpPort,
HTTPSPort: httpsPort,
HTTPAddrs: httpAddrs,
HTTPSAddrs: httpsAddrs,
HTTPBlockEndpoints: c.HTTPConfig.BlockEndpoints,
HTTPMaxHeaderBytes: intVal(c.HTTPConfig.MaxHeaderBytes),
HTTPResponseHeaders: c.HTTPConfig.ResponseHeaders,
AllowWriteHTTPFrom: b.cidrsVal("allow_write_http_from", c.HTTPConfig.AllowWriteHTTPFrom),
HTTPUseCache: boolValWithDefault(c.HTTPConfig.UseCache, true),
// Telemetry
Telemetry: lib.TelemetryConfig{
CirconusAPIApp: stringVal(c.Telemetry.CirconusAPIApp),
CirconusAPIToken: stringVal(c.Telemetry.CirconusAPIToken),
CirconusAPIURL: stringVal(c.Telemetry.CirconusAPIURL),
CirconusBrokerID: stringVal(c.Telemetry.CirconusBrokerID),
CirconusBrokerSelectTag: stringVal(c.Telemetry.CirconusBrokerSelectTag),
CirconusCheckDisplayName: stringVal(c.Telemetry.CirconusCheckDisplayName),
CirconusCheckForceMetricActivation: stringVal(c.Telemetry.CirconusCheckForceMetricActivation),
CirconusCheckID: stringVal(c.Telemetry.CirconusCheckID),
CirconusCheckInstanceID: stringVal(c.Telemetry.CirconusCheckInstanceID),
CirconusCheckSearchTag: stringVal(c.Telemetry.CirconusCheckSearchTag),
CirconusCheckTags: stringVal(c.Telemetry.CirconusCheckTags),
CirconusSubmissionInterval: stringVal(c.Telemetry.CirconusSubmissionInterval),
CirconusSubmissionURL: stringVal(c.Telemetry.CirconusSubmissionURL),
DisableHostname: boolVal(c.Telemetry.DisableHostname),
DisablePerTenancyUsageMetrics: boolVal(c.Telemetry.DisablePerTenancyUsageMetrics),
DogstatsdAddr: stringVal(c.Telemetry.DogstatsdAddr),
DogstatsdTags: c.Telemetry.DogstatsdTags,
RetryFailedConfiguration: boolVal(c.Telemetry.RetryFailedConfiguration),
FilterDefault: boolVal(c.Telemetry.FilterDefault),
AllowedPrefixes: telemetryAllowedPrefixes,
BlockedPrefixes: telemetryBlockedPrefixes,
MetricsPrefix: stringVal(c.Telemetry.MetricsPrefix),
StatsdAddr: stringVal(c.Telemetry.StatsdAddr),
StatsiteAddr: stringVal(c.Telemetry.StatsiteAddr),
PrometheusOpts: prometheus.PrometheusOpts{
Expiration: b.durationVal("prometheus_retention_time", c.Telemetry.PrometheusRetentionTime),
Name: stringVal(c.Telemetry.MetricsPrefix),
},
},
// Agent
AdvertiseAddrLAN: advertiseAddrLAN,
AdvertiseAddrWAN: advertiseAddrWAN,
AdvertiseReconnectTimeout: b.durationVal("advertise_reconnect_timeout", c.AdvertiseReconnectTimeout),
BindAddr: bindAddr,
Bootstrap: boolVal(c.Bootstrap),
BootstrapExpect: intVal(c.BootstrapExpect),
Cache: cache.Options{
EntryFetchRate: limitValWithDefault(
c.Cache.EntryFetchRate, float64(cache.DefaultEntryFetchRate),
),
EntryFetchMaxBurst: intValWithDefault(
c.Cache.EntryFetchMaxBurst, cache.DefaultEntryFetchMaxBurst,
),
},
AutoReloadConfig: boolVal(c.AutoReloadConfig),
CheckUpdateInterval: b.durationVal("check_update_interval", c.CheckUpdateInterval),
CheckOutputMaxSize: intValWithDefault(c.CheckOutputMaxSize, 4096),
Checks: checks,
ClientAddrs: clientAddrs,
ConfigEntryBootstrap: configEntries,
AutoEncryptTLS: boolVal(c.AutoEncrypt.TLS),
AutoEncryptDNSSAN: autoEncryptDNSSAN,
AutoEncryptIPSAN: autoEncryptIPSAN,
AutoEncryptAllowTLS: autoEncryptAllowTLS,
AutoConfig: autoConfig,
Cloud: b.cloudConfigVal(c),
ConnectEnabled: connectEnabled,
ConnectCAProvider: connectCAProvider,
ConnectCAConfig: connectCAConfig,
ConnectMeshGatewayWANFederationEnabled: connectMeshGatewayWANFederationEnabled,
ConnectSidecarMinPort: sidecarMinPort,
ConnectSidecarMaxPort: sidecarMaxPort,
ConnectTestCALeafRootChangeSpread: b.durationVal("connect.test_ca_leaf_root_change_spread", c.Connect.TestCALeafRootChangeSpread),
ExposeMinPort: exposeMinPort,