| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package vnodectl |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | |
| 8 | "github.com/netdata/netdata/go/plugins/plugin/framework/vnodes" |
| 9 | ) |
| 10 | |
| 11 | // vnodeStore is intentionally lock-free because mutations are serialized by jobmgr. |
| 12 | // Any caller outside that serialized path must add its own synchronization first. |
| 13 | type vnodeStore struct { |
| 14 | items map[string]*vnodes.VirtualNode |
| 15 | } |
| 16 | |
| 17 | func newVnodeStore(items map[string]*vnodes.VirtualNode) *vnodeStore { |
| 18 | if items == nil { |
| 19 | items = make(map[string]*vnodes.VirtualNode) |
| 20 | } |
| 21 | return &vnodeStore{items: items} |
| 22 | } |
| 23 | |
| 24 | func (s *vnodeStore) Lookup(name string) (*vnodes.VirtualNode, bool) { |
| 25 | cfg, ok := s.items[name] |
| 26 | return cfg, ok |
| 27 | } |
| 28 | |
| 29 | func (s *vnodeStore) Upsert(cfg *vnodes.VirtualNode) (bool, error) { |
| 30 | if cfg == nil { |
| 31 | return false, fmt.Errorf("nil vnode config") |
| 32 | } |
| 33 | if orig, ok := s.items[cfg.Name]; ok && sameStoredVnode(orig, cfg) { |
| 34 | return false, nil |
| 35 | } |
| 36 | s.items[cfg.Name] = cfg |
| 37 | return true, nil |
| 38 | } |
| 39 | |
| 40 | func (s *vnodeStore) Remove(name string) bool { |
| 41 | if _, ok := s.items[name]; !ok { |
| 42 | return false |
| 43 | } |
| 44 | delete(s.items, name) |
| 45 | return true |
| 46 | } |
| 47 | |
| 48 | func (s *vnodeStore) ForEach(fn func(cfg *vnodes.VirtualNode) bool) { |
| 49 | for _, cfg := range s.items { |
| 50 | if !fn(cfg) { |
| 51 | return |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | func sameStoredVnode(orig, next *vnodes.VirtualNode) bool { |
| 57 | if orig == nil || next == nil { |
| 58 | return orig == next |
| 59 | } |
| 60 | return orig.Equal(next) && |
| 61 | orig.SourceType == next.SourceType |
| 62 | } |