forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute_rule_test.go
551 lines (503 loc) · 15.1 KB
/
route_rule_test.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
544
545
546
547
548
549
550
551
// Copyright (c) 2020 Tigera, Inc. All rights reserved.
//
// 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 routerule_test
import (
"errors"
"fmt"
"net"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
log "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"k8s.io/utils/ptr"
"github.com/projectcalico/calico/felix/logutils"
. "github.com/projectcalico/calico/felix/routerule"
"github.com/projectcalico/calico/libcalico-go/lib/set"
)
var (
simulatedError = errors.New("dummy error")
alreadyExists = errors.New("already exists")
)
var _ = Describe("RouteRules Construct", func() {
var dataplane *mockDataplane
BeforeEach(func() {
dataplane = &mockDataplane{
ruleKeyToRule: map[string]netlink.Rule{},
addedRuleKeys: set.New[string](),
deletedRuleKeys: set.New[string](),
}
})
It("should not be constructable with no table index", func() {
tableIndexSet := set.New[int]()
_, err := New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).To(HaveOccurred())
})
It("should not be constructable with wrong table index", func() {
tableIndexSet := set.From(0, 10)
_, err := New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).To(HaveOccurred())
tableIndexSet.Discard(0)
tableIndexSet.Add(254)
_, err = New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).To(HaveOccurred())
tableIndexSet.Discard(254)
tableIndexSet.Add(0x100000000)
_, err = New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).To(HaveOccurred())
})
It("should be constructable", func() {
tableIndexSet := set.From(1, 10, 250)
_, err := New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).NotTo(HaveOccurred())
})
})
var _ = Describe("RouteRules", func() {
var dataplane *mockDataplane
var rrs *RouteRules
BeforeEach(func() {
dataplane = &mockDataplane{
ruleKeyToRule: map[string]netlink.Rule{},
addedRuleKeys: set.New[string](),
deletedRuleKeys: set.New[string](),
}
tableIndexSet := set.From(1, 10, 250)
var err error
rrs, err = New(
4,
tableIndexSet,
RulesMatchSrcFWMarkTable,
RulesMatchSrcFWMark,
10*time.Second,
dataplane.NewNetlinkHandle,
logutils.NewSummarizer("test loop"),
)
Expect(err).NotTo(HaveOccurred())
Expect(rrs).ToNot(BeNil())
})
Context("with existing cali and nonCali rules", func() {
var cali1Rule, cali2Rule, nonCaliRule netlink.Rule
BeforeEach(func() {
// Calico rule in both control plane and dataplane.
cali1Rule = netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.1/32"),
Mark: 0x100,
Mask: ptr.To[uint32](0x100),
Table: 1,
Invert: true,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}
dataplane.addMockRule(&cali1Rule)
Expect(rrs).ToNot(BeNil())
// Set rule to control plane.
rrs.SetRule(FromNetlinkRule(&cali1Rule))
// Calico rule in dataplane only.
cali2Rule = netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.2/32"),
Mark: 0x200,
Mask: ptr.To[uint32](0x200),
Table: 10,
Invert: false,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}
dataplane.addMockRule(&cali2Rule)
// Non Calico rule in dataplane only.
nonCaliRule = netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.1/32"),
Mark: 0x800,
Mask: ptr.To[uint32](0x800),
Table: 90,
Invert: true,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}
dataplane.addMockRule(&nonCaliRule)
})
It("should remove Calico rule not in control plane", func() {
rrs.QueueResync()
err := rrs.Apply()
Expect(err).ToNot(HaveOccurred())
Expect(dataplane.ruleKeyToRule).To(ConsistOf(cali1Rule, nonCaliRule))
Expect(dataplane.deletedRuleKeys.Contains("10.0.0.2/32-0x200")).To(BeTrue())
})
Describe("set rule with specific table idx and fwmark", func() {
var netlinkRule netlink.Rule
BeforeEach(func() {
rule := NewRule(4, 100).
MatchSrcAddress(*mustParseCIDR("10.0.0.3/32")).
MatchFWMark(0x400).
GoToTable(250)
rrs.SetRule(rule)
netlinkRule = netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.3/32"),
Mark: 0x400,
Mask: ptr.To[uint32](0x400),
Table: 250,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}
err := rrs.Apply()
Expect(err).ToNot(HaveOccurred())
})
It("should add the correct rule", func() {
Expect(dataplane.ruleKeyToRule).To(ConsistOf(cali1Rule, netlinkRule, nonCaliRule))
Expect(dataplane.addedRuleKeys.Contains("10.0.0.3/32-0x400")).To(BeTrue())
})
It("should re-add the rule on resync if deleted out-of-band", func() {
dataplane.addedRuleKeys = set.New[string]()
dataplane.removeMockRule(&netlinkRule)
// Next apply should be a no-op.
err := rrs.Apply()
Expect(err).ToNot(HaveOccurred())
Expect(dataplane.ruleKeyToRule).To(ConsistOf(cali1Rule, nonCaliRule))
Expect(dataplane.addedRuleKeys.Len()).To(BeZero())
// Resync will spot the missing rule and re-add it.
rrs.QueueResync()
err = rrs.Apply()
Expect(err).ToNot(HaveOccurred())
Expect(dataplane.ruleKeyToRule).To(ConsistOf(cali1Rule, netlinkRule, nonCaliRule))
Expect(dataplane.addedRuleKeys.Contains("10.0.0.3/32-0x400")).To(BeTrue())
})
})
It("should update rule with updated table index", func() {
rule := NewRule(4, 100).
MatchSrcAddress(*mustParseCIDR("10.0.0.2/32")).
MatchFWMark(0x200).
GoToTable(250)
rrs.SetRule(rule)
netlinkRule := netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.2/32"),
Mark: 0x200,
Mask: ptr.To[uint32](0x200),
Table: 250,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}
err := rrs.Apply()
Expect(err).ToNot(HaveOccurred())
Expect(dataplane.ruleKeyToRule).To(ConsistOf(cali1Rule, netlinkRule, nonCaliRule))
Expect(dataplane.addedRuleKeys.Contains("10.0.0.2/32-0x200")).To(BeTrue())
Expect(dataplane.deletedRuleKeys.Contains("10.0.0.2/32-0x200")).To(BeTrue())
})
It("should panic adding rule with table index not managed by calico", func() {
rule := NewRule(4, 100).
MatchSrcAddress(*mustParseCIDR("10.0.0.3/32")).
MatchFWMark(0x400).
GoToTable(249)
Expect(func() { rrs.SetRule(rule) }).To(Panic())
})
It("should remove rule", func() {
rule := NewRule(4, 100).
Not().
MatchSrcAddress(*mustParseCIDR("10.0.0.1/32")).
MatchFWMark(0x100)
rrs.RemoveRule(rule)
err := rrs.Apply()
Expect(err).ToNot(HaveOccurred())
Expect(dataplane.ruleKeyToRule).To(ConsistOf(nonCaliRule))
Expect(dataplane.deletedRuleKeys.Contains("10.0.0.1/32-0x100")).To(BeTrue())
})
Context("with a persistent failure to connect", func() {
BeforeEach(func() {
dataplane.PersistentlyFailToConnect = true
})
It("should panic after all its retries are exhausted", func() {
for i := 0; i < 3; i++ {
Expect(rrs.Apply()).To(Equal(ConnectFailed))
}
Expect(func() { _ = rrs.Apply() }).To(Panic())
})
})
// We do the following tests in different failure (and non-failure) scenarios. In
// each case, we make the failure transient so that only the first Apply() should
// fail. Then, at most, the second call to Apply() should succeed.
for _, failFlags := range failureScenarios {
failFlags := failFlags
desc := fmt.Sprintf("with some rules added and failures: %v", failFlags)
Context(desc, func() {
BeforeEach(func() {
rule := NewRule(4, 100).
MatchSrcAddress(*mustParseCIDR("10.0.0.3/32")).
MatchFWMark(0x400).
GoToTable(250)
rrs.SetRule(rule)
dataplane.failuresToSimulate = failFlags
})
JustBeforeEach(func() {
maxTries := 1
if failFlags != 0 {
maxTries = 2
}
for try := 0; try < maxTries; try++ {
err := rrs.Apply()
if err == nil {
// We should only need to retry if Apply returns an error.
log.Info("Apply returned no error, breaking out of loop")
break
}
}
})
It("should have consumed all failures", func() {
// Check that all the failures we simulated were hit.
Expect(dataplane.failuresToSimulate).To(Equal(failNone))
})
It("should keep correct rule", func() {
Expect(dataplane.ruleKeyToRule["10.0.0.1/32-0x100"]).To(Equal(cali1Rule))
})
It("should add new rule", func() {
Expect(dataplane.ruleKeyToRule["10.0.0.3/32-0x400"]).To(Equal(netlink.Rule{
Priority: 100,
Family: unix.AF_INET,
Src: mustParseCIDR("10.0.0.3/32"),
Mark: 0x400,
Mask: ptr.To[uint32](0x400),
Table: 250,
Goto: -1,
Flow: -1,
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
}))
})
It("should have expected number of rules at the end", func() {
Expect(len(dataplane.ruleKeyToRule)).To(Equal(3),
fmt.Sprintf("Wrong number of rules %v: %v",
len(dataplane.ruleKeyToRule),
dataplane.ruleKeyToRule))
})
if failFlags&(failNextSetSocketTimeout|
failNextNewNetlinkHandle|
failNextRuleAdd|
failNextRuleDel|
failNextRuleList) != 0 {
It("should reconnect to netlink", func() {
Expect(dataplane.NumNewNetlinkCalls).To(Equal(2))
})
} else {
It("should not reconnect to netlink", func() {
Expect(dataplane.NumNewNetlinkCalls).To(Equal(1))
})
}
})
}
})
})
var _ = Describe("Tests to verify netlink interface", func() {
It("Should give expected error for missing interface", func() {
_, err := netlink.LinkByName("dsfhjakdhfjk")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("not found"))
})
})
func mustParseCIDR(cidr string) *net.IPNet {
_, c, err := net.ParseCIDR(cidr)
Expect(err).NotTo(HaveOccurred())
return c
}
type failFlags uint32
const (
failNextRuleList failFlags = 1 << iota
failNextRuleAdd
failNextRuleDel
failNextNewNetlinkHandle
failNextSetSocketTimeout
failNone failFlags = 0
)
var failureScenarios = []failFlags{
failNone,
failNextRuleList,
failNextRuleAdd,
failNextRuleDel,
failNextNewNetlinkHandle,
failNextSetSocketTimeout,
}
func (f failFlags) String() string {
parts := []string{}
if f&failNextRuleList != 0 {
parts = append(parts, "failNextRuleList")
}
if f&failNextRuleAdd != 0 {
parts = append(parts, "failNextRuleAdd")
}
if f&failNextRuleDel != 0 {
parts = append(parts, "failNextRuleDel")
}
if f&failNextNewNetlinkHandle != 0 {
parts = append(parts, "failNextNewNetlinkHandle")
}
if f&failNextSetSocketTimeout != 0 {
parts = append(parts, "failNextSetSocketTimeout")
}
if f == 0 {
parts = append(parts, "failNone")
}
return strings.Join(parts, "|")
}
type mockDataplane struct {
ruleKeyToRule map[string]netlink.Rule
addedRuleKeys set.Set[string]
deletedRuleKeys set.Set[string]
NumNewNetlinkCalls int
NetlinkOpen bool
PersistentlyFailToConnect bool
failuresToSimulate failFlags
}
func (d *mockDataplane) shouldFail(flag failFlags) bool {
flagPresent := d.failuresToSimulate&flag != 0
d.failuresToSimulate &^= flag
if flagPresent {
log.WithField("flag", flag).Warn("Mock dataplane: triggering failure")
}
return flagPresent
}
func (d *mockDataplane) NewNetlinkHandle() (HandleIface, error) {
d.NumNewNetlinkCalls++
if d.PersistentlyFailToConnect || d.shouldFail(failNextNewNetlinkHandle) {
return nil, simulatedError
}
Expect(d.NetlinkOpen).To(BeFalse())
d.NetlinkOpen = true
return d, nil
}
func (d *mockDataplane) Delete() {
Expect(d.NetlinkOpen).To(BeTrue())
d.NetlinkOpen = false
}
func (d *mockDataplane) SetSocketTimeout(to time.Duration) error {
Expect(d.NetlinkOpen).To(BeTrue())
if d.shouldFail(failNextSetSocketTimeout) {
return simulatedError
}
return nil
}
func (d *mockDataplane) RuleList(family int) ([]netlink.Rule, error) {
Expect(d.NetlinkOpen).To(BeTrue())
if d.shouldFail(failNextRuleList) {
return nil, simulatedError
}
var rules []netlink.Rule
for _, rule := range d.ruleKeyToRule {
if rule.Family == family {
rules = append(rules, rule)
}
}
return rules, nil
}
func (d *mockDataplane) addMockRule(rule *netlink.Rule) {
key := keyForRule(rule)
d.ruleKeyToRule[key] = *rule
}
func (d *mockDataplane) removeMockRule(rule *netlink.Rule) {
key := keyForRule(rule)
delete(d.ruleKeyToRule, key)
}
func (d *mockDataplane) RuleAdd(rule *netlink.Rule) error {
Expect(d.NetlinkOpen).To(BeTrue())
if d.shouldFail(failNextRuleAdd) {
return simulatedError
}
key := keyForRule(rule)
log.WithField("ruleKey", key).Info("Mock dataplane: RuleAdd called")
d.addedRuleKeys.Add(key)
if _, ok := d.ruleKeyToRule[key]; ok {
return alreadyExists
} else {
d.ruleKeyToRule[key] = *rule
return nil
}
}
func (d *mockDataplane) RuleDel(rule *netlink.Rule) error {
Expect(d.NetlinkOpen).To(BeTrue())
if d.shouldFail(failNextRuleDel) {
return simulatedError
}
key := keyForRule(rule)
log.WithField("ruleKey", key).Info("Mock dataplane: RuleDel called")
d.deletedRuleKeys.Add(key)
// Rule was deleted, but is planned on being re-added
if _, ok := d.ruleKeyToRule[key]; ok {
delete(d.ruleKeyToRule, key)
return nil
} else {
return nil
}
}
func keyForRule(rule *netlink.Rule) string {
key := fmt.Sprintf("%s-%#x", rule.Src.String(), rule.Mark)
log.WithField("ruleKey", key).Debug("Calculated rule key")
return key
}