-
Notifications
You must be signed in to change notification settings - Fork 77
/
adapter.go
452 lines (372 loc) · 11.2 KB
/
adapter.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
Copyright 2018 Turbine Labs, Inc.
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 adapter provides adapters between Turbine Labs API objects and envoy
// xDS objects, in the form of an xDS server and ClusterCollector
// implementations
package adapter
import (
"encoding/base64"
"fmt"
"math"
"net"
"net/url"
"strings"
"time"
envoyapi "github.com/envoyproxy/go-control-plane/envoy/api/v2"
envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
"github.com/envoyproxy/go-control-plane/pkg/cache"
"github.com/gogo/protobuf/types"
tbnapi "github.com/turbinelabs/api"
"github.com/turbinelabs/nonstdlib/log/console"
"github.com/turbinelabs/nonstdlib/ptr"
"github.com/turbinelabs/rotor/xds/poller"
)
//go:generate $TBN_HOME/scripts/mockgen_internal.sh -type resourceAdapter -type listenerAdapter -type clusterAdapter -source $GOFILE -destination mock_$GOFILE -package $GOPACKAGE --write_package_comment=false
// SnapshotAdapter turns poller.Objects into a cache.Snapshot
type snapshotAdapter func(*poller.Objects) (cache.Snapshot, error)
// ResourceAdapter turns poller.Objects into cache.Resources
type resourceAdapter interface {
adapt(*poller.Objects) (cache.Resources, error)
}
type listenerAdapter interface {
resourceAdapter
inject(*envoyapi.Listener) error
}
type clusterAdapter interface {
resourceAdapter
withTemplate(*envoyapi.Cluster) clusterAdapter
}
// NewSnapshotAdapter creates an SnapshotAdapter from the given ResourceAdapters.
func newSnapshotAdapter(
eAdapter resourceAdapter,
cAdapter clusterAdapter,
rAdapter resourceAdapter,
lAdapter listenerAdapter,
provider staticResourcesProvider,
) snapshotAdapter {
return func(objs *poller.Objects) (cache.Snapshot, error) {
var staticRes staticResources
if provider != nil {
staticRes = provider.StaticResources()
}
endpoints, err := eAdapter.adapt(objs)
if err != nil {
return cache.Snapshot{}, err
}
if len(staticRes.loadAssigments) > 0 {
if staticRes.conflictBehavior == overwriteBehavior {
endpoints.Items = map[string]cache.Resource{}
}
for _, la := range staticRes.loadAssigments {
endpoints.Items[la.GetClusterName()] = la
}
}
clusters, err := cAdapter.withTemplate(staticRes.clusterTemplate).adapt(objs)
if err != nil {
return cache.Snapshot{}, err
}
if len(staticRes.clusters) > 0 {
if staticRes.conflictBehavior == overwriteBehavior {
clusters.Items = map[string]cache.Resource{}
}
for _, cluster := range staticRes.clusters {
clusters.Items[cluster.GetName()] = cluster
}
}
// if there are static clusters or a cluster template, vary the version
if len(staticRes.clusters) > 0 || staticRes.clusterTemplate != nil {
clusters.Version += staticRes.version
}
routes, err := rAdapter.adapt(objs)
if err != nil {
return cache.Snapshot{}, err
}
listeners, err := lAdapter.adapt(objs)
if err != nil {
return cache.Snapshot{}, err
}
if len(staticRes.listeners) > 0 {
lm := newListenerMap(false)
if staticRes.conflictBehavior == mergeBehavior {
for k := range listeners.Items {
if l, ok := listeners.Items[k].(*envoyapi.Listener); ok {
lm.addListener(l)
}
}
}
// inject, then add listeners to map
for _, l := range staticRes.listeners {
err = lAdapter.inject(l)
if err != nil {
console.Error().Printf(
"failed to inject ALS logging into static listener %s: %s", l.Name, err)
} else {
lm.addListener(l)
}
}
listeners.Items = lm.resourceMap()
// change the version, since it's different than without static resources
listeners.Version += staticRes.version
}
return cache.Snapshot{
Endpoints: endpoints,
Clusters: clusters,
Routes: routes,
Listeners: listeners,
}, nil
}
}
// newEndpointAdapter returns a resourceAdapter that produces Endpoint
// Resources.
func newEndpointAdapter(resolveDNS bool) resourceAdapter {
if resolveDNS {
return eds{resolveDNS: net.LookupIP}
}
return eds{}
}
// newClusterAdapter returns a resourceAdapter that produces Cluster Resources.
// If non-empty, the caFile string specifies a path for the certificate
// authority, which must be present on the Envoy serving traffic to these
// Clusters.
func newClusterAdapter(caFile string) clusterAdapter {
return cds{caFile: caFile}
}
// newRouteAdapter returns a resourceAdapter that produces Route Resources. The
// defaultTimeout specifies the request timeout to be used for each RouteAction
// if no Route-specific timeout is configured.
func newRouteAdapter(defaultTimeout time.Duration) resourceAdapter {
return rds{defaultTimeout}
}
// newListenerAdapter returns a resourceAdapter that produces Listener
// Resources. The loggingCluster argument specifies the AccessLogService cluster
// name to be used when configuring logging for each Listener.
func newListenerAdapter(loggingCluster string) listenerAdapter {
return lds{loggingCluster: loggingCluster}
}
// constants used when handing out configs for other xDS resources,
// served by this service
const (
defaultRoutingPriority = envoycore.RoutingPriority_DEFAULT
loadBalancerMetadataKey = "envoy.lb"
xdsClusterName = "tbn-xds"
xdsRefreshDelaySecs = 30
httpsRedirectName = "force-https"
)
var (
xdsClusterConfig = envoycore.ConfigSource{
ConfigSourceSpecifier: &envoycore.ConfigSource_ApiConfigSource{
ApiConfigSource: &envoycore.ApiConfigSource{
ApiType: envoycore.ApiConfigSource_GRPC,
GrpcServices: []*envoycore.GrpcService{
{
TargetSpecifier: &envoycore.GrpcService_EnvoyGrpc_{
EnvoyGrpc: &envoycore.GrpcService_EnvoyGrpc{
ClusterName: xdsClusterName,
},
},
},
},
RefreshDelay: ptr.Duration(xdsRefreshDelaySecs * time.Second),
},
},
}
)
func mkEnvoyAddress(host string, port int) *envoycore.Address {
return &envoycore.Address{
Address: &envoycore.Address_SocketAddress{
SocketAddress: &envoycore.SocketAddress{
Protocol: envoycore.TCP,
Address: host,
PortSpecifier: &envoycore.SocketAddress_PortValue{
PortValue: uint32(port),
},
},
},
}
}
func mkStatsName(name string, port int) string {
return fmt.Sprintf("%s-%d", name, port)
}
func toEnvoyMetadata(metadata tbnapi.Metadata) *envoycore.Metadata {
if len(metadata) == 0 {
return &envoycore.Metadata{}
}
fields := make(map[string]*types.Value, len(metadata))
for _, metadatum := range metadata {
value := escapeMetadata(metadatum.Value)
fields[metadatum.Key] = valueString(value)
}
return &envoycore.Metadata{
FilterMetadata: map[string]*types.Struct{
loadBalancerMetadataKey: {Fields: fields},
},
}
}
// Determines if a redirect is a valid https for the provided domain name.
func isHTTPSRedirect(host string, rd tbnapi.Redirect) bool {
nameOk := rd.Name == httpsRedirectName
fromOk := rd.From == "(.*)"
u, err := url.Parse(rd.To)
// who knows what happened here, but it's not a redirect
if err != nil {
return false
}
hostPortOk := false
// Url parsing is a bit weird when it comes to including capture groups.
// Depending on whether there's a port specified, the '$1' will end up
// in a different spot.
switch {
case u.Hostname() == "$host" || u.Hostname() == host:
hostPortOk = strings.HasSuffix(u.Port(), "$1") && strings.Count(u.Port(), "$1") == 1
case u.Hostname() == "$host$1" || u.Hostname() == fmt.Sprintf("%s$1", host):
hostPortOk = u.Port() == ""
}
destPathOk := u.EscapedPath() == ""
toOk := u.Scheme == "https" && hostPortOk && destPathOk
typeOk := rd.RedirectType == tbnapi.PermanentRedirect
hcsOk := false
switch {
case len(rd.HeaderConstraints) == 0:
hcsOk = true
case len(rd.HeaderConstraints) == 1:
hc := rd.HeaderConstraints[0]
hcsOk = hc.Name == "X-Forwarded-Proto" && hc.Value == "https" && hc.Invert
default:
hcsOk = false
}
return nameOk && fromOk && toOk && typeOk && hcsOk
}
func boolValue(b bool) *types.BoolValue {
return &types.BoolValue{Value: b}
}
func boolPtrToBoolValue(bPtr *bool) *types.BoolValue {
if bPtr == nil {
return nil
}
return boolValue(*bPtr)
}
func boolValueToBoolPtr(bv *types.BoolValue) *bool {
if bv == nil {
return nil
}
return ptr.Bool(bv.Value)
}
func uint32Value(v uint32) *types.UInt32Value {
return &types.UInt32Value{Value: v}
}
func valueString(s string) *types.Value {
return &types.Value{
Kind: &types.Value_StringValue{StringValue: s},
}
}
func intPtrToUint32Ptr(intPtr *int) *types.UInt32Value {
if intPtr == nil {
return nil
}
return intToUint32Ptr(*intPtr)
}
func intToUint32Ptr(i int) *types.UInt32Value {
return &types.UInt32Value{Value: uint32(i)}
}
func uint32PtrToIntPtr(ui32 *types.UInt32Value) *int {
if ui32 == nil {
return nil
}
return ptr.Int(int(ui32.GetValue()))
}
func uint32PtrToInt(ui32 *types.UInt32Value) int {
iPtr := uint32PtrToIntPtr(ui32)
if iPtr == nil {
return 0
}
return *iPtr
}
func intPtrToDurationPtr(intPtr *int) *types.Duration {
if intPtr == nil {
return nil
}
return intToDurationPtr(*intPtr)
}
func intToDurationPtr(i int) *types.Duration {
return &types.Duration{
Seconds: int64(i / 1000),
Nanos: int32((i % 1000) * int(time.Millisecond)),
}
}
func intToTimeDurationPtr(i int, scale time.Duration) *time.Duration {
return durationPtr(time.Duration(i) * scale)
}
func intPtrToTimeDurationPtr(i *int, scale time.Duration) *time.Duration {
if i == nil {
return nil
}
return intToTimeDurationPtr(*i, scale)
}
func durationPtr(d time.Duration) *time.Duration {
return &d
}
// durationPtrToIntPtr supports millisecond granularity, which has the following
// implications:
// - a Duration greater than math.MaxInt32 milliseconds will return nil
// - Nanos will be truncated at the millisecond boundary
func durationPtrToIntPtr(d *types.Duration) *int {
if d == nil {
return nil
}
secs := time.Duration(d.Seconds) * time.Second
nanos := time.Duration(d.Nanos)
final := (secs + nanos) / time.Millisecond
if final > math.MaxInt32 {
return nil
}
return ptr.Int(int(final))
}
func durationPtrToInt(d *types.Duration) int {
iPtr := durationPtrToIntPtr(d)
if iPtr == nil {
return 0
}
return *iPtr
}
func timeDurationPtrToInt(d *time.Duration, scale time.Duration) int {
if d == nil {
return 0
}
return int(*d / scale)
}
func base64StringToPayload(str string) (*envoycore.HealthCheck_Payload, error) {
if len(str) == 0 {
return nil, nil
}
sb, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, err
}
return bytesToPayload(sb), nil
}
func bytesToPayload(b []byte) *envoycore.HealthCheck_Payload {
if len(b) == 0 {
return nil
}
return &envoycore.HealthCheck_Payload{
Payload: &envoycore.HealthCheck_Payload_Binary{
Binary: b,
},
}
}
func bytesToBase64String(b []byte) string {
if b == nil {
return ""
}
return base64.StdEncoding.EncodeToString(b)
}