Debian Codegraph @

pkg/server/sotw/v3/server.go

raw symbols SCIP
1 // Copyright 2020 Envoyproxy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package sotw provides an implementation of GRPC SoTW (State of The World) part of XDS server
16 package sotw
17
18 import (
19 "context"
20 "errors"
21 "strconv"
22 "sync/atomic"
23
24 core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
25 discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
26 "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
27 "github.com/envoyproxy/go-control-plane/pkg/server/config"
28 "github.com/envoyproxy/go-control-plane/pkg/server/stream/v3"
29 )
30
31 type Server interface {
32 StreamHandler(stream stream.Stream, typeURL string) error
33 }
34
35 type Callbacks interface {
36 // OnStreamOpen is called once an xDS stream is open with a stream ID and the type URL (or "" for ADS).
37 // Returning an error will end processing and close the stream. OnStreamClosed will still be called.
38 OnStreamOpen(context.Context, int64, string) error
39 // OnStreamClosed is called immediately prior to closing an xDS stream with a stream ID.
40 OnStreamClosed(int64, *core.Node)
41 // OnStreamRequest is called once a request is received on a stream.
42 // Returning an error will end processing and close the stream. OnStreamClosed will still be called.
43 OnStreamRequest(int64, *discovery.DiscoveryRequest) error
44 // OnStreamResponse is called immediately prior to sending a response on a stream.
45 OnStreamResponse(context.Context, int64, *discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
46 }
47
48 // NewServer creates handlers from a config watcher and callbacks.
49 func NewServer(ctx context.Context, cw cache.ConfigWatcher, callbacks Callbacks, opts ...config.XDSOption) Server {
50 s := &server{cache: cw, callbacks: callbacks, ctx: ctx, opts: config.NewOpts()}
51
52 // Parse through our options
53 for _, opt := range opts {
54 opt(&s.opts)
55 }
56
57 return s
58 }
59
60 // WithOrderedADS enables the internal flag to order responses
61 // strictly.
62 func WithOrderedADS() config.XDSOption {
63 return func(o *config.Opts) {
64 o.Ordered = true
65 }
66 }
67
68 type server struct {
69 cache cache.ConfigWatcher
70 callbacks Callbacks
71 ctx context.Context
72
73 // streamCount for counting bi-di streams
74 streamCount int64
75
76 // Local configuration flags for individual xDS implementations.
77 opts config.Opts
78 }
79
80 // streamWrapper abstracts critical data passed around a stream for to be accessed
81 // through various code paths in the xDS lifecycle. This comes in handy when dealing
82 // with varying implementation types such as ordered vs unordered resource handling.
83 type streamWrapper struct {
84 stream stream.Stream // parent stream object
85 ID int64 // stream ID in relation to total stream count
86 nonce int64 // nonce per stream
87 watches watches // collection of stack allocated watchers per request type
88 callbacks Callbacks // callbacks for performing actions through stream lifecycle
89
90 node *core.Node // registered xDS client
91
92 // The below fields are used for tracking resource
93 // cache state and should be maintained per stream.
94 streamState stream.StreamState
95 lastDiscoveryResponses map[string]lastDiscoveryResponse
96 }
97
98 // Send packages the necessary resources before sending on the gRPC stream,
99 // and sets the current state of the world.
100 func (s *streamWrapper) send(resp cache.Response) (string, error) {
101 if resp == nil {
102 return "", errors.New("missing response")
103 }
104
105 out, err := resp.GetDiscoveryResponse()
106 if err != nil {
107 return "", err
108 }
109
110 // increment nonce and convert it to base10
111 out.Nonce = strconv.FormatInt(atomic.AddInt64(&s.nonce, 1), 10)
112
113 lastResponse := lastDiscoveryResponse{
114 nonce: out.GetNonce(),
115 resources: make(map[string]struct{}),
116 }
117 for _, r := range resp.GetRequest().GetResourceNames() {
118 lastResponse.resources[r] = struct{}{}
119 }
120 s.lastDiscoveryResponses[resp.GetRequest().GetTypeUrl()] = lastResponse
121
122 // Register with the callbacks provided that we are sending the response.
123 if s.callbacks != nil {
124 s.callbacks.OnStreamResponse(resp.GetContext(), s.ID, resp.GetRequest(), out)
125 }
126
127 return out.GetNonce(), s.stream.Send(out)
128 }
129
130 // Shutdown closes all open watches, and notifies API consumers the stream has closed.
131 func (s *streamWrapper) shutdown() {
132 s.watches.close()
133 if s.callbacks != nil {
134 s.callbacks.OnStreamClosed(s.ID, s.node)
135 }
136 }
137
138 // Discovery response that is sent over GRPC stream.
139 // We need to record what resource names are already sent to a client
140 // So if the client requests a new name we can respond back
141 // regardless current snapshot version (even if it is not changed yet)
142 type lastDiscoveryResponse struct {
143 nonce string
144 resources map[string]struct{}
145 }
146
147 // StreamHandler converts a blocking read call to channels and initiates stream processing
148 func (s *server) StreamHandler(stream stream.Stream, typeURL string) error {
149 // a channel for receiving incoming requests
150 reqCh := make(chan *discovery.DiscoveryRequest)
151 go func() {
152 defer close(reqCh)
153 for {
154 req, err := stream.Recv()
155 if err != nil {
156 return
157 }
158 select {
159 case reqCh <- req:
160 case <-stream.Context().Done():
161 return
162 case <-s.ctx.Done():
163 return
164 }
165 }
166 }()
167
168 return s.process(stream, reqCh, typeURL)
169 }