File: cache.go

package info (click to toggle)
nebula 1.6.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,376 kB
  • sloc: makefile: 149; sh: 100; python: 16
file content (59 lines) | stat: -rw-r--r-- 1,159 bytes parent folder | download
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
package firewall

import (
	"sync/atomic"
	"time"

	"github.com/sirupsen/logrus"
)

// ConntrackCache is used as a local routine cache to know if a given flow
// has been seen in the conntrack table.
type ConntrackCache map[Packet]struct{}

type ConntrackCacheTicker struct {
	cacheV    uint64
	cacheTick uint64

	cache ConntrackCache
}

func NewConntrackCacheTicker(d time.Duration) *ConntrackCacheTicker {
	if d == 0 {
		return nil
	}

	c := &ConntrackCacheTicker{
		cache: ConntrackCache{},
	}

	go c.tick(d)

	return c
}

func (c *ConntrackCacheTicker) tick(d time.Duration) {
	for {
		time.Sleep(d)
		atomic.AddUint64(&c.cacheTick, 1)
	}
}

// Get checks if the cache ticker has moved to the next version before returning
// the map. If it has moved, we reset the map.
func (c *ConntrackCacheTicker) Get(l *logrus.Logger) ConntrackCache {
	if c == nil {
		return nil
	}
	if tick := atomic.LoadUint64(&c.cacheTick); tick != c.cacheV {
		c.cacheV = tick
		if ll := len(c.cache); ll > 0 {
			if l.Level == logrus.DebugLevel {
				l.WithField("len", ll).Debug("resetting conntrack cache")
			}
			c.cache = make(ConntrackCache, ll)
		}
	}

	return c.cache
}