Debian Codegraph @

pkg/server/sotw/v3/xds.go

raw symbols SCIP
1 package sotw
2
3 import (
4 "reflect"
5 "sync/atomic"
6
7 "google.golang.org/grpc/codes"
8 "google.golang.org/grpc/status"
9
10 core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
11 discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
12 "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
13 "github.com/envoyproxy/go-control-plane/pkg/resource/v3"
14 "github.com/envoyproxy/go-control-plane/pkg/server/stream/v3"
15 )
16
17 // process handles a bi-di stream request
18 func (s *server) process(str stream.Stream, reqCh chan *discovery.DiscoveryRequest, defaultTypeURL string) error {
19 // create our streamWrapper which can be passed down to sub control loops.
20 // this is useful for abstracting critical information for various types of
21 // xDS resource processing.
22 sw := streamWrapper{
23 stream: str,
24 ID: atomic.AddInt64(&s.streamCount, 1), // increment stream count
25 callbacks: s.callbacks,
26 node: &core.Node{}, // node may only be set on the first discovery request
27
28 // a collection of stack allocated watches per request type.
29 watches: newWatches(),
30 streamState: stream.NewStreamState(false, map[string]string{}),
31 lastDiscoveryResponses: make(map[string]lastDiscoveryResponse),
32 }
33
34 // cleanup once our stream has ended.
35 defer sw.shutdown()
36
37 if s.callbacks != nil {
38 if err := s.callbacks.OnStreamOpen(str.Context(), sw.ID, defaultTypeURL); err != nil {
39 return err
40 }
41 }
42
43 // do an initial recompute so we can load the first 2 channels:
44 // <-reqCh
45 // s.ctx.Done()
46 sw.watches.recompute(s.ctx, reqCh)
47
48 for {
49 // The list of select cases looks like this:
50 // 0: <- ctx.Done
51 // 1: <- reqCh
52 // 2...: per type watches
53 index, value, ok := reflect.Select(sw.watches.cases)
54 switch index {
55 // ctx.Done() -> if we receive a value here we return
56 // as no further computation is needed
57 case 0:
58 return nil
59 // Case 1 handles any request inbound on the stream
60 // and handles all initialization as needed
61 case 1:
62 // input stream ended or failed
63 if !ok {
64 return nil
65 }
66
67 req := value.Interface().(*discovery.DiscoveryRequest)
68 if req == nil {
69 return status.Errorf(codes.Unavailable, "empty request")
70 }
71
72 // Only first request is guaranteed to hold node info so if it's missing, reassign.
73 if req.GetNode() != nil {
74 sw.node = req.GetNode()
75 } else {
76 req.Node = sw.node
77 }
78
79 // nonces can be reused across streams; we verify nonce only if nonce is not initialized
80 nonce := req.GetResponseNonce()
81
82 // type URL is required for ADS but is implicit for xDS
83 if defaultTypeURL == resource.AnyType {
84 if req.GetTypeUrl() == "" {
85 return status.Errorf(codes.InvalidArgument, "type URL is required for ADS")
86 }
87
88 // When using ADS we need to order responses.
89 // This is guaranteed in the xDS protocol specification
90 // as ADS is required to be eventually consistent.
91 // More details can be found here if interested:
92 // https://www.envoyproxy.io/docs/envoy/latest/api-docs/xds_protocol#eventual-consistency-considerations
93 if s.opts.Ordered {
94 // send our first request on the stream again so it doesn't get
95 // lost in processing on the new control loop
96 // There's a risk (albeit very limited) that we'd end up handling requests in the wrong order here.
97 // If envoy is using ADS for endpoints, and clusters are added in short sequence,
98 // the following request might include a new cluster and be discarded as the previous one will be handled after.
99 go func() {
100 reqCh <- req
101 }()
102
103 // Trigger a different code path specifically for ADS.
104 // We want resource ordering so things don't get sent before they should.
105 // This is a blocking call and will exit the process function
106 // on successful completion.
107 return s.processADS(&sw, reqCh, defaultTypeURL)
108 }
109 } else if req.GetTypeUrl() == "" {
110 req.TypeUrl = defaultTypeURL
111 }
112
113 if s.callbacks != nil {
114 if err := s.callbacks.OnStreamRequest(sw.ID, req); err != nil {
115 return err
116 }
117 }
118
119 if lastResponse, ok := sw.lastDiscoveryResponses[req.GetTypeUrl()]; ok {
120 if lastResponse.nonce == "" || lastResponse.nonce == nonce {
121 // Let's record Resource names that a client has received.
122 sw.streamState.SetKnownResourceNames(req.GetTypeUrl(), lastResponse.resources)
123 }
124 }
125
126 typeURL := req.GetTypeUrl()
127 responder := make(chan cache.Response, 1)
128 if w, ok := sw.watches.responders[typeURL]; ok {
129 // We've found a pre-existing watch, lets check and update if needed.
130 // If these requirements aren't satisfied, leave an open watch.
131 if w.nonce == "" || w.nonce == nonce {
132 w.close()
133
134 sw.watches.addWatch(typeURL, &watch{
135 cancel: s.cache.CreateWatch(req, sw.streamState, responder),
136 response: responder,
137 })
138 }
139 } else {
140 // No pre-existing watch exists, let's create one.
141 // We need to precompute the watches first then open a watch in the cache.
142 sw.watches.addWatch(typeURL, &watch{
143 cancel: s.cache.CreateWatch(req, sw.streamState, responder),
144 response: responder,
145 })
146 }
147
148 // Recompute the dynamic select cases for this stream.
149 sw.watches.recompute(s.ctx, reqCh)
150 default:
151 // Channel n -> these are the dynamic list of responders that correspond to the stream request typeURL
152 // nil is used to close the streams in the caches
153 if value.IsNil() || !ok {
154 // Receiver channel was closed. TODO(jpeach): probably cancel the watch or something?
155 return status.Errorf(codes.Unavailable, "resource watch %d -> failed", index)
156 }
157
158 // If a non cache.Response arrived here, there are serious issues
159 res := value.Interface().(cache.Response)
160 nonce, err := sw.send(res)
161 if err != nil {
162 return err
163 }
164
165 sw.watches.responders[res.GetRequest().GetTypeUrl()].nonce = nonce
166 }
167 }
168 }