|
| 1 | +// @license |
| 2 | +// Copyright (C) 2025 Dinko Korunic |
| 3 | +// |
| 4 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 | +// of this software and associated documentation files (the "Software"), to deal |
| 6 | +// in the Software without restriction, including without limitation the rights |
| 7 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 | +// copies of the Software, and to permit persons to whom the Software is |
| 9 | +// furnished to do so, subject to the following conditions: |
| 10 | +// |
| 11 | +// The above copyright notice and this permission notice shall be included in all |
| 12 | +// copies or substantial portions of the Software. |
| 13 | +// |
| 14 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 20 | +// SOFTWARE. |
| 21 | + |
| 22 | +package main |
| 23 | + |
| 24 | +import ( |
| 25 | + "errors" |
| 26 | + "sync" |
| 27 | + "time" |
| 28 | + |
| 29 | + "github.com/cilium/ebpf" |
| 30 | +) |
| 31 | + |
| 32 | +var ( |
| 33 | + haveBatchMapSupport bool |
| 34 | + checkBatchMapSupportOnce sync.Once |
| 35 | +) |
| 36 | + |
| 37 | +// checkBatchMapSupport checks whether the given ebpf.Map supports batch lookups. |
| 38 | +// |
| 39 | +// A batch lookup is supported if the map supports the BPF_MAP_LOOKUP_BATCH |
| 40 | +// flag. This flag is only supported on Linux 5.7 and above. |
| 41 | +// |
| 42 | +// The function performs a batch lookup on the map with a single dummy key and |
| 43 | +// value to test whether the operation is supported. If the map does not |
| 44 | +// support batch lookups, the function returns false. Otherwise, it returns true. |
| 45 | +func checkBatchMapSupport(m *ebpf.Map) bool { |
| 46 | + keys := make([]counterStatkey, 1) |
| 47 | + values := make([]counterStatvalue, 1) |
| 48 | + |
| 49 | + var cursor ebpf.MapBatchCursor |
| 50 | + |
| 51 | + // BPF_MAP_LOOKUP_BATCH support requires v5.6 kernel |
| 52 | + _, err := m.BatchLookup(&cursor, keys, values, nil) |
| 53 | + |
| 54 | + if err != nil && errors.Is(err, ebpf.ErrNotSupported) { |
| 55 | + return false |
| 56 | + } |
| 57 | + |
| 58 | + return true |
| 59 | +} |
| 60 | + |
| 61 | +// listMap lists all the entries in the given ebpf.Map, converting the counter |
| 62 | +// values into a statEntry slice. |
| 63 | +// |
| 64 | +// The function uses the start time to calculate the duration of each entry. |
| 65 | +// |
| 66 | +// The function checks whether the map supports batch lookups and uses the |
| 67 | +// optimized listMapBatch or listMapIterate functions accordingly. |
| 68 | +// |
| 69 | +// listMap is safe to call concurrently. |
| 70 | +func listMap(m *ebpf.Map, start time.Time) ([]statEntry, error) { |
| 71 | + checkBatchMapSupportOnce.Do(func() { |
| 72 | + haveBatchMapSupport = checkBatchMapSupport(m) |
| 73 | + }) |
| 74 | + |
| 75 | + if haveBatchMapSupport { |
| 76 | + return listMapBatch(m, start) |
| 77 | + } |
| 78 | + |
| 79 | + // fallback to regular eBPF map iteration which might get interrupted for BPF_MAP_TYPE_LRU_HASH |
| 80 | + return listMapIterate(m, start) |
| 81 | +} |
| 82 | + |
| 83 | +// listMapBatch lists all the entries in the given ebpf.Map, converting the |
| 84 | +// counter values into a statEntry slice using batch lookups. |
| 85 | +// |
| 86 | +// The function uses the start time to calculate the duration of each entry. |
| 87 | +// |
| 88 | +// The function is safe to call concurrently. |
| 89 | +// |
| 90 | +// listMapBatch is used by listMap when the map supports batch lookups. |
| 91 | +func listMapBatch(m *ebpf.Map, start time.Time) ([]statEntry, error) { |
| 92 | + keys := make([]counterStatkey, m.MaxEntries()) |
| 93 | + values := make([]counterStatvalue, m.MaxEntries()) |
| 94 | + |
| 95 | + dur := time.Since(start).Seconds() |
| 96 | + stats := make([]statEntry, 0, m.MaxEntries()) |
| 97 | + |
| 98 | + var cursor ebpf.MapBatchCursor |
| 99 | + var ( |
| 100 | + count int |
| 101 | + c int |
| 102 | + err error |
| 103 | + ) |
| 104 | + |
| 105 | + // BPF_MAP_LOOKUP_BATCH support requires v5.6 kernel |
| 106 | + for { |
| 107 | + c, err = m.BatchLookup(&cursor, keys, values, nil) |
| 108 | + count += c |
| 109 | + |
| 110 | + if err != nil { |
| 111 | + if errors.Is(err, ebpf.ErrKeyNotExist) { |
| 112 | + break |
| 113 | + } |
| 114 | + |
| 115 | + return nil, err |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + for i := 0; i < len(keys) && i < count; i++ { |
| 120 | + stats = addStats(stats, keys[i], values[i], dur) |
| 121 | + } |
| 122 | + |
| 123 | + return stats, nil |
| 124 | +} |
| 125 | + |
| 126 | +// listMapIterate iterates over all the entries in the given ebpf.Map, |
| 127 | +// converting the counter values into a statEntry slice. |
| 128 | +// |
| 129 | +// The function uses the start time to calculate the duration of each entry, |
| 130 | +// which is used to compute the bitrate. |
| 131 | +// |
| 132 | +// Parameters: |
| 133 | +// - m *ebpf.Map: the eBPF map to iterate over |
| 134 | +// - start time.Time: the start time for calculating entry duration |
| 135 | +// |
| 136 | +// Returns: |
| 137 | +// - []statEntry: a slice of statEntry objects containing the converted map entries |
| 138 | +// - error: an error if any occurred during map iteration, otherwise nil |
| 139 | +func listMapIterate(m *ebpf.Map, start time.Time) ([]statEntry, error) { |
| 140 | + var ( |
| 141 | + key counterStatkey |
| 142 | + val counterStatvalue |
| 143 | + ) |
| 144 | + |
| 145 | + dur := time.Since(start).Seconds() |
| 146 | + stats := make([]statEntry, 0, m.MaxEntries()) |
| 147 | + |
| 148 | + iter := m.Iterate() |
| 149 | + |
| 150 | + // build statEntry slice converting data where needed |
| 151 | + for iter.Next(&key, &val) { |
| 152 | + stats = addStats(stats, key, val, dur) |
| 153 | + } |
| 154 | + |
| 155 | + return stats, iter.Err() |
| 156 | +} |
| 157 | + |
| 158 | +// addStats takes a slice of statEntry, a counterStatkey, a counterStatvalue, |
| 159 | +// and a duration in seconds, and appends a new statEntry to the slice using |
| 160 | +// the provided data. The function converts the key SrcIP and DstIP fields to |
| 161 | +// netip.Addr objects, and the Comm field to a string. It also calculates the |
| 162 | +// bitrate by dividing the number of bytes by the duration. |
| 163 | +// |
| 164 | +// Parameters: |
| 165 | +// - stats []statEntry: the slice of statEntry objects to which the new entry is appended |
| 166 | +// - key counterStatkey: the counterStatkey object containing the source and |
| 167 | +// destination IP addresses, protocol, and ports, as well as the PID, Comm, |
| 168 | +// and CGroup information |
| 169 | +// - val counterStatvalue: the counterStatvalue object containing the packet |
| 170 | +// and byte counters |
| 171 | +// - dur float64: the duration in seconds |
| 172 | +// |
| 173 | +// Returns: |
| 174 | +// - []statEntry: the updated slice of statEntry objects |
| 175 | +func addStats(stats []statEntry, key counterStatkey, val counterStatvalue, dur float64) []statEntry { |
| 176 | + stats = append(stats, statEntry{ |
| 177 | + SrcIP: bytesToAddr(key.Srcip.In6U.U6Addr8), |
| 178 | + DstIP: bytesToAddr(key.Dstip.In6U.U6Addr8), |
| 179 | + Proto: protoToString(key.Proto), |
| 180 | + SrcPort: key.SrcPort, |
| 181 | + DstPort: key.DstPort, |
| 182 | + Bytes: val.Bytes, |
| 183 | + Packets: val.Packets, |
| 184 | + Bitrate: 8 * float64(val.Bytes) / dur, |
| 185 | + Pid: key.Pid, |
| 186 | + Comm: bsliceToString(key.Comm[:]), |
| 187 | + CGroup: cGroupToPath(key.Cgroupid), |
| 188 | + }) |
| 189 | + |
| 190 | + return stats |
| 191 | +} |
0 commit comments