-
Notifications
You must be signed in to change notification settings - Fork 681
/
server.go
543 lines (469 loc) · 17.1 KB
/
server.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Code generated by create_version. DO NOT EDIT.
// Copyright 2018 Envoyproxy 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 server provides an implementation of a streaming xDS server.
package server
import (
"context"
"errors"
"strconv"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
core "github.com/datawire/ambassador/pkg/api/envoy/config/core/v3"
clusterservice "github.com/datawire/ambassador/pkg/api/envoy/service/cluster/v3"
discovery "github.com/datawire/ambassador/pkg/api/envoy/service/discovery/v3"
discoverygrpc "github.com/datawire/ambassador/pkg/api/envoy/service/discovery/v3"
endpointservice "github.com/datawire/ambassador/pkg/api/envoy/service/endpoint/v3"
listenerservice "github.com/datawire/ambassador/pkg/api/envoy/service/listener/v3"
routeservice "github.com/datawire/ambassador/pkg/api/envoy/service/route/v3"
runtimeservice "github.com/datawire/ambassador/pkg/api/envoy/service/runtime/v3"
secretservice "github.com/datawire/ambassador/pkg/api/envoy/service/secret/v3"
"github.com/datawire/ambassador/pkg/envoy-control-plane/cache/v3"
"github.com/datawire/ambassador/pkg/envoy-control-plane/resource/v3"
)
// Server is a collection of handlers for streaming discovery requests.
type Server interface {
endpointservice.EndpointDiscoveryServiceServer
clusterservice.ClusterDiscoveryServiceServer
routeservice.RouteDiscoveryServiceServer
listenerservice.ListenerDiscoveryServiceServer
discoverygrpc.AggregatedDiscoveryServiceServer
secretservice.SecretDiscoveryServiceServer
runtimeservice.RuntimeDiscoveryServiceServer
// Fetch is the universal fetch method.
Fetch(context.Context, *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error)
}
// Callbacks is a collection of callbacks inserted into the server operation.
// The callbacks are invoked synchronously.
type Callbacks interface {
// OnStreamOpen is called once an xDS stream is open with a stream ID and the type URL (or "" for ADS).
// Returning an error will end processing and close the stream. OnStreamClosed will still be called.
OnStreamOpen(context.Context, int64, string) error
// OnStreamClosed is called immediately prior to closing an xDS stream with a stream ID.
OnStreamClosed(int64)
// OnStreamRequest is called once a request is received on a stream.
// Returning an error will end processing and close the stream. OnStreamClosed will still be called.
OnStreamRequest(int64, *discovery.DiscoveryRequest) error
// OnStreamResponse is called immediately prior to sending a response on a stream.
OnStreamResponse(int64, *discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
// OnFetchRequest is called for each Fetch request. Returning an error will end processing of the
// request and respond with an error.
OnFetchRequest(context.Context, *discovery.DiscoveryRequest) error
// OnFetchResponse is called immediately prior to sending a response.
OnFetchResponse(*discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
}
// CallbackFuncs is a convenience type for implementing the Callbacks interface.
type CallbackFuncs struct {
StreamOpenFunc func(context.Context, int64, string) error
StreamClosedFunc func(int64)
StreamRequestFunc func(int64, *discovery.DiscoveryRequest) error
StreamResponseFunc func(int64, *discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
FetchRequestFunc func(context.Context, *discovery.DiscoveryRequest) error
FetchResponseFunc func(*discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
}
var _ Callbacks = CallbackFuncs{}
// OnStreamOpen invokes StreamOpenFunc.
func (c CallbackFuncs) OnStreamOpen(ctx context.Context, streamID int64, typeURL string) error {
if c.StreamOpenFunc != nil {
return c.StreamOpenFunc(ctx, streamID, typeURL)
}
return nil
}
// OnStreamClosed invokes StreamClosedFunc.
func (c CallbackFuncs) OnStreamClosed(streamID int64) {
if c.StreamClosedFunc != nil {
c.StreamClosedFunc(streamID)
}
}
// OnStreamRequest invokes StreamRequestFunc.
func (c CallbackFuncs) OnStreamRequest(streamID int64, req *discovery.DiscoveryRequest) error {
if c.StreamRequestFunc != nil {
return c.StreamRequestFunc(streamID, req)
}
return nil
}
// OnStreamResponse invokes StreamResponseFunc.
func (c CallbackFuncs) OnStreamResponse(streamID int64, req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) {
if c.StreamResponseFunc != nil {
c.StreamResponseFunc(streamID, req, resp)
}
}
// OnFetchRequest invokes FetchRequestFunc.
func (c CallbackFuncs) OnFetchRequest(ctx context.Context, req *discovery.DiscoveryRequest) error {
if c.FetchRequestFunc != nil {
return c.FetchRequestFunc(ctx, req)
}
return nil
}
// OnFetchResponse invoked FetchResponseFunc.
func (c CallbackFuncs) OnFetchResponse(req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) {
if c.FetchResponseFunc != nil {
c.FetchResponseFunc(req, resp)
}
}
// NewServer creates handlers from a config watcher and callbacks.
func NewServer(ctx context.Context, config cache.Cache, callbacks Callbacks) Server {
return &server{cache: config, callbacks: callbacks, ctx: ctx}
}
type server struct {
cache cache.Cache
callbacks Callbacks
// streamCount for counting bi-di streams
streamCount int64
ctx context.Context
}
type stream interface {
grpc.ServerStream
Send(*discovery.DiscoveryResponse) error
Recv() (*discovery.DiscoveryRequest, error)
}
// watches for all xDS resource types
type watches struct {
endpoints chan cache.Response
clusters chan cache.Response
routes chan cache.Response
listeners chan cache.Response
secrets chan cache.Response
runtimes chan cache.Response
endpointCancel func()
clusterCancel func()
routeCancel func()
listenerCancel func()
secretCancel func()
runtimeCancel func()
endpointNonce string
clusterNonce string
routeNonce string
listenerNonce string
secretNonce string
runtimeNonce string
}
// Cancel all watches
func (values watches) Cancel() {
if values.endpointCancel != nil {
values.endpointCancel()
}
if values.clusterCancel != nil {
values.clusterCancel()
}
if values.routeCancel != nil {
values.routeCancel()
}
if values.listenerCancel != nil {
values.listenerCancel()
}
if values.secretCancel != nil {
values.secretCancel()
}
if values.runtimeCancel != nil {
values.runtimeCancel()
}
}
func createResponse(resp cache.Response, typeURL string) (*discovery.DiscoveryResponse, error) {
if resp == nil {
return nil, errors.New("missing response")
}
marshalledResponse, err := resp.GetDiscoveryResponse()
if err != nil {
return nil, err
}
return marshalledResponse, nil
}
// process handles a bi-di stream request
func (s *server) process(stream stream, reqCh <-chan *discovery.DiscoveryRequest, defaultTypeURL string) error {
// increment stream count
streamID := atomic.AddInt64(&s.streamCount, 1)
// unique nonce generator for req-resp pairs per xDS stream; the server
// ignores stale nonces. nonce is only modified within send() function.
var streamNonce int64
// a collection of watches per request type
var values watches
defer func() {
values.Cancel()
if s.callbacks != nil {
s.callbacks.OnStreamClosed(streamID)
}
}()
// sends a response by serializing to protobuf Any
send := func(resp cache.Response, typeURL string) (string, error) {
out, err := createResponse(resp, typeURL)
if err != nil {
return "", err
}
// increment nonce
streamNonce = streamNonce + 1
out.Nonce = strconv.FormatInt(streamNonce, 10)
if s.callbacks != nil {
s.callbacks.OnStreamResponse(streamID, resp.GetRequest(), out)
}
return out.Nonce, stream.Send(out)
}
if s.callbacks != nil {
if err := s.callbacks.OnStreamOpen(stream.Context(), streamID, defaultTypeURL); err != nil {
return err
}
}
// node may only be set on the first discovery request
var node = &core.Node{}
for {
select {
case <-s.ctx.Done():
return nil
// config watcher can send the requested resources types in any order
case resp, more := <-values.endpoints:
if !more {
return status.Errorf(codes.Unavailable, "endpoints watch failed")
}
nonce, err := send(resp, resource.EndpointType)
if err != nil {
return err
}
values.endpointNonce = nonce
case resp, more := <-values.clusters:
if !more {
return status.Errorf(codes.Unavailable, "clusters watch failed")
}
nonce, err := send(resp, resource.ClusterType)
if err != nil {
return err
}
values.clusterNonce = nonce
case resp, more := <-values.routes:
if !more {
return status.Errorf(codes.Unavailable, "routes watch failed")
}
nonce, err := send(resp, resource.RouteType)
if err != nil {
return err
}
values.routeNonce = nonce
case resp, more := <-values.listeners:
if !more {
return status.Errorf(codes.Unavailable, "listeners watch failed")
}
nonce, err := send(resp, resource.ListenerType)
if err != nil {
return err
}
values.listenerNonce = nonce
case resp, more := <-values.secrets:
if !more {
return status.Errorf(codes.Unavailable, "secrets watch failed")
}
nonce, err := send(resp, resource.SecretType)
if err != nil {
return err
}
values.secretNonce = nonce
case resp, more := <-values.runtimes:
if !more {
return status.Errorf(codes.Unavailable, "runtimes watch failed")
}
nonce, err := send(resp, resource.RuntimeType)
if err != nil {
return err
}
values.runtimeNonce = nonce
case req, more := <-reqCh:
// input stream ended or errored out
if !more {
return nil
}
if req == nil {
return status.Errorf(codes.Unavailable, "empty request")
}
// node field in discovery request is delta-compressed
if req.Node != nil {
node = req.Node
} else {
req.Node = node
}
// nonces can be reused across streams; we verify nonce only if nonce is not initialized
nonce := req.GetResponseNonce()
// type URL is required for ADS but is implicit for xDS
if defaultTypeURL == resource.AnyType {
if req.TypeUrl == "" {
return status.Errorf(codes.InvalidArgument, "type URL is required for ADS")
}
} else if req.TypeUrl == "" {
req.TypeUrl = defaultTypeURL
}
if s.callbacks != nil {
if err := s.callbacks.OnStreamRequest(streamID, req); err != nil {
return err
}
}
// cancel existing watches to (re-)request a newer version
switch {
case req.TypeUrl == resource.EndpointType && (values.endpointNonce == "" || values.endpointNonce == nonce):
if values.endpointCancel != nil {
values.endpointCancel()
}
values.endpoints, values.endpointCancel = s.cache.CreateWatch(*req)
case req.TypeUrl == resource.ClusterType && (values.clusterNonce == "" || values.clusterNonce == nonce):
if values.clusterCancel != nil {
values.clusterCancel()
}
values.clusters, values.clusterCancel = s.cache.CreateWatch(*req)
case req.TypeUrl == resource.RouteType && (values.routeNonce == "" || values.routeNonce == nonce):
if values.routeCancel != nil {
values.routeCancel()
}
values.routes, values.routeCancel = s.cache.CreateWatch(*req)
case req.TypeUrl == resource.ListenerType && (values.listenerNonce == "" || values.listenerNonce == nonce):
if values.listenerCancel != nil {
values.listenerCancel()
}
values.listeners, values.listenerCancel = s.cache.CreateWatch(*req)
case req.TypeUrl == resource.SecretType && (values.secretNonce == "" || values.secretNonce == nonce):
if values.secretCancel != nil {
values.secretCancel()
}
values.secrets, values.secretCancel = s.cache.CreateWatch(*req)
case req.TypeUrl == resource.RuntimeType && (values.runtimeNonce == "" || values.runtimeNonce == nonce):
if values.runtimeCancel != nil {
values.runtimeCancel()
}
values.runtimes, values.runtimeCancel = s.cache.CreateWatch(*req)
}
}
}
}
// handler converts a blocking read call to channels and initiates stream processing
func (s *server) handler(stream stream, typeURL string) error {
// a channel for receiving incoming requests
reqCh := make(chan *discovery.DiscoveryRequest)
reqStop := int32(0)
go func() {
for {
req, err := stream.Recv()
if atomic.LoadInt32(&reqStop) != 0 {
return
}
if err != nil {
close(reqCh)
return
}
reqCh <- req
}
}()
err := s.process(stream, reqCh, typeURL)
// prevents writing to a closed channel if send failed on blocked recv
// TODO(kuat) figure out how to unblock recv through gRPC API
atomic.StoreInt32(&reqStop, 1)
return err
}
func (s *server) StreamAggregatedResources(stream discoverygrpc.AggregatedDiscoveryService_StreamAggregatedResourcesServer) error {
return s.handler(stream, resource.AnyType)
}
func (s *server) StreamEndpoints(stream endpointservice.EndpointDiscoveryService_StreamEndpointsServer) error {
return s.handler(stream, resource.EndpointType)
}
func (s *server) StreamClusters(stream clusterservice.ClusterDiscoveryService_StreamClustersServer) error {
return s.handler(stream, resource.ClusterType)
}
func (s *server) StreamRoutes(stream routeservice.RouteDiscoveryService_StreamRoutesServer) error {
return s.handler(stream, resource.RouteType)
}
func (s *server) StreamListeners(stream listenerservice.ListenerDiscoveryService_StreamListenersServer) error {
return s.handler(stream, resource.ListenerType)
}
func (s *server) StreamSecrets(stream secretservice.SecretDiscoveryService_StreamSecretsServer) error {
return s.handler(stream, resource.SecretType)
}
func (s *server) StreamRuntime(stream runtimeservice.RuntimeDiscoveryService_StreamRuntimeServer) error {
return s.handler(stream, resource.RuntimeType)
}
// Fetch is the universal fetch method.
func (s *server) Fetch(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if s.callbacks != nil {
if err := s.callbacks.OnFetchRequest(ctx, req); err != nil {
return nil, err
}
}
resp, err := s.cache.Fetch(ctx, *req)
if err != nil {
return nil, err
}
out, err := createResponse(resp, req.TypeUrl)
if s.callbacks != nil {
s.callbacks.OnFetchResponse(req, out)
}
return out, err
}
func (s *server) FetchEndpoints(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.EndpointType
return s.Fetch(ctx, req)
}
func (s *server) FetchClusters(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.ClusterType
return s.Fetch(ctx, req)
}
func (s *server) FetchRoutes(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.RouteType
return s.Fetch(ctx, req)
}
func (s *server) FetchListeners(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.ListenerType
return s.Fetch(ctx, req)
}
func (s *server) FetchSecrets(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.SecretType
return s.Fetch(ctx, req)
}
func (s *server) FetchRuntime(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
if req == nil {
return nil, status.Errorf(codes.Unavailable, "empty request")
}
req.TypeUrl = resource.RuntimeType
return s.Fetch(ctx, req)
}
func (s *server) DeltaAggregatedResources(_ discoverygrpc.AggregatedDiscoveryService_DeltaAggregatedResourcesServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaEndpoints(_ endpointservice.EndpointDiscoveryService_DeltaEndpointsServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaClusters(_ clusterservice.ClusterDiscoveryService_DeltaClustersServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaRoutes(_ routeservice.RouteDiscoveryService_DeltaRoutesServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaListeners(_ listenerservice.ListenerDiscoveryService_DeltaListenersServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaSecrets(_ secretservice.SecretDiscoveryService_DeltaSecretsServer) error {
return errors.New("not implemented")
}
func (s *server) DeltaRuntime(_ runtimeservice.RuntimeDiscoveryService_DeltaRuntimeServer) error {
return errors.New("not implemented")
}