/
map_linux.go
1206 lines (987 loc) · 28.6 KB
/
map_linux.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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
//go:build linux
package bpf
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path"
"reflect"
"strings"
"github.com/cilium/ebpf"
"github.com/sirupsen/logrus"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/spanstat"
"github.com/cilium/cilium/pkg/time"
)
var (
// ErrMaxLookup is returned when the maximum number of map element lookups has
// been reached.
ErrMaxLookup = errors.New("maximum number of lookups reached")
bpfMapSyncControllerGroup = controller.NewGroup("bpf-map-sync")
)
type MapKey interface {
fmt.Stringer
// New must return a pointer to a new MapKey.
New() MapKey
}
type MapValue interface {
fmt.Stringer
// New must return a pointer to a new MapValue.
New() MapValue
}
type cacheEntry struct {
Key MapKey
Value MapValue
DesiredAction DesiredAction
LastError error
}
type Map struct {
m *ebpf.Map
// spec will be nil after the map has been created
spec *ebpf.MapSpec
key MapKey
value MapValue
name string
path string
lock lock.RWMutex
// cachedCommonName is the common portion of the name excluding any
// endpoint ID
cachedCommonName string
// enableSync is true when synchronization retries have been enabled.
enableSync bool
// withValueCache is true when map cache has been enabled
withValueCache bool
// cache as key/value entries when map cache is enabled or as key-only when
// pressure metric is enabled
cache map[string]*cacheEntry
// errorResolverLastScheduled is the timestamp when the error resolver
// was last scheduled
errorResolverLastScheduled time.Time
// outstandingErrors states whether there are outstanding errors, occurred while
// syncing an entry with the kernel, that need to be resolved. This variable exists
// to avoid iterating over the full cache to check if reconciliation is necessary,
// but it is possible that it gets out of sync if an error is automatically
// resolved while performing a subsequent Update/Delete operation on the same key.
outstandingErrors bool
// pressureGauge is a metric that tracks the pressure on this map
pressureGauge *metrics.GaugeWithThreshold
// is true when events buffer is enabled.
eventsBufferEnabled bool
// contains optional event buffer which stores last n bpf map events.
events *eventsBuffer
// group is the metric group name for this map, it classifies maps of the same
// type that share the same metric group.
group string
}
func (m *Map) Type() ebpf.MapType {
if m.m != nil {
return m.m.Type()
}
if m.spec != nil {
return m.spec.Type
}
return ebpf.UnspecifiedMap
}
func (m *Map) KeySize() uint32 {
if m.m != nil {
return m.m.KeySize()
}
if m.spec != nil {
return m.spec.KeySize
}
return 0
}
func (m *Map) ValueSize() uint32 {
if m.m != nil {
return m.m.ValueSize()
}
if m.spec != nil {
return m.spec.ValueSize
}
return 0
}
func (m *Map) MaxEntries() uint32 {
if m.m != nil {
return m.m.MaxEntries()
}
if m.spec != nil {
return m.spec.MaxEntries
}
return 0
}
func (m *Map) Flags() uint32 {
if m.m != nil {
return m.m.Flags()
}
if m.spec != nil {
return m.spec.Flags
}
return 0
}
func (m *Map) updateMetrics() {
if m.group == "" {
return
}
metrics.UpdateMapCapacity(m.group, m.MaxEntries())
}
// NewMap creates a new Map instance - object representing a BPF map
func NewMap(name string, mapType ebpf.MapType, mapKey MapKey, mapValue MapValue,
maxEntries int, flags uint32) *Map {
keySize := reflect.TypeOf(mapKey).Elem().Size()
valueSize := reflect.TypeOf(mapValue).Elem().Size()
return &Map{
spec: &ebpf.MapSpec{
Type: mapType,
Name: path.Base(name),
KeySize: uint32(keySize),
ValueSize: uint32(valueSize),
MaxEntries: uint32(maxEntries),
Flags: flags,
},
name: path.Base(name),
key: mapKey,
value: mapValue,
group: name,
}
}
// NewMap creates a new Map instance - object representing a BPF map
func NewMapWithInnerSpec(name string, mapType ebpf.MapType, mapKey MapKey, mapValue MapValue,
maxEntries int, flags uint32, innerSpec *ebpf.MapSpec) *Map {
keySize := reflect.TypeOf(mapKey).Elem().Size()
valueSize := reflect.TypeOf(mapValue).Elem().Size()
return &Map{
spec: &ebpf.MapSpec{
Type: mapType,
Name: path.Base(name),
KeySize: uint32(keySize),
ValueSize: uint32(valueSize),
MaxEntries: uint32(maxEntries),
Flags: flags,
InnerMap: innerSpec,
},
name: path.Base(name),
key: mapKey,
value: mapValue,
}
}
func (m *Map) commonName() string {
if m.cachedCommonName != "" {
return m.cachedCommonName
}
m.cachedCommonName = extractCommonName(m.name)
return m.cachedCommonName
}
func (m *Map) NonPrefixedName() string {
return strings.TrimPrefix(m.name, metrics.Namespace+"_")
}
// scheduleErrorResolver schedules a periodic resolver controller that scans
// all BPF map caches for unresolved errors and attempts to resolve them. On
// error of resolution, the controller is-rescheduled in an expedited manner
// with an exponential back-off.
//
// m.lock must be held for writing
func (m *Map) scheduleErrorResolver() {
m.outstandingErrors = true
if time.Since(m.errorResolverLastScheduled) <= errorResolverSchedulerMinInterval {
return
}
m.errorResolverLastScheduled = time.Now()
go func() {
time.Sleep(errorResolverSchedulerDelay)
mapControllers.UpdateController(m.controllerName(),
controller.ControllerParams{
Group: bpfMapSyncControllerGroup,
DoFunc: m.resolveErrors,
RunInterval: errorResolverSchedulerMinInterval,
},
)
}()
}
// WithCache enables use of a cache. This will store all entries inserted from
// user space in a local cache (map) and will indicate the status of each
// individual entry.
func (m *Map) WithCache() *Map {
if m.cache == nil {
m.cache = map[string]*cacheEntry{}
}
m.withValueCache = true
m.enableSync = true
return m
}
// WithEvents enables use of the event buffer, if the buffer is enabled.
// This stores all map events (i.e. add/update/delete) in a bounded event buffer.
// If eventTTL is not zero, than events that are older than the TTL
// will periodically be removed from the buffer.
// Enabling events will use aprox proportional to 100MB for every million capacity
// in maxSize.
//
// TODO: The IPCache map have many periodic update events added by a controller for entries such as the 0.0.0.0/0 range.
// These fill the event buffer with possibly unnecessary events.
// We should either provide an option to aggregate these events, ignore hem from the ipcache event buffer or store them in a separate buffer.
func (m *Map) WithEvents(c option.BPFEventBufferConfig) *Map {
if !c.Enabled {
return m
}
m.scopedLogger().WithFields(logrus.Fields{
"size": c.MaxSize,
"ttl": c.TTL,
}).Debug("enabling events buffer")
m.eventsBufferEnabled = true
m.initEventsBuffer(c.MaxSize, c.TTL)
return m
}
func (m *Map) WithGroupName(group string) *Map {
m.group = group
return m
}
// WithPressureMetricThreshold enables the tracking of a metric that measures
// the pressure of this map. This metric is only reported if over the
// threshold.
func (m *Map) WithPressureMetricThreshold(threshold float64) *Map {
// When pressure metric is enabled, we keep track of map keys in cache
if m.cache == nil {
m.cache = map[string]*cacheEntry{}
}
m.pressureGauge = metrics.NewBPFMapPressureGauge(m.NonPrefixedName(), threshold)
return m
}
// WithPressureMetric enables tracking and reporting of this map pressure with
// threshold 0.
func (m *Map) WithPressureMetric() *Map {
return m.WithPressureMetricThreshold(0.0)
}
// UpdatePressureMetricWithSize updates map pressure metric using the given map size.
func (m *Map) UpdatePressureMetricWithSize(size int32) {
if m.pressureGauge == nil {
return
}
// Do a lazy check of MetricsConfig as it is not available at map static
// initialization.
if !metrics.BPFMapPressure {
if !m.withValueCache {
m.cache = nil
}
m.pressureGauge = nil
return
}
pvalue := float64(size) / float64(m.MaxEntries())
m.pressureGauge.Set(pvalue)
}
func (m *Map) updatePressureMetric() {
// Skipping pressure metric gauge updates for LRU map as the cache size
// does not accurately represent the actual map sie.
if m.spec != nil && m.spec.Type == ebpf.LRUHash {
return
}
m.UpdatePressureMetricWithSize(int32(len(m.cache)))
}
func (m *Map) FD() int {
return m.m.FD()
}
// Name returns the basename of this map.
func (m *Map) Name() string {
return m.name
}
// Path returns the path to this map on the filesystem.
func (m *Map) Path() (string, error) {
if err := m.setPathIfUnset(); err != nil {
return "", err
}
return m.path, nil
}
// Unpin attempts to unpin (remove) the map from the filesystem.
func (m *Map) Unpin() error {
path, err := m.Path()
if err != nil {
return err
}
return os.RemoveAll(path)
}
// UnpinIfExists tries to unpin (remove) the map only if it exists.
func (m *Map) UnpinIfExists() error {
found, err := m.exist()
if err != nil {
return err
}
if !found {
return nil
}
return m.Unpin()
}
func (m *Map) controllerName() string {
return fmt.Sprintf("bpf-map-sync-%s", m.name)
}
// OpenMap opens the map at pinPath.
func OpenMap(pinPath string, key MapKey, value MapValue) (*Map, error) {
if !path.IsAbs(pinPath) {
return nil, fmt.Errorf("pinPath must be absolute: %s", pinPath)
}
em, err := ebpf.LoadPinnedMap(pinPath, nil)
if err != nil {
return nil, err
}
m := &Map{
m: em,
name: path.Base(pinPath),
path: pinPath,
key: key,
value: value,
}
m.updateMetrics()
registerMap(pinPath, m)
return m, nil
}
func (m *Map) setPathIfUnset() error {
if m.path == "" {
if m.name == "" {
return fmt.Errorf("either path or name must be set")
}
m.path = MapPath(m.name)
}
return nil
}
// Recreate removes any pin at the Map's pin path, recreates and re-pins it.
func (m *Map) Recreate() error {
m.lock.Lock()
defer m.lock.Unlock()
if m.m != nil {
return fmt.Errorf("map already open: %s", m.name)
}
if err := m.setPathIfUnset(); err != nil {
return err
}
if err := os.Remove(m.path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("removing pinned map %s: %w", m.name, err)
}
m.scopedLogger().Infof("Removed map pin at %s, recreating and re-pinning map %s", m.path, m.name)
return m.openOrCreate(true)
}
// OpenOrCreate attempts to open the Map, or if it does not yet exist, create
// the Map. If the existing map's attributes such as map type, key/value size,
// capacity, etc. do not match the Map's attributes, then the map will be
// deleted and reopened without any attempt to retain its previous contents.
// If the map is marked as non-persistent, it will always be recreated.
//
// Returns whether the map was deleted and recreated, or an optional error.
func (m *Map) OpenOrCreate() error {
m.lock.Lock()
defer m.lock.Unlock()
return m.openOrCreate(true)
}
// CreateUnpinned creates the map without pinning it to the file system.
//
// TODO(tb): Remove this when all map creation takes MapSpec.
func (m *Map) CreateUnpinned() error {
m.lock.Lock()
defer m.lock.Unlock()
return m.openOrCreate(false)
}
// Create is similar to OpenOrCreate, but closes the map after creating or
// opening it.
func (m *Map) Create() error {
if err := m.OpenOrCreate(); err != nil {
return err
}
return m.Close()
}
func (m *Map) openOrCreate(pin bool) error {
if m.m != nil {
return nil
}
if m.spec == nil {
return fmt.Errorf("attempted to create map %s without MapSpec", m.name)
}
if err := m.setPathIfUnset(); err != nil {
return err
}
m.spec.Flags |= GetPreAllocateMapFlags(m.spec.Type)
if m.spec.InnerMap != nil {
m.spec.InnerMap.Flags |= GetPreAllocateMapFlags(m.spec.InnerMap.Type)
}
if pin {
m.spec.Pinning = ebpf.PinByName
}
em, err := OpenOrCreateMap(m.spec, path.Dir(m.path))
if err != nil {
return err
}
m.updateMetrics()
registerMap(m.path, m)
// Consume the MapSpec.
m.spec = nil
// Retain the Map.
m.m = em
return nil
}
// Open opens the BPF map. All calls to Open() are serialized due to acquiring
// m.lock
func (m *Map) Open() error {
m.lock.Lock()
defer m.lock.Unlock()
return m.open()
}
// open opens the BPF map. It is identical to Open() but should be used when
// m.lock is already held. open() may only be used if m.lock is held for
// writing.
func (m *Map) open() error {
if m.m != nil {
return nil
}
if err := m.setPathIfUnset(); err != nil {
return err
}
em, err := ebpf.LoadPinnedMap(m.path, nil)
if err != nil {
return fmt.Errorf("loading pinned map %s: %w", m.path, err)
}
m.updateMetrics()
registerMap(m.path, m)
m.m = em
return nil
}
func (m *Map) Close() error {
m.lock.Lock()
defer m.lock.Unlock()
if m.enableSync {
mapControllers.RemoveController(m.controllerName())
}
if m.m != nil {
m.m.Close()
m.m = nil
}
unregisterMap(m.path, m)
return nil
}
func (m *Map) NextKey(key, nextKeyOut interface{}) error {
var duration *spanstat.SpanStat
if metrics.BPFSyscallDuration.IsEnabled() {
duration = spanstat.Start()
}
err := m.m.NextKey(key, nextKeyOut)
if metrics.BPFSyscallDuration.IsEnabled() {
metrics.BPFSyscallDuration.WithLabelValues(metricOpGetNextKey, metrics.Error2Outcome(err)).Observe(duration.End(err == nil).Total().Seconds())
}
return err
}
type DumpCallback func(key MapKey, value MapValue)
// DumpWithCallback iterates over the Map and calls the given DumpCallback for
// each map entry. With the current implementation, it is safe for callbacks to
// retain the values received, as they are guaranteed to be new instances.
//
// TODO(tb): This package currently doesn't support dumping per-cpu maps, as
// ReadValueSize is always set to the size of a single value.
func (m *Map) DumpWithCallback(cb DumpCallback) error {
if cb == nil {
return errors.New("empty callback")
}
if err := m.Open(); err != nil {
return err
}
m.lock.RLock()
defer m.lock.RUnlock()
// Don't need deep copies here, only fresh pointers.
mk := m.key.New()
mv := m.value.New()
i := m.m.Iterate()
for i.Next(mk, mv) {
cb(mk, mv)
mk = m.key.New()
mv = m.value.New()
}
return i.Err()
}
// DumpWithCallbackIfExists is similar to DumpWithCallback, but returns earlier
// if the given map does not exist.
func (m *Map) DumpWithCallbackIfExists(cb DumpCallback) error {
found, err := m.exist()
if err != nil {
return err
}
if found {
return m.DumpWithCallback(cb)
}
return nil
}
// DumpReliablyWithCallback is similar to DumpWithCallback, but performs
// additional tracking of the current and recently seen keys, so that if an
// element is removed from the underlying kernel map during the dump, the dump
// can continue from a recently seen key rather than restarting from scratch.
// In addition, it caps the maximum number of map entry iterations at 4 times
// the maximum map size. If this limit is reached, ErrMaxLookup is returned.
//
// The caller must provide a callback for handling each entry, and a stats
// object initialized via a call to NewDumpStats().
func (m *Map) DumpReliablyWithCallback(cb DumpCallback, stats *DumpStats) error {
if cb == nil {
return errors.New("empty callback")
}
if stats == nil {
return errors.New("stats is nil")
}
var (
prevKey = m.key.New()
currentKey = m.key.New()
nextKey = m.key.New()
value = m.value.New()
prevKeyValid = false
)
stats.start()
defer stats.finish()
if err := m.Open(); err != nil {
return err
}
// Get the first map key.
if err := m.NextKey(nil, currentKey); err != nil {
stats.Lookup = 1
if errors.Is(err, ebpf.ErrKeyNotExist) {
// Empty map, nothing to iterate.
stats.Completed = true
return nil
}
}
// maxLookup is an upper bound limit to prevent backtracking forever
// when iterating over the map's elements (the map might be concurrently
// updated while being iterated)
maxLookup := stats.MaxEntries * 4
// This loop stops when all elements have been iterated (Map.NextKey() returns
// ErrKeyNotExist) OR, in order to avoid hanging if
// the map is continuously updated, when maxLookup has been reached
for stats.Lookup = 1; stats.Lookup <= maxLookup; stats.Lookup++ {
// currentKey was set by the first m.NextKey() above. We know it existed in
// the map, but it may have been deleted by a concurrent map operation.
//
// If currentKey is no longer in the map, nextKey may be the first key in
// the map again. Continue with nextKey only if we still find currentKey in
// the Lookup() after the call to m.NextKey(), this way we know nextKey is
// NOT the first key in the map and iteration hasn't reset.
nextKeyErr := m.NextKey(currentKey, nextKey)
if err := m.m.Lookup(currentKey, value); err != nil {
stats.LookupFailed++
// Restarting from a invalid key starts the iteration again from the beginning.
// If we have a previously found key, try to restart from there instead
if prevKeyValid {
currentKey = prevKey
// Restart from a given previous key only once, otherwise if the prevKey is
// concurrently deleted we might loop forever trying to look it up.
prevKeyValid = false
stats.KeyFallback++
} else {
// Depending on exactly when currentKey was deleted from the
// map, nextKey may be the actual key element after the deleted
// one, or the first element in the map.
currentKey = nextKey
// To avoid having nextKey and currentKey pointing at the same memory
// we allocate a new key for nextKey. Without this currentKey and nextKey
// would be the same pointer value and would get double iterated on the next
// iterations m.NextKey(...) call.
nextKey = m.key.New()
stats.Interrupted++
}
continue
}
cb(currentKey, value)
if nextKeyErr != nil {
if errors.Is(nextKeyErr, ebpf.ErrKeyNotExist) {
stats.Completed = true
return nil // end of map, we're done iterating
}
return nextKeyErr
}
// Prepare keys to move to the next iteration.
prevKey = currentKey
currentKey = nextKey
nextKey = m.key.New()
prevKeyValid = true
}
return ErrMaxLookup
}
// Dump returns the map (type map[string][]string) which contains all
// data stored in BPF map.
func (m *Map) Dump(hash map[string][]string) error {
callback := func(key MapKey, value MapValue) {
// No need to deep copy since we are creating strings.
hash[key.String()] = append(hash[key.String()], value.String())
}
if err := m.DumpWithCallback(callback); err != nil {
return err
}
return nil
}
// DumpIfExists dumps the contents of the map into hash via Dump() if the map
// file exists
func (m *Map) DumpIfExists(hash map[string][]string) error {
found, err := m.exist()
if err != nil {
return err
}
if found {
return m.Dump(hash)
}
return nil
}
func (m *Map) Lookup(key MapKey) (MapValue, error) {
if err := m.Open(); err != nil {
return nil, err
}
m.lock.RLock()
defer m.lock.RUnlock()
var duration *spanstat.SpanStat
if metrics.BPFSyscallDuration.IsEnabled() {
duration = spanstat.Start()
}
value := m.value.New()
err := m.m.Lookup(key, value)
if metrics.BPFSyscallDuration.IsEnabled() {
metrics.BPFSyscallDuration.WithLabelValues(metricOpLookup, metrics.Error2Outcome(err)).Observe(duration.End(err == nil).Total().Seconds())
}
if err != nil {
return nil, err
}
return value, nil
}
func (m *Map) Update(key MapKey, value MapValue) error {
var err error
m.lock.Lock()
defer m.lock.Unlock()
defer func() {
desiredAction := OK
if err != nil {
desiredAction = Insert
}
entry := &cacheEntry{
Key: key,
Value: value,
DesiredAction: desiredAction,
LastError: err,
}
m.addToEventsLocked(MapUpdate, *entry)
if m.cache == nil {
return
}
if m.withValueCache {
if err != nil {
m.scheduleErrorResolver()
}
m.cache[key.String()] = &cacheEntry{
Key: key,
Value: value,
DesiredAction: desiredAction,
LastError: err,
}
m.updatePressureMetric()
} else if err == nil {
m.cache[key.String()] = nil
m.updatePressureMetric()
}
}()
if err = m.open(); err != nil {
return err
}
err = m.m.Update(key, value, ebpf.UpdateAny)
if metrics.BPFMapOps.IsEnabled() {
metrics.BPFMapOps.WithLabelValues(m.commonName(), metricOpUpdate, metrics.Error2Outcome(err)).Inc()
}
if err != nil {
return fmt.Errorf("update map %s: %w", m.Name(), err)
}
return nil
}
// deleteMapEvent is run at every delete map event.
// If cache is enabled, it will update the cache to reflect the delete.
// As well, if event buffer is enabled, it adds a new event to the buffer.
func (m *Map) deleteMapEvent(key MapKey, err error) {
m.addToEventsLocked(MapDelete, cacheEntry{
Key: key,
DesiredAction: Delete,
LastError: err,
})
m.deleteCacheEntry(key, err)
}
func (m *Map) deleteAllMapEvent() {
m.addToEventsLocked(MapDeleteAll, cacheEntry{})
}
// deleteCacheEntry evaluates the specified error, if nil the map key is
// removed from the cache to indicate successful deletion. If non-nil, the map
// key entry in the cache is updated to indicate deletion failure with the
// specified error.
//
// Caller must hold m.lock for writing
func (m *Map) deleteCacheEntry(key MapKey, err error) {
if m.cache == nil {
return
}
k := key.String()
if err == nil {
delete(m.cache, k)
} else if !m.withValueCache {
return
} else {
entry, ok := m.cache[k]
if !ok {
m.cache[k] = &cacheEntry{
Key: key,
}
entry = m.cache[k]
}
entry.DesiredAction = Delete
entry.LastError = err
m.scheduleErrorResolver()
}
}
// delete deletes the map entry corresponding to the given key. If ignoreMissing
// is set to true and the entry was not found, the error metric is not
// incremented for missing entries and nil error is returned.
func (m *Map) delete(key MapKey, ignoreMissing bool) (_ bool, err error) {
defer func() {
m.deleteMapEvent(key, err)
if err != nil {
m.updatePressureMetric()
}
}()
if err = m.open(); err != nil {
return false, err
}
var duration *spanstat.SpanStat
if metrics.BPFSyscallDuration.IsEnabled() {
duration = spanstat.Start()
}
err = m.m.Delete(key)
if metrics.BPFSyscallDuration.IsEnabled() {
metrics.BPFSyscallDuration.WithLabelValues(metricOpDelete, metrics.Error2Outcome(err)).Observe(duration.End(err == nil).Total().Seconds())
}
if errors.Is(err, ebpf.ErrKeyNotExist) && ignoreMissing {
// Error and metrics handling is skipped in case ignoreMissing is set and
// the map key did not exist. This removes false positives in the delete
// metrics and skips the deferred cleanup of nonexistent entries. This
// situation occurs at least in the context of cleanup of NAT mappings from
// CT GC.
return false, nil
}
if metrics.BPFMapOps.IsEnabled() {
// err can be nil or any error other than ebpf.ErrKeyNotExist.
metrics.BPFMapOps.WithLabelValues(m.commonName(), metricOpDelete, metrics.Error2Outcome(err)).Inc()
}
if err != nil {
return false, fmt.Errorf("unable to delete element %s from map %s: %w", key, m.name, err)
}
return true, nil
}
// SilentDelete deletes the map entry corresponding to the given key.
// If a map entry is not found this returns (false, nil).
func (m *Map) SilentDelete(key MapKey) (deleted bool, err error) {
m.lock.Lock()
defer m.lock.Unlock()
return m.delete(key, true)
}
// Delete deletes the map entry corresponding to the given key.
func (m *Map) Delete(key MapKey) error {
m.lock.Lock()
defer m.lock.Unlock()
_, err := m.delete(key, false)
return err
}
// scopedLogger returns a logger scoped for the map. m.lock must be held.
func (m *Map) scopedLogger() *logrus.Entry {
return log.WithFields(logrus.Fields{logfields.Path: m.path, "name": m.name})
}
// DeleteAll deletes all entries of a map by traversing the map and deleting individual
// entries. Note that if entries are added while the taversal is in progress,
// such entries may survive the deletion process.
func (m *Map) DeleteAll() error {
m.lock.Lock()
defer m.lock.Unlock()
defer m.updatePressureMetric()
scopedLog := m.scopedLogger()
scopedLog.Debug("deleting all entries in map")
if m.withValueCache {
// Mark all entries for deletion, upon successful deletion,
// entries will be removed or the LastError will be updated
for _, entry := range m.cache {
entry.DesiredAction = Delete
entry.LastError = fmt.Errorf("deletion pending")
}
}
if err := m.open(); err != nil {
return err
}