summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/agent/confgroup/cache.go
blob: 40c8071d5c12be49f56bee43d04505341ca83371 (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package confgroup

func NewCache() *Cache {
	return &Cache{
		hashes:  make(map[uint64]uint),
		sources: make(map[string]map[uint64]Config),
	}
}

type Cache struct {
	hashes  map[uint64]uint              // map[cfgHash]cfgCount
	sources map[string]map[uint64]Config // map[cfgSource]map[cfgHash]cfg
}

func (c *Cache) Add(group *Group) (added, removed []Config) {
	if group == nil {
		return nil, nil
	}

	if len(group.Configs) == 0 {
		return c.addEmpty(group)
	}

	return c.addNotEmpty(group)
}

func (c *Cache) addEmpty(group *Group) (added, removed []Config) {
	set, ok := c.sources[group.Source]
	if !ok {
		return nil, nil
	}

	for hash, cfg := range set {
		c.hashes[hash]--
		if c.hashes[hash] == 0 {
			removed = append(removed, cfg)
		}
		delete(set, hash)
	}

	delete(c.sources, group.Source)

	return nil, removed
}

func (c *Cache) addNotEmpty(group *Group) (added, removed []Config) {
	set, ok := c.sources[group.Source]
	if !ok {
		set = make(map[uint64]Config)
		c.sources[group.Source] = set
	}

	seen := make(map[uint64]struct{})

	for _, cfg := range group.Configs {
		hash := cfg.Hash()
		seen[hash] = struct{}{}

		if _, ok := set[hash]; ok {
			continue
		}

		set[hash] = cfg
		if c.hashes[hash] == 0 {
			added = append(added, cfg)
		}
		c.hashes[hash]++
	}

	if !ok {
		return added, nil
	}

	for hash, cfg := range set {
		if _, ok := seen[hash]; ok {
			continue
		}

		delete(set, hash)
		c.hashes[hash]--
		if c.hashes[hash] == 0 {
			removed = append(removed, cfg)
		}
	}

	if ok && len(set) == 0 {
		delete(c.sources, group.Source)
	}

	return added, removed
}