generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuilder_kubernetes.go
350 lines (300 loc) · 8.53 KB
/
builder_kubernetes.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
package ferrite
import (
"errors"
"fmt"
"net"
"strings"
"unicode"
"github.com/dogmatiq/ferrite/internal/variable"
)
// KubernetesAddress is the address of a Kubernetes service.
type KubernetesAddress struct {
Host string
Port string
}
func (a KubernetesAddress) String() string {
return net.JoinHostPort(a.Host, a.Port)
}
// KubernetesService configures environment variables used to obtain the network
// address of a specific Kubernetes service.
//
// svc is the name of the Kubernetes service, NOT the environment variable.
//
// The environment variables "<svc>_SERVICE_HOST" and "<svc>_SERVICE_PORT" are
// used to construct an address for the service.
func KubernetesService(svc string) *KubernetesServiceBuilder {
if err := validateKubernetesName(svc); err != nil {
panic(fmt.Sprintf(
"kubernetes service name is invalid: %s",
err,
))
}
b := &KubernetesServiceBuilder{
service: svc,
}
const docs = "It is expected that this variable will be implicitly defined by Kubernetes; " +
"it typically does not need to be specified in the pod manifest."
b.hostBuilder.Name(
fmt.Sprintf(
"%s_SERVICE_HOST",
kubernetesNameToEnv(svc),
),
)
b.hostBuilder.Description(
fmt.Sprintf(
"kubernetes %q service host",
b.service,
),
)
b.hostBuilder.BuiltInConstraint(
"**MUST** be a valid hostname",
func(_ variable.ConstraintContext, h string) variable.ConstraintError {
return validateHost(h)
},
)
b.hostBuilder.Documentation().
Paragraph(docs).
Format().
Important().
Done()
b.portBuilder.Name(
fmt.Sprintf(
"%s_SERVICE_PORT",
kubernetesNameToEnv(svc),
),
)
b.portBuilder.Description(
fmt.Sprintf(
"kubernetes %q service port",
b.service,
),
)
b.portBuilder.BuiltInConstraint(
"**MUST** be a valid network port",
func(_ variable.ConstraintContext, p string) variable.ConstraintError {
return validatePort(p)
},
)
b.portBuilder.Documentation().
Paragraph(docs).
Format().
Important().
Done()
buildNetworkPortSyntaxDocumentation(b.portBuilder.Documentation())
variable.EstablishRelationships(
variable.RefersTo{
Subject: b.hostBuilder.Peek(),
RefersTo: b.portBuilder.Peek(),
},
variable.RefersTo{
Subject: b.portBuilder.Peek(),
RefersTo: b.hostBuilder.Peek(),
},
)
return b
}
// KubernetesServiceBuilder is the specification for a Kubernetes service.
type KubernetesServiceBuilder struct {
service string
hostSchema variable.TypedString[string]
portSchema variable.TypedString[string]
hostBuilder variable.TypedSpecBuilder[string]
portBuilder variable.TypedSpecBuilder[string]
}
var _ isBuilderOf[KubernetesAddress, *KubernetesServiceBuilder]
// WithNamedPort uses a Kubernetes named port instead of the default service
// port.
//
// The "<service>_SERVICE_PORT_<port>" environment variable is used instead of
// "<service>_SERVICE_PORT".
//
// The Kubernetes port name is the name configured in the service manifest. It
// is not to be confused with an IANA registered service name (e.g. "https"),
// although the two may use the same names.
//
// See https://kubernetes.io/docs/concepts/services-networking/service/#multi-port-services
func (b *KubernetesServiceBuilder) WithNamedPort(port string) *KubernetesServiceBuilder {
if err := validateKubernetesName(port); err != nil {
panic(fmt.Sprintf(
"specification of kubernetes %q service is invalid: invalid named port: %s",
b.service,
err,
))
}
b.portBuilder.Name(
fmt.Sprintf(
"%s_SERVICE_PORT_%s",
kubernetesNameToEnv(b.service),
kubernetesNameToEnv(port),
),
)
return b
}
// WithDefault sets a default value to use when the environment variables are
// undefined.
//
// The port may be a numeric value between 1 and 65535, or an IANA registered
// service name (such as "https"). The IANA name is not to be confused with the
// Kubernetes servcice name or port name.
func (b *KubernetesServiceBuilder) WithDefault(host, port string) *KubernetesServiceBuilder {
b.hostBuilder.Default(host)
b.portBuilder.Default(port)
return b
}
// Required completes the build process and registers required variables with
// Ferrite's validation system.
func (b *KubernetesServiceBuilder) Required(options ...RequiredOption) Required[KubernetesAddress] {
b.hostBuilder.MarkRequired()
b.portBuilder.MarkRequired()
var cfg variableSetConfig
for _, opt := range options {
opt.applyRequiredOptionToConfig(&cfg)
opt.applyRequiredOptionToSpec(&b.hostBuilder)
opt.applyRequiredOptionToSpec(&b.portBuilder)
}
host := variable.Register(
cfg.Registries,
b.hostBuilder.Done(b.hostSchema),
)
port := variable.Register(
cfg.Registries,
b.portBuilder.Done(b.portSchema),
)
return requiredFunc[KubernetesAddress]{
[]variable.Any{host, port},
func() (KubernetesAddress, error) {
if err := host.Error(); err != nil {
return KubernetesAddress{}, err
}
if err := port.Error(); err != nil {
return KubernetesAddress{}, err
}
return KubernetesAddress{
host.NativeValue(),
port.NativeValue(),
}, nil
},
}
}
// Optional completes the build process and registers optional variables with
// Ferrite's validation system.
func (b *KubernetesServiceBuilder) Optional(options ...OptionalOption) Optional[KubernetesAddress] {
var cfg variableSetConfig
for _, opt := range options {
opt.applyOptionalOptionToConfig(&cfg)
opt.applyOptionalOptionToSpec(&b.hostBuilder)
opt.applyOptionalOptionToSpec(&b.portBuilder)
}
host := variable.Register(
cfg.Registries,
b.hostBuilder.Done(b.hostSchema),
)
port := variable.Register(
cfg.Registries,
b.portBuilder.Done(b.portSchema),
)
return optionalFunc[KubernetesAddress]{
[]variable.Any{host, port},
b.optionalResolver(host, port),
}
}
// Deprecated completes the build process and registers deprecated variables
// with Ferrite's validation system.
func (b *KubernetesServiceBuilder) Deprecated(options ...DeprecatedOption) Deprecated[KubernetesAddress] {
b.hostBuilder.MarkDeprecated()
b.portBuilder.MarkDeprecated()
var cfg variableSetConfig
for _, opt := range options {
opt.applyDeprecatedOptionToConfig(&cfg)
opt.applyDeprecatedOptionToSpec(&b.hostBuilder)
opt.applyDeprecatedOptionToSpec(&b.portBuilder)
}
host := variable.Register(
cfg.Registries,
b.hostBuilder.Done(b.hostSchema),
)
port := variable.Register(
cfg.Registries,
b.portBuilder.Done(b.portSchema),
)
return deprecatedFunc[KubernetesAddress]{
[]variable.Any{host, port},
b.optionalResolver(host, port),
}
}
func (b *KubernetesServiceBuilder) optionalResolver(
host, port *variable.OfType[string],
) func() (KubernetesAddress, bool, error) {
return func() (KubernetesAddress, bool, error) {
if err := host.Error(); err != nil {
return KubernetesAddress{}, false, err
}
if err := port.Error(); err != nil {
return KubernetesAddress{}, false, err
}
availability := host.Availability()
if port.Availability() != availability {
def, undef := host, port
if availability != variable.AvailabilityOK {
def, undef = undef, def
}
return KubernetesAddress{}, false, fmt.Errorf(
"%s is defined but %s is not, define both or neither",
def.Spec().Name(),
undef.Spec().Name(),
)
}
return KubernetesAddress{
host.NativeValue(),
port.NativeValue(),
}, availability == variable.AvailabilityOK, nil
}
}
// kubernetesNameToEnv converts a kubernetes resource name to an environment variable
// name, as per Kubernetes own behavior.
func kubernetesNameToEnv(s string) string {
return strings.ToUpper(
strings.ReplaceAll(s, "-", "_"),
)
}
// validateKubernetesName returns an error if name is not a valid Kubernetes
// resource name.
func validateKubernetesName(name string) error {
if name == "" {
return errors.New("name must not be empty")
}
n := len(name)
if name[0] == '-' || name[n-1] == '-' {
return errors.New("name must not begin or end with a hyphen")
}
for i := range name {
ch := name[i] // iterate by byte (not rune)
switch {
case ch >= 'a' && ch <= 'z':
case ch >= '0' && ch <= '9':
case ch == '-':
default:
return errors.New("name must contain only lowercase ASCII letters, digits and hyphen")
}
}
return nil
}
// validateHost returns an error of host is not a valid hostname.
func validateHost(host string) error {
if host == "" {
return errors.New("host must not be empty")
}
if net.ParseIP(host) != nil {
return nil
}
n := len(host)
if host[0] == '.' || host[n-1] == '.' {
return errors.New("host must not begin or end with a dot")
}
for _, r := range host {
if unicode.IsSpace(r) {
return errors.New("host must not contain whitespace")
}
}
return nil
}