-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
service.go
1437 lines (1227 loc) · 46.4 KB
/
service.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 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file describes the abstract model of services (and their instances) as
// represented in Istio. This model is independent of the underlying platform
// (Kubernetes, Mesos, etc.). Platform specific adapters found populate the
// model object with various fields, from the metadata found in the platform.
// The platform independent proxy code uses the representation in the model to
// generate the configuration files for the Layer 7 proxy sidecar. The proxy
// code is specific to individual proxy implementations
package model
import (
"fmt"
"net/netip"
"sort"
"strconv"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/mitchellh/copystructure"
"google.golang.org/protobuf/proto"
"k8s.io/apimachinery/pkg/types"
"istio.io/api/label"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/serviceregistry/provider"
"istio.io/istio/pkg/cluster"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/host"
"istio.io/istio/pkg/config/labels"
"istio.io/istio/pkg/config/protocol"
"istio.io/istio/pkg/config/schema/kind"
"istio.io/istio/pkg/config/visibility"
"istio.io/istio/pkg/maps"
pm "istio.io/istio/pkg/model"
"istio.io/istio/pkg/network"
"istio.io/istio/pkg/slices"
"istio.io/istio/pkg/util/sets"
"istio.io/istio/pkg/workloadapi"
"istio.io/istio/pkg/workloadapi/security"
)
// Service describes an Istio service (e.g., catalog.mystore.com:8080)
// Each service has a fully qualified domain name (FQDN) and one or more
// ports where the service is listening for connections. *Optionally*, a
// service can have a single load balancer/virtual IP address associated
// with it, such that the DNS queries for the FQDN resolves to the virtual
// IP address (a load balancer IP).
//
// E.g., in kubernetes, a service foo is associated with
// foo.default.svc.cluster.local hostname, has a virtual IP of 10.0.1.1 and
// listens on ports 80, 8080
type Service struct {
// Attributes contains additional attributes associated with the service
// used mostly by RBAC for policy enforcement purposes.
Attributes ServiceAttributes
// Ports is the set of network ports where the service is listening for
// connections
Ports PortList `json:"ports,omitempty"`
// ServiceAccounts specifies the service accounts that run the service.
ServiceAccounts []string `json:"serviceAccounts,omitempty"`
// CreationTime records the time this service was created, if available.
CreationTime time.Time `json:"creationTime,omitempty"`
// Name of the service, e.g. "catalog.mystore.com"
Hostname host.Name `json:"hostname"`
// ClusterVIPs specifies the service address of the load balancer
// in each of the clusters where the service resides
ClusterVIPs AddressMap `json:"clusterVIPs,omitempty"`
// DefaultAddress specifies the default service IP of the load balancer.
// Do not access directly. Use GetAddressForProxy
DefaultAddress string `json:"defaultAddress,omitempty"`
// AutoAllocatedIPv4Address and AutoAllocatedIPv6Address specifies
// the automatically allocated IPv4/IPv6 address out of the reserved
// Class E subnet (240.240.0.0/16) or reserved Benchmarking IP range
// (2001:2::/48) in RFC5180.for service entries with non-wildcard
// hostnames. The IPs assigned to services are not
// synchronized across istiod replicas as the DNS resolution
// for these service entries happens completely inside a pod
// whose proxy is managed by one istiod. That said, the algorithm
// to allocate IPs is pretty deterministic that at stable state, two
// istiods will allocate the exact same set of IPs for a given set of
// service entries.
AutoAllocatedIPv4Address string `json:"autoAllocatedIPv4Address,omitempty"`
AutoAllocatedIPv6Address string `json:"autoAllocatedIPv6Address,omitempty"`
// Resolution indicates how the service instances need to be resolved before routing
// traffic. Most services in the service registry will use static load balancing wherein
// the proxy will decide the service instance that will receive the traffic. Service entries
// could either use DNS load balancing (i.e. proxy will query DNS server for the IP of the service)
// or use the passthrough model (i.e. proxy will forward the traffic to the network endpoint requested
// by the caller)
Resolution Resolution
// MeshExternal (if true) indicates that the service is external to the mesh.
// These services are defined using Istio's ServiceEntry spec.
MeshExternal bool
// ResourceVersion represents the internal version of this object.
ResourceVersion string
}
func (s *Service) NamespacedName() types.NamespacedName {
return types.NamespacedName{Name: s.Attributes.Name, Namespace: s.Attributes.Namespace}
}
func (s *Service) Key() string {
if s == nil {
return ""
}
return s.Attributes.Namespace + "/" + string(s.Hostname)
}
var serviceCmpOpts = []cmp.Option{cmpopts.IgnoreFields(AddressMap{}, "mutex")}
func (s *Service) CmpOpts() []cmp.Option {
return serviceCmpOpts
}
// Resolution indicates how the service instances need to be resolved before routing traffic.
type Resolution int
const (
// ClientSideLB implies that the proxy will decide the endpoint from its local lb pool
ClientSideLB Resolution = iota
// DNSLB implies that the proxy will resolve a DNS address and forward to the resolved address
DNSLB
// Passthrough implies that the proxy should forward traffic to the destination IP requested by the caller
Passthrough
// DNSRoundRobinLB implies that the proxy will resolve a DNS address and forward to the resolved address
DNSRoundRobinLB
// Alias defines a Service that is an alias for another.
Alias
)
// String converts Resolution in to String.
func (resolution Resolution) String() string {
switch resolution {
case ClientSideLB:
return "ClientSide"
case DNSLB:
return "DNS"
case DNSRoundRobinLB:
return "DNSRoundRobin"
case Passthrough:
return "Passthrough"
default:
return fmt.Sprintf("%d", int(resolution))
}
}
const (
// LocalityLabel indicates the region/zone/subzone of an instance. It is used to override the native
// registry's value.
//
// Note: because k8s labels does not support `/`, so we use `.` instead in k8s.
LocalityLabel = pm.LocalityLabel
)
const (
// TunnelLabel defines the label workloads describe to indicate that they support tunneling.
// Values are expected to be a CSV list, sorted by preference, of protocols supported.
// Currently supported values:
// * "http": indicates tunneling over HTTP over TCP. HTTP/2 vs HTTP/1.1 may be supported by ALPN negotiation.
// Planned future values:
// * "http3": indicates tunneling over HTTP over QUIC. This is distinct from "http", since we cannot do ALPN
// negotiation for QUIC vs TCP.
// Users should appropriately parse the full list rather than doing a string literal check to
// ensure future-proofing against new protocols being added.
TunnelLabel = "networking.istio.io/tunnel"
// TunnelLabelShortName is a short name for TunnelLabel to be used in optimized scenarios.
TunnelLabelShortName = "tunnel"
// TunnelHTTP indicates tunneling over HTTP over TCP. HTTP/2 vs HTTP/1.1 may be supported by ALPN
// negotiation. Note: ALPN negotiation is not currently implemented; HTTP/2 will always be used.
// This is future-proofed, however, because only the `h2` ALPN is exposed.
TunnelHTTP = "http"
)
const (
// TLSModeLabelShortname name used for determining endpoint level tls transport socket configuration
TLSModeLabelShortname = "tlsMode"
// DisabledTLSModeLabel implies that this endpoint should receive traffic as is (mostly plaintext)
DisabledTLSModeLabel = "disabled"
// IstioMutualTLSModeLabel implies that the endpoint is ready to receive Istio mTLS connections.
IstioMutualTLSModeLabel = "istio"
// IstioCanonicalServiceLabelName is the name of label for the Istio Canonical Service for a workload instance.
IstioCanonicalServiceLabelName = pm.IstioCanonicalServiceLabelName
// IstioCanonicalServiceRevisionLabelName is the name of label for the Istio Canonical Service revision for a workload instance.
IstioCanonicalServiceRevisionLabelName = pm.IstioCanonicalServiceRevisionLabelName
)
func SupportsTunnel(labels map[string]string, tunnelType string) bool {
return sets.New(strings.Split(labels[TunnelLabel], ",")...).Contains(tunnelType)
}
// Port represents a network port where a service is listening for
// connections. The port should be annotated with the type of protocol
// used by the port.
type Port struct {
// Name ascribes a human readable name for the port object. When a
// service has multiple ports, the name field is mandatory
Name string `json:"name,omitempty"`
// Port number where the service can be reached. Does not necessarily
// map to the corresponding port numbers for the instances behind the
// service.
Port int `json:"port"`
// Protocol to be used for the port.
Protocol protocol.Instance `json:"protocol,omitempty"`
}
func (p Port) String() string {
return fmt.Sprintf("Name:%s Port:%d Protocol:%v", p.Name, p.Port, p.Protocol)
}
// PortList is a set of ports
type PortList []*Port
// TrafficDirection defines whether traffic exists a service instance or enters a service instance
type TrafficDirection string
const (
// TrafficDirectionInbound indicates inbound traffic
TrafficDirectionInbound TrafficDirection = "inbound"
// TrafficDirectionInboundVIP indicates inbound traffic for vip
TrafficDirectionInboundVIP TrafficDirection = "inbound-vip"
// TrafficDirectionOutbound indicates outbound traffic
TrafficDirectionOutbound TrafficDirection = "outbound"
// trafficDirectionOutboundSrvPrefix the prefix for a DNS SRV type subset key
trafficDirectionOutboundSrvPrefix = string(TrafficDirectionOutbound) + "_"
// trafficDirectionInboundSrvPrefix the prefix for a DNS SRV type subset key
trafficDirectionInboundSrvPrefix = string(TrafficDirectionInbound) + "_"
)
// ServiceInstance represents an individual instance of a specific version
// of a service. It binds a network endpoint (ip:port), the service
// description (which is oblivious to various versions) and a set of labels
// that describe the service version associated with this instance.
//
// Since a ServiceInstance has a single IstioEndpoint, which has a single port,
// multiple ServiceInstances are required to represent a workload that listens
// on multiple ports.
//
// The labels associated with a service instance are unique per a network endpoint.
// There is one well defined set of labels for each service instance network endpoint.
//
// For example, the set of service instances associated with catalog.mystore.com
// are modeled like this
//
// --> IstioEndpoint(172.16.0.1:8888), Service(catalog.myservice.com), Labels(foo=bar)
// --> IstioEndpoint(172.16.0.2:8888), Service(catalog.myservice.com), Labels(foo=bar)
// --> IstioEndpoint(172.16.0.3:8888), Service(catalog.myservice.com), Labels(kitty=cat)
// --> IstioEndpoint(172.16.0.4:8888), Service(catalog.myservice.com), Labels(kitty=cat)
type ServiceInstance struct {
Service *Service `json:"service,omitempty"`
ServicePort *Port `json:"servicePort,omitempty"`
Endpoint *IstioEndpoint `json:"endpoint,omitempty"`
}
func (instance *ServiceInstance) CmpOpts() []cmp.Option {
res := []cmp.Option{}
res = append(res, istioEndpointCmpOpts...)
res = append(res, serviceCmpOpts...)
return res
}
// ServiceTarget includes a Service object, along with a specific service port
// and target port. This is basically a smaller version of ServiceInstance,
// intended to avoid the need to have the full object when only port information
// is needed.
type ServiceTarget struct {
Service *Service
Port ServiceInstancePort
}
func (st ServiceTarget) NamespacedName() types.NamespacedName {
return st.Service.NamespacedName()
}
type (
ServicePort = *Port
// ServiceInstancePort defines a port that has both a port and targetPort (which distinguishes it from model.Port)
// Note: ServiceInstancePort only makes sense in the context of a specific ServiceInstance, because TargetPort depends on a specific instance.
ServiceInstancePort struct {
ServicePort
TargetPort uint32
}
)
func ServiceInstanceToTarget(e *ServiceInstance) ServiceTarget {
return ServiceTarget{
Service: e.Service,
Port: ServiceInstancePort{
ServicePort: e.ServicePort,
TargetPort: e.Endpoint.EndpointPort,
},
}
}
// DeepCopy creates a copy of ServiceInstance.
func (instance *ServiceInstance) DeepCopy() *ServiceInstance {
return &ServiceInstance{
Service: instance.Service.DeepCopy(),
Endpoint: instance.Endpoint.DeepCopy(),
ServicePort: &Port{
Name: instance.ServicePort.Name,
Port: instance.ServicePort.Port,
Protocol: instance.ServicePort.Protocol,
},
}
}
type workloadKind int
const (
// PodKind indicates the workload is from pod
PodKind workloadKind = iota
// WorkloadEntryKind indicates the workload is from workloadentry
WorkloadEntryKind
)
func (k workloadKind) String() string {
if k == PodKind {
return "Pod"
}
if k == WorkloadEntryKind {
return "WorkloadEntry"
}
return ""
}
type WorkloadInstance struct {
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
// Where the workloadInstance come from, valid values are`Pod` or `WorkloadEntry`
Kind workloadKind `json:"kind"`
Endpoint *IstioEndpoint `json:"endpoint,omitempty"`
PortMap map[string]uint32 `json:"portMap,omitempty"`
// Can only be selected by service entry of DNS type.
DNSServiceEntryOnly bool `json:"dnsServiceEntryOnly,omitempty"`
}
func (instance *WorkloadInstance) CmpOpts() []cmp.Option {
return istioEndpointCmpOpts
}
// DeepCopy creates a copy of WorkloadInstance.
func (instance *WorkloadInstance) DeepCopy() *WorkloadInstance {
pmap := map[string]uint32{}
for k, v := range instance.PortMap {
pmap[k] = v
}
return &WorkloadInstance{
Name: instance.Name,
Namespace: instance.Namespace,
Kind: instance.Kind,
PortMap: pmap,
Endpoint: instance.Endpoint.DeepCopy(),
}
}
// WorkloadInstancesEqual is a custom comparison of workload instances based on the fields that we need.
// Returns true if equal, false otherwise.
func WorkloadInstancesEqual(first, second *WorkloadInstance) bool {
if first.Endpoint == nil || second.Endpoint == nil {
return first.Endpoint == second.Endpoint
}
if first.Endpoint.Address != second.Endpoint.Address {
return false
}
if first.Endpoint.Network != second.Endpoint.Network {
return false
}
if first.Endpoint.TLSMode != second.Endpoint.TLSMode {
return false
}
if !first.Endpoint.Labels.Equals(second.Endpoint.Labels) {
return false
}
if first.Endpoint.ServiceAccount != second.Endpoint.ServiceAccount {
return false
}
if first.Endpoint.Locality != second.Endpoint.Locality {
return false
}
if first.Endpoint.GetLoadBalancingWeight() != second.Endpoint.GetLoadBalancingWeight() {
return false
}
if first.Namespace != second.Namespace {
return false
}
if first.Name != second.Name {
return false
}
if first.Kind != second.Kind {
return false
}
if !maps.Equal(first.PortMap, second.PortMap) {
return false
}
return true
}
// GetLocalityLabel returns the locality from the supplied label. Because Kubernetes
// labels don't support `/`, we replace "." with "/" in the supplied label as a workaround.
func GetLocalityLabel(label string) string {
return pm.GetLocalityLabel(label)
}
// Locality information for an IstioEndpoint
type Locality struct {
// Label for locality on the endpoint. This is a "/" separated string.
Label string
// ClusterID where the endpoint is located
ClusterID cluster.ID
}
// Endpoint health status.
type HealthStatus int32
const (
// Healthy.
Healthy HealthStatus = 1
// Unhealthy.
UnHealthy HealthStatus = 2
// Draining - the constant matches envoy
Draining HealthStatus = 3
)
// IstioEndpoint defines a network address (IP:port) associated with an instance of the
// service. A service has one or more instances each running in a
// container/VM/pod. If a service has multiple ports, then the same
// instance IP is expected to be listening on multiple ports (one per each
// service port). Note that the port associated with an instance does not
// have to be the same as the port associated with the service. Depending
// on the network setup (NAT, overlays), this could vary.
//
// For e.g., if catalog.mystore.com is accessible through port 80 and 8080,
// and it maps to an instance with IP 172.16.0.1, such that connections to
// port 80 are forwarded to port 55446, and connections to port 8080 are
// forwarded to port 33333,
//
// then internally, we have two endpoint structs for the
// service catalog.mystore.com
//
// --> 172.16.0.1:55446 (with ServicePort pointing to 80) and
// --> 172.16.0.1:33333 (with ServicePort pointing to 8080)
//
// TODO: Investigate removing ServiceInstance entirely.
type IstioEndpoint struct {
// Labels points to the workload or deployment labels.
Labels labels.Instance
// Address is the address of the endpoint, using envoy proto.
Address string
// ServicePortName tracks the name of the port, this is used to select the IstioEndpoint by service port.
ServicePortName string
// LegacyClusterPortKey provides an alternative key from ServicePortName to support legacy quirks in the API.
// Basically, EDS merges by port name, but CDS historically ignored port name and matched on number.
// Note that for Kubernetes Service, this is identical - its only ServiceEntry where these checks can differ
LegacyClusterPortKey int
// ServiceAccount holds the associated service account.
ServiceAccount string
// Network holds the network where this endpoint is present
Network network.ID
// The locality where the endpoint is present.
Locality Locality
// EndpointPort is the port where the workload is listening, can be different
// from the service port.
EndpointPort uint32
// The load balancing weight associated with this endpoint.
LbWeight uint32
// TLSMode endpoint is injected with istio sidecar and ready to configure Istio mTLS
TLSMode string
// Namespace that this endpoint belongs to. This is for telemetry purpose.
Namespace string
// Name of the workload that this endpoint belongs to. This is for telemetry purpose.
WorkloadName string
// Specifies the hostname of the Pod, empty for vm workload.
HostName string
// If specified, the fully qualified Pod hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>".
SubDomain string
// Determines the discoverability of this endpoint throughout the mesh.
DiscoverabilityPolicy EndpointDiscoverabilityPolicy `json:"-"`
// Indicates the endpoint health status.
HealthStatus HealthStatus
// If in k8s, the node where the pod resides
NodeName string
}
func (ep *IstioEndpoint) SupportsTunnel(tunnelType string) bool {
return SupportsTunnel(ep.Labels, tunnelType)
}
// GetLoadBalancingWeight returns the weight for this endpoint, normalized to always be > 0.
func (ep *IstioEndpoint) GetLoadBalancingWeight() uint32 {
if ep.LbWeight > 0 {
return ep.LbWeight
}
return 1
}
// IsDiscoverableFromProxy indicates whether this endpoint is discoverable from the given Proxy.
func (ep *IstioEndpoint) IsDiscoverableFromProxy(p *Proxy) bool {
if ep == nil || ep.DiscoverabilityPolicy == nil {
// If no policy was assigned, default to discoverable mesh-wide.
// TODO(nmittler): Will need to re-think this default when cluster.local is actually cluster-local.
return true
}
return ep.DiscoverabilityPolicy.IsDiscoverableFromProxy(ep, p)
}
// MetadataClone returns the cloned endpoint metadata used for telemetry purposes.
// This should be used when the endpoint labels should be updated.
func (ep *IstioEndpoint) MetadataClone() *EndpointMetadata {
return &EndpointMetadata{
Network: ep.Network,
TLSMode: ep.TLSMode,
WorkloadName: ep.WorkloadName,
Namespace: ep.Namespace,
Labels: maps.Clone(ep.Labels),
ClusterID: ep.Locality.ClusterID,
}
}
// Metadata returns the endpoint metadata used for telemetry purposes.
func (ep *IstioEndpoint) Metadata() *EndpointMetadata {
return &EndpointMetadata{
Network: ep.Network,
TLSMode: ep.TLSMode,
WorkloadName: ep.WorkloadName,
Namespace: ep.Namespace,
Labels: ep.Labels,
ClusterID: ep.Locality.ClusterID,
}
}
var istioEndpointCmpOpts = []cmp.Option{cmpopts.IgnoreUnexported(IstioEndpoint{}), endpointDiscoverabilityPolicyImplCmpOpt, cmp.AllowUnexported()}
func (ep *IstioEndpoint) CmpOpts() []cmp.Option {
return istioEndpointCmpOpts
}
// EndpointMetadata represents metadata set on Envoy LbEndpoint used for telemetry purposes.
type EndpointMetadata struct {
// Network holds the network where this endpoint is present
Network network.ID
// TLSMode endpoint is injected with istio sidecar and ready to configure Istio mTLS
TLSMode string
// Name of the workload that this endpoint belongs to. This is for telemetry purpose.
WorkloadName string
// Namespace that this endpoint belongs to. This is for telemetry purpose.
Namespace string
// Labels points to the workload or deployment labels.
Labels labels.Instance
// ClusterID where the endpoint is located
ClusterID cluster.ID
}
// EndpointDiscoverabilityPolicy determines the discoverability of an endpoint throughout the mesh.
type EndpointDiscoverabilityPolicy interface {
// IsDiscoverableFromProxy indicates whether an endpoint is discoverable from the given Proxy.
IsDiscoverableFromProxy(*IstioEndpoint, *Proxy) bool
// String returns name of this policy.
String() string
}
type endpointDiscoverabilityPolicyImpl struct {
name string
f func(*IstioEndpoint, *Proxy) bool
}
func (p *endpointDiscoverabilityPolicyImpl) IsDiscoverableFromProxy(ep *IstioEndpoint, proxy *Proxy) bool {
return p.f(ep, proxy)
}
func (p *endpointDiscoverabilityPolicyImpl) String() string {
return p.name
}
var endpointDiscoverabilityPolicyImplCmpOpt = cmp.Comparer(func(x, y endpointDiscoverabilityPolicyImpl) bool {
return x.String() == y.String()
})
func (p *endpointDiscoverabilityPolicyImpl) CmpOpts() []cmp.Option {
return []cmp.Option{endpointDiscoverabilityPolicyImplCmpOpt}
}
// AlwaysDiscoverable is an EndpointDiscoverabilityPolicy that allows an endpoint to be discoverable throughout the mesh.
var AlwaysDiscoverable EndpointDiscoverabilityPolicy = &endpointDiscoverabilityPolicyImpl{
name: "AlwaysDiscoverable",
f: func(*IstioEndpoint, *Proxy) bool {
return true
},
}
// DiscoverableFromSameCluster is an EndpointDiscoverabilityPolicy that only allows an endpoint to be discoverable
// from proxies within the same cluster.
var DiscoverableFromSameCluster EndpointDiscoverabilityPolicy = &endpointDiscoverabilityPolicyImpl{
name: "DiscoverableFromSameCluster",
f: func(ep *IstioEndpoint, p *Proxy) bool {
return p.InCluster(ep.Locality.ClusterID)
},
}
// ServiceAttributes represents a group of custom attributes of the service.
type ServiceAttributes struct {
// ServiceRegistry indicates the backing service registry system where this service
// was sourced from.
// TODO: move the ServiceRegistry type from platform.go to model
ServiceRegistry provider.ID
// Name is "destination.service.name" attribute
Name string
// Namespace is "destination.service.namespace" attribute
Namespace string
// Labels applied to the service
Labels map[string]string
// ExportTo defines the visibility of Service in
// a namespace when the namespace is imported.
ExportTo sets.Set[visibility.Instance]
// LabelSelectors are the labels used by the service to select workloads.
// Applicable to both Kubernetes and ServiceEntries.
LabelSelectors map[string]string
// Aliases is the resolved set of aliases for this service. This is computed based on a global view of all Service's `AliasFor`
// fields.
// For example, if I had two Services with `externalName: foo`, "a" and "b", then the "foo" service would have Aliases=[a,b].
Aliases []NamespacedHostname
// For Kubernetes platform
// ClusterExternalAddresses is a mapping between a cluster name and the external
// address(es) to access the service from outside the cluster.
// Used by the aggregator to aggregate the Attributes.ClusterExternalAddresses
// for clusters where the service resides
ClusterExternalAddresses *AddressMap
// ClusterExternalPorts is a mapping between a cluster name and the service port
// to node port mappings for a given service. When accessing the service via
// node port IPs, we need to use the kubernetes assigned node ports of the service
// The port that the user provides in the meshNetworks config is the service port.
// We translate that to the appropriate node port here.
ClusterExternalPorts map[cluster.ID]map[uint32]uint32
PassthroughTargetPorts map[uint32]uint32
K8sAttributes
}
type NamespacedHostname struct {
Hostname host.Name
Namespace string
}
type K8sAttributes struct {
// Type holds the value of the corev1.Type of the Kubernetes service
// spec.Type
Type string
// spec.ExternalName
ExternalName string
// NodeLocal means the proxy will only forward traffic to node local endpoints
// spec.InternalTrafficPolicy == Local
NodeLocal bool
}
// DeepCopy creates a deep copy of ServiceAttributes, but skips internal mutexes.
func (s *ServiceAttributes) DeepCopy() ServiceAttributes {
// AddressMap contains a mutex, which is safe to copy in this case.
// nolint: govet
out := *s
if s.Labels != nil {
out.Labels = make(map[string]string, len(s.Labels))
for k, v := range s.Labels {
out.Labels[k] = v
}
}
if s.ExportTo != nil {
out.ExportTo = s.ExportTo.Copy()
}
if s.LabelSelectors != nil {
out.LabelSelectors = make(map[string]string, len(s.LabelSelectors))
for k, v := range s.LabelSelectors {
out.LabelSelectors[k] = v
}
}
out.ClusterExternalAddresses = s.ClusterExternalAddresses.DeepCopy()
if s.ClusterExternalPorts != nil {
out.ClusterExternalPorts = make(map[cluster.ID]map[uint32]uint32, len(s.ClusterExternalPorts))
for k, m := range s.ClusterExternalPorts {
if m == nil {
out.ClusterExternalPorts[k] = nil
continue
}
out.ClusterExternalPorts[k] = make(map[uint32]uint32, len(m))
for sp, np := range m {
out.ClusterExternalPorts[k][sp] = np
}
}
}
out.Aliases = slices.Clone(s.Aliases)
// AddressMap contains a mutex, which is safe to return a copy in this case.
// nolint: govet
return out
}
// Equals checks whether the attributes are equal from the passed in service.
func (s *ServiceAttributes) Equals(other *ServiceAttributes) bool {
if s == nil {
return other == nil
}
if other == nil {
return s == nil
}
if !maps.Equal(s.Labels, other.Labels) {
return false
}
if !maps.Equal(s.LabelSelectors, other.LabelSelectors) {
return false
}
if !maps.Equal(s.ExportTo, other.ExportTo) {
return false
}
if !slices.Equal(s.Aliases, other.Aliases) {
return false
}
if s.ClusterExternalAddresses.Len() != other.ClusterExternalAddresses.Len() {
return false
}
for k, v1 := range s.ClusterExternalAddresses.GetAddresses() {
if v2, ok := other.ClusterExternalAddresses.Addresses[k]; !ok || !slices.Equal(v1, v2) {
return false
}
}
if len(s.ClusterExternalPorts) != len(other.ClusterExternalPorts) {
return false
}
for k, v1 := range s.ClusterExternalPorts {
if v2, ok := s.ClusterExternalPorts[k]; !ok || !maps.Equal(v1, v2) {
return false
}
}
return s.Name == other.Name && s.Namespace == other.Namespace &&
s.ServiceRegistry == other.ServiceRegistry && s.K8sAttributes == other.K8sAttributes
}
// ServiceDiscovery enumerates Istio service instances.
// nolint: lll
type ServiceDiscovery interface {
NetworkGatewaysWatcher
// Services list declarations of all services in the system
Services() []*Service
// GetService retrieves a service by host name if it exists
GetService(hostname host.Name) *Service
// GetProxyServiceTargets returns the service targets that co-located with a given Proxy
//
// Co-located generally means running in the same network namespace and security context.
//
// A Proxy operating as a Sidecar will return a non-empty slice. A stand-alone Proxy
// will return an empty slice.
//
// There are two reasons why this returns multiple ServiceTargets instead of one:
// - A ServiceTargets has a single Port. But a Service
// may have many ports. So a workload implementing such a Service would need
// multiple ServiceTargets, one for each port.
// - A single workload may implement multiple logical Services.
//
// In the second case, multiple services may be implemented by the same physical port number,
// though with a different ServicePort and IstioEndpoint for each. If any of these overlapping
// services are not HTTP or H2-based, behavior is undefined, since the listener may not be able to
// determine the intended destination of a connection without a Host header on the request.
GetProxyServiceTargets(*Proxy) []ServiceTarget
GetProxyWorkloadLabels(*Proxy) labels.Instance
// MCSServices returns information about the services that have been exported/imported via the
// Kubernetes Multi-Cluster Services (MCS) ServiceExport API. Only applies to services in
// Kubernetes clusters.
MCSServices() []MCSServiceInfo
AmbientIndexes
}
type AmbientIndexes interface {
AddressInformation(addresses sets.String) ([]AddressInfo, sets.String)
AdditionalPodSubscriptions(
proxy *Proxy,
allAddresses sets.String,
currentSubs sets.String,
) sets.String
Policies(requested sets.Set[ConfigKey]) []WorkloadAuthorization
ServicesForWaypoint(WaypointKey) []ServiceInfo
WorkloadsForWaypoint(WaypointKey) []WorkloadInfo
}
// WaypointKey is a multi-address extension of NetworkAddress which is commonly used for lookups in AmbientIndex
// We likely need to consider alternative keying options internally such as hostname as we look to expand beyong istio-waypoint
// This extension can ideally support that type of lookup in the interface without introducing scope creep into things
// like NetworkAddress
type WaypointKey struct {
Network string
Addresses []string
}
// WaypointKey contains all of the VIPs that the Proxy serves.
func WaypointKeyForProxy(node *Proxy) WaypointKey {
// TODO IP based lookup should switch to looking up services by name/ns
key := WaypointKey{
Network: node.Metadata.Network.String(),
}
for _, svct := range node.ServiceTargets {
ips := svct.Service.ClusterVIPs.GetAddressesFor(node.GetClusterID())
key.Addresses = append(key.Addresses, ips...)
}
return key
}
// NoopAmbientIndexes provides an implementation of AmbientIndexes that always returns nil, to easily "skip" it.
type NoopAmbientIndexes struct{}
func (u NoopAmbientIndexes) AddressInformation(sets.String) ([]AddressInfo, sets.String) {
return nil, nil
}
func (u NoopAmbientIndexes) AdditionalPodSubscriptions(
*Proxy,
sets.String,
sets.String,
) sets.String {
return nil
}
func (u NoopAmbientIndexes) Policies(sets.Set[ConfigKey]) []WorkloadAuthorization {
return nil
}
func (u NoopAmbientIndexes) ServicesForWaypoint(WaypointKey) []ServiceInfo {
return nil
}
func (u NoopAmbientIndexes) Waypoint(string, string) []netip.Addr {
return nil
}
func (u NoopAmbientIndexes) WorkloadsForWaypoint(WaypointKey) []WorkloadInfo {
return nil
}
var _ AmbientIndexes = NoopAmbientIndexes{}
type AddressInfo struct {
*workloadapi.Address
}
func (i AddressInfo) Aliases() []string {
switch addr := i.Type.(type) {
case *workloadapi.Address_Workload:
aliases := make([]string, 0, len(addr.Workload.Addresses))
network := addr.Workload.Network
for _, workloadAddr := range addr.Workload.Addresses {
ip, _ := netip.AddrFromSlice(workloadAddr)
aliases = append(aliases, network+"/"+ip.String())
}
return aliases
case *workloadapi.Address_Service:
aliases := make([]string, 0, len(addr.Service.Addresses))
for _, networkAddr := range addr.Service.Addresses {
ip, _ := netip.AddrFromSlice(networkAddr.Address)
aliases = append(aliases, networkAddr.Network+"/"+ip.String())
}
return aliases
}
return nil
}
func (i AddressInfo) ResourceName() string {
var name string
switch addr := i.Type.(type) {
case *workloadapi.Address_Workload:
name = workloadResourceName(addr.Workload)
case *workloadapi.Address_Service:
name = serviceResourceName(addr.Service)
}
return name
}
type ServicePortName struct {
PortName string
TargetPortName string
}
type ServiceInfo struct {
*workloadapi.Service
// LabelSelectors for the Service. Note these are only used internally, not sent over XDS
LabelSelector
// PortNames provides a mapping of ServicePort -> port names. Note these are only used internally, not sent over XDS
PortNames map[int32]ServicePortName
// Source is the type that introduced this service.
Source kind.Kind
// Waypoint that clients should use when addressing traffic to this Service.
Waypoint string
}
func (i ServiceInfo) NamespacedName() types.NamespacedName {
return types.NamespacedName{Name: i.Name, Namespace: i.Namespace}
}
func (i ServiceInfo) Equals(other ServiceInfo) bool {
return proto.Equal(i.Service, other.Service) &&
maps.Equal(i.LabelSelector.Labels, other.LabelSelector.Labels) &&
maps.Equal(i.PortNames, other.PortNames) &&
i.Source == other.Source
}
func (i ServiceInfo) ResourceName() string {
return serviceResourceName(i.Service)
}
func serviceResourceName(s *workloadapi.Service) string {
return s.Namespace + "/" + s.Hostname
}
type WorkloadSource string
type WorkloadInfo struct {
*workloadapi.Workload
// Labels for the workload. Note these are only used internally, not sent over XDS
Labels map[string]string
// Source is the type that introduced this workload.
Source kind.Kind
// CreationTime is the time when the workload was created. Note this is used internally only.