-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
252 lines (215 loc) · 7.57 KB
/
main.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
// 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 main
import (
"context"
"fmt"
"google.golang.org/protobuf/types/known/anypb"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"namespacelabs.dev/foundation/framework/kubernetes/kubedef"
"namespacelabs.dev/foundation/framework/provisioning"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/networking/ingress/nginx"
"namespacelabs.dev/foundation/internal/planning/tool/protocol"
"namespacelabs.dev/foundation/library/kubernetes/ingress"
"namespacelabs.dev/foundation/library/runtime"
"namespacelabs.dev/foundation/schema"
)
func main() {
h := provisioning.NewHandlers()
henv := h.MatchEnv(&schema.Environment{Runtime: "kubernetes"})
henv.HandleApply(func(ctx context.Context, req provisioning.StackRequest, out *provisioning.ApplyOutput) error {
intent := &ingress.IngressIntent{}
if err := req.UnpackInput(intent); err != nil {
return err
}
labels := kubedef.MakeLabels(intent.Env, intent.Deployable)
source := &protocol.ResourceInstance{}
if err := req.UnpackInput(source); err != nil {
return err
}
instance := &runtime.IngressInstance{}
for _, endpoint := range intent.Endpoint {
if endpoint.Port == nil {
// Maybe fail.
continue
}
var domains []*schema.Domain
for _, base := range intent.ApplicationBaseDomain {
domains = append(domains, &schema.Domain{
Fqdn: fmt.Sprintf("%s.%s", endpoint.AllocatedName, base),
Managed: schema.Domain_LOCAL_MANAGED,
})
}
for _, domain := range endpoint.GetIngressSpec().GetDomain() {
domains = append(domains, &schema.Domain{
Fqdn: domain.Fqdn,
Managed: schema.Domain_USER_SPECIFIED,
})
}
if len(domains) == 0 {
continue
}
name := endpoint.ServiceName
backend := networkingv1.IngressBackend{
Service: &networkingv1.IngressServiceBackend{
Name: endpoint.AllocatedName,
Port: networkingv1.ServiceBackendPort{
Number: endpoint.Port.ContainerPort,
},
},
}
for _, domain := range domains {
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 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 {
continue
}
var spec networkingv1.IngressSpec
var grpcCount, clearTextGrpcCount int
switch *protocol {
case schema.HttpProtocol:
for _, details := range protocolDetails {
p := &schema.HttpUrlMap{}
if err := details.UnmarshalTo(p); err != nil {
return err
}
var rules networkingv1.HTTPIngressRuleValue
for _, entry := range p.Entry {
rules.Paths = append(rules.Paths, makePathPrefix(entry.PathPrefix, backend))
}
spec.Rules = append(spec.Rules, makeRule(domain.Fqdn, rules))
}
case schema.GrpcProtocol, schema.ClearTextGrpcProtocol:
for _, details := range protocolDetails {
msg, err := details.UnmarshalNew()
if err != nil {
return fnerrors.InternalError("failed to unserialize grpc configuration: %w", err)
}
if *protocol == schema.ClearTextGrpcProtocol {
clearTextGrpcCount++
} else {
grpcCount++
}
switch p := msg.(type) {
case *schema.GrpcExportService:
grpcService := p.ProtoTypename
if grpcService == "" {
return fnerrors.InternalError("%s: grpc service name is required", endpoint.ServiceName)
}
var rules networkingv1.HTTPIngressRuleValue
for _, method := range p.Method {
rules.Paths = append(rules.Paths, makePathPrefix(fmt.Sprintf("/%s/%s", grpcService, method), backend))
}
if len(rules.Paths) == 0 {
rules.Paths = append(rules.Paths, makePathPrefix("/"+grpcService, backend))
}
if p.ServerReflectionIncluded {
rules.Paths = append(rules.Paths, makePathPrefix("/grpc.reflection.v1alpha.ServerReflection", backend))
}
spec.Rules = append(spec.Rules, makeRule(domain.Fqdn, rules))
case *schema.GrpcExportAllServices:
var rules networkingv1.HTTPIngressRuleValue
rules.Paths = append(rules.Paths, makePathPrefix("/", backend))
spec.Rules = append(spec.Rules, makeRule(domain.Fqdn, rules))
default:
return fnerrors.InternalError("unsupported grpc configuration: %v", p.ProtoReflect().Descriptor().FullName())
}
}
default:
return fnerrors.New("%s: unsupported ingress protocol", *protocol)
}
if len(spec.Rules) == 0 {
var rules networkingv1.HTTPIngressRuleValue
rules.Paths = append(rules.Paths, makePathPrefix("/", backend))
spec.Rules = append(spec.Rules, makeRule(domain.Fqdn, rules))
}
backendProtocol := kubedef.BackendProtocol_HTTP
if clearTextGrpcCount > 0 {
backendProtocol = kubedef.BackendProtocol_GRPC
}
if grpcCount > 0 {
backendProtocol = kubedef.BackendProtocol_GRPCS
}
// XXX make nginx configurable.
annotations, err := nginx.Annotate(false, backendProtocol, httpExtensions, endpoint.GetIngressSpec().GetAnnotations())
if err != nil {
return err
}
out.Invocations = append(out.Invocations, kubedef.Apply{
Description: fmt.Sprintf("Ingress %s", name),
SetNamespace: true,
Resource: networkingv1.Ingress{
TypeMeta: metav1.TypeMeta{
Kind: "Ingress",
APIVersion: "networking.k8s.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: labels,
Annotations: annotations.Annotations,
},
Spec: spec,
},
SchedAfterCategory: []string{
kubedef.MakeServicesCat(intent.Deployable),
},
})
out.Invocations = append(out.Invocations, annotations.Resources...)
// A fragment is emited for visualization purposes.
// XXX revisit "fragment" as an input, into strictly being an output.
fragment := &schema.IngressFragment{
Owner: endpoint.EndpointOwner,
Endpoint: endpoint,
Domain: domain,
}
for _, path := range spec.Rules {
for _, y := range path.HTTP.Paths {
fragment.HttpPath = append(fragment.HttpPath, &schema.IngressFragment_IngressHttpPath{
Path: y.Path,
Owner: endpoint.EndpointOwner,
Service: endpoint.AllocatedName,
ServicePort: endpoint.GetExportedPort(),
})
}
}
instance.IngressFragment = append(instance.IngressFragment, fragment)
}
}
out.OutputResourceInstance = instance
return nil
})
provisioning.Handle(h)
}
func makeRule(domain string, rules networkingv1.HTTPIngressRuleValue) networkingv1.IngressRule {
return networkingv1.IngressRule{
Host: domain,
IngressRuleValue: networkingv1.IngressRuleValue{HTTP: &rules},
}
}
func makePathPrefix(path string, backend networkingv1.IngressBackend) networkingv1.HTTPIngressPath {
x := networkingv1.PathTypePrefix
return networkingv1.HTTPIngressPath{
Path: "/",
PathType: &x,
Backend: backend,
}
}