|
| 1 | +package exporter |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "regexp" |
| 7 | + "unsafe" |
| 8 | + |
| 9 | + "github.com/aquasecurity/libbpfgo" |
| 10 | + "github.com/cloudflare/ebpf_exporter/v2/cgroup" |
| 11 | + "github.com/cloudflare/ebpf_exporter/v2/config" |
| 12 | +) |
| 13 | + |
| 14 | +// CgroupIDMap synchronises cgroup changes with the shared bpf map. |
| 15 | +type CgroupIDMap struct { |
| 16 | + bpfMap *libbpfgo.BPFMap |
| 17 | + ch chan cgroup.ChangeNotification |
| 18 | + cache map[string]*regexp.Regexp |
| 19 | +} |
| 20 | + |
| 21 | +func newCgroupIDMap(module *libbpfgo.Module, cfg config.Config) (*CgroupIDMap, error) { |
| 22 | + m, err := module.GetMap(cfg.CgroupIDMap.Name) |
| 23 | + if err != nil { |
| 24 | + return nil, fmt.Errorf("failed to get map %q: %w", cfg.CgroupIDMap.Name, err) |
| 25 | + } |
| 26 | + |
| 27 | + keySize := m.KeySize() |
| 28 | + if keySize != 8 { |
| 29 | + return nil, fmt.Errorf("key size for map %q is not expected 8 bytes (u64), it is %d bytes", cfg.CgroupIDMap.Name, keySize) |
| 30 | + } |
| 31 | + valueSize := m.ValueSize() |
| 32 | + if valueSize != 8 { |
| 33 | + return nil, fmt.Errorf("value size for map %q is not expected 8 bytes (u64), it is %d bytes", cfg.CgroupIDMap.Name, valueSize) |
| 34 | + } |
| 35 | + |
| 36 | + c := &CgroupIDMap{ |
| 37 | + bpfMap: m, |
| 38 | + ch: make(chan cgroup.ChangeNotification, 10), |
| 39 | + cache: map[string]*regexp.Regexp{}, |
| 40 | + } |
| 41 | + |
| 42 | + for _, expr := range cfg.CgroupIDMap.Regexps { |
| 43 | + if _, ok := c.cache[expr]; !ok { |
| 44 | + compiled, err := regexp.Compile(expr) |
| 45 | + if err != nil { |
| 46 | + return nil, fmt.Errorf("error compiling regexp %q: %w", expr, err) |
| 47 | + } |
| 48 | + c.cache[expr] = compiled |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return c, nil |
| 53 | +} |
| 54 | + |
| 55 | +func (c *CgroupIDMap) subscribe(m *cgroup.Monitor) error { |
| 56 | + return m.SubscribeCgroupChange(c.ch) |
| 57 | +} |
| 58 | + |
| 59 | +func (c *CgroupIDMap) runLoop() { |
| 60 | + for update := range c.ch { |
| 61 | + if update.Remove { |
| 62 | + key := uint64(update.ID) |
| 63 | + err := c.bpfMap.DeleteKey(unsafe.Pointer(&key)) |
| 64 | + log.Printf("Error deleting key from CgroupIDMap: %v", err) |
| 65 | + } else { |
| 66 | + key := uint64(update.ID) |
| 67 | + value := uint64(1) |
| 68 | + if c.checkMatch(update.Path) { |
| 69 | + err := c.bpfMap.Update(unsafe.Pointer(&key), unsafe.Pointer(&value)) |
| 70 | + log.Printf("Error updating CgroupIDMap: %v", err) |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func (c *CgroupIDMap) checkMatch(path string) bool { |
| 77 | + for _, compiled := range c.cache { |
| 78 | + if compiled.MatchString(path) { |
| 79 | + return true |
| 80 | + } |
| 81 | + } |
| 82 | + return false |
| 83 | +} |
0 commit comments