Debian Codegraph @

fake.go

raw symbols SCIP
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package knftables
18
19 import (
20 "context"
21 "fmt"
22 "reflect"
23 "regexp"
24 "sort"
25 "strings"
26 "sync"
27 )
28
29 // Fake is a fake implementation of Interface
30 type Fake struct {
31 nftContext
32 // mutex is used to protect Table and LastTransaction.
33 // When Table and LastTransaction are accessed directly, the caller must acquire Fake.RLock
34 // and release when finished.
35 sync.RWMutex
36
37 nextHandle int
38
39 // Table contains the Interface's table. This will be `nil` until you `tx.Add()`
40 // the table.
41 // Make sure to acquire Fake.RLock before accessing Table in a concurrent environment.
42 Table *FakeTable
43
44 // LastTransaction is the last transaction passed to Run(). It will remain set until the
45 // next time Run() is called. (It is not affected by Check().)
46 // Make sure to acquire Fake.RLock before accessing LastTransaction in a concurrent environment.
47 LastTransaction *Transaction
48 }
49
50 // FakeTable wraps Table for the Fake implementation
51 type FakeTable struct {
52 Table
53
54 // Flowtables contains the table's flowtables, keyed by name
55 Flowtables map[string]*FakeFlowtable
56
57 // Chains contains the table's chains, keyed by name
58 Chains map[string]*FakeChain
59
60 // Sets contains the table's sets, keyed by name
61 Sets map[string]*FakeSet
62
63 // Maps contains the table's maps, keyed by name
64 Maps map[string]*FakeMap
65 }
66
67 // FakeFlowtable wraps Flowtable for the Fake implementation
68 type FakeFlowtable struct {
69 Flowtable
70 }
71
72 // FakeChain wraps Chain for the Fake implementation
73 type FakeChain struct {
74 Chain
75
76 // Rules contains the chain's rules, in order
77 Rules []*Rule
78 }
79
80 // FakeSet wraps Set for the Fake implementation
81 type FakeSet struct {
82 Set
83
84 // Elements contains the set's elements. You can also use the FakeSet's
85 // FindElement() method to see if a particular element is present.
86 Elements []*Element
87 }
88
89 // FakeMap wraps Set for the Fake implementation
90 type FakeMap struct {
91 Map
92
93 // Elements contains the map's elements. You can also use the FakeMap's
94 // FindElement() method to see if a particular element is present.
95 Elements []*Element
96 }
97
98 // NewFake creates a new fake Interface, for unit tests
99 func NewFake(family Family, table string) *Fake {
100 return &Fake{
101 nftContext: nftContext{
102 family: family,
103 table: table,
104 },
105 }
106 }
107
108 var _ Interface = &Fake{}
109
110 // List is part of Interface.
111 func (fake *Fake) List(_ context.Context, objectType string) ([]string, error) {
112 fake.RLock()
113 defer fake.RUnlock()
114 if fake.Table == nil {
115 return nil, notFoundError("no such table %q", fake.table)
116 }
117
118 var result []string
119
120 switch objectType {
121 case "flowtable", "flowtables":
122 for name := range fake.Table.Flowtables {
123 result = append(result, name)
124 }
125 case "chain", "chains":
126 for name := range fake.Table.Chains {
127 result = append(result, name)
128 }
129 case "set", "sets":
130 for name := range fake.Table.Sets {
131 result = append(result, name)
132 }
133 case "map", "maps":
134 for name := range fake.Table.Maps {
135 result = append(result, name)
136 }
137
138 default:
139 return nil, fmt.Errorf("unsupported object type %q", objectType)
140 }
141
142 return result, nil
143 }
144
145 // ListRules is part of Interface
146 func (fake *Fake) ListRules(_ context.Context, chain string) ([]*Rule, error) {
147 fake.RLock()
148 defer fake.RUnlock()
149 if fake.Table == nil {
150 return nil, notFoundError("no such table %q", fake.table)
151 }
152
153 rules := []*Rule{}
154 if chain == "" {
155 // Include all rules across all chains.
156 for _, ch := range fake.Table.Chains {
157 rules = append(rules, ch.Rules...)
158 }
159 } else {
160 ch := fake.Table.Chains[chain]
161 if ch == nil {
162 return nil, notFoundError("no such chain %q", chain)
163 }
164 rules = append(rules, ch.Rules...)
165 }
166 return rules, nil
167 }
168
169 // ListElements is part of Interface
170 func (fake *Fake) ListElements(_ context.Context, objectType, name string) ([]*Element, error) {
171 fake.RLock()
172 defer fake.RUnlock()
173 if fake.Table == nil {
174 return nil, notFoundError("no such %s %q", objectType, name)
175 }
176 if objectType == "set" {
177 s := fake.Table.Sets[name]
178 if s != nil {
179 return s.Elements, nil
180 }
181 } else if objectType == "map" {
182 m := fake.Table.Maps[name]
183 if m != nil {
184 return m.Elements, nil
185 }
186 }
187 return nil, notFoundError("no such %s %q", objectType, name)
188 }
189
190 // NewTransaction is part of Interface
191 func (fake *Fake) NewTransaction() *Transaction {
192 return &Transaction{nftContext: &fake.nftContext}
193 }
194
195 // Run is part of Interface
196 func (fake *Fake) Run(_ context.Context, tx *Transaction) error {
197 fake.Lock()
198 defer fake.Unlock()
199 fake.LastTransaction = tx
200 updatedTable, err := fake.run(tx)
201 if err == nil {
202 fake.Table = updatedTable
203 }
204 return err
205 }
206
207 // Check is part of Interface
208 func (fake *Fake) Check(_ context.Context, tx *Transaction) error {
209 fake.RLock()
210 defer fake.RUnlock()
211 _, err := fake.run(tx)
212 return err
213 }
214
215 // must be called with fake.lock held
216 func (fake *Fake) run(tx *Transaction) (*FakeTable, error) {
217 if tx.err != nil {
218 return nil, tx.err
219 }
220
221 updatedTable := fake.Table.copy()
222 for _, op := range tx.operations {
223 // If the table hasn't been created, and this isn't a Table operation, then fail
224 if updatedTable == nil {
225 if _, ok := op.obj.(*Table); !ok {
226 return nil, notFoundError("no such table \"%s %s\"", fake.family, fake.table)
227 }
228 }
229
230 if op.verb == addVerb || op.verb == createVerb || op.verb == insertVerb {
231 fake.nextHandle++
232 }
233
234 switch obj := op.obj.(type) {
235 case *Table:
236 err := checkExists(op.verb, "table", fake.table, updatedTable != nil)
237 if err != nil {
238 return nil, err
239 }
240 switch op.verb {
241 case flushVerb:
242 updatedTable = nil
243 fallthrough
244 case addVerb, createVerb:
245 if updatedTable != nil {
246 continue
247 }
248 table := *obj
249 table.Handle = PtrTo(fake.nextHandle)
250 updatedTable = &FakeTable{
251 Table: table,
252 Flowtables: make(map[string]*FakeFlowtable),
253 Chains: make(map[string]*FakeChain),
254 Sets: make(map[string]*FakeSet),
255 Maps: make(map[string]*FakeMap),
256 }
257 case deleteVerb:
258 updatedTable = nil
259 default:
260 return nil, fmt.Errorf("unhandled operation %q", op.verb)
261 }
262
263 case *Flowtable:
264 existingFlowtable := updatedTable.Flowtables[obj.Name]
265 err := checkExists(op.verb, "flowtable", obj.Name, existingFlowtable != nil)
266 if err != nil {
267 return nil, err
268 }
269 switch op.verb {
270 case addVerb, createVerb:
271 if existingFlowtable != nil {
272 continue
273 }
274 flowtable := *obj
275 flowtable.Handle = PtrTo(fake.nextHandle)
276 updatedTable.Flowtables[obj.Name] = &FakeFlowtable{
277 Flowtable: flowtable,
278 }
279 case deleteVerb:
280 // FIXME delete-by-handle
281 delete(updatedTable.Flowtables, obj.Name)
282 default:
283 return nil, fmt.Errorf("unhandled operation %q", op.verb)
284 }
285
286 case *Chain:
287 existingChain := updatedTable.Chains[obj.Name]
288 err := checkExists(op.verb, "chain", obj.Name, existingChain != nil)
289 if err != nil {
290 return nil, err
291 }
292 switch op.verb {
293 case addVerb, createVerb:
294 if existingChain != nil {
295 continue
296 }
297 chain := *obj
298 chain.Handle = PtrTo(fake.nextHandle)
299 updatedTable.Chains[obj.Name] = &FakeChain{
300 Chain: chain,
301 }
302 case flushVerb:
303 existingChain.Rules = nil
304 case deleteVerb:
305 // FIXME delete-by-handle
306 delete(updatedTable.Chains, obj.Name)
307 default:
308 return nil, fmt.Errorf("unhandled operation %q", op.verb)
309 }
310
311 case *Rule:
312 existingChain := updatedTable.Chains[obj.Chain]
313 if existingChain == nil {
314 return nil, notFoundError("no such chain %q", obj.Chain)
315 }
316 if op.verb == deleteVerb {
317 i := findRule(existingChain.Rules, *obj.Handle)
318 if i == -1 {
319 return nil, notFoundError("no rule with handle %d", *obj.Handle)
320 }
321 existingChain.Rules = append(existingChain.Rules[:i], existingChain.Rules[i+1:]...)
322 continue
323 }
324
325 rule := *obj
326 refRule := -1
327 if rule.Handle != nil {
328 refRule = findRule(existingChain.Rules, *obj.Handle)
329 if refRule == -1 {
330 return nil, notFoundError("no rule with handle %d", *obj.Handle)
331 }
332 } else if obj.Index != nil {
333 if *obj.Index >= len(existingChain.Rules) {
334 return nil, notFoundError("no rule with index %d", *obj.Index)
335 }
336 refRule = *obj.Index
337 }
338
339 if err := checkRuleRefs(obj, updatedTable); err != nil {
340 return nil, err
341 }
342
343 switch op.verb {
344 case addVerb:
345 if refRule == -1 {
346 existingChain.Rules = append(existingChain.Rules, &rule)
347 } else {
348 existingChain.Rules = append(existingChain.Rules[:refRule+1], append([]*Rule{&rule}, existingChain.Rules[refRule+1:]...)...)
349 }
350 rule.Handle = PtrTo(fake.nextHandle)
351 case insertVerb:
352 if refRule == -1 {
353 existingChain.Rules = append([]*Rule{&rule}, existingChain.Rules...)
354 } else {
355 existingChain.Rules = append(existingChain.Rules[:refRule], append([]*Rule{&rule}, existingChain.Rules[refRule:]...)...)
356 }
357 rule.Handle = PtrTo(fake.nextHandle)
358 case replaceVerb:
359 existingChain.Rules[refRule] = &rule
360 default:
361 return nil, fmt.Errorf("unhandled operation %q", op.verb)
362 }
363
364 case *Set:
365 existingSet := updatedTable.Sets[obj.Name]
366 err := checkExists(op.verb, "set", obj.Name, existingSet != nil)
367 if err != nil {
368 return nil, err
369 }
370 switch op.verb {
371 case addVerb, createVerb:
372 if existingSet != nil {
373 continue
374 }
375 set := *obj
376 set.Handle = PtrTo(fake.nextHandle)
377 updatedTable.Sets[obj.Name] = &FakeSet{
378 Set: set,
379 }
380 case flushVerb:
381 existingSet.Elements = nil
382 case deleteVerb:
383 // FIXME delete-by-handle
384 delete(updatedTable.Sets, obj.Name)
385 default:
386 return nil, fmt.Errorf("unhandled operation %q", op.verb)
387 }
388 case *Map:
389 existingMap := updatedTable.Maps[obj.Name]
390 err := checkExists(op.verb, "map", obj.Name, existingMap != nil)
391 if err != nil {
392 return nil, err
393 }
394 switch op.verb {
395 case addVerb:
396 if existingMap != nil {
397 continue
398 }
399 mapObj := *obj
400 mapObj.Handle = PtrTo(fake.nextHandle)
401 updatedTable.Maps[obj.Name] = &FakeMap{
402 Map: mapObj,
403 }
404 case flushVerb:
405 existingMap.Elements = nil
406 case deleteVerb:
407 // FIXME delete-by-handle
408 delete(updatedTable.Maps, obj.Name)
409 default:
410 return nil, fmt.Errorf("unhandled operation %q", op.verb)
411 }
412 case *Element:
413 if obj.Set != "" {
414 existingSet := updatedTable.Sets[obj.Set]
415 if existingSet == nil {
416 return nil, notFoundError("no such set %q", obj.Set)
417 }
418 switch op.verb {
419 case addVerb, createVerb:
420 element := *obj
421 if i := findElement(existingSet.Elements, element.Key); i != -1 {
422 if op.verb == createVerb {
423 return nil, existsError("element %q already exists", strings.Join(element.Key, " . "))
424 }
425 existingSet.Elements[i] = &element
426 } else {
427 existingSet.Elements = append(existingSet.Elements, &element)
428 }
429 case deleteVerb:
430 element := *obj
431 if i := findElement(existingSet.Elements, element.Key); i != -1 {
432 existingSet.Elements = append(existingSet.Elements[:i], existingSet.Elements[i+1:]...)
433 } else {
434 return nil, notFoundError("no such element %q", strings.Join(element.Key, " . "))
435 }
436 default:
437 return nil, fmt.Errorf("unhandled operation %q", op.verb)
438 }
439 } else {
440 existingMap := updatedTable.Maps[obj.Map]
441 if existingMap == nil {
442 return nil, notFoundError("no such map %q", obj.Map)
443 }
444 if err := checkElementRefs(obj, updatedTable); err != nil {
445 return nil, err
446 }
447 switch op.verb {
448 case addVerb, createVerb:
449 element := *obj
450 if i := findElement(existingMap.Elements, element.Key); i != -1 {
451 if op.verb == createVerb {
452 return nil, existsError("element %q already exists", strings.Join(element.Key, ". "))
453 }
454 existingMap.Elements[i] = &element
455 } else {
456 existingMap.Elements = append(existingMap.Elements, &element)
457 }
458 case deleteVerb:
459 element := *obj
460 if i := findElement(existingMap.Elements, element.Key); i != -1 {
461 existingMap.Elements = append(existingMap.Elements[:i], existingMap.Elements[i+1:]...)
462 } else {
463 return nil, notFoundError("no such element %q", strings.Join(element.Key, " . "))
464 }
465 default:
466 return nil, fmt.Errorf("unhandled operation %q", op.verb)
467 }
468 }
469 default:
470 return nil, fmt.Errorf("unhandled object type %T", op.obj)
471 }
472 }
473
474 return updatedTable, nil
475 }
476
477 func checkExists(verb verb, objectType, name string, exists bool) error {
478 switch verb {
479 case addVerb:
480 // It's fine if the object either exists or doesn't
481 return nil
482 case createVerb:
483 if exists {
484 return existsError("%s %q already exists", objectType, name)
485 }
486 default:
487 if !exists {
488 return notFoundError("no such %s %q", objectType, name)
489 }
490 }
491 return nil
492 }
493
494 // checkRuleRefs checks for chains, sets, and maps referenced by rule in table
495 func checkRuleRefs(rule *Rule, table *FakeTable) error {
496 words := strings.Split(rule.Rule, " ")
497 for i, word := range words {
498 if strings.HasPrefix(word, "@") {
499 name := word[1:]
500 if i > 0 && (words[i-1] == "map" || words[i-1] == "vmap") {
501 if table.Maps[name] == nil {
502 return notFoundError("no such map %q", name)
503 }
504 } else if i > 0 && words[i-1] == "offload" {
505 if table.Flowtables[name] == nil {
506 return notFoundError("no such flowtable %q", name)
507 }
508 } else {
509 // recent nft lets you use a map in a set lookup
510 if table.Sets[name] == nil && table.Maps[name] == nil {
511 return notFoundError("no such set %q", name)
512 }
513 }
514 } else if (word == "goto" || word == "jump") && i < len(words)-1 {
515 name := words[i+1]
516 if table.Chains[name] == nil {
517 return notFoundError("no such chain %q", name)
518 }
519 }
520 }
521 return nil
522 }
523
524 // checkElementRefs checks for chains referenced by an element
525 func checkElementRefs(element *Element, table *FakeTable) error {
526 if len(element.Value) != 1 {
527 return nil
528 }
529 words := strings.Split(element.Value[0], " ")
530 if len(words) == 2 && (words[0] == "goto" || words[0] == "jump") {
531 name := words[1]
532 if table.Chains[name] == nil {
533 return notFoundError("no such chain %q", name)
534 }
535 }
536 return nil
537 }
538
539 // Dump dumps the current contents of fake, in a way that looks like an nft transaction.
540 func (fake *Fake) Dump() string {
541 fake.RLock()
542 defer fake.RUnlock()
543 if fake.Table == nil {
544 return ""
545 }
546
547 buf := &strings.Builder{}
548
549 table := fake.Table
550 flowtables := sortKeys(table.Flowtables)
551 chains := sortKeys(table.Chains)
552 sets := sortKeys(table.Sets)
553 maps := sortKeys(table.Maps)
554
555 // Write out all of the object adds first.
556
557 table.writeOperation(addVerb, &fake.nftContext, buf)
558 for _, fname := range flowtables {
559 ft := table.Flowtables[fname]
560 ft.writeOperation(addVerb, &fake.nftContext, buf)
561 }
562 for _, cname := range chains {
563 ch := table.Chains[cname]
564 ch.writeOperation(addVerb, &fake.nftContext, buf)
565 }
566 for _, sname := range sets {
567 s := table.Sets[sname]
568 s.writeOperation(addVerb, &fake.nftContext, buf)
569 }
570 for _, mname := range maps {
571 m := table.Maps[mname]
572 m.writeOperation(addVerb, &fake.nftContext, buf)
573 }
574
575 // Now write their contents.
576
577 for _, cname := range chains {
578 ch := table.Chains[cname]
579 for _, rule := range ch.Rules {
580 // Avoid outputing handles
581 dumpRule := *rule
582 dumpRule.Handle = nil
583 dumpRule.Index = nil
584 dumpRule.writeOperation(addVerb, &fake.nftContext, buf)
585 }
586 }
587 for _, sname := range sets {
588 s := table.Sets[sname]
589 for _, element := range s.Elements {
590 element.writeOperation(addVerb, &fake.nftContext, buf)
591 }
592 }
593 for _, mname := range maps {
594 m := table.Maps[mname]
595 for _, element := range m.Elements {
596 element.writeOperation(addVerb, &fake.nftContext, buf)
597 }
598 }
599
600 return buf.String()
601 }
602
603 // ParseDump can parse a dump for a given nft instance.
604 // It expects fake's table name and family in all rules.
605 // The best way to verify that everything important was properly parsed is to
606 // compare given data with nft.Dump() output.
607 func (fake *Fake) ParseDump(data string) (err error) {
608 lines := strings.Split(data, "\n")
609 var i int
610 var line string
611 parsingDone := false
612 defer func() {
613 if err != nil && !parsingDone {
614 err = fmt.Errorf("%w (at line %v: %s", err, i+1, line)
615 }
616 }()
617 tx := fake.NewTransaction()
618 commonRegexp := regexp.MustCompile(fmt.Sprintf(`add ([^ ]*) %s %s( (.*))?`, fake.family, fake.table))
619
620 for i, line = range lines {
621 line = strings.TrimSpace(line)
622 if line == "" || line[0] == '#' {
623 continue
624 }
625 match := commonRegexp.FindStringSubmatch(line)
626 if match == nil {
627 return fmt.Errorf("could not parse, or wrong table/family")
628 }
629 var obj Object
630 switch match[1] {
631 case "table":
632 obj = &Table{}
633 case "flowtable":
634 obj = &Flowtable{}
635 case "chain":
636 obj = &Chain{}
637 case "rule":
638 obj = &Rule{}
639 case "map":
640 obj = &Map{}
641 case "set":
642 obj = &Set{}
643 case "element":
644 obj = &Element{}
645 default:
646 return fmt.Errorf("unknown object %s", match[1])
647 }
648 err = obj.parse(match[3])
649 if err != nil {
650 return err
651 }
652 tx.Add(obj)
653 }
654 parsingDone = true
655 return fake.Run(context.Background(), tx)
656 }
657
658 func sortKeys[K ~string, V any](m map[K]V) []K {
659 keys := make([]K, 0, len(m))
660 for key := range m {
661 keys = append(keys, key)
662 }
663 sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
664 return keys
665 }
666
667 func findRule(rules []*Rule, handle int) int {
668 for i := range rules {
669 if rules[i].Handle != nil && *rules[i].Handle == handle {
670 return i
671 }
672 }
673 return -1
674 }
675
676 func findElement(elements []*Element, key []string) int {
677 for i := range elements {
678 if reflect.DeepEqual(elements[i].Key, key) {
679 return i
680 }
681 }
682 return -1
683 }
684
685 // copy creates a copy of table with new arrays/maps so we can perform a transaction
686 // on it without changing the original table.
687 func (table *FakeTable) copy() *FakeTable {
688 if table == nil {
689 return nil
690 }
691
692 tcopy := &FakeTable{
693 Table: table.Table,
694 Flowtables: make(map[string]*FakeFlowtable),
695 Chains: make(map[string]*FakeChain),
696 Sets: make(map[string]*FakeSet),
697 Maps: make(map[string]*FakeMap),
698 }
699 for name, flowtable := range table.Flowtables {
700 tcopy.Flowtables[name] = &FakeFlowtable{
701 Flowtable: flowtable.Flowtable,
702 }
703 }
704 for name, chain := range table.Chains {
705 tcopy.Chains[name] = &FakeChain{
706 Chain: chain.Chain,
707 Rules: append([]*Rule{}, chain.Rules...),
708 }
709 }
710 for name, set := range table.Sets {
711 tcopy.Sets[name] = &FakeSet{
712 Set: set.Set,
713 Elements: append([]*Element{}, set.Elements...),
714 }
715 }
716 for name, mapObj := range table.Maps {
717 tcopy.Maps[name] = &FakeMap{
718 Map: mapObj.Map,
719 Elements: append([]*Element{}, mapObj.Elements...),
720 }
721 }
722
723 return tcopy
724 }
725
726 // FindElement finds an element of the set with the given key. If there is no matching
727 // element, it returns nil.
728 func (s *FakeSet) FindElement(key ...string) *Element {
729 index := findElement(s.Elements, key)
730 if index == -1 {
731 return nil
732 }
733 return s.Elements[index]
734 }
735
736 // FindElement finds an element of the map with the given key. If there is no matching
737 // element, it returns nil.
738 func (m *FakeMap) FindElement(key ...string) *Element {
739 index := findElement(m.Elements, key)
740 if index == -1 {
741 return nil
742 }
743 return m.Elements[index]
744 }