-
Notifications
You must be signed in to change notification settings - Fork 240
/
goalstateprocessor.go
423 lines (367 loc) · 12.6 KB
/
goalstateprocessor.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
package goalstateprocessor
import (
"bytes"
"context"
"fmt"
cp "github.com/Azure/azure-container-networking/npm/pkg/controlplane"
"github.com/Azure/azure-container-networking/npm/pkg/dataplane"
"github.com/Azure/azure-container-networking/npm/pkg/dataplane/ipsets"
"github.com/Azure/azure-container-networking/npm/pkg/protos"
"github.com/Azure/azure-container-networking/npm/util"
npmerrors "github.com/Azure/azure-container-networking/npm/util/errors"
"k8s.io/klog"
)
var ErrPodOrNodeNameNil = fmt.Errorf("both pod and node name must be set")
type GoalStateProcessor struct {
ctx context.Context
cancel context.CancelFunc
nodeID string
podName string
dp dataplane.GenericDataplane
inputChannel chan *protos.Events
backoffChannel chan *protos.Events
}
func NewGoalStateProcessor(
ctx context.Context,
nodeID string,
podName string,
inputChan chan *protos.Events,
dp dataplane.GenericDataplane) (*GoalStateProcessor, error) {
if nodeID == "" || podName == "" {
return nil, ErrPodOrNodeNameNil
}
klog.Infof("Creating GoalStateProcessor for node %s", nodeID)
return &GoalStateProcessor{
ctx: ctx,
nodeID: nodeID,
podName: podName,
dp: dp,
inputChannel: inputChan,
backoffChannel: make(chan *protos.Events),
}, nil
}
// Start kicks off the GoalStateProcessor
func (gsp *GoalStateProcessor) Start(stopCh <-chan struct{}) {
klog.Infof("Starting GoalStateProcessor for node %s", gsp.nodeID)
go gsp.run(stopCh)
}
// Stop stops the GoalStateProcessor
func (gsp *GoalStateProcessor) Stop() {
klog.Infof("Stopping GoalStateProcessor for node %s", gsp.nodeID)
gsp.cancel()
}
func (gsp *GoalStateProcessor) run(stopCh <-chan struct{}) {
klog.Infof("Starting dataplane for node %s", gsp.nodeID)
for gsp.processNext(stopCh) {
}
}
func (gsp *GoalStateProcessor) processNext(stopCh <-chan struct{}) bool {
select {
// TODO benchmark how many events can stay in pipeline as we work
// on a previous event
case inputEvents := <-gsp.inputChannel:
// TODO remove this large print later
klog.Infof("Received event %s", inputEvents)
gsp.process(inputEvents)
return true
case backoffEvents := <-gsp.backoffChannel:
// For now keep it simple. Do not worry about backoff events
// but if we need to handle them, we can do it here.
// TODO remove this large print later
klog.Infof("Received backoff event %s", backoffEvents)
gsp.process(backoffEvents)
return true
case <-gsp.ctx.Done():
klog.Infof("GoalStateProcessor for node %s received context Done", gsp.nodeID)
return false
case <-stopCh:
klog.Infof("GoalStateProcessor for node %s stopped", gsp.nodeID)
return false
}
}
func (gsp *GoalStateProcessor) process(inputEvent *protos.Events) {
klog.Infof("Processing event")
// apply dataplane after syncing
defer func() {
dperr := gsp.dp.ApplyDataPlane()
if dperr != nil {
klog.Errorf("Apply Dataplane failed with %v", dperr)
}
}()
payload := inputEvent.GetPayload()
if !validatePayload(payload) {
klog.Warningf("Empty payload in event %s", inputEvent)
return
}
switch inputEvent.GetEventType() {
case protos.Events_Hydration:
// in hydration event, any thing in local cache and not in event should be deleted.
klog.Infof("Received hydration event")
gsp.processHydrationEvent(payload)
case protos.Events_GoalState:
klog.Infof("Received goal state event")
gsp.processGoalStateEvent(payload)
default:
klog.Errorf("Received unknown event type %s", inputEvent.GetEventType())
}
}
func (gsp *GoalStateProcessor) processHydrationEvent(payload map[string]*protos.GoalState) {
// Hydration events are sent when the daemon first starts up, or a reconnection to controller happens.
// In this case, the controller will send a current state of the cache down to daemon.
// Daemon will need to calculate what updates and deleted have been missed and send them to the dataplane.
// Sequence of processing will be:
// Apply IPsets
// Apply Policies
// Get all existing IPSets and policies in the dataplane
// Delete cached Policies not in event
// Delete cached IPSets (without references) not in the event
var appendedIPSets map[string]struct{}
var appendedPolicies map[string]struct{}
var err error
if ipsetApplyPayload, ok := payload[cp.IpsetApply]; ok {
appendedIPSets, err = gsp.processIPSetsApplyEvent(ipsetApplyPayload)
if err != nil {
klog.Errorf("Error processing IPSET apply HYDRATION event %s", err)
}
}
if policyApplyPayload, ok := payload[cp.PolicyApply]; ok {
appendedPolicies, err = gsp.processPolicyApplyEvent(policyApplyPayload)
if err != nil {
klog.Errorf("Error processing POLICY apply HYDRATION event %s", err)
}
}
cachedPolicyKeys := gsp.dp.GetAllPolicies()
toDeletePolicies := make([]string, 0)
if appendedPolicies == nil {
toDeletePolicies = cachedPolicyKeys
} else {
for _, policy := range cachedPolicyKeys {
if _, ok := appendedPolicies[policy]; !ok {
toDeletePolicies = append(toDeletePolicies, policy)
}
}
}
if len(toDeletePolicies) > 0 {
klog.Infof("Deleting %d policies", len(toDeletePolicies))
err = gsp.processPolicyRemoveEvent(toDeletePolicies)
if err != nil {
klog.Errorf("Error processing POLICY remove HYDRATION event %s", err)
}
}
cachedIPSetNames := gsp.dp.GetAllIPSets()
hashedsetnames := make([]string, len(cachedIPSetNames))
toDeleteIPSets := make([]string, 0)
i := 0
for name := range cachedIPSetNames {
hashedsetnames[i] = name
i++
}
if appendedIPSets == nil {
toDeleteIPSets = hashedsetnames
} else {
for _, ipset := range cachedIPSetNames {
if _, ok := appendedIPSets[ipset]; !ok {
toDeleteIPSets = append(toDeleteIPSets, ipset)
}
}
}
if len(toDeleteIPSets) > 0 {
klog.Infof("Deleting %d ipsets", len(toDeleteIPSets))
gsp.processIPSetsRemoveEvent(toDeleteIPSets, util.ForceDelete)
}
}
func (gsp *GoalStateProcessor) processGoalStateEvent(payload map[string]*protos.GoalState) {
// Process these individual buckets in order
// 1. Apply IPSET
// 2. Apply POLICY
// 3. Remove POLICY
// 4. Remove IPSET
if ipsetApplyPayload, ok := payload[cp.IpsetApply]; ok {
_, err := gsp.processIPSetsApplyEvent(ipsetApplyPayload)
if err != nil {
klog.Errorf("Error processing IPSET apply event %s", err)
}
}
if policyApplyPayload, ok := payload[cp.PolicyApply]; ok {
_, err := gsp.processPolicyApplyEvent(policyApplyPayload)
if err != nil {
klog.Errorf("Error processing POLICY apply event %s", err)
}
}
if policyRemovePayload, ok := payload[cp.PolicyRemove]; ok {
payload := bytes.NewBuffer(policyRemovePayload.GetData())
netpolNames, err := cp.DecodeStrings(payload)
if err != nil {
klog.Errorf("Error processing POLICY remove event, failed to decode Policy remove event %s", err)
}
err = gsp.processPolicyRemoveEvent(netpolNames)
if err != nil {
klog.Errorf("Error processing POLICY remove event %s", err)
}
}
if ipsetRemovePayload, ok := payload[cp.IpsetRemove]; ok {
payload := bytes.NewBuffer(ipsetRemovePayload.GetData())
ipsetNames, err := cp.DecodeStrings(payload)
if err != nil {
klog.Errorf("Error processing IPSET remove event, failed to decode IPSet remove event: %s", err)
}
gsp.processIPSetsRemoveEvent(ipsetNames, util.SoftDelete)
}
}
func (gsp *GoalStateProcessor) processIPSetsApplyEvent(goalState *protos.GoalState) (map[string]struct{}, error) {
payload := bytes.NewBuffer(goalState.GetData())
payloadIPSets, err := cp.DecodeControllerIPSets(payload)
if err != nil {
return nil, npmerrors.SimpleErrorWrapper("failed to decode IPSet apply event", err)
}
klog.Infof("Processing IPSet apply event %v", payloadIPSets)
appendedIPSets := make(map[string]struct{}, len(payloadIPSets))
for _, ipset := range payloadIPSets {
if ipset == nil {
klog.Warningf("Empty IPSet apply event")
continue
}
klog.Infof("ipset: %v", ipset)
ipsetName := ipset.GetPrefixName()
klog.Infof("Processing %s IPSET apply event", ipsetName)
cachedIPSet := gsp.dp.GetIPSet(ipsetName)
if cachedIPSet == nil {
klog.Infof("IPSet %s not found in cache, adding to cache", ipsetName)
}
switch ipset.GetSetKind() {
case ipsets.HashSet:
err = gsp.applySets(ipset, cachedIPSet)
if err != nil {
return nil, err
}
case ipsets.ListSet:
err = gsp.applyLists(ipset, cachedIPSet)
if err != nil {
return nil, err
}
case ipsets.UnknownKind:
return nil, npmerrors.SimpleError(
fmt.Sprintf("failed to decode IPSet apply event: Unknown IPSet kind %s", cachedIPSet.Kind),
)
}
appendedIPSets[ipsetName] = struct{}{}
}
return appendedIPSets, nil
}
func (gsp *GoalStateProcessor) applySets(ipSet *cp.ControllerIPSets, cachedIPSet *ipsets.IPSet) error {
if len(ipSet.IPPodMetadata) == 0 {
gsp.dp.CreateIPSets([]*ipsets.IPSetMetadata{ipSet.GetMetadata()})
return nil
}
setMetadata := ipSet.GetMetadata()
for _, podMetadata := range ipSet.IPPodMetadata {
err := gsp.dp.AddToSets([]*ipsets.IPSetMetadata{setMetadata}, podMetadata)
if err != nil {
return npmerrors.SimpleErrorWrapper("IPSet apply event, failed at AddToSet.", err)
}
}
if cachedIPSet != nil {
for podIP, cachedPodKey := range cachedIPSet.IPPodKey {
if _, ok := ipSet.IPPodMetadata[podIP]; !ok {
err := gsp.dp.RemoveFromSets([]*ipsets.IPSetMetadata{setMetadata}, dataplane.NewPodMetadata(podIP, cachedPodKey, ""))
if err != nil {
return npmerrors.SimpleErrorWrapper("IPSet apply event, failed at RemoveFromSets.", err)
}
}
}
}
return nil
}
func (gsp *GoalStateProcessor) applyLists(ipSet *cp.ControllerIPSets, cachedIPSet *ipsets.IPSet) error {
if len(ipSet.MemberIPSets) == 0 {
gsp.dp.CreateIPSets([]*ipsets.IPSetMetadata{ipSet.GetMetadata()})
return nil
}
setMetadata := ipSet.GetMetadata()
membersToAdd := make([]*ipsets.IPSetMetadata, len(ipSet.MemberIPSets))
idx := 0
for _, memberIPSet := range ipSet.MemberIPSets {
membersToAdd[idx] = memberIPSet
idx++
}
err := gsp.dp.AddToLists([]*ipsets.IPSetMetadata{setMetadata}, membersToAdd)
if err != nil {
return npmerrors.SimpleErrorWrapper("IPSet apply event, failed at AddToLists.", err)
}
if cachedIPSet != nil {
toDeleteMembers := make([]*ipsets.IPSetMetadata, 0)
for _, memberSet := range cachedIPSet.MemberIPSets {
if _, ok := ipSet.MemberIPSets[memberSet.Name]; !ok {
toDeleteMembers = append(toDeleteMembers, memberSet.GetSetMetadata())
}
}
if len(toDeleteMembers) > 0 {
err := gsp.dp.RemoveFromList(setMetadata, toDeleteMembers)
if err != nil {
return npmerrors.SimpleErrorWrapper("IPSet apply event, failed at RemoveFromList.", err)
}
}
}
return nil
}
func (gsp *GoalStateProcessor) processIPSetsRemoveEvent(ipsetNames []string, forceDelete util.DeleteOption) {
for _, ipsetName := range ipsetNames {
if ipsetName == "" {
klog.Warningf("Empty IPSet remove event")
continue
}
klog.Infof("Processing %s IPSET remove event", ipsetName)
cachedIPSet := gsp.dp.GetIPSet(ipsetName)
if cachedIPSet == nil {
klog.Infof("IPSet %s not found in cache, ignoring delete call.", ipsetName)
continue
}
gsp.dp.DeleteIPSet(ipsets.NewIPSetMetadata(cachedIPSet.Name, cachedIPSet.Type), forceDelete)
}
}
func (gsp *GoalStateProcessor) processPolicyApplyEvent(goalState *protos.GoalState) (map[string]struct{}, error) {
payload := bytes.NewBuffer(goalState.GetData())
netpols, err := cp.DecodeNPMNetworkPolicies(payload)
if err != nil {
return nil, npmerrors.SimpleErrorWrapper("failed to decode Policy apply event", err)
}
appendedPolicies := make(map[string]struct{}, len(netpols))
for _, netpol := range netpols {
if netpol == nil {
klog.Warningf("Empty Policy apply event")
continue
}
klog.Infof("Processing %s Policy ADD event", netpol.PolicyKey)
klog.Infof("Netpol: %v", netpol)
err = gsp.dp.UpdatePolicy(netpol)
if err != nil {
klog.Errorf("Error applying policy %s to dataplane with error: %s", netpol.PolicyKey, err.Error())
return nil, npmerrors.SimpleErrorWrapper("failed update policy event", err)
}
appendedPolicies[netpol.PolicyKey] = struct{}{}
}
return appendedPolicies, nil
}
func (gsp *GoalStateProcessor) processPolicyRemoveEvent(netpolNames []string) error {
for _, netpolName := range netpolNames {
klog.Infof("Processing %s Policy remove event", netpolName)
if netpolName == "" {
klog.Warningf("Empty Policy remove event")
continue
}
err := gsp.dp.RemovePolicy(netpolName)
if err != nil {
klog.Errorf("Error removing policy %s from dataplane with error: %s", netpolName, err.Error())
return npmerrors.SimpleErrorWrapper("failed remove policy event", err)
}
}
return nil
}
func validatePayload(payload map[string]*protos.GoalState) bool {
for _, v := range payload {
if len(v.GetData()) != 0 {
return true
}
}
return false
}