forked from hashicorp/nomad
/
services.go
2235 lines (1838 loc) · 57.7 KB
/
services.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 structs
import (
"crypto/sha1"
"encoding/binary"
"errors"
"fmt"
"hash"
"io"
"net/url"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-set"
"github.com/hernad/nomad/helper"
"github.com/hernad/nomad/helper/args"
"github.com/hernad/nomad/helper/pointer"
"github.com/mitchellh/copystructure"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
)
const (
EnvoyBootstrapPath = "${NOMAD_SECRETS_DIR}/envoy_bootstrap.json"
ServiceCheckHTTP = "http"
ServiceCheckTCP = "tcp"
ServiceCheckScript = "script"
ServiceCheckGRPC = "grpc"
OnUpdateRequireHealthy = "require_healthy"
OnUpdateIgnoreWarn = "ignore_warnings"
OnUpdateIgnore = "ignore"
// minCheckInterval is the minimum check interval permitted. Consul
// currently has its MinInterval set to 1s. Mirror that here for
// consistency.
minCheckInterval = 1 * time.Second
// minCheckTimeout is the minimum check timeout permitted for Consul
// script TTL checks.
minCheckTimeout = 1 * time.Second
)
// ServiceCheck represents a Nomad or Consul service health check.
//
// The fields available depend on the service provider the check is being
// registered into.
type ServiceCheck struct {
Name string // Name of the check, defaults to a generated label
Type string // Type of the check - tcp, http, docker and script
Command string // Command is the command to run for script checks
Args []string // Args is a list of arguments for script checks
Path string // path of the health check url for http type check
Protocol string // Protocol to use if check is http, defaults to http
PortLabel string // The port to use for tcp/http checks
Expose bool // Whether to have Envoy expose the check path (connect-enabled group-services only)
AddressMode string // Must be empty, "alloc", "host", or "driver"
Interval time.Duration // Interval of the check
Timeout time.Duration // Timeout of the response from the check before consul fails the check
InitialStatus string // Initial status of the check
TLSServerName string // ServerName to use for SNI and TLS verification when (Type=https and Protocol=https) or (Type=grpc and GRPCUseTLS=true)
TLSSkipVerify bool // Skip TLS verification when (type=https and Protocol=https) or (type=grpc and grpc_use_tls=true)
Method string // HTTP Method to use (GET by default)
Header map[string][]string // HTTP Headers for Consul to set when making HTTP checks
CheckRestart *CheckRestart // If and when a task should be restarted based on checks
GRPCService string // Service for GRPC checks
GRPCUseTLS bool // Whether or not to use TLS for GRPC checks
TaskName string // What task to execute this check in
SuccessBeforePassing int // Number of consecutive successes required before considered healthy
FailuresBeforeCritical int // Number of consecutive failures required before considered unhealthy
Body string // Body to use in HTTP check
OnUpdate string
}
// IsReadiness returns whether the configuration of the ServiceCheck is effectively
// a readiness check - i.e. check failures do not affect a deployment.
func (sc *ServiceCheck) IsReadiness() bool {
return sc != nil && sc.OnUpdate == OnUpdateIgnore
}
// Copy the block recursively. Returns nil if nil.
func (sc *ServiceCheck) Copy() *ServiceCheck {
if sc == nil {
return nil
}
nsc := new(ServiceCheck)
*nsc = *sc
nsc.Args = slices.Clone(sc.Args)
nsc.Header = helper.CopyMapOfSlice(sc.Header)
nsc.CheckRestart = sc.CheckRestart.Copy()
return nsc
}
// Equal returns true if the structs are recursively equal.
func (sc *ServiceCheck) Equal(o *ServiceCheck) bool {
if sc == nil || o == nil {
return sc == o
}
if sc.Name != o.Name {
return false
}
if sc.AddressMode != o.AddressMode {
return false
}
if !helper.SliceSetEq(sc.Args, o.Args) {
return false
}
if !sc.CheckRestart.Equal(o.CheckRestart) {
return false
}
if sc.TaskName != o.TaskName {
return false
}
if sc.SuccessBeforePassing != o.SuccessBeforePassing {
return false
}
if sc.FailuresBeforeCritical != o.FailuresBeforeCritical {
return false
}
if sc.Command != o.Command {
return false
}
if sc.GRPCService != o.GRPCService {
return false
}
if sc.GRPCUseTLS != o.GRPCUseTLS {
return false
}
// Use DeepEqual here as order of slice values could matter
if !reflect.DeepEqual(sc.Header, o.Header) {
return false
}
if sc.InitialStatus != o.InitialStatus {
return false
}
if sc.Interval != o.Interval {
return false
}
if sc.Method != o.Method {
return false
}
if sc.Path != o.Path {
return false
}
if sc.PortLabel != o.Path {
return false
}
if sc.Expose != o.Expose {
return false
}
if sc.Protocol != o.Protocol {
return false
}
if sc.TLSSkipVerify != o.TLSSkipVerify {
return false
}
if sc.TLSServerName != o.TLSServerName {
return false
}
if sc.Timeout != o.Timeout {
return false
}
if sc.Type != o.Type {
return false
}
if sc.Body != o.Body {
return false
}
if sc.OnUpdate != o.OnUpdate {
return false
}
return true
}
func (sc *ServiceCheck) Canonicalize(serviceName, taskName string) {
// Ensure empty maps/slices are treated as null to avoid scheduling
// issues when using DeepEquals.
if len(sc.Args) == 0 {
sc.Args = nil
}
// Ensure empty slices are nil
if len(sc.Header) == 0 {
sc.Header = nil
} else {
for k, v := range sc.Header {
if len(v) == 0 {
sc.Header[k] = nil
}
}
}
// Ensure a default name for the check
if sc.Name == "" {
sc.Name = fmt.Sprintf("service: %q check", serviceName)
}
// Set task name if not already set
if sc.TaskName == "" && taskName != "group" {
sc.TaskName = taskName
}
// Ensure OnUpdate defaults to require_healthy (i.e. healthiness check)
if sc.OnUpdate == "" {
sc.OnUpdate = OnUpdateRequireHealthy
}
}
// validateCommon validates the parts of ServiceCheck shared across providers.
func (sc *ServiceCheck) validateCommon(allowableTypes []string) error {
// validate the type is allowable (different between nomad, consul checks)
checkType := strings.ToLower(sc.Type)
if !slices.Contains(allowableTypes, checkType) {
s := strings.Join(allowableTypes, ", ")
return fmt.Errorf(`invalid check type (%q), must be one of %s`, checkType, s)
}
// validate specific check types
switch checkType {
case ServiceCheckHTTP:
if sc.Path == "" {
return fmt.Errorf("http type must have http path")
}
checkPath, pathErr := url.Parse(sc.Path)
if pathErr != nil {
return fmt.Errorf("http type must have valid http path")
}
if checkPath.IsAbs() {
return fmt.Errorf("http type must have relative http path")
}
case ServiceCheckScript:
if sc.Command == "" {
return fmt.Errorf("script type must have a valid script path")
}
}
// validate interval
if sc.Interval == 0 {
return fmt.Errorf("missing required value interval. Interval cannot be less than %v", minCheckInterval)
} else if sc.Interval < minCheckInterval {
return fmt.Errorf("interval (%v) cannot be lower than %v", sc.Interval, minCheckInterval)
}
// validate timeout
if sc.Timeout == 0 {
return fmt.Errorf("missing required value timeout. Timeout cannot be less than %v", minCheckInterval)
} else if sc.Timeout < minCheckTimeout {
return fmt.Errorf("timeout (%v) is lower than required minimum timeout %v", sc.Timeout, minCheckInterval)
}
// validate the initial status
switch sc.InitialStatus {
case "":
case api.HealthPassing:
case api.HealthWarning:
case api.HealthCritical:
default:
return fmt.Errorf(`invalid initial check state (%s), must be one of %q, %q, %q or empty`, sc.InitialStatus, api.HealthPassing, api.HealthWarning, api.HealthCritical)
}
// validate address_mode
switch sc.AddressMode {
case "", AddressModeHost, AddressModeDriver, AddressModeAlloc:
// Ok
case AddressModeAuto:
return fmt.Errorf("invalid address_mode %q - %s only valid for services", sc.AddressMode, AddressModeAuto)
default:
return fmt.Errorf("invalid address_mode %q", sc.AddressMode)
}
// validate on_update
switch sc.OnUpdate {
case "", OnUpdateIgnore, OnUpdateRequireHealthy, OnUpdateIgnoreWarn:
// OK
default:
return fmt.Errorf("on_update must be %q, %q, or %q; got %q", OnUpdateRequireHealthy, OnUpdateIgnoreWarn, OnUpdateIgnore, sc.OnUpdate)
}
// validate check_restart and on_update do not conflict
if sc.CheckRestart != nil {
// CheckRestart and OnUpdate Ignore are incompatible If OnUpdate treats
// an error has healthy, and the deployment succeeds followed by check
// restart restarting failing checks, the deployment is left in an odd
// state
if sc.OnUpdate == OnUpdateIgnore {
return fmt.Errorf("on_update value %q is not compatible with check_restart", sc.OnUpdate)
}
// CheckRestart IgnoreWarnings must be true if a check has defined OnUpdate
// ignore_warnings
if !sc.CheckRestart.IgnoreWarnings && sc.OnUpdate == OnUpdateIgnoreWarn {
return fmt.Errorf("on_update value %q not supported with check_restart ignore_warnings value %q", sc.OnUpdate, strconv.FormatBool(sc.CheckRestart.IgnoreWarnings))
}
}
// validate check_restart
if err := sc.CheckRestart.Validate(); err != nil {
return err
}
return nil
}
// validate a Service's ServiceCheck in the context of the Nomad provider.
func (sc *ServiceCheck) validateNomad() error {
allowable := []string{ServiceCheckTCP, ServiceCheckHTTP}
if err := sc.validateCommon(allowable); err != nil {
return err
}
// expose is connect (consul) specific
if sc.Expose {
return fmt.Errorf("expose may only be set for Consul service checks")
}
// nomad checks do not have warnings
if sc.OnUpdate == OnUpdateIgnoreWarn {
return fmt.Errorf("on_update may only be set to ignore_warnings for Consul service checks")
}
// below are temporary limitations on checks in nomad
// https://github.com/hashicorp/team-nomad/issues/354
// check_restart.ignore_warnings is not a thing in Nomad (which has no warnings in checks)
if sc.CheckRestart != nil {
if sc.CheckRestart.IgnoreWarnings {
return fmt.Errorf("ignore_warnings on check_restart only supported for Consul service checks")
}
}
// address_mode="driver" not yet supported on nomad
if sc.AddressMode == "driver" {
return fmt.Errorf("address_mode = driver may only be set for Consul service checks")
}
if sc.Type == "http" {
if sc.Method != "" && !helper.IsMethodHTTP(sc.Method) {
return fmt.Errorf("method type %q not supported in Nomad http check", sc.Method)
}
}
// success_before_passing is consul only
if sc.SuccessBeforePassing != 0 {
return fmt.Errorf("success_before_passing may only be set for Consul service checks")
}
// failures_before_critical is consul only
if sc.FailuresBeforeCritical != 0 {
return fmt.Errorf("failures_before_critical may only be set for Consul service checks")
}
// tls_server_name is consul only
if sc.TLSServerName != "" {
return fmt.Errorf("tls_server_name may only be set for Consul service checks")
}
return nil
}
// validate a Service's ServiceCheck in the context of the Consul provider.
func (sc *ServiceCheck) validateConsul() error {
allowable := []string{ServiceCheckGRPC, ServiceCheckTCP, ServiceCheckHTTP, ServiceCheckScript}
if err := sc.validateCommon(allowable); err != nil {
return err
}
checkType := strings.ToLower(sc.Type)
// Note that we cannot completely validate the Expose field yet - we do not
// know whether this ServiceCheck belongs to a connect-enabled group-service.
// Instead, such validation will happen in a job admission controller.
//
// Consul only.
if sc.Expose {
// We can however immediately ensure expose is configured only for HTTP
// and gRPC checks.
switch checkType {
case ServiceCheckGRPC, ServiceCheckHTTP: // ok
default:
return fmt.Errorf("expose may only be set on HTTP or gRPC checks")
}
}
// passFailCheckTypes are intersection of check types supported by both Consul
// and Nomad when using the pass/fail check threshold features.
//
// Consul only.
passFailCheckTypes := []string{"tcp", "http", "grpc"}
if sc.SuccessBeforePassing < 0 {
return fmt.Errorf("success_before_passing must be non-negative")
} else if sc.SuccessBeforePassing > 0 && !slices.Contains(passFailCheckTypes, sc.Type) {
return fmt.Errorf("success_before_passing not supported for check of type %q", sc.Type)
}
if sc.FailuresBeforeCritical < 0 {
return fmt.Errorf("failures_before_critical must be non-negative")
} else if sc.FailuresBeforeCritical > 0 && !slices.Contains(passFailCheckTypes, sc.Type) {
return fmt.Errorf("failures_before_critical not supported for check of type %q", sc.Type)
}
return nil
}
// RequiresPort returns whether the service check requires the task has a port.
func (sc *ServiceCheck) RequiresPort() bool {
switch sc.Type {
case ServiceCheckGRPC, ServiceCheckHTTP, ServiceCheckTCP:
return true
default:
return false
}
}
// TriggersRestarts returns true if this check should be watched and trigger a restart
// on failure.
func (sc *ServiceCheck) TriggersRestarts() bool {
return sc.CheckRestart != nil && sc.CheckRestart.Limit > 0
}
// Hash all ServiceCheck fields and the check's corresponding service ID to
// create an identifier. The identifier is not guaranteed to be unique as if
// the PortLabel is blank, the Service's PortLabel will be used after Hash is
// called.
func (sc *ServiceCheck) Hash(serviceID string) string {
h := sha1.New()
hashString(h, serviceID)
hashString(h, sc.Name)
hashString(h, sc.Type)
hashString(h, sc.Command)
hashString(h, strings.Join(sc.Args, ""))
hashString(h, sc.Path)
hashString(h, sc.Protocol)
hashString(h, sc.PortLabel)
hashString(h, sc.Interval.String())
hashString(h, sc.Timeout.String())
hashString(h, sc.Method)
hashString(h, sc.Body)
hashString(h, sc.OnUpdate)
// use name "true" to maintain ID stability
hashBool(h, sc.TLSSkipVerify, "true")
// Only include TLSServerName if set to maintain ID stability with Nomad <1.6.0
hashStringIfNonEmpty(h, sc.TLSServerName)
// maintain artisanal map hashing to maintain ID stability
hashHeader(h, sc.Header)
// Only include AddressMode if set to maintain ID stability with Nomad <0.7.1
hashStringIfNonEmpty(h, sc.AddressMode)
// Only include gRPC if set to maintain ID stability with Nomad <0.8.4
hashStringIfNonEmpty(h, sc.GRPCService)
// use name "true" to maintain ID stability
hashBool(h, sc.GRPCUseTLS, "true")
// Only include pass/fail if non-zero to maintain ID stability with Nomad < 0.12
hashIntIfNonZero(h, "success", sc.SuccessBeforePassing)
hashIntIfNonZero(h, "failures", sc.FailuresBeforeCritical)
// Hash is used for diffing against the Consul check definition, which does
// not have an expose parameter. Instead we rely on implied changes to
// other fields if the Expose setting is changed in a nomad service.
// hashBool(h, sc.Expose, "Expose")
// maintain use of hex (i.e. not b32) to maintain ID stability
return fmt.Sprintf("%x", h.Sum(nil))
}
func hashStringIfNonEmpty(h hash.Hash, s string) {
if len(s) > 0 {
hashString(h, s)
}
}
func hashIntIfNonZero(h hash.Hash, name string, i int) {
if i != 0 {
hashString(h, fmt.Sprintf("%s:%d", name, i))
}
}
func hashDuration(h hash.Hash, dur time.Duration) {
_ = binary.Write(h, binary.LittleEndian, dur)
}
func hashHeader(h hash.Hash, m map[string][]string) {
// maintain backwards compatibility for ID stability
// using the %v formatter on a map with string keys produces consistent
// output, but our existing format here is incompatible
if len(m) > 0 {
headers := make([]string, 0, len(m))
for k, v := range m {
headers = append(headers, k+strings.Join(v, ""))
}
sort.Strings(headers)
hashString(h, strings.Join(headers, ""))
}
}
const (
AddressModeAuto = "auto"
AddressModeHost = "host"
AddressModeDriver = "driver"
AddressModeAlloc = "alloc"
// ServiceProviderConsul is the default service provider and the way Nomad
// worked before native service discovery.
ServiceProviderConsul = "consul"
// ServiceProviderNomad is the native service discovery provider. At the
// time of writing, there are a number of restrictions around its
// functionality and use.
ServiceProviderNomad = "nomad"
)
// Service represents a Consul service definition
type Service struct {
// Name of the service registered with Consul. Consul defaults the
// Name to ServiceID if not specified. The Name if specified is used
// as one of the seed values when generating a Consul ServiceID.
Name string
// Name of the Task associated with this service.
// Group services do not have a task name, unless they are a connect native
// service specifying the task implementing the service.
// Task-level services automatically have the task name plumbed through
// down to checks for convenience.
TaskName string
// PortLabel is either the numeric port number or the `host:port`.
// To specify the port number using the host's Consul Advertise
// address, specify an empty host in the PortLabel (e.g. `:port`).
PortLabel string
// AddressMode specifies how the address in service registration is
// determined. Must be "auto" (default), "host", "driver", or "alloc".
AddressMode string
// Address enables explicitly setting a custom address to use in service
// registration. AddressMode must be "auto" if Address is set.
Address string
// EnableTagOverride will disable Consul's anti-entropy mechanism for the
// tags of this service. External updates to the service definition via
// Consul will not be corrected to match the service definition set in the
// Nomad job specification.
//
// https://www.consul.io/docs/agent/services.html#service-definition
EnableTagOverride bool
Tags []string // List of tags for the service
CanaryTags []string // List of tags for the service when it is a canary
Checks []*ServiceCheck // List of checks associated with the service
Connect *ConsulConnect // Consul Connect configuration
Meta map[string]string // Consul service meta
CanaryMeta map[string]string // Consul service meta when it is a canary
// The values to set for tagged_addresses in Consul service registration.
// Does not affect Nomad networking, these are for Consul service discovery.
TaggedAddresses map[string]string
// The consul namespace in which this service will be registered. Namespace
// at the service.check level is not part of the Nomad API - it must be
// set at the job or group level. This field is managed internally so
// that Hash can work correctly.
Namespace string
// OnUpdate Specifies how the service and its checks should be evaluated
// during an update
OnUpdate string
// Provider dictates which service discovery provider to use. This can be
// either ServiceProviderConsul or ServiceProviderNomad and defaults to the former when
// left empty by the operator.
Provider string
}
// Copy the block recursively. Returns nil if nil.
func (s *Service) Copy() *Service {
if s == nil {
return nil
}
ns := new(Service)
*ns = *s
ns.Tags = slices.Clone(ns.Tags)
ns.CanaryTags = slices.Clone(ns.CanaryTags)
if s.Checks != nil {
checks := make([]*ServiceCheck, len(ns.Checks))
for i, c := range ns.Checks {
checks[i] = c.Copy()
}
ns.Checks = checks
}
ns.Connect = s.Connect.Copy()
ns.Meta = maps.Clone(s.Meta)
ns.CanaryMeta = maps.Clone(s.CanaryMeta)
ns.TaggedAddresses = maps.Clone(s.TaggedAddresses)
return ns
}
// Canonicalize interpolates values of Job, Task Group and Task in the Service
// Name. This also generates check names, service id and check ids.
func (s *Service) Canonicalize(job, taskGroup, task, jobNamespace string) {
// Ensure empty lists are treated as null to avoid scheduler issues when
// using DeepEquals
if len(s.Tags) == 0 {
s.Tags = nil
}
if len(s.CanaryTags) == 0 {
s.CanaryTags = nil
}
if len(s.Checks) == 0 {
s.Checks = nil
}
if len(s.TaggedAddresses) == 0 {
s.TaggedAddresses = nil
}
// Set the task name if not already set
if s.TaskName == "" && task != "group" {
s.TaskName = task
}
s.Name = args.ReplaceEnv(s.Name, map[string]string{
"JOB": job,
"TASKGROUP": taskGroup,
"TASK": task,
"BASE": fmt.Sprintf("%s-%s-%s", job, taskGroup, task),
})
for _, check := range s.Checks {
check.Canonicalize(s.Name, s.TaskName)
}
// Set the provider to its default value. The value of consul ensures this
// new feature and parameter behaves in the same manner a previous versions
// which did not include this.
if s.Provider == "" {
s.Provider = ServiceProviderConsul
}
// Consul API returns "default" whether the namespace is empty or set as
// such, so we coerce our copy of the service to be the same if using the
// consul provider.
//
// When using ServiceProviderNomad, set the namespace to that of the job. This
// makes modifications and diffs on the service correct.
if s.Namespace == "" && s.Provider == ServiceProviderConsul {
s.Namespace = "default"
} else if s.Provider == ServiceProviderNomad {
s.Namespace = jobNamespace
}
}
// Validate checks if the Service definition is valid
func (s *Service) Validate() error {
var mErr multierror.Error
// Ensure the service name is valid per the below RFCs but make an exception
// for our interpolation syntax by first stripping any environment variables from the name
serviceNameStripped := args.ReplaceEnvWithPlaceHolder(s.Name, "ENV-VAR")
if err := s.ValidateName(serviceNameStripped); err != nil {
// Log actual service name, not the stripped version.
mErr.Errors = append(mErr.Errors, fmt.Errorf("%v: %q", err, s.Name))
}
switch s.AddressMode {
case "", AddressModeAuto:
case AddressModeHost, AddressModeDriver, AddressModeAlloc:
if s.Address != "" {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Service address_mode must be %q if address is set", AddressModeAuto))
}
default:
mErr.Errors = append(mErr.Errors, fmt.Errorf("Service address_mode must be %q, %q, or %q; not %q", AddressModeAuto, AddressModeHost, AddressModeDriver, s.AddressMode))
}
switch s.OnUpdate {
case "", OnUpdateIgnore, OnUpdateRequireHealthy, OnUpdateIgnoreWarn:
// OK
default:
mErr.Errors = append(mErr.Errors, fmt.Errorf("Service on_update must be %q, %q, or %q; not %q", OnUpdateRequireHealthy, OnUpdateIgnoreWarn, OnUpdateIgnore, s.OnUpdate))
}
// Up until this point, all service validation has been independent of the
// provider. From this point on, we have different validation paths. We can
// also catch an incorrect provider parameter.
switch s.Provider {
case ServiceProviderConsul:
s.validateConsulService(&mErr)
case ServiceProviderNomad:
s.validateNomadService(&mErr)
default:
mErr.Errors = append(mErr.Errors, fmt.Errorf("Service provider must be %q, or %q; not %q",
ServiceProviderConsul, ServiceProviderNomad, s.Provider))
}
return mErr.ErrorOrNil()
}
func (s *Service) validateCheckPort(c *ServiceCheck) error {
if s.PortLabel == "" && c.PortLabel == "" && c.RequiresPort() {
return fmt.Errorf("Check %s invalid: check requires a port but neither check nor service %+q have a port", c.Name, s.Name)
}
return nil
}
// validateConsulService performs validation on a service which is using the
// consul provider.
func (s *Service) validateConsulService(mErr *multierror.Error) {
// check checks
for _, c := range s.Checks {
// validat ethe check port
if err := s.validateCheckPort(c); err != nil {
mErr.Errors = append(mErr.Errors, err)
continue
}
// TCP checks against a Consul Connect enabled service are not supported
// due to the service being bound to the loopback interface inside the
// network namespace
if c.Type == ServiceCheckTCP && s.Connect != nil && s.Connect.SidecarService != nil {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Check %s invalid: tcp checks are not valid for Connect enabled services", c.Name))
continue
}
// validate the consul check
if err := c.validateConsul(); err != nil {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Check %s invalid: %v", c.Name, err))
}
}
// check connect
if s.Connect != nil {
if err := s.Connect.Validate(); err != nil {
mErr.Errors = append(mErr.Errors, err)
}
// if service is connect native, service task must be set (which may
// happen implicitly in a job mutation if there is only one task)
if s.Connect.IsNative() && len(s.TaskName) == 0 {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Service %s is Connect Native and requires setting the task", s.Name))
}
}
}
// validateNomadService performs validation on a service which is using the
// nomad provider.
func (s *Service) validateNomadService(mErr *multierror.Error) {
// check checks
for _, c := range s.Checks {
// validate the check port
if err := s.validateCheckPort(c); err != nil {
mErr.Errors = append(mErr.Errors, err)
continue
}
// validate the nomad check
if err := c.validateNomad(); err != nil {
mErr.Errors = append(mErr.Errors, err)
}
}
// Services using the Nomad provider do not support Consul connect.
if s.Connect != nil {
mErr.Errors = append(mErr.Errors, errors.New("Service with provider nomad cannot include Connect blocks"))
}
}
// ValidateName checks if the service Name is valid and should be called after
// the name has been interpolated
func (s *Service) ValidateName(name string) error {
// Ensure the service name is valid per RFC-952 §1
// (https://tools.ietf.org/html/rfc952), RFC-1123 §2.1
// (https://tools.ietf.org/html/rfc1123), and RFC-2782
// (https://tools.ietf.org/html/rfc2782).
// This validation is enforced on Nomad, but not on Consul, however if
// consul-template is being used, service names with dots in them wont be
// admissible.
re := regexp.MustCompile(`^(?i:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])$`)
if !re.MatchString(name) {
return fmt.Errorf("Service name must be valid per RFC 1123 and can contain only alphanumeric characters or dashes and must be no longer than 63 characters")
}
return nil
}
// Hash returns a base32 encoded hash of a Service's contents excluding checks
// as they're hashed independently and the provider in order to not cause churn
// during cluster upgrades.
func (s *Service) Hash(allocID, taskName string, canary bool) string {
h := sha1.New()
hashString(h, allocID)
hashString(h, taskName)
hashString(h, s.Name)
hashString(h, s.PortLabel)
hashString(h, s.AddressMode)
hashString(h, s.Address)
hashTags(h, s.Tags)
hashTags(h, s.CanaryTags)
hashBool(h, canary, "Canary")
hashBool(h, s.EnableTagOverride, "ETO")
hashMeta(h, s.Meta)
hashMeta(h, s.CanaryMeta)
hashMeta(h, s.TaggedAddresses)
hashConnect(h, s.Connect)
hashString(h, s.OnUpdate)
hashString(h, s.Namespace)
// Don't hash the provider parameter, so we don't cause churn of all
// registered services when upgrading Nomad versions. The provider is not
// used at the level the hash is and therefore is not needed to tell
// whether the service has changed.
// Base32 is used for encoding the hash as sha1 hashes can always be
// encoded without padding, only 4 bytes larger than base64, and saves
// 8 bytes vs hex. Since these hashes are used in Consul URLs it's nice
// to have a reasonably compact URL-safe representation.
return b32.EncodeToString(h.Sum(nil))
}
func hashConnect(h hash.Hash, connect *ConsulConnect) {
if connect != nil && connect.SidecarService != nil {
hashString(h, connect.SidecarService.Port)
hashTags(h, connect.SidecarService.Tags)
if p := connect.SidecarService.Proxy; p != nil {
hashString(h, p.LocalServiceAddress)
hashString(h, strconv.Itoa(p.LocalServicePort))
hashConfig(h, p.Config)
for _, upstream := range p.Upstreams {
hashString(h, upstream.DestinationName)
hashString(h, upstream.DestinationNamespace)
hashString(h, strconv.Itoa(upstream.LocalBindPort))
hashStringIfNonEmpty(h, upstream.Datacenter)
hashStringIfNonEmpty(h, upstream.LocalBindAddress)
hashConfig(h, upstream.Config)
}
}
}
}
func hashString(h hash.Hash, s string) {
_, _ = io.WriteString(h, s)
}
func hashBool(h hash.Hash, b bool, name string) {
if b {
hashString(h, name)
}
}
func hashTags(h hash.Hash, tags []string) {
for _, tag := range tags {
hashString(h, tag)
}
}
func hashMeta(h hash.Hash, m map[string]string) {
_, _ = fmt.Fprintf(h, "%v", m)
}
func hashConfig(h hash.Hash, c map[string]interface{}) {
_, _ = fmt.Fprintf(h, "%v", c)
}
// Equal returns true if the structs are recursively equal.
func (s *Service) Equal(o *Service) bool {
if s == nil || o == nil {
return s == o
}
if s.Provider != o.Provider {
return false
}
if s.Namespace != o.Namespace {
return false
}
if s.AddressMode != o.AddressMode {
return false
}
if s.Address != o.Address {
return false
}
if s.OnUpdate != o.OnUpdate {
return false
}
if !helper.SliceSetEq(s.CanaryTags, o.CanaryTags) {
return false
}
if !helper.ElementsEqual(s.Checks, o.Checks) {
return false
}
if !s.Connect.Equal(o.Connect) {
return false
}
if s.Name != o.Name {
return false
}
if s.PortLabel != o.PortLabel {
return false
}
if !maps.Equal(s.Meta, o.Meta) {
return false
}
if !maps.Equal(s.CanaryMeta, o.CanaryMeta) {
return false
}
if !maps.Equal(s.TaggedAddresses, o.TaggedAddresses) {
return false
}
if !helper.SliceSetEq(s.Tags, o.Tags) {
return false
}
if s.EnableTagOverride != o.EnableTagOverride {
return false
}
return true
}
// ConsulConnect represents a Consul Connect jobspec block.
type ConsulConnect struct {
// Native indicates whether the service is Consul Connect Native enabled.
Native bool
// SidecarService is non-nil if a service requires a sidecar.
SidecarService *ConsulSidecarService
// SidecarTask is non-nil if sidecar overrides are set
SidecarTask *SidecarTask
// Gateway is a Consul Connect Gateway Proxy.
Gateway *ConsulGateway
}
// Copy the block recursively. Returns nil if nil.
func (c *ConsulConnect) Copy() *ConsulConnect {
if c == nil {
return nil
}
return &ConsulConnect{
Native: c.Native,
SidecarService: c.SidecarService.Copy(),
SidecarTask: c.SidecarTask.Copy(),
Gateway: c.Gateway.Copy(),