-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
conversion.go
463 lines (426 loc) · 16.7 KB
/
conversion.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
// 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.
package serviceentry
import (
"net/netip"
"strings"
"time"
"istio.io/api/label"
networking "istio.io/api/networking/v1alpha3"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pilot/pkg/serviceregistry/provider"
labelutil "istio.io/istio/pilot/pkg/serviceregistry/util/label"
"istio.io/istio/pkg/cluster"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/host"
"istio.io/istio/pkg/config/protocol"
"istio.io/istio/pkg/config/schema/gvk"
"istio.io/istio/pkg/config/visibility"
"istio.io/istio/pkg/kube/labels"
"istio.io/istio/pkg/network"
"istio.io/istio/pkg/spiffe"
netutil "istio.io/istio/pkg/util/net"
"istio.io/istio/pkg/util/sets"
)
func convertPort(port *networking.ServicePort) *model.Port {
return &model.Port{
Name: port.Name,
Port: int(port.Number),
Protocol: protocol.Parse(port.Protocol),
}
}
type HostAddress struct {
host string
address string
}
// ServiceToServiceEntry converts from internal Service representation to ServiceEntry
// This does not include endpoints - they'll be represented as EndpointSlice or EDS.
//
// See convertServices() for the reverse conversion, used by Istio to handle ServiceEntry configs.
// See kube.ConvertService for the conversion from K8S to internal Service.
func ServiceToServiceEntry(svc *model.Service, proxy *model.Proxy) *config.Config {
gvk := gvk.ServiceEntry
se := &networking.ServiceEntry{
// Host is fully qualified: name, namespace, domainSuffix
Hosts: []string{string(svc.Hostname)},
// Internal Service and K8S Service have a single Address.
// ServiceEntry can represent multiple - but we are not using that. SE may be merged.
// Will be 0.0.0.0 if not specified as ClusterIP or ClusterIP==None. In such case resolution is Passthrough.
Addresses: svc.GetAddresses(proxy),
// This is based on alpha.istio.io/canonical-serviceaccounts and
// alpha.istio.io/kubernetes-serviceaccounts.
SubjectAltNames: svc.ServiceAccounts,
}
if len(svc.Attributes.LabelSelectors) > 0 {
se.WorkloadSelector = &networking.WorkloadSelector{Labels: svc.Attributes.LabelSelectors}
}
// Based on networking.istio.io/exportTo annotation
for k := range svc.Attributes.ExportTo {
// k is Private or Public
se.ExportTo = append(se.ExportTo, string(k))
}
if svc.MeshExternal {
se.Location = networking.ServiceEntry_MESH_EXTERNAL // 0 - default
} else {
se.Location = networking.ServiceEntry_MESH_INTERNAL
}
// Reverse in convertServices. Note that enum values are different
var resolution networking.ServiceEntry_Resolution
switch svc.Resolution {
case model.Passthrough: // 2
resolution = networking.ServiceEntry_NONE // 0
case model.DNSLB: // 1
resolution = networking.ServiceEntry_DNS // 2
case model.DNSRoundRobinLB: // 3
resolution = networking.ServiceEntry_DNS_ROUND_ROBIN // 3
case model.ClientSideLB: // 0
resolution = networking.ServiceEntry_STATIC // 1
}
se.Resolution = resolution
// Port is mapped from ServicePort
for _, p := range svc.Ports {
se.Ports = append(se.Ports, &networking.ServicePort{
Number: uint32(p.Port),
Name: p.Name,
// Protocol is converted to protocol.Instance - reverse conversion will use the name.
Protocol: string(p.Protocol),
// TODO: target port
})
}
cfg := &config.Config{
Meta: config.Meta{
GroupVersionKind: gvk,
Name: "synthetic-" + svc.Attributes.Name,
Namespace: svc.Attributes.Namespace,
CreationTimestamp: svc.CreationTime,
ResourceVersion: svc.ResourceVersion,
},
Spec: se,
}
// TODO: WorkloadSelector
// TODO: preserve ServiceRegistry. The reverse conversion sets it to 'external'
// TODO: preserve UID ? It seems MCP didn't preserve it - but that code path was not used much.
// TODO: ClusterExternalPorts map - for NodePort services, with "traffic.istio.io/nodeSelector" ann
// It's a per-cluster map
// TODO: ClusterExternalAddresses - for LB types, per cluster. Populated from K8S, missing
// in SE. Used for multi-network support.
return cfg
}
// convertServices transforms a ServiceEntry config to a list of internal Service objects.
func convertServices(cfg config.Config) []*model.Service {
serviceEntry := cfg.Spec.(*networking.ServiceEntry)
creationTime := cfg.CreationTimestamp
var resolution model.Resolution
switch serviceEntry.Resolution {
case networking.ServiceEntry_NONE:
resolution = model.Passthrough
case networking.ServiceEntry_DNS:
resolution = model.DNSLB
case networking.ServiceEntry_DNS_ROUND_ROBIN:
resolution = model.DNSRoundRobinLB
case networking.ServiceEntry_STATIC:
resolution = model.ClientSideLB
}
svcPorts := make(model.PortList, 0, len(serviceEntry.Ports))
var portOverrides map[uint32]uint32
for _, port := range serviceEntry.Ports {
svcPorts = append(svcPorts, convertPort(port))
if resolution == model.Passthrough && port.TargetPort != 0 {
if portOverrides == nil {
portOverrides = map[uint32]uint32{}
}
portOverrides[port.Number] = port.TargetPort
}
}
var exportTo sets.Set[visibility.Instance]
if len(serviceEntry.ExportTo) > 0 {
exportTo = sets.NewWithLength[visibility.Instance](len(serviceEntry.ExportTo))
for _, e := range serviceEntry.ExportTo {
exportTo.Insert(visibility.Instance(e))
}
}
var labelSelectors map[string]string
if serviceEntry.WorkloadSelector != nil {
labelSelectors = serviceEntry.WorkloadSelector.Labels
}
hostAddresses := []*HostAddress{}
for _, hostname := range serviceEntry.Hosts {
if len(serviceEntry.Addresses) > 0 {
for _, address := range serviceEntry.Addresses {
// Check if address is an IP first because that is the most common case.
if netutil.IsValidIPAddress(address) {
hostAddresses = append(hostAddresses, &HostAddress{hostname, address})
} else if cidr, cidrErr := netip.ParsePrefix(address); cidrErr == nil {
newAddress := address
if cidr.Bits() == cidr.Addr().BitLen() {
// /32 mask. Remove the /32 and make it a normal IP address
newAddress = cidr.Addr().String()
}
hostAddresses = append(hostAddresses, &HostAddress{hostname, newAddress})
}
}
} else {
hostAddresses = append(hostAddresses, &HostAddress{hostname, constants.UnspecifiedIP})
}
}
return buildServices(hostAddresses, cfg.Name, cfg.Namespace, svcPorts, serviceEntry.Location, resolution,
exportTo, labelSelectors, serviceEntry.SubjectAltNames, creationTime, cfg.Labels, portOverrides)
}
func buildServices(hostAddresses []*HostAddress, name, namespace string, ports model.PortList, location networking.ServiceEntry_Location,
resolution model.Resolution, exportTo sets.Set[visibility.Instance], selectors map[string]string, saccounts []string,
ctime time.Time, labels map[string]string, overrides map[uint32]uint32,
) []*model.Service {
out := make([]*model.Service, 0, len(hostAddresses))
lbls := labels
if features.CanonicalServiceForMeshExternalServiceEntry && location == networking.ServiceEntry_MESH_EXTERNAL {
lbls = ensureCanonicalServiceLabels(name, labels)
}
for _, ha := range hostAddresses {
out = append(out, &model.Service{
CreationTime: ctime,
MeshExternal: location == networking.ServiceEntry_MESH_EXTERNAL,
Hostname: host.Name(ha.host),
DefaultAddress: ha.address,
Ports: ports,
Resolution: resolution,
Attributes: model.ServiceAttributes{
ServiceRegistry: provider.External,
PassthroughTargetPorts: overrides,
Name: ha.host,
Namespace: namespace,
Labels: lbls,
ExportTo: exportTo,
LabelSelectors: selectors,
},
ServiceAccounts: saccounts,
})
}
return out
}
func ensureCanonicalServiceLabels(name string, srcLabels map[string]string) map[string]string {
if srcLabels == nil {
srcLabels = make(map[string]string)
}
_, svcLabelFound := srcLabels[model.IstioCanonicalServiceLabelName]
_, revLabelFound := srcLabels[model.IstioCanonicalServiceRevisionLabelName]
if svcLabelFound && revLabelFound {
return srcLabels
}
srcLabels[model.IstioCanonicalServiceLabelName], srcLabels[model.IstioCanonicalServiceRevisionLabelName] = labels.CanonicalService(srcLabels, name)
return srcLabels
}
func (s *Controller) convertEndpoint(service *model.Service, servicePort *networking.ServicePort,
wle *networking.WorkloadEntry, configKey *configKey, clusterID cluster.ID,
) *model.ServiceInstance {
var instancePort uint32
addr := wle.GetAddress()
// priority level: unixAddress > we.ports > se.port.targetPort > se.port.number
if strings.HasPrefix(addr, model.UnixAddressPrefix) {
instancePort = 0
addr = strings.TrimPrefix(addr, model.UnixAddressPrefix)
} else if port, ok := wle.Ports[servicePort.Name]; ok && port > 0 {
instancePort = port
} else if servicePort.TargetPort > 0 {
instancePort = servicePort.TargetPort
} else {
// final fallback is to the service port value
instancePort = servicePort.Number
}
tlsMode := getTLSModeFromWorkloadEntry(wle)
sa := ""
if wle.ServiceAccount != "" {
sa = spiffe.MustGenSpiffeURI(service.Attributes.Namespace, wle.ServiceAccount)
}
networkID := s.workloadEntryNetwork(wle)
locality := wle.Locality
if locality == "" && len(wle.Labels[model.LocalityLabel]) > 0 {
locality = model.GetLocalityLabel(wle.Labels[model.LocalityLabel])
}
labels := labelutil.AugmentLabels(wle.Labels, clusterID, locality, "", networkID)
return &model.ServiceInstance{
Endpoint: &model.IstioEndpoint{
Address: addr,
EndpointPort: instancePort,
ServicePortName: servicePort.Name,
LegacyClusterPortKey: int(servicePort.Number),
Network: network.ID(wle.Network),
Locality: model.Locality{
Label: locality,
ClusterID: clusterID,
},
LbWeight: wle.Weight,
Labels: labels,
TLSMode: tlsMode,
ServiceAccount: sa,
// Workload entry config name is used as workload name, which will appear in metric label.
// After VM auto registry is introduced, workload group annotation should be used for workload name.
WorkloadName: configKey.name,
Namespace: configKey.namespace,
},
Service: service,
ServicePort: convertPort(servicePort),
}
}
// convertWorkloadEntryToServiceInstances translates a WorkloadEntry into ServiceEndpoints. This logic is largely the
// same as the ServiceEntry convertServiceEntryToInstances.
func (s *Controller) convertWorkloadEntryToServiceInstances(wle *networking.WorkloadEntry, services []*model.Service,
se *networking.ServiceEntry, configKey *configKey, clusterID cluster.ID,
) []*model.ServiceInstance {
out := make([]*model.ServiceInstance, 0)
for _, service := range services {
for _, port := range se.Ports {
out = append(out, s.convertEndpoint(service, port, wle, configKey, clusterID))
}
}
return out
}
func (s *Controller) convertServiceEntryToInstances(cfg config.Config, services []*model.Service) []*model.ServiceInstance {
out := make([]*model.ServiceInstance, 0)
serviceEntry := cfg.Spec.(*networking.ServiceEntry)
if serviceEntry == nil {
return nil
}
if services == nil {
services = convertServices(cfg)
}
for _, service := range services {
for _, serviceEntryPort := range serviceEntry.Ports {
if len(serviceEntry.Endpoints) == 0 && serviceEntry.WorkloadSelector == nil &&
(serviceEntry.Resolution == networking.ServiceEntry_DNS || serviceEntry.Resolution == networking.ServiceEntry_DNS_ROUND_ROBIN) {
// Note: only convert the hostname to service instance if WorkloadSelector is not set
// when service entry has discovery type DNS and no endpoints
// we create endpoints from service's host
// Do not use serviceentry.hosts as a service entry is converted into
// multiple services (one for each host)
endpointPort := serviceEntryPort.Number
if serviceEntryPort.TargetPort > 0 {
endpointPort = serviceEntryPort.TargetPort
}
out = append(out, &model.ServiceInstance{
Endpoint: &model.IstioEndpoint{
Address: string(service.Hostname),
EndpointPort: endpointPort,
ServicePortName: serviceEntryPort.Name,
LegacyClusterPortKey: int(serviceEntryPort.Number),
Labels: nil,
TLSMode: model.DisabledTLSModeLabel,
},
Service: service,
ServicePort: convertPort(serviceEntryPort),
})
} else {
for _, endpoint := range serviceEntry.Endpoints {
out = append(out, s.convertEndpoint(service, serviceEntryPort, endpoint, &configKey{}, s.clusterID))
}
}
}
}
return out
}
func getTLSModeFromWorkloadEntry(wle *networking.WorkloadEntry) string {
// * Use security.istio.io/tlsMode if its present
// * If not, set TLS mode if ServiceAccount is specified
tlsMode := model.DisabledTLSModeLabel
if val, exists := wle.Labels[label.SecurityTlsMode.Name]; exists {
tlsMode = val
} else if wle.ServiceAccount != "" {
tlsMode = model.IstioMutualTLSModeLabel
}
return tlsMode
}
// The workload instance has pointer to the service and its service port.
// We need to create our own but we can retain the endpoint already created.
func convertWorkloadInstanceToServiceInstance(workloadInstance *model.WorkloadInstance, serviceEntryServices []*model.Service,
serviceEntry *networking.ServiceEntry,
) []*model.ServiceInstance {
out := make([]*model.ServiceInstance, 0)
for _, service := range serviceEntryServices {
for _, serviceEntryPort := range serviceEntry.Ports {
// note: this is same as workloadentry handler
// endpoint port will first use the port defined in wle with same port name,
// if not port name not match, use the targetPort specified in ServiceEntry
// if both not matched, fallback to ServiceEntry port number.
var targetPort uint32
if port, ok := workloadInstance.PortMap[serviceEntryPort.Name]; ok && port > 0 {
targetPort = port
} else if serviceEntryPort.TargetPort > 0 {
targetPort = serviceEntryPort.TargetPort
} else {
targetPort = serviceEntryPort.Number
}
ep := workloadInstance.Endpoint.ShallowCopy()
ep.ServicePortName = serviceEntryPort.Name
ep.LegacyClusterPortKey = int(serviceEntryPort.Number)
ep.EndpointPort = targetPort
out = append(out, &model.ServiceInstance{
Endpoint: ep,
Service: service,
ServicePort: convertPort(serviceEntryPort),
})
}
}
return out
}
// Convenience function to convert a workloadEntry into a WorkloadInstance object encoding the endpoint (without service
// port names) and the namespace - k8s will consume this workload instance when selecting workload entries
func (s *Controller) convertWorkloadEntryToWorkloadInstance(cfg config.Config, clusterID cluster.ID) *model.WorkloadInstance {
we := ConvertWorkloadEntry(cfg)
addr := we.GetAddress()
dnsServiceEntryOnly := false
if strings.HasPrefix(addr, model.UnixAddressPrefix) {
// k8s can't use uds for service objects
dnsServiceEntryOnly = true
}
if addr != "" && !netutil.IsValidIPAddress(addr) {
// k8s can't use workloads with hostnames in the address field.
dnsServiceEntryOnly = true
}
tlsMode := getTLSModeFromWorkloadEntry(we)
sa := ""
if we.ServiceAccount != "" {
sa = spiffe.MustGenSpiffeURI(cfg.Namespace, we.ServiceAccount)
}
networkID := s.workloadEntryNetwork(we)
locality := we.Locality
if locality == "" && len(we.Labels[model.LocalityLabel]) > 0 {
locality = model.GetLocalityLabel(we.Labels[model.LocalityLabel])
}
labels := labelutil.AugmentLabels(we.Labels, clusterID, locality, "", networkID)
return &model.WorkloadInstance{
Endpoint: &model.IstioEndpoint{
Address: addr,
// Not setting ports here as its done by k8s controller
Network: network.ID(we.Network),
Locality: model.Locality{
Label: locality,
ClusterID: clusterID,
},
LbWeight: we.Weight,
Namespace: cfg.Namespace,
// Workload entry config name is used as workload name, which will appear in metric label.
// After VM auto registry is introduced, workload group annotation should be used for workload name.
WorkloadName: cfg.Name,
Labels: labels,
TLSMode: tlsMode,
ServiceAccount: sa,
},
PortMap: we.Ports,
Namespace: cfg.Namespace,
Name: cfg.Name,
Kind: model.WorkloadEntryKind,
DNSServiceEntryOnly: dnsServiceEntryOnly,
}
}