-
Notifications
You must be signed in to change notification settings - Fork 9
/
ingress.go
403 lines (336 loc) · 12.2 KB
/
ingress.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package runtime
import (
"context"
"fmt"
"strings"
anypb "google.golang.org/protobuf/types/known/anypb"
"namespacelabs.dev/foundation/framework/kubernetes/kubenaming"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/planning/constants"
"namespacelabs.dev/foundation/internal/protos"
"namespacelabs.dev/foundation/internal/uniquestrings"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/cfg"
)
const LocalIngressPort = 40080
func ComputeIngress(ctx context.Context, env cfg.Context, planner Planner, sch *schema.Stack_Entry, allEndpoints []*schema.Endpoint) ([]*schema.IngressFragment, error) {
var ingresses []*schema.IngressFragment
var serverEndpoints []*schema.Endpoint
for _, endpoint := range allEndpoints {
if endpoint.ServerOwner == sch.Server.PackageName {
serverEndpoints = append(serverEndpoints, endpoint)
}
}
for _, endpoint := range serverEndpoints {
if !(endpoint.Type == schema.Endpoint_INTERNET_FACING && endpoint.Port != nil) {
continue
}
if endpoint.IngressProvider != nil {
fmt.Fprintf(console.Debug(ctx), "Skipping endpoint %s/%s: has ingress provider\n", endpoint.EndpointOwner, endpoint.AllocatedName)
continue
}
var protocol *string
var protocolDetails []*anypb.Any
var httpExtensions []*anypb.Any
for _, md := range endpoint.ServiceMetadata {
if md.Protocol != "" {
if protocol == nil {
protocol = &md.Protocol
if md.Details != nil {
protocolDetails = append(protocolDetails, md.Details)
}
} else if *protocol != md.Protocol {
return nil, fnerrors.InternalError("%s: inconsistent protocol definition, %q and %q", endpoint.GetServiceName(), *protocol, md.Protocol)
}
}
if md.Kind == "http-extension" && md.Details != nil {
httpExtensions = append(httpExtensions, md.Details)
}
}
if protocol == nil {
fmt.Fprintf(console.Debug(ctx), "Skipping endpoint %s/%s: no protocol\n", endpoint.EndpointOwner, endpoint.AllocatedName)
continue
}
var paths []*schema.IngressFragment_IngressHttpPath
var grpc []*schema.IngressFragment_IngressGrpcService
var clearTextGrpcCount int
switch *protocol {
case schema.HttpProtocol:
var kind string
if *protocol != schema.HttpProtocol {
kind = *protocol
}
for _, details := range protocolDetails {
p := &schema.HttpUrlMap{}
if err := details.UnmarshalTo(p); err != nil {
return nil, err
}
for _, entry := range p.Entry {
target := endpoint
if entry.BackendService != nil {
for _, nd := range allEndpoints {
if nd.EndpointOwner == entry.BackendService.PackageName && nd.ServiceName == entry.BackendService.Name {
target = nd
}
}
}
paths = append(paths, &schema.IngressFragment_IngressHttpPath{
Path: entry.PathPrefix,
Kind: kind,
Owner: target.EndpointOwner,
Service: target.AllocatedName,
ServicePort: target.ExportedPort,
})
}
}
// XXX still relevant? We used to do this when grpc followed the http path.
if len(paths) == 0 {
paths = []*schema.IngressFragment_IngressHttpPath{
{Path: "/", Kind: kind, Owner: endpoint.EndpointOwner, Service: endpoint.AllocatedName, ServicePort: endpoint.ExportedPort},
}
}
case schema.GrpcProtocol, schema.ClearTextGrpcProtocol:
for _, details := range protocolDetails {
msg, err := details.UnmarshalNew()
if err != nil {
return nil, fnerrors.InternalError("failed to unserialize grpc configuration: %w", err)
}
if *protocol == schema.ClearTextGrpcProtocol {
clearTextGrpcCount++
}
switch p := msg.(type) {
case *schema.GrpcExportService:
grpc = append(grpc, &schema.IngressFragment_IngressGrpcService{
GrpcService: p.ProtoTypename,
Owner: endpoint.EndpointOwner,
Service: endpoint.AllocatedName,
ServicePort: endpoint.ExportedPort,
Method: p.Method,
BackendTls: *protocol == schema.GrpcProtocol,
})
if p.ServerReflectionIncluded {
grpc = append(grpc, &schema.IngressFragment_IngressGrpcService{
GrpcService: "grpc.reflection.v1alpha.ServerReflection",
Owner: endpoint.EndpointOwner,
Service: endpoint.AllocatedName,
ServicePort: endpoint.ExportedPort,
BackendTls: *protocol == schema.GrpcProtocol,
})
}
case *schema.GrpcExportAllServices:
grpc = append(grpc, &schema.IngressFragment_IngressGrpcService{
AllServices: true,
Owner: endpoint.EndpointOwner,
Service: endpoint.AllocatedName,
ServicePort: endpoint.ExportedPort,
BackendTls: *protocol == schema.GrpcProtocol,
})
default:
return nil, fnerrors.InternalError("unsupported grpc configuration: %v", p.ProtoReflect().Descriptor().FullName())
}
}
default:
return nil, fnerrors.New("%s: unsupported ingress protocol", *protocol)
}
if len(paths) > 0 && len(grpc) > 0 {
return nil, fnerrors.BadInputError("can't mix grpc and http paths within a single endpoint")
}
attached, err := AttachComputedDomains(ctx, env.Workspace().ModuleName(), env, planner, sch, &schema.IngressFragment{
Name: endpoint.ServiceName,
Owner: endpoint.ServerOwner,
Endpoint: endpoint,
Extension: httpExtensions,
HttpPath: paths,
GrpcService: grpc,
}, DomainsRequest{
ServerID: sch.Server.Id,
ServiceName: endpoint.ServiceName,
Key: endpoint.AllocatedName,
Alias: endpoint.ServiceName,
RequiresTLS: clearTextGrpcCount > 0,
UserSpecified: endpoint.GetIngressSpec().GetDomain(),
})
if err != nil {
return nil, err
}
ingresses = append(ingresses, attached...)
}
// Handle HTTP.
if needsHTTP := len(sch.Server.UrlMap) > 0; needsHTTP {
var httpEndpoints []*schema.Endpoint
for _, endpoint := range serverEndpoints {
if endpoint.ServiceName == constants.HttpServiceName {
httpEndpoints = append(httpEndpoints, endpoint)
break
}
}
if len(httpEndpoints) != 1 {
return nil, fnerrors.InternalError("urlmap is present, but single http endpoint is missing")
}
httpEndpoint := httpEndpoints[0]
perIngress := map[string][]*schema.Server_URLMapEntry{}
perIngressAlias := map[string]string{}
ingressNames := uniquestrings.List{}
for _, url := range sch.Server.UrlMap {
ingressName := url.IngressName
alias := url.IngressName
if ingressName == "" {
ingressName = httpEndpoint.AllocatedName
alias = httpEndpoint.ServiceName
}
perIngress[ingressName] = append(perIngress[ingressName], url)
perIngressAlias[ingressName] = alias
ingressNames.Add(ingressName)
}
for _, name := range ingressNames.Strings() {
var paths []*schema.IngressFragment_IngressHttpPath
for _, u := range perIngress[name] {
owner := u.PackageName
if owner == "" {
owner = sch.Server.PackageName
}
paths = append(paths, &schema.IngressFragment_IngressHttpPath{
Path: u.PathPrefix,
Kind: u.Kind,
Owner: owner,
Service: httpEndpoint.AllocatedName,
ServicePort: httpEndpoint.ExportedPort,
})
}
attached, err := AttachComputedDomains(ctx, env.Workspace().ModuleName(), env, planner, sch, &schema.IngressFragment{
Name: serverScoped(sch.Server, name),
Owner: sch.GetPackageName().String(),
HttpPath: paths,
}, DomainsRequest{
ServerID: sch.GetServer().GetId(),
Key: name,
Alias: perIngressAlias[name],
})
if err != nil {
return nil, err
}
ingresses = append(ingresses, attached...)
}
}
return ingresses, nil
}
func AttachComputedDomains(ctx context.Context, ws string, env cfg.Context, cluster Planner, sch *schema.Stack_Entry, template *schema.IngressFragment, allocatedName DomainsRequest) ([]*schema.IngressFragment, error) {
domains, err := computeDomains(ctx, ws, env, cluster, sch.ServerNaming, allocatedName)
if err != nil {
return nil, err
}
fmt.Fprintf(console.Debug(ctx), "%s: %s: computed domains: %v\n", sch.Server.PackageName, template.GetName(), domains)
var ingresses []*schema.IngressFragment
for _, domain := range domains {
// It can be modified below.
fragment := protos.Clone(template)
fragment.Domain = domain
ingresses = append(ingresses, fragment)
}
return ingresses, nil
}
func computeDomains(ctx context.Context, ws string, env cfg.Context, cluster Planner, serverNaming *schema.Naming, allocatedName DomainsRequest) ([]*schema.Domain, error) {
computed, err := ComputeNaming(ctx, ws, env, cluster, serverNaming)
if err != nil {
return nil, err
}
return CalculateDomains(env.Environment(), computed, allocatedName)
}
type DomainsRequest struct {
ServerID string
ServiceName string
Key string // Usually `{ServiceName}-{ServerID}`
Alias string
// Set to true if the service we're allocating a domain for should be TLS
// terminated, regardless of whether we can emit a public-CA rooted
// certificate or not. E.g. for gRPC.
RequiresTLS bool
UserSpecified []*schema.DomainSpec
}
func CalculateDomains(env *schema.Environment, computed *schema.ComputedNaming, allocatedName DomainsRequest) ([]*schema.Domain, error) {
var domains []*schema.Domain
if computed.GetManaged() == schema.Domain_CLOUD_MANAGED ||
computed.GetManaged() == schema.Domain_CLOUD_TERMINATION ||
computed.GetManaged() == schema.Domain_LOCAL_MANAGED {
inclusterTls := allocatedName.RequiresTLS || env.Purpose == schema.Environment_PRODUCTION
computedDomain := &schema.Domain{
Managed: computed.Managed,
// If we have TLS termination at an upstream ingress (e.g. in nscloud's
// ingress), then still emit https (etc) addresses regardless of whether
// the in-cluster ingress has TLS termination or not.
TlsFrontend: computed.UpstreamTlsTermination || inclusterTls,
}
if computed.UseShortAlias {
// grpc-abcdef.nslocal.host
//
// grpc-abcdef.hugosantos.nscloud.dev
//
// grpc-abcdef-9d5h25dto9nkm.a.nscluster.cloud
// -> abcdef = sha256(env.name, pkggraph.Module_name)[6:]
if computed.MainModuleName == "" {
return nil, fnerrors.NamespaceTooOld("domain allocation", 0, 0)
}
x := kubenaming.StableIDN(fmt.Sprintf("%s:%s", env.Name, computed.MainModuleName), 6)
name := fmt.Sprintf("%s-%s", allocatedName.Alias, x)
if computed.DomainFragmentSuffix != "" {
computedDomain.Fqdn = fmt.Sprintf("%s-%s", name, computed.DomainFragmentSuffix)
} else {
computedDomain.Fqdn = name
}
} else {
if computed.DomainFragmentSuffix != "" {
computedDomain.Fqdn = fmt.Sprintf("%s-%s-%s", allocatedName.Key, env.Name, computed.DomainFragmentSuffix)
} else {
computedDomain.Fqdn = fmt.Sprintf("%s.%s", allocatedName.Key, env.Name)
}
}
baseDomain := computed.BaseDomain
// XXX make these runtime calls?
if allocatedName.RequiresTLS && computed.TlsPassthroughBaseDomain != "" {
baseDomain = computed.TlsPassthroughBaseDomain
}
computedDomain.Fqdn += "." + baseDomain
domains = append(domains, computedDomain)
}
for _, d := range computed.GetSource().GetAdditionalTlsManaged() {
d := d // Capture d.
if d.AllocatedName == allocatedName.Key {
domains = append(domains, &schema.Domain{
Fqdn: d.Fqdn,
Managed: schema.Domain_USER_SPECIFIED_TLS_MANAGED,
TlsFrontend: true,
})
}
}
for _, d := range computed.GetSource().GetAdditionalUserSpecified() {
if d.AllocatedName == allocatedName.Key {
domains = append(domains, &schema.Domain{
Fqdn: d.Fqdn,
Managed: schema.Domain_USER_SPECIFIED,
TlsFrontend: true,
})
}
}
for _, d := range allocatedName.UserSpecified {
domain := &schema.Domain{
Fqdn: d.Fqdn,
Managed: d.Managed,
}
if d.Managed == schema.Domain_USER_SPECIFIED_TLS_MANAGED {
domain.TlsFrontend = true
}
domains = append(domains, domain)
}
return domains, nil
}
func serverScoped(srv Deployable, name string) string {
name = srv.GetName() + "-" + name
if !strings.HasSuffix(name, "-"+srv.GetId()) {
return name + "-" + srv.GetId()
}
return name
}