-
Notifications
You must be signed in to change notification settings - Fork 2k
/
service_client.go
2200 lines (1914 loc) · 71 KB
/
service_client.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 consul
import (
"context"
"errors"
"fmt"
"maps"
"net"
"net/url"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/armon/go-metrics"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-set/v3"
"github.com/hashicorp/nomad/client/serviceregistration"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/envoy"
"github.com/hashicorp/nomad/nomad/structs"
)
const (
// nomadServicePrefix is the prefix that scopes all Nomad registered
// services (both agent and task entries).
nomadServicePrefix = "_nomad"
// nomadServerPrefix is the prefix that scopes Nomad registered Servers.
nomadServerPrefix = nomadServicePrefix + "-server-"
// nomadClientPrefix is the prefix that scopes Nomad registered Clients.
nomadClientPrefix = nomadServicePrefix + "-client-"
// nomadTaskPrefix is the prefix that scopes Nomad registered services
// for tasks.
nomadTaskPrefix = nomadServicePrefix + "-task-"
// nomadCheckPrefix is the prefix that scopes Nomad registered checks for
// services.
nomadCheckPrefix = nomadServicePrefix + "-check-"
// defaultRetryInterval is how quickly to retry syncing services and
// checks to Consul when an error occurs. Will backoff up to a max.
defaultRetryInterval = time.Second
// defaultMaxRetryInterval is the default max retry interval.
defaultMaxRetryInterval = 30 * time.Second
// defaultPeriodicalInterval is the interval at which the service
// client reconciles state between the desired services and checks and
// what's actually registered in Consul. This is done at an interval,
// rather than being purely edge triggered, to handle the case that the
// Consul agent's state may change underneath us
defaultPeriodicInterval = 30 * time.Second
// ttlCheckBuffer is the time interval that Nomad can take to report Consul
// the check result
ttlCheckBuffer = 31 * time.Second
// defaultShutdownWait is how long Shutdown() should block waiting for
// enqueued operations to sync to Consul by default.
defaultShutdownWait = time.Minute
// DefaultQueryWaitDuration is the max duration the Consul Agent will
// spend waiting for a response from a Consul Query.
DefaultQueryWaitDuration = 2 * time.Second
// ServiceTagHTTP is the tag assigned to HTTP services
ServiceTagHTTP = "http"
// ServiceTagRPC is the tag assigned to RPC services
ServiceTagRPC = "rpc"
// ServiceTagSerf is the tag assigned to Serf services
ServiceTagSerf = "serf"
// deregisterProbationPeriod is the initialization period where
// services registered in Consul but not in Nomad don't get deregistered,
// to allow for nomad restoring tasks
deregisterProbationPeriod = time.Minute
)
// Additional Consul ACLs required
// - Consul Template: key:read
// Used in tasks with template block that use Consul keys.
// CatalogAPI is the consul/api.Catalog API used by Nomad.
//
// ACL requirements
// - node:read (listing datacenters)
// - service:read
type CatalogAPI interface {
Datacenters() ([]string, error)
Service(service, tag string, q *api.QueryOptions) ([]*api.CatalogService, *api.QueryMeta, error)
}
// NamespaceAPI is the consul/api.Namespace API used by Nomad.
//
// ACL requirements
// - operator:read OR namespace:*:read
type NamespaceAPI interface {
List(q *api.QueryOptions) ([]*api.Namespace, *api.QueryMeta, error)
}
// AgentAPI is the consul/api.Agent API used by Nomad.
//
// ACL requirements
// - agent:read
// - service:write
type AgentAPI interface {
CheckRegisterOpts(check *api.AgentCheckRegistration, q *api.QueryOptions) error
CheckDeregisterOpts(checkID string, q *api.QueryOptions) error
ChecksWithFilterOpts(filter string, q *api.QueryOptions) (map[string]*api.AgentCheck, error)
UpdateTTLOpts(id, output, status string, q *api.QueryOptions) error
ServiceRegisterOpts(service *api.AgentServiceRegistration, opts api.ServiceRegisterOpts) error
ServiceDeregisterOpts(serviceID string, q *api.QueryOptions) error
ServicesWithFilterOpts(filter string, q *api.QueryOptions) (map[string]*api.AgentService, error)
Self() (map[string]map[string]interface{}, error)
}
// ConfigAPI is the consul/api.ConfigEntries API subset used by Nomad Server.
//
// ACL requirements
// - operator:write (server only)
type ConfigAPI interface {
Set(entry api.ConfigEntry, w *api.WriteOptions) (bool, *api.WriteMeta, error)
// Delete(kind, name string, w *api.WriteOptions) (*api.WriteMeta, error) (not used)
}
// ConfigAPIFunc returns a ConfigAPI interface for the specific cluster
type ConfigAPIFunc func(clusterName string) ConfigAPI
// ACLsAPI is the consul/api.ACL API subset used by Nomad Server.
//
// ACL requirements
// - acl:write (server only)
type ACLsAPI interface {
TokenReadSelf(q *api.QueryOptions) (*api.ACLToken, *api.QueryMeta, error) // for lookup via operator token
PolicyRead(policyID string, q *api.QueryOptions) (*api.ACLPolicy, *api.QueryMeta, error)
RoleRead(roleID string, q *api.QueryOptions) (*api.ACLRole, *api.QueryMeta, error)
TokenCreate(partial *api.ACLToken, q *api.WriteOptions) (*api.ACLToken, *api.WriteMeta, error)
TokenDelete(accessorID string, q *api.WriteOptions) (*api.WriteMeta, error)
TokenList(q *api.QueryOptions) ([]*api.ACLTokenListEntry, *api.QueryMeta, error)
}
// agentServiceUpdateRequired checks if any critical fields in Nomad's version
// of a service definition are different from the existing service definition as
// known by Consul.
//
// reason - The syncReason that triggered this synchronization with the consul
// agent API.
// wanted - Nomad's view of what the service definition is intended to be.
// Not nil.
// existing - Consul's view (agent, not catalog) of the actual service definition.
// Not nil.
// sidecar - Consul's view (agent, not catalog) of the service definition of the sidecar
// associated with existing that may or may not exist.
// May be nil.
func (s *ServiceClient) agentServiceUpdateRequired(reason syncReason, wanted *api.AgentServiceRegistration, existing *api.AgentService, sidecar *api.AgentService) bool {
switch reason {
case syncPeriodic:
// In a periodic sync with Consul, we need to respect the value of
// the enable_tag_override field so that we maintain the illusion that the
// user is in control of the Consul tags, as they may be externally edited
// via the Consul catalog API (e.g. a user manually sets them).
//
// As Consul does by disabling anti-entropy for the tags field, Nomad will
// ignore differences in the tags field during the periodic syncs with
// the Consul agent API.
//
// We do so by over-writing the nomad service registration by the value
// of the tags that Consul contains, if enable_tag_override = true.
maybeTweakTags(wanted, existing, sidecar)
// Also, purge tagged address fields of nomad agent services.
maybeTweakTaggedAddresses(wanted, existing)
// Okay now it is safe to compare.
return s.different(wanted, existing, sidecar)
default:
// A non-periodic sync with Consul indicates an operation has been set
// on the queue. This happens when service has been added / removed / modified
// and implies the Consul agent should be sync'd with nomad, because
// nomad is the ultimate source of truth for the service definition.
// But do purge tagged address fields of nomad agent services.
maybeTweakTaggedAddresses(wanted, existing)
// Okay now it is safe to compare.
return s.different(wanted, existing, sidecar)
}
}
// maybeTweakTags will override wanted.Tags with a copy of existing.Tags only if
// EnableTagOverride is true. Otherwise the wanted service registration is left
// unchanged.
func maybeTweakTags(wanted *api.AgentServiceRegistration, existing *api.AgentService, sidecar *api.AgentService) {
if wanted.EnableTagOverride {
wanted.Tags = slices.Clone(existing.Tags)
// If the service registration also defines a sidecar service, use the ETO
// setting for the parent service to also apply to the sidecar.
if wanted.Connect != nil && wanted.Connect.SidecarService != nil {
if sidecar != nil {
wanted.Connect.SidecarService.Tags = slices.Clone(sidecar.Tags)
}
}
}
}
// maybeTweakTaggedAddresses will remove the Consul-injected .TaggedAddresses fields
// from existing if wanted represents a Nomad agent (Client or Server) or Nomad managed
// service, which do not themselves configure those tagged addresses. We do this
// because Consul will magically set the .TaggedAddress to values Nomad does not
// know about if they are submitted as unset.
func maybeTweakTaggedAddresses(wanted *api.AgentServiceRegistration, existing *api.AgentService) {
if isNomadAgent(wanted.ID) || isNomadService(wanted.ID) {
if _, exists := wanted.TaggedAddresses["lan_ipv4"]; !exists {
delete(existing.TaggedAddresses, "lan_ipv4")
}
if _, exists := wanted.TaggedAddresses["wan_ipv4"]; !exists {
delete(existing.TaggedAddresses, "wan_ipv4")
}
if _, exists := wanted.TaggedAddresses["lan_ipv6"]; !exists {
delete(existing.TaggedAddresses, "lan_ipv6")
}
if _, exists := wanted.TaggedAddresses["wan_ipv6"]; !exists {
delete(existing.TaggedAddresses, "wan_ipv6")
}
}
}
// different compares the wanted state of the service registration with the actual
// (cached) state of the service registration reported by Consul. If any of the
// critical fields are not deeply equal, they considered different.
func (s *ServiceClient) different(wanted *api.AgentServiceRegistration, existing *api.AgentService, sidecar *api.AgentService) bool {
trace := func(field string, left, right any) {
s.logger.Trace("registrations different", "id", wanted.ID,
"field", field, "wanted", fmt.Sprintf("%#v", left), "existing", fmt.Sprintf("%#v", right),
)
}
switch {
case wanted.Kind != existing.Kind:
trace("kind", wanted.Kind, existing.Kind)
return true
case wanted.ID != existing.ID:
trace("id", wanted.ID, existing.ID)
return true
case wanted.Port != existing.Port:
trace("port", wanted.Port, existing.Port)
return true
case wanted.Address != existing.Address:
trace("address", wanted.Address, existing.Address)
return true
case wanted.Name != existing.Service:
trace("service name", wanted.Name, existing.Service)
return true
case wanted.EnableTagOverride != existing.EnableTagOverride:
trace("enable_tag_override", wanted.EnableTagOverride, existing.EnableTagOverride)
return true
case !maps.Equal(wanted.Meta, existing.Meta):
trace("meta", wanted.Meta, existing.Meta)
return true
case !maps.Equal(wanted.TaggedAddresses, existing.TaggedAddresses):
trace("tagged_addresses", wanted.TaggedAddresses, existing.TaggedAddresses)
return true
case !helper.SliceSetEq(wanted.Tags, existing.Tags):
trace("tags", wanted.Tags, existing.Tags)
return true
case connectSidecarDifferent(wanted, sidecar):
trace("connect_sidecar", wanted.Name, existing.Service)
return true
case weightsDifferent(wanted.Weights, existing.Weights):
trace("weights", wanted.Weights, existing.Weights)
return true
}
return false
}
// sidecarTagsDifferent includes the special logic for comparing sidecar tags
// from Nomad vs. Consul perspective. Because Consul forces the sidecar tags
// to inherit the parent service tags if the sidecar tags are unset, we need to
// take that into consideration when Nomad's sidecar tags are unset by instead
// comparing them to the parent service tags.
func sidecarTagsDifferent(parent, wanted, sidecar []string) bool {
if len(wanted) == 0 {
return !helper.SliceSetEq(parent, sidecar)
}
return !helper.SliceSetEq(wanted, sidecar)
}
// proxyUpstreamsDifferent determines if the sidecar_service.proxy.upstreams
// configurations are different between the desired sidecar service state, and
// the actual sidecar service state currently registered in Consul.
func proxyUpstreamsDifferent(wanted *api.AgentServiceConnect, sidecar *api.AgentServiceConnectProxyConfig) bool {
// There is similar code that already does this in Nomad's API package,
// however here we are operating on Consul API package structs, and they do not
// provide such helper functions.
getProxyUpstreams := func(pc *api.AgentServiceConnectProxyConfig) []api.Upstream {
switch {
case pc == nil:
return nil
case len(pc.Upstreams) == 0:
return nil
default:
return pc.Upstreams
}
}
getConnectUpstreams := func(sc *api.AgentServiceConnect) []api.Upstream {
switch {
case sc.SidecarService.Proxy == nil:
return nil
case len(sc.SidecarService.Proxy.Upstreams) == 0:
return nil
default:
return sc.SidecarService.Proxy.Upstreams
}
}
upstreamsDifferent := func(a, b []api.Upstream) bool {
if len(a) != len(b) {
return true
}
for i := 0; i < len(a); i++ {
A := a[i]
B := b[i]
switch {
case A.Datacenter != B.Datacenter:
return true
case A.DestinationName != B.DestinationName:
return true
case A.LocalBindAddress != B.LocalBindAddress:
return true
case A.LocalBindPort != B.LocalBindPort:
return true
case A.MeshGateway.Mode != B.MeshGateway.Mode:
return true
case A.DestinationPeer != B.DestinationPeer:
return true
case A.DestinationPartition != B.DestinationPartition:
return true
case A.DestinationType != B.DestinationType:
return true
case A.LocalBindSocketPath != B.LocalBindSocketPath:
return true
case A.LocalBindSocketMode != B.LocalBindSocketMode:
return true
case !reflect.DeepEqual(A.Config, B.Config):
return true
}
}
return false
}
return upstreamsDifferent(
getConnectUpstreams(wanted),
getProxyUpstreams(sidecar),
)
}
// connectSidecarDifferent returns true if Nomad expects there to be a sidecar
// hanging off the desired parent service definition on the Consul side, and does
// not match with what Consul has.
//
// This is used to determine if the connect sidecar service registration should be
// updated - potentially (but not necessarily) in-place.
func connectSidecarDifferent(wanted *api.AgentServiceRegistration, sidecar *api.AgentService) bool {
if wanted.Connect != nil && wanted.Connect.SidecarService != nil {
if sidecar == nil {
// consul lost our sidecar (?)
return true
}
if sidecarTagsDifferent(wanted.Tags, wanted.Connect.SidecarService.Tags, sidecar.Tags) {
// tags on the nomad definition have been modified
return true
}
if proxyUpstreamsDifferent(wanted.Connect, sidecar.Proxy) {
// proxy upstreams on the nomad definition have been modified
return true
}
}
// Either Nomad does not expect there to be a sidecar_service, or there is
// no actionable difference from the Consul sidecar_service definition.
return false
}
func weightsDifferent(wanted *api.AgentWeights, existing api.AgentWeights) bool {
if wanted == nil {
// When we are either missing or unsetting the weights on Nomad side, check
// whether the existing values differ from the Consul defaults.
return existing.Passing != 1 || existing.Warning != 1
}
if wanted.Passing != existing.Passing {
return true
}
if wanted.Warning != existing.Warning {
return true
}
return false
}
// operations are submitted to the main loop via commit() for synchronizing
// with Consul.
type operations struct {
regServices []*api.AgentServiceRegistration
regChecks []*api.AgentCheckRegistration
deregServices []string
deregChecks []string
}
func (o *operations) empty() bool {
switch {
case o == nil:
return true
case len(o.regServices) > 0:
return false
case len(o.regChecks) > 0:
return false
case len(o.deregServices) > 0:
return false
case len(o.deregChecks) > 0:
return false
default:
return true
}
}
func (o *operations) String() string {
return fmt.Sprintf("<%d, %d, %d, %d>", len(o.regServices), len(o.regChecks), len(o.deregServices), len(o.deregChecks))
}
// newWeights creates a new Consul AgentWeights struct based on a Nomad ServiceWeights struct.
func newWeights(weights *structs.ServiceWeights) *api.AgentWeights {
if weights == nil {
return nil
}
return &api.AgentWeights{
Passing: weights.Passing,
Warning: weights.Warning,
}
}
type ServiceClientWrapper struct {
serviceClients map[string]*ServiceClient // cluster name -> client
// lock controls access to serviceClients so that we can gracefully reload
// Consul configuration
lock sync.RWMutex
}
func NewServiceClientWrapper() *ServiceClientWrapper {
return &ServiceClientWrapper{
serviceClients: map[string]*ServiceClient{},
}
}
func (scw *ServiceClientWrapper) AddClient(name string, client *ServiceClient) {
scw.lock.Lock()
defer scw.lock.Unlock()
scw.serviceClients[name] = client
}
func (scw *ServiceClientWrapper) Run() {
scw.lock.Lock()
defer scw.lock.Unlock()
for _, serviceClient := range scw.serviceClients {
go serviceClient.Run()
}
}
func (scw *ServiceClientWrapper) Shutdown() error {
scw.lock.Lock()
defer scw.lock.Unlock()
for _, serviceClient := range scw.serviceClients {
// TODO(tgross): we never return error from ServiceClient.Shutdown, so
// there's no point in returning it here either
_ = serviceClient.Shutdown()
}
return nil
}
func (scw *ServiceClientWrapper) RegisterAgent(role string, services []*structs.Service) error {
scw.lock.RLock()
defer scw.lock.RUnlock()
serviceClient, ok := scw.serviceClients[structs.ConsulDefaultCluster]
if !ok {
return errors.New("no default Consul services client")
}
return serviceClient.RegisterAgent(role, services)
}
func (scw *ServiceClientWrapper) RegisterWorkload(workload *serviceregistration.WorkloadServices) error {
scw.lock.RLock()
defer scw.lock.RUnlock()
clusters := scw.clustersInWorkload(workload)
if len(clusters) == 1 {
return scw.serviceClients[clusters[0]].RegisterWorkload(workload)
}
workloadsByCluster := scw.sliceWorkloadsByCluster(workload, clusters)
for cluster, workload := range workloadsByCluster {
err := scw.serviceClients[cluster].RegisterWorkload(workload)
if err != nil {
return err
}
}
return nil
}
func (scw *ServiceClientWrapper) RemoveWorkload(workload *serviceregistration.WorkloadServices) {
scw.lock.RLock()
defer scw.lock.RUnlock()
clusters := scw.clustersInWorkload(workload)
if len(clusters) == 1 {
scw.serviceClients[clusters[0]].RemoveWorkload(workload)
return
}
workloadsByCluster := scw.sliceWorkloadsByCluster(workload, clusters)
for cluster, workload := range workloadsByCluster {
scw.serviceClients[cluster].RemoveWorkload(workload)
}
}
func (scw *ServiceClientWrapper) UpdateWorkload(
old, newTask *serviceregistration.WorkloadServices) error {
scw.lock.RLock()
defer scw.lock.RUnlock()
clusters := scw.clustersInWorkload(newTask)
if len(clusters) == 1 {
return scw.serviceClients[clusters[0]].UpdateWorkload(old, newTask)
}
newWorkloadsByCluster := scw.sliceWorkloadsByCluster(newTask, clusters)
oldWorkloadsByCluster := scw.sliceWorkloadsByCluster(old, clusters)
for cluster, old := range oldWorkloadsByCluster {
newTask := newWorkloadsByCluster[cluster]
err := scw.serviceClients[cluster].UpdateWorkload(old, newTask)
if err != nil {
return err
}
}
return nil
}
func (scw *ServiceClientWrapper) AllocRegistrations(allocID string) (
*serviceregistration.AllocRegistration, error) {
scw.lock.RLock()
defer scw.lock.RUnlock()
// shortcut for non-ENT clients which will never have multiple Consul
// clusters
if len(scw.serviceClients) == 1 {
return scw.serviceClients[structs.ConsulDefaultCluster].AllocRegistrations(allocID)
}
allocReg := &serviceregistration.AllocRegistration{
Tasks: map[string]*serviceregistration.ServiceRegistrations{},
}
for _, serviceClient := range scw.serviceClients {
reg, err := serviceClient.AllocRegistrations(allocID)
if err != nil {
return nil, err
}
if reg != nil {
for t, task := range reg.Tasks {
if a, ok := allocReg.Tasks[t]; !ok {
allocReg.Tasks[t] = task
} else {
for serviceName, service := range task.Services {
a.Services[serviceName] = service
}
}
}
}
}
return allocReg, nil
}
func (scw *ServiceClientWrapper) UpdateTTL(id, namespace, output, status string) error {
scw.lock.RLock()
defer scw.lock.RUnlock()
// shortcut for non-ENT clients which will never have multiple Consul
// clusters
if len(scw.serviceClients) == 1 {
return scw.serviceClients[structs.ConsulDefaultCluster].UpdateTTL(id, namespace, output, status)
}
for _, serviceClient := range scw.serviceClients {
if serviceClient.agentServices.Contains(id) {
return serviceClient.UpdateTTL(id, namespace, output, status)
}
}
return nil
}
// clustersInWorkload returns a de-duplicated set of clusters in the workload,
// always returning at least the default workload
func (scw *ServiceClientWrapper) clustersInWorkload(workload *serviceregistration.WorkloadServices) []string {
clusters := set.From([]string{structs.ConsulDefaultCluster})
for _, service := range workload.Services {
if service.IsConsul() && service.Cluster != "" {
clusters.Insert(service.Cluster)
}
}
return clusters.Slice()
}
// sliceWorkloadsByCluster returns a map of clusters to WorkloadServices. This
// does some expensive copying of the services so callers should check there's
// actually multiple clusters first with clustersInWorkload
func (scw *ServiceClientWrapper) sliceWorkloadsByCluster(workload *serviceregistration.WorkloadServices, clusters []string) map[string]*serviceregistration.WorkloadServices {
workloadsByCluster := make(map[string]*serviceregistration.WorkloadServices, len(clusters))
for _, cluster := range clusters {
clusterWorkload := workload.Copy()
clusterWorkload.Services = slices.DeleteFunc(
clusterWorkload.Services, func(service *structs.Service) bool {
if !service.IsConsul() {
return true
}
if service.Cluster == "" && cluster != structs.ConsulDefaultCluster {
return true
}
if service.Cluster != cluster {
return true
}
return false
})
if len(clusterWorkload.Services) > 0 {
workloadsByCluster[cluster] = clusterWorkload
}
}
return workloadsByCluster
}
// ServiceClient handles task and agent service registration with Consul.
type ServiceClient struct {
agentAPI AgentAPI
namespacesClient *NamespacesClient
logger hclog.Logger
retryInterval time.Duration
maxRetryInterval time.Duration
periodicInterval time.Duration
// exitCh is closed when the main Run loop exits
exitCh chan struct{}
// shutdownCh is closed when the client should shutdown
shutdownCh chan struct{}
// shutdownWait is how long Shutdown() blocks waiting for the final
// sync() to finish. Defaults to defaultShutdownWait
shutdownWait time.Duration
opCh chan *operations
services map[string]*api.AgentServiceRegistration
checks map[string]*api.AgentCheckRegistration
explicitlyDeregisteredServices *set.Set[string]
explicitlyDeregisteredChecks *set.Set[string]
// allocRegistrations stores the services and checks that are registered
// with Consul by allocation ID.
allocRegistrations map[string]*serviceregistration.AllocRegistration
allocRegistrationsLock sync.RWMutex
// serviceTokens is a map of service ID -> Consul tokens,
// where the token is set in the Workload by the client hooks when using
// Workload Identity. Access should be protected by allocRegistrationsLock
serviceTokens map[string]string
serviceTokensLock sync.RWMutex
// Nomad agent services and checks that are recorded so they can be removed
// on shutdown. Defers to consul namespace specified in client consul config.
agentServices *set.Set[string]
agentChecks *set.Set[string]
agentLock sync.Mutex
// seen is 1 if Consul has ever been seen; otherwise 0. Accessed with
// atomics.
seen int32
// deregisterProbationExpiry is the time before which consul sync shouldn't deregister
// unknown services.
// Used to mitigate risk of deleting restored services upon client restart.
deregisterProbationExpiry time.Time
// checkWatcher restarts checks that are unhealthy.
checkWatcher *serviceregistration.UniversalCheckWatcher
// isClientAgent specifies whether this Consul client is being used
// by a Nomad client.
isClientAgent bool
}
// checkStatusGetter is the consul-specific implementation of serviceregistration.CheckStatusGetter
type checkStatusGetter struct {
agentAPI AgentAPI
namespacesClient *NamespacesClient
}
// Get returns the status of checks.
// Note: this query has to use the Nomad agent's own Consul token
func (csg *checkStatusGetter) Get() (map[string]string, error) {
// Get the list of all namespaces so we can iterate them.
namespaces, err := csg.namespacesClient.List()
if err != nil {
return nil, err
}
results := make(map[string]string)
for _, namespace := range namespaces {
resultsInNamespace, err := csg.agentAPI.ChecksWithFilterOpts("", &api.QueryOptions{Namespace: normalizeNamespace(namespace)})
if err != nil {
return nil, err
}
for k, v := range resultsInNamespace {
results[k] = v.Status
}
}
return results, nil
}
// NewServiceClient creates a new Consul ServiceClient from an existing Consul API
// Client, logger and takes whether the client is being used by a Nomad Client agent.
// When being used by a Nomad client, this Consul client reconciles all services and
// checks created by Nomad on behalf of running tasks.
func NewServiceClient(agentAPI AgentAPI, namespacesClient *NamespacesClient, logger hclog.Logger, isNomadClient bool) *ServiceClient {
logger = logger.ResetNamed("consul.sync")
return &ServiceClient{
agentAPI: agentAPI,
namespacesClient: namespacesClient,
logger: logger,
retryInterval: defaultRetryInterval,
maxRetryInterval: defaultMaxRetryInterval,
periodicInterval: defaultPeriodicInterval,
exitCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
shutdownWait: defaultShutdownWait,
opCh: make(chan *operations, 8),
services: make(map[string]*api.AgentServiceRegistration),
checks: make(map[string]*api.AgentCheckRegistration),
explicitlyDeregisteredServices: set.New[string](0),
explicitlyDeregisteredChecks: set.New[string](0),
allocRegistrations: make(map[string]*serviceregistration.AllocRegistration),
serviceTokens: make(map[string]string),
agentServices: set.New[string](4),
agentChecks: set.New[string](0),
isClientAgent: isNomadClient,
deregisterProbationExpiry: time.Now().Add(deregisterProbationPeriod),
checkWatcher: serviceregistration.NewCheckWatcher(logger, &checkStatusGetter{
agentAPI: agentAPI,
namespacesClient: namespacesClient,
}),
}
}
// seen is used by markSeen and hasSeen
const seen = 1
// markSeen marks Consul as having been seen (meaning at least one operation
// has succeeded).
func (c *ServiceClient) markSeen() {
atomic.StoreInt32(&c.seen, seen)
}
// hasSeen returns true if any Consul operation has ever succeeded. Useful to
// squelch errors if Consul isn't running.
func (c *ServiceClient) hasSeen() bool {
return atomic.LoadInt32(&c.seen) == seen
}
// syncReason indicates why a sync operation with consul is about to happen.
//
// The trigger for a sync may have implications on the behavior of the sync itself.
// In particular if a service is defined with enable_tag_override=true, the sync
// should ignore changes to the service's Tags field.
type syncReason byte
const (
syncPeriodic syncReason = iota
syncShutdown
syncNewOps
)
func (sr syncReason) String() string {
switch sr {
case syncPeriodic:
return "periodic"
case syncShutdown:
return "shutdown"
case syncNewOps:
return "operations"
default:
return "unexpected"
}
}
// Run the Consul main loop which retries operations against Consul. It should
// be called exactly once.
func (c *ServiceClient) Run() {
defer close(c.exitCh)
// when Run is shutdown, it needs to complete its current sync before
// shutting down any child goroutines, so we don't use a context from the
// caller to coordinate shutdown of those children here
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// init will be closed when Consul has been contacted
init := make(chan struct{})
go checkConsulTLSSkipVerify(ctx, c.logger, c.agentAPI, init)
// Process operations while waiting for initial contact with Consul but
// do not sync until contact has been made.
INIT:
for {
select {
case <-init:
c.markSeen()
break INIT
case <-c.shutdownCh:
return
case ops := <-c.opCh:
c.merge(ops)
}
}
c.logger.Trace("able to contact Consul")
// Block until contact with Consul has been established
// Start checkWatcher
go c.checkWatcher.Run(ctx)
// Always immediately sync to reconcile Nomad and Consul's state
retryTimer := time.NewTimer(0)
failures := 0
for {
// On every iteration take note of what the trigger for the next sync
// was, so that it may be referenced during the sync itself.
var reasonForSync syncReason
select {
case <-retryTimer.C:
reasonForSync = syncPeriodic
case <-c.shutdownCh:
reasonForSync = syncShutdown
// Cancel check watcher but sync one last time
cancel()
case ops := <-c.opCh:
reasonForSync = syncNewOps
c.merge(ops)
}
if err := c.sync(reasonForSync); err != nil {
if failures == 0 {
// Log on the first failure
c.logger.Warn("failed to update services in Consul", "error", err)
} else if failures%10 == 0 {
// Log every 10th consecutive failure
c.logger.Error("still unable to update services in Consul", "failures", failures, "error", err)
}
failures++
if !retryTimer.Stop() {
// Timer already expired, since the timer may
// or may not have been read in the select{}
// above, conditionally receive on it
select {
case <-retryTimer.C:
default:
}
}
backoff := c.retryInterval * time.Duration(failures)
if backoff > c.maxRetryInterval {
backoff = c.maxRetryInterval
}
retryTimer.Reset(backoff)
} else {
if failures > 0 {
c.logger.Info("successfully updated services in Consul")
failures = 0
}
// on successful sync, clear deregistered consul entities
c.clearExplicitlyDeregistered()
// Reset timer to periodic interval to periodically
// reconile with Consul
if !retryTimer.Stop() {
select {
case <-retryTimer.C:
default:
}
}
retryTimer.Reset(c.periodicInterval)
}
select {
case <-c.shutdownCh:
// Exit only after sync'ing all outstanding operations
if len(c.opCh) > 0 {
for len(c.opCh) > 0 {
c.merge(<-c.opCh)
}
continue
}
return
default:
}
}
}
// commit operations unless already shutting down.
func (c *ServiceClient) commit(ops *operations) {
c.logger.Trace("commit sync operations", "ops", ops)
// Ignore empty operations - ideally callers will optimize out syncs with
// nothing to do, but be defensive anyway. Sending an empty ops on the chan
// will trigger an unnecessary sync with Consul.
if ops.empty() {
return
}
// Prioritize doing nothing if we are being signaled to shutdown.
select {
case <-c.shutdownCh:
return
default:
}
// Send the ops down the ops chan, triggering a sync with Consul. Unless we
// receive a signal to shutdown.
select {
case c.opCh <- ops:
case <-c.shutdownCh:
}
}
func (c *ServiceClient) clearExplicitlyDeregistered() {
c.gcDeregisteredServiceTokens()
c.explicitlyDeregisteredServices = set.New[string](0)
c.explicitlyDeregisteredChecks = set.New[string](0)
}
// merge registrations into state map prior to sync'ing with Consul
func (c *ServiceClient) merge(ops *operations) {
for _, s := range ops.regServices {
c.services[s.ID] = s
}
for _, check := range ops.regChecks {
c.checks[check.ID] = check
}
for _, sid := range ops.deregServices {
delete(c.services, sid)
c.explicitlyDeregisteredServices.Insert(sid)
}
for _, cid := range ops.deregChecks {
delete(c.checks, cid)
c.explicitlyDeregisteredChecks.Insert(cid)
}
metrics.SetGauge([]string{"client", "consul", "services"}, float32(len(c.services)))
metrics.SetGauge([]string{"client", "consul", "checks"}, float32(len(c.checks)))