-
Notifications
You must be signed in to change notification settings - Fork 7.9k
/
Copy pathconversion.go
362 lines (324 loc) · 12.3 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
// 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 ingress
import (
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/hashicorp/go-multierror"
"k8s.io/api/networking/v1beta1"
"k8s.io/apimachinery/pkg/util/intstr"
listerv1 "k8s.io/client-go/listers/core/v1"
meshconfig "istio.io/api/mesh/v1alpha1"
networking "istio.io/api/networking/v1alpha3"
"istio.io/istio/pilot/pkg/serviceregistry/kube"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/labels"
"istio.io/istio/pkg/config/protocol"
"istio.io/istio/pkg/config/schema/gvk"
"istio.io/pkg/log"
)
const (
IstioIngressController = "istio.io/ingress-controller"
)
var errNotFound = errors.New("item not found")
// EncodeIngressRuleName encodes an ingress rule name for a given ingress resource name,
// as well as the position of the rule and path specified within it, counting from 1.
// ruleNum == pathNum == 0 indicates the default backend specified for an ingress.
func EncodeIngressRuleName(ingressName string, ruleNum, pathNum int) string {
return fmt.Sprintf("%s-%d-%d", ingressName, ruleNum, pathNum)
}
// decodeIngressRuleName decodes an ingress rule name previously encoded with EncodeIngressRuleName.
func decodeIngressRuleName(name string) (ingressName string, ruleNum, pathNum int, err error) {
parts := strings.Split(name, "-")
if len(parts) < 3 {
err = fmt.Errorf("could not decode string into ingress rule name: %s", name)
return
}
ingressName = strings.Join(parts[0:len(parts)-2], "-")
ruleNum, ruleErr := strconv.Atoi(parts[len(parts)-2])
pathNum, pathErr := strconv.Atoi(parts[len(parts)-1])
if pathErr != nil || ruleErr != nil {
err = multierror.Append(
fmt.Errorf("could not decode string into ingress rule name: %s", name),
pathErr, ruleErr)
return
}
return
}
// ConvertIngressV1alpha3 converts from ingress spec to Istio Gateway
func ConvertIngressV1alpha3(ingress v1beta1.Ingress, mesh *meshconfig.MeshConfig, domainSuffix string) config.Config {
gateway := &networking.Gateway{}
gateway.Selector = getIngressGatewaySelector(mesh.IngressSelector, mesh.IngressService)
for i, tls := range ingress.Spec.TLS {
if tls.SecretName == "" {
log.Infof("invalid ingress rule %s:%s for hosts %q, no secretName defined", ingress.Namespace, ingress.Name, tls.Hosts)
continue
}
// TODO validation when multiple wildcard tls secrets are given
if len(tls.Hosts) == 0 {
tls.Hosts = []string{"*"}
}
gateway.Servers = append(gateway.Servers, &networking.Server{
Port: &networking.Port{
Number: 443,
Protocol: string(protocol.HTTPS),
Name: fmt.Sprintf("https-443-ingress-%s-%s-%d", ingress.Name, ingress.Namespace, i),
},
Hosts: tls.Hosts,
Tls: &networking.ServerTLSSettings{
HttpsRedirect: false,
Mode: networking.ServerTLSSettings_SIMPLE,
CredentialName: tls.SecretName,
},
})
}
gateway.Servers = append(gateway.Servers, &networking.Server{
Port: &networking.Port{
Number: 80,
Protocol: string(protocol.HTTP),
Name: fmt.Sprintf("http-80-ingress-%s-%s", ingress.Name, ingress.Namespace),
},
Hosts: []string{"*"},
})
gatewayConfig := config.Config{
Meta: config.Meta{
GroupVersionKind: gvk.Gateway,
Name: ingress.Name + "-" + constants.IstioIngressGatewayName + "-" + ingress.Namespace,
Namespace: ingressNamespace,
Domain: domainSuffix,
},
Spec: gateway,
}
return gatewayConfig
}
// prefixMatchRegex optionally matches "/..." at the end of a path.
// regex taken from https://github.com/projectcontour/contour/blob/2b3376449bedfea7b8cea5fbade99fb64009c0f6/internal/envoy/v3/route.go#L59
const prefixMatchRegex = `((\/).*)?`
// ConvertIngressVirtualService converts from ingress spec to Istio VirtualServices
func ConvertIngressVirtualService(ingress v1beta1.Ingress, domainSuffix string, ingressByHost map[string]*config.Config, serviceLister listerv1.ServiceLister) {
// Ingress allows a single host - if missing '*' is assumed
// We need to merge all rules with a particular host across
// all ingresses, and return a separate VirtualService for each
// host.
if ingressNamespace == "" {
ingressNamespace = constants.IstioIngressNamespace
}
for _, rule := range ingress.Spec.Rules {
if rule.HTTP == nil {
log.Infof("invalid ingress rule %s:%s for host %q, no paths defined", ingress.Namespace, ingress.Name, rule.Host)
continue
}
host := rule.Host
namePrefix := strings.Replace(host, ".", "-", -1)
if host == "" {
host = "*"
}
virtualService := &networking.VirtualService{
Hosts: []string{},
Gateways: []string{fmt.Sprintf("%s/%s-%s-%s", ingressNamespace, ingress.Name, constants.IstioIngressGatewayName, ingress.Namespace)},
}
virtualService.Hosts = []string{host}
httpRoutes := make([]*networking.HTTPRoute, 0)
for _, httpPath := range rule.HTTP.Paths {
httpMatch := &networking.HTTPMatchRequest{}
if httpPath.PathType != nil {
switch *httpPath.PathType {
case v1beta1.PathTypeExact:
httpMatch.Uri = &networking.StringMatch{
MatchType: &networking.StringMatch_Exact{Exact: httpPath.Path},
}
case v1beta1.PathTypePrefix:
// From the spec: /foo/bar matches /foo/bar/baz, but does not match /foo/barbaz
// and if the prefix is /foo/bar/ we must match /foo/bar and /foo/bar. We cannot simply strip the
// trailing "/" and do a prefix match since we'll match unwanted path continuations and we cannot add
// a "/" if not present since we won't match the prefix without trailing "/". Must be smarter and
// use regex.
path := httpPath.Path
if path == "/" {
// Optimize common case of / to not needed regex
httpMatch.Uri = &networking.StringMatch{
MatchType: &networking.StringMatch_Prefix{Prefix: path},
}
} else {
path = strings.TrimSuffix(path, "/")
httpMatch.Uri = &networking.StringMatch{
MatchType: &networking.StringMatch_Regex{Regex: regexp.QuoteMeta(path) + prefixMatchRegex},
}
}
default:
// Fallback to the legacy string matching
httpMatch.Uri = createFallbackStringMatch(httpPath.Path)
}
} else {
httpMatch.Uri = createFallbackStringMatch(httpPath.Path)
}
httpRoute := ingressBackendToHTTPRoute(&httpPath.Backend, ingress.Namespace, domainSuffix, serviceLister)
if httpRoute == nil {
log.Infof("invalid ingress rule %s:%s for host %q, no backend defined for path", ingress.Namespace, ingress.Name, rule.Host)
continue
}
httpRoute.Match = []*networking.HTTPMatchRequest{httpMatch}
httpRoutes = append(httpRoutes, httpRoute)
}
virtualService.Http = httpRoutes
virtualServiceConfig := config.Config{
Meta: config.Meta{
GroupVersionKind: gvk.VirtualService,
Name: namePrefix + "-" + ingress.Name + "-" + constants.IstioIngressGatewayName,
Namespace: ingress.Namespace,
Domain: domainSuffix,
},
Spec: virtualService,
}
old, f := ingressByHost[host]
if f {
vs := old.Spec.(*networking.VirtualService)
vs.Http = append(vs.Http, httpRoutes...)
sort.SliceStable(vs.Http, func(i, j int) bool {
r1 := vs.Http[i].Match[0].GetUri()
r2 := vs.Http[j].Match[0].GetUri()
_, r1Ex := r1.GetMatchType().(*networking.StringMatch_Exact)
_, r2Ex := r2.GetMatchType().(*networking.StringMatch_Exact)
// TODO: default at the end
if r1Ex && !r2Ex {
return true
}
return false
})
} else {
ingressByHost[host] = &virtualServiceConfig
}
}
// Matches * and "/". Currently not supported - would conflict
// with any other explicit VirtualService.
if ingress.Spec.Backend != nil {
log.Infof("Ignore default wildcard ingress, use VirtualService %s:%s",
ingress.Namespace, ingress.Name)
}
}
func ingressBackendToHTTPRoute(backend *v1beta1.IngressBackend, namespace string, domainSuffix string,
serviceLister listerv1.ServiceLister) *networking.HTTPRoute {
if backend == nil {
return nil
}
port := &networking.PortSelector{}
if backend.ServicePort.Type == intstr.Int {
port.Number = uint32(backend.ServicePort.IntVal)
} else {
resolvedPort, err := resolveNamedPort(backend, namespace, serviceLister)
if err != nil {
log.Infof("failed to resolve named port %s, error: %v", backend.ServicePort.StrVal, err)
return nil
}
port.Number = uint32(resolvedPort)
}
return &networking.HTTPRoute{
Route: []*networking.HTTPRouteDestination{
{
Destination: &networking.Destination{
Host: fmt.Sprintf("%s.%s.svc.%s", backend.ServiceName, namespace, domainSuffix),
Port: port,
},
Weight: 100,
},
},
}
}
func resolveNamedPort(backend *v1beta1.IngressBackend, namespace string, serviceLister listerv1.ServiceLister) (int32, error) {
svc, err := serviceLister.Services(namespace).Get(backend.ServiceName)
if err != nil {
return 0, err
}
for _, port := range svc.Spec.Ports {
if port.Name == backend.ServicePort.StrVal {
return port.Port, nil
}
}
return 0, errNotFound
}
// shouldProcessIngress determines whether the given ingress resource should be processed
// by the controller, based on its ingress class annotation or, in more recent versions of
// kubernetes (v1.18+), based on the Ingress's specified IngressClass
// See https://kubernetes.io/docs/concepts/services-networking/ingress/#ingress-class
func shouldProcessIngressWithClass(mesh *meshconfig.MeshConfig, ingress *v1beta1.Ingress, ingressClass *v1beta1.IngressClass) bool {
if class, exists := ingress.Annotations[kube.IngressClassAnnotation]; exists {
switch mesh.IngressControllerMode {
case meshconfig.MeshConfig_OFF:
return false
case meshconfig.MeshConfig_STRICT:
return class == mesh.IngressClass
case meshconfig.MeshConfig_DEFAULT:
return class == mesh.IngressClass
default:
log.Warnf("invalid ingress synchronization mode: %v", mesh.IngressControllerMode)
return false
}
} else if ingressClass != nil {
return ingressClass.Spec.Controller == IstioIngressController
} else {
switch mesh.IngressControllerMode {
case meshconfig.MeshConfig_OFF:
return false
case meshconfig.MeshConfig_STRICT:
return false
case meshconfig.MeshConfig_DEFAULT:
return true
default:
log.Warnf("invalid ingress synchronization mode: %v", mesh.IngressControllerMode)
return false
}
}
}
func createFallbackStringMatch(s string) *networking.StringMatch {
if s == "" {
return nil
}
// Note that this implementation only converts prefix and exact matches, not regexps.
// Replace e.g. "foo.*" with prefix match
if strings.HasSuffix(s, ".*") {
return &networking.StringMatch{
MatchType: &networking.StringMatch_Prefix{Prefix: strings.TrimSuffix(s, ".*")},
}
}
if strings.HasSuffix(s, "/*") {
return &networking.StringMatch{
MatchType: &networking.StringMatch_Prefix{Prefix: strings.TrimSuffix(s, "/*")},
}
}
// Replace e.g. "foo" with a exact match
return &networking.StringMatch{
MatchType: &networking.StringMatch_Exact{Exact: s},
}
}
func getIngressGatewaySelector(ingressSelector, ingressService string) map[string]string {
// Setup the selector for the gateway
if ingressSelector != "" {
// If explicitly defined, use this one
return labels.Instance{constants.IstioLabel: ingressSelector}
} else if ingressService != "istio-ingressgateway" && ingressService != "" {
// Otherwise, we will use the ingress service as the default. It is common for the selector and service
// to be the same, so this removes the need for two configurations
// However, if its istio-ingressgateway we need to use the old values for backwards compatibility
return labels.Instance{constants.IstioLabel: ingressService}
} else {
// If we have neither an explicitly defined ingressSelector or ingressService then use a selector
// pointing to the ingressgateway from the default installation
return labels.Instance{constants.IstioLabel: constants.IstioIngressLabelValue}
}
}