forked from knative/serving
/
gateway.go
307 lines (278 loc) · 10.2 KB
/
gateway.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
/*
Copyright 2019 The Knative 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 resources
import (
"context"
"fmt"
"hash/adler32"
"sort"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
corev1listers "k8s.io/client-go/listers/core/v1"
"knative.dev/pkg/apis/istio/v1alpha3"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/system"
"knative.dev/serving/pkg/apis/networking"
"knative.dev/serving/pkg/apis/networking/v1alpha1"
"knative.dev/serving/pkg/network"
"knative.dev/serving/pkg/reconciler/ingress/config"
)
var httpServerPortName = "http-server"
// Istio Gateway requires to have at least one server. This placeholderServer is used when
// all of the real servers are deleted.
var placeholderServer = v1alpha3.Server{
Hosts: []string{"place-holder.place-holder"},
Port: v1alpha3.Port{
Name: "place-holder",
Number: 9999,
Protocol: v1alpha3.ProtocolHTTP,
},
}
// GetServers gets the `Servers` from `Gateway` that belongs to the given ClusterIngress.
func GetServers(gateway *v1alpha3.Gateway, ia v1alpha1.IngressAccessor) []v1alpha3.Server {
servers := []v1alpha3.Server{}
for i := range gateway.Spec.Servers {
if belongsToClusterIngress(&gateway.Spec.Servers[i], ia) {
servers = append(servers, gateway.Spec.Servers[i])
}
}
return SortServers(servers)
}
// GetHTTPServer gets the HTTP `Server` from `Gateway`.
func GetHTTPServer(gateway *v1alpha3.Gateway) *v1alpha3.Server {
for _, server := range gateway.Spec.Servers {
if server.Port.Name == httpServerPortName {
return &server
}
}
return nil
}
func belongsToClusterIngress(server *v1alpha3.Server, ia v1alpha1.IngressAccessor) bool {
// The format of the portName should be "<namespace>/<ingress_name>:<number>".
// For example, default/routetest:0.
portNameSplits := strings.Split(server.Port.Name, ":")
if len(portNameSplits) != 2 {
return false
}
// TODO: This should be removed after ClusterIngress codes are cleaned up.
if len(ia.GetNamespace()) == 0 {
return portNameSplits[0] == ia.GetName()
}
return portNameSplits[0] == ia.GetNamespace()+"/"+ia.GetName()
}
// SortServers sorts `Server` according to its port name.
func SortServers(servers []v1alpha3.Server) []v1alpha3.Server {
sort.Slice(servers, func(i, j int) bool {
return strings.Compare(servers[i].Port.Name, servers[j].Port.Name) < 0
})
return servers
}
// MakeIngressGateways creates Gateways for a given IngressAccessor.
func MakeIngressGateways(ctx context.Context, ia v1alpha1.IngressAccessor, originSecrets map[string]*corev1.Secret, svcLister corev1listers.ServiceLister) ([]*v1alpha3.Gateway, error) {
gatewayServices, err := getGatewayServices(ctx, svcLister)
if err != nil {
return nil, err
}
gateways := make([]*v1alpha3.Gateway, len(gatewayServices))
for i, gatewayService := range gatewayServices {
gateway, err := makeIngressGateway(ctx, ia, originSecrets, gatewayService.Spec.Selector, gatewayService)
if err != nil {
return nil, err
}
gateways[i] = gateway
}
return gateways, nil
}
func makeIngressGateway(ctx context.Context, ia v1alpha1.IngressAccessor, originSecrets map[string]*corev1.Secret, selector map[string]string, gatewayService *corev1.Service) (*v1alpha3.Gateway, error) {
ns := ia.GetNamespace()
if len(ns) == 0 {
ns = system.Namespace()
}
servers, err := MakeTLSServers(ia, gatewayService.Namespace, originSecrets)
if err != nil {
return nil, err
}
hosts := sets.String{}
for _, rule := range ia.GetSpec().Rules {
hosts.Insert(rule.Hosts...)
}
servers = append(servers, *MakeHTTPServer(config.FromContext(ctx).Network.HTTPProtocol, hosts.List()))
return &v1alpha3.Gateway{
ObjectMeta: metav1.ObjectMeta{
Name: GatewayName(ia, gatewayService),
Namespace: ns,
OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(ia)},
Labels: map[string]string{
// We need this label to find out all of Gateways of a given Ingress.
networking.IngressLabelKey: ia.GetName(),
},
},
Spec: v1alpha3.GatewaySpec{
Selector: selector,
Servers: servers,
},
}, nil
}
func getGatewayServices(ctx context.Context, svcLister corev1listers.ServiceLister) ([]*corev1.Service, error) {
ingressSvcMetas, err := getIngressGatewaySvcNameNamespaces(ctx)
if err != nil {
return nil, err
}
services := make([]*corev1.Service, len(ingressSvcMetas))
for i, ingressSvcMeta := range ingressSvcMetas {
svc, err := svcLister.Services(ingressSvcMeta.Namespace).Get(ingressSvcMeta.Name)
if err != nil {
return nil, err
}
services[i] = svc
}
return services, nil
}
// GatewayName create a name for the Gateway that is built based on the given IngressAccessor and bonds to the
// given ingress gateway service.
func GatewayName(accessor kmeta.Accessor, gatewaySvc *corev1.Service) string {
gatewayServiceKey := fmt.Sprintf("%s/%s", gatewaySvc.Namespace, gatewaySvc.Name)
return fmt.Sprintf("%s-%d", accessor.GetName(), adler32.Checksum([]byte(gatewayServiceKey)))
}
// MakeTLSServers creates the expected Gateway TLS `Servers` based on the given
// IngressAccessor.
func MakeTLSServers(ia v1alpha1.IngressAccessor, gatewayServiceNamespace string, originSecrets map[string]*corev1.Secret) ([]v1alpha3.Server, error) {
servers := make([]v1alpha3.Server, len(ia.GetSpec().TLS))
// TODO(zhiminx): for the hosts that does not included in the ClusterIngressTLS but listed in the ClusterIngressRule,
// do we consider them as hosts for HTTP?
for i, tls := range ia.GetSpec().TLS {
credentialName := tls.SecretName
// If the origin secret is not in the target namespace, then it should have been
// copied into the target namespace. So we use the name of the copy.
if tls.SecretNamespace != gatewayServiceNamespace {
originSecret, ok := originSecrets[secretKey(tls)]
if !ok {
return nil, fmt.Errorf("unable to get the original secret %s/%s", tls.SecretNamespace, tls.SecretName)
}
credentialName = targetSecret(originSecret, ia)
}
port := ia.GetName()
// TODO: This namespace check should be removed after ClusterIngress codes are cleaned up.
if len(ia.GetNamespace()) > 0 {
port = ia.GetNamespace() + "/" + ia.GetName()
}
servers[i] = v1alpha3.Server{
Hosts: tls.Hosts,
Port: v1alpha3.Port{
Name: fmt.Sprintf("%s:%d", port, i),
Number: 443,
Protocol: v1alpha3.ProtocolHTTPS,
},
TLS: &v1alpha3.TLSOptions{
Mode: v1alpha3.TLSModeSimple,
ServerCertificate: tls.ServerCertificate,
PrivateKey: tls.PrivateKey,
CredentialName: credentialName,
},
}
}
return SortServers(servers), nil
}
// MakeHTTPServer creates a HTTP Gateway `Server` based on the HTTPProtocol
// configureation.
func MakeHTTPServer(httpProtocol network.HTTPProtocol, hosts []string) *v1alpha3.Server {
if httpProtocol == network.HTTPDisabled {
return nil
}
server := &v1alpha3.Server{
Hosts: hosts,
Port: v1alpha3.Port{
Name: httpServerPortName,
Number: 80,
Protocol: v1alpha3.ProtocolHTTP,
},
}
if httpProtocol == network.HTTPRedirected {
server.TLS = &v1alpha3.TLSOptions{
HTTPSRedirect: true,
}
}
return server
}
// ServiceNamespaceFromURL extracts the namespace part from the service URL.
// TODO(nghia): Remove this by parsing at config parsing time.
func ServiceNamespaceFromURL(svc string) (string, error) {
parts := strings.SplitN(svc, ".", 3)
if len(parts) != 3 {
return "", fmt.Errorf("unexpected service URL form: %s", svc)
}
return parts[1], nil
}
// TODO(nghia): Remove this by parsing at config parsing time.
func getIngressGatewaySvcNameNamespaces(ctx context.Context) ([]metav1.ObjectMeta, error) {
cfg := config.FromContext(ctx).Istio
nameNamespaces := make([]metav1.ObjectMeta, len(cfg.IngressGateways))
for i, ingressgateway := range cfg.IngressGateways {
parts := strings.SplitN(ingressgateway.ServiceURL, ".", 3)
if len(parts) != 3 {
return nil, fmt.Errorf("unexpected service URL form: %s", ingressgateway.ServiceURL)
}
nameNamespaces[i] = metav1.ObjectMeta{
Name: parts[0],
Namespace: parts[1],
}
}
return nameNamespaces, nil
}
// UpdateGateway replaces the existing servers with the wanted servers.
func UpdateGateway(gateway *v1alpha3.Gateway, want []v1alpha3.Server, existing []v1alpha3.Server) *v1alpha3.Gateway {
existingServers := sets.String{}
for i := range existing {
existingServers.Insert(existing[i].Port.Name)
}
servers := []v1alpha3.Server{}
for _, server := range gateway.Spec.Servers {
// We remove
// 1) the existing servers
// 2) the default HTTP server and HTTPS server in the gateway because they are only used for the scenario of not reconciling gateway.
// 3) the placeholder servers.
if existingServers.Has(server.Port.Name) || isDefaultServer(&server) || isPlaceHolderServer(&server) {
continue
}
servers = append(servers, server)
}
servers = append(servers, want...)
// Istio Gateway requires to have at least one server. So if the final gateway does not have any server,
// we add "placeholder" server back.
if len(servers) == 0 {
servers = append(servers, placeholderServer)
}
SortServers(servers)
gateway.Spec.Servers = servers
return gateway
}
func isDefaultServer(server *v1alpha3.Server) bool {
return server.Port.Name == "http" || server.Port.Name == "https"
}
func isPlaceHolderServer(server *v1alpha3.Server) bool {
return equality.Semantic.DeepEqual(server, &placeholderServer)
}
// CanProbeGateway return whether the specified Gateway can be probed using HTTP on port 80.
func CanProbeGateway(gateway *v1alpha3.Gateway) bool {
for _, server := range gateway.Spec.Servers {
if len(server.Hosts) == 1 &&
server.Hosts[0] == "*" &&
server.Port.Protocol == v1alpha3.ProtocolHTTP {
return true
}
}
return false
}