This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
forked from istio/old_pilot_repo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
conversion.go
271 lines (238 loc) · 8.2 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
// Copyright 2017 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 kube
import (
"fmt"
"sort"
"strconv"
"strings"
multierror "github.com/hashicorp/go-multierror"
"k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"istio.io/pilot/model"
)
const (
// IngressClassAnnotation is the annotation on ingress resources for the class of controllers
// responsible for it
IngressClassAnnotation = "kubernetes.io/ingress.class"
// KubeServiceAccountsOnVMAnnotation is to specify the K8s service accounts that are allowed to run
// this service on the VMs
KubeServiceAccountsOnVMAnnotation = "alpha.istio.io/kubernetes-serviceaccounts"
// CanonicalServiceAccountsOnVMAnnotation is to specify the non-Kubernetes service accounts that
// are allowed to run this service on the VMs
CanonicalServiceAccountsOnVMAnnotation = "alpha.istio.io/canonical-serviceaccounts"
// IstioURIPrefix is the URI prefix in the Istio service account scheme
IstioURIPrefix = "spiffe"
// PortAuthenticationAnnotationKeyPrefix is the annotation key prefix that used to define
// authentication policy.
PortAuthenticationAnnotationKeyPrefix = "tls.istio.io"
)
func convertLabels(obj meta_v1.ObjectMeta) model.Labels {
out := make(model.Labels, len(obj.Labels))
for k, v := range obj.Labels {
out[k] = v
}
return out
}
// Extracts security option for given port from annotation. If there is no such
// annotation, or the annotation value is not recognized, returns
// model.SecurityDefault.
func extractAuthenticationPolicy(port v1.ServicePort, obj meta_v1.ObjectMeta) model.AuthenticationPolicy {
if obj.Annotations == nil {
return model.AuthenticationDefault
}
switch obj.Annotations[portAuthenticationAnnotationKey(int(port.Port))] {
case "disable":
return model.AuthenticationDisable
case "enable":
return model.AuthenticationEnable
default:
return model.AuthenticationDefault
}
}
func convertPort(port v1.ServicePort, obj meta_v1.ObjectMeta) *model.Port {
return &model.Port{
Name: port.Name,
Port: int(port.Port),
Protocol: ConvertProtocol(port.Name, port.Protocol),
AuthenticationPolicy: extractAuthenticationPolicy(port, obj),
}
}
func convertService(svc v1.Service, domainSuffix string) *model.Service {
addr, external := "", ""
if svc.Spec.ClusterIP != "" && svc.Spec.ClusterIP != v1.ClusterIPNone {
addr = svc.Spec.ClusterIP
}
if svc.Spec.Type == v1.ServiceTypeExternalName && svc.Spec.ExternalName != "" {
external = svc.Spec.ExternalName
}
ports := make([]*model.Port, 0, len(svc.Spec.Ports))
for _, port := range svc.Spec.Ports {
ports = append(ports, convertPort(port, svc.ObjectMeta))
}
loadBalancingDisabled := addr == "" && external == "" // headless services should not be load balanced
serviceaccounts := make([]string, 0)
if svc.Annotations != nil {
if svc.Annotations[CanonicalServiceAccountsOnVMAnnotation] != "" {
for _, csa := range strings.Split(svc.Annotations[CanonicalServiceAccountsOnVMAnnotation], ",") {
serviceaccounts = append(serviceaccounts, canonicalToIstioServiceAccount(csa))
}
}
if svc.Annotations[KubeServiceAccountsOnVMAnnotation] != "" {
for _, ksa := range strings.Split(svc.Annotations[KubeServiceAccountsOnVMAnnotation], ",") {
serviceaccounts = append(serviceaccounts, kubeToIstioServiceAccount(ksa, svc.Namespace, domainSuffix))
}
}
}
sort.Sort(sort.StringSlice(serviceaccounts))
return &model.Service{
Hostname: serviceHostname(svc.Name, svc.Namespace, domainSuffix),
Ports: ports,
Address: addr,
ExternalName: external,
ServiceAccounts: serviceaccounts,
LoadBalancingDisabled: loadBalancingDisabled,
}
}
// serviceHostname produces FQDN for a k8s service
func serviceHostname(name, namespace, domainSuffix string) string {
return fmt.Sprintf("%s.%s.svc.%s", name, namespace, domainSuffix)
}
// canonicalToIstioServiceAccount converts a Canonical service account to an Istio service account
func canonicalToIstioServiceAccount(saname string) string {
return fmt.Sprintf("%v://%v", IstioURIPrefix, saname)
}
func portAuthenticationAnnotationKey(port int) string {
return fmt.Sprintf("%s/%d", PortAuthenticationAnnotationKeyPrefix, port)
}
// kubeToIstioServiceAccount converts a K8s service account to an Istio service account
func kubeToIstioServiceAccount(saname string, ns string, domain string) string {
return fmt.Sprintf("%v://%v/ns/%v/sa/%v", IstioURIPrefix, domain, ns, saname)
}
// KeyFunc is the internal API key function that returns "namespace"/"name" or
// "name" if "namespace" is empty
func KeyFunc(name, namespace string) string {
if len(namespace) == 0 {
return name
}
return namespace + "/" + name
}
// parseHostname extracts service name and namespace from the service hostname
func parseHostname(hostname string) (name string, namespace string, err error) {
parts := strings.Split(hostname, ".")
if len(parts) < 2 {
err = fmt.Errorf("missing service name and namespace from the service hostname %q", hostname)
return
}
name = parts[0]
namespace = parts[1]
return
}
// ConvertProtocol from k8s protocol and port name
func ConvertProtocol(name string, proto v1.Protocol) model.Protocol {
out := model.ProtocolTCP
switch proto {
case v1.ProtocolUDP:
out = model.ProtocolUDP
case v1.ProtocolTCP:
prefix := name
i := strings.Index(name, "-")
if i >= 0 {
prefix = name[:i]
}
switch prefix {
case "grpc":
out = model.ProtocolGRPC
case "http":
out = model.ProtocolHTTP
case "http2":
out = model.ProtocolHTTP2
case "https":
out = model.ProtocolHTTPS
case "mongo":
out = model.ProtocolMongo
case "redis":
out = model.ProtocolRedis
}
}
return out
}
func convertProbePort(c v1.Container, handler *v1.Handler) (*model.Port, error) {
if handler == nil {
return nil, nil
}
var protocol model.Protocol
var portVal intstr.IntOrString
var port int
// Only one type of handler is allowed by Kubernetes (HTTPGet or TCPSocket)
if handler.HTTPGet != nil {
portVal = handler.HTTPGet.Port
protocol = model.ProtocolHTTP
} else if handler.TCPSocket != nil {
portVal = handler.TCPSocket.Port
protocol = model.ProtocolTCP
} else {
return nil, nil
}
switch portVal.Type {
case intstr.Int:
port = portVal.IntValue()
return &model.Port{
Name: "mgmt-" + strconv.Itoa(port),
Port: port,
Protocol: protocol,
}, nil
case intstr.String:
for _, named := range c.Ports {
if named.Name == portVal.String() {
port = int(named.ContainerPort)
return &model.Port{
Name: "mgmt-" + strconv.Itoa(port),
Port: port,
Protocol: protocol,
}, nil
}
}
return nil, fmt.Errorf("missing named port %q", portVal)
default:
return nil, fmt.Errorf("incorrect port type %q", portVal)
}
}
// convertProbesToPorts returns a PortList consisting of the ports where the
// pod is configured to do Liveness and Readiness probes
func convertProbesToPorts(t *v1.PodSpec) (model.PortList, error) {
set := make(map[string]*model.Port)
var errs error
for _, container := range t.Containers {
for _, probe := range []*v1.Probe{container.LivenessProbe, container.ReadinessProbe} {
if probe == nil {
continue
}
p, err := convertProbePort(container, &probe.Handler)
if err != nil {
errs = multierror.Append(errs, err)
} else if p != nil && set[p.Name] == nil {
// Deduplicate along the way. We don't differentiate between HTTP vs TCP mgmt ports
set[p.Name] = p
}
}
}
mgmtPorts := make(model.PortList, 0, len(set))
for _, p := range set {
mgmtPorts = append(mgmtPorts, p)
}
sort.Slice(mgmtPorts, func(i, j int) bool { return mgmtPorts[i].Port < mgmtPorts[j].Port })
return mgmtPorts, errs
}