-
Notifications
You must be signed in to change notification settings - Fork 280
/
xdsmgr.go
242 lines (213 loc) · 6.63 KB
/
xdsmgr.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
// Package xdsmgr implements a resource discovery manager for envoy.
package xdsmgr
import (
"context"
"sync"
envoy_service_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/signal"
)
type streamState struct {
typeURL string
clientResourceVersions map[string]string
unsubscribedResources map[string]struct{}
}
var onHandleDeltaRequest = func(_ *streamState) {}
// A Manager manages xDS resources.
type Manager struct {
signal *signal.Signal
mu sync.Mutex
nonce string
resources map[string][]*envoy_service_discovery_v3.Resource
}
// NewManager creates a new Manager.
func NewManager(resources map[string][]*envoy_service_discovery_v3.Resource) *Manager {
return &Manager{
signal: signal.New(),
nonce: uuid.New().String(),
resources: resources,
}
}
// DeltaAggregatedResources implements the increment xDS server.
func (mgr *Manager) DeltaAggregatedResources(
stream envoy_service_discovery_v3.AggregatedDiscoveryService_DeltaAggregatedResourcesServer,
) error {
ch := mgr.signal.Bind()
defer mgr.signal.Unbind(ch)
stateByTypeURL := map[string]*streamState{}
getDeltaResponse := func(_ context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse {
mgr.mu.Lock()
defer mgr.mu.Unlock()
state, ok := stateByTypeURL[typeURL]
if !ok {
return nil
}
res := &envoy_service_discovery_v3.DeltaDiscoveryResponse{
TypeUrl: typeURL,
Nonce: mgr.nonce,
}
seen := map[string]struct{}{}
for _, resource := range mgr.resources[typeURL] {
seen[resource.Name] = struct{}{}
if resource.Version != state.clientResourceVersions[resource.Name] {
res.Resources = append(res.Resources, resource)
}
}
for name := range state.clientResourceVersions {
_, ok := seen[name]
if !ok {
res.RemovedResources = append(res.RemovedResources, name)
}
}
if len(res.Resources) == 0 && len(res.RemovedResources) == 0 {
return nil
}
return res
}
handleDeltaRequest := func(ctx context.Context, req *envoy_service_discovery_v3.DeltaDiscoveryRequest) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
state, ok := stateByTypeURL[req.GetTypeUrl()]
if !ok {
// first time we've seen a message for this type URL.
state = &streamState{
typeURL: req.GetTypeUrl(),
clientResourceVersions: req.GetInitialResourceVersions(),
unsubscribedResources: make(map[string]struct{}),
}
if state.clientResourceVersions == nil {
state.clientResourceVersions = make(map[string]string)
}
stateByTypeURL[req.GetTypeUrl()] = state
}
switch {
case req.GetResponseNonce() == "":
// neither an ACK or a NACK
case req.GetErrorDetail() != nil:
// a NACK
// - set the client resource versions to the current resource versions
state.clientResourceVersions = make(map[string]string)
for _, resource := range mgr.resources[req.GetTypeUrl()] {
state.clientResourceVersions[resource.Name] = resource.Version
}
logNACK(req)
case req.GetResponseNonce() == mgr.nonce:
// an ACK for the last response
// - set the client resource versions to the current resource versions
state.clientResourceVersions = make(map[string]string)
for _, resource := range mgr.resources[req.GetTypeUrl()] {
state.clientResourceVersions[resource.Name] = resource.Version
}
logACK(req)
default:
// an ACK for a response that's not the last response
log.Debug(ctx).
Str("type-url", req.GetTypeUrl()).
Msg("xdsmgr: ack")
}
// update subscriptions
for _, name := range req.GetResourceNamesSubscribe() {
delete(state.unsubscribedResources, name)
}
for _, name := range req.GetResourceNamesUnsubscribe() {
state.unsubscribedResources[name] = struct{}{}
// from the docs:
// NOTE: the server must respond with all resources listed in
// resource_names_subscribe, even if it believes the client has
// the most recent version of them. The reason: the client may
// have dropped them, but then regained interest before it had
// a chance to send the unsubscribe message.
// so we reset the version to treat it like a new version
delete(state.clientResourceVersions, name)
}
onHandleDeltaRequest(state)
}
incoming := make(chan *envoy_service_discovery_v3.DeltaDiscoveryRequest)
outgoing := make(chan *envoy_service_discovery_v3.DeltaDiscoveryResponse)
eg, ctx := errgroup.WithContext(stream.Context())
// 1. receive all incoming messages
eg.Go(func() error {
for {
req, err := stream.Recv()
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case incoming <- req:
}
}
})
// 2. handle incoming requests or resource changes
eg.Go(func() error {
changeCtx := ctx
for {
var typeURLs []string
select {
case <-ctx.Done():
return ctx.Err()
case req := <-incoming:
handleDeltaRequest(changeCtx, req)
typeURLs = []string{req.GetTypeUrl()}
case changeCtx = <-ch:
mgr.mu.Lock()
for typeURL := range mgr.resources {
typeURLs = append(typeURLs, typeURL)
}
mgr.mu.Unlock()
}
for _, typeURL := range typeURLs {
res := getDeltaResponse(changeCtx, typeURL)
if res == nil {
continue
}
select {
case <-ctx.Done():
return ctx.Err()
case outgoing <- res:
}
}
}
})
// 3. send all outgoing messages
eg.Go(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case res := <-outgoing:
log.Debug(ctx).
Str("type-url", res.GetTypeUrl()).
Int("resource-count", len(res.GetResources())).
Int("removed-resource-count", len(res.GetRemovedResources())).
Msg("xdsmgr: sending resources")
err := stream.Send(res)
if err != nil {
return err
}
}
}
})
return eg.Wait()
}
// StreamAggregatedResources is not implemented.
func (mgr *Manager) StreamAggregatedResources(
_ envoy_service_discovery_v3.AggregatedDiscoveryService_StreamAggregatedResourcesServer,
) error {
return status.Errorf(codes.Unimplemented, "method StreamAggregatedResources not implemented")
}
// Update updates the state of resources. If any changes are made they will be pushed to any listening
// streams. For each TypeURL the list of resources should be the complete list of resources.
func (mgr *Manager) Update(ctx context.Context, resources map[string][]*envoy_service_discovery_v3.Resource) {
nonce := uuid.New().String()
mgr.mu.Lock()
mgr.nonce = nonce
mgr.resources = resources
mgr.mu.Unlock()
mgr.signal.Broadcast(ctx)
}