-
Notifications
You must be signed in to change notification settings - Fork 78
/
hook.go
66 lines (54 loc) · 1.53 KB
/
hook.go
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
package xdpcap
import (
"os"
"path/filepath"
"github.com/cloudflare/xdpcap/internal"
"github.com/cilium/ebpf"
"github.com/pkg/errors"
)
// Hook represents an xdpcap hook point.
// This hook can be reused with several programs.
type Hook struct {
hookMap *ebpf.Map
fileName string
}
// NewHook creates a new Hook, that can be Pin()'d to fileName.
// fileName must be inside a bpffs
func NewHook(fileName string) (*Hook, error) {
spec := internal.HookMapSpec.Copy()
spec.Name = ebpf.SanitizeName(filepath.Base(fileName), '_')
hookMap, err := ebpf.NewMap(spec)
if err != nil {
return nil, errors.Wrap(err, "creating hook map")
}
return &Hook{
hookMap: hookMap,
fileName: fileName,
}, nil
}
// Close releases any resources held
// It does not Rm()
func (h *Hook) Close() error {
return h.hookMap.Close()
}
// Pin persists the underlying map to a file, overwriting it if it already exists
func (h *Hook) Pin() error {
// Pin() fails if the file already exists, try to remove it first
h.Rm()
return errors.Wrapf(h.hookMap.Pin(h.fileName), "file %s", h.fileName)
}
// Rm deletes files created by Pin()
func (h *Hook) Rm() error {
return errors.Wrapf(os.Remove(h.fileName), "file %s", h.fileName)
}
// Patch edits all programs in the spec that refer to hookMapSymbol to use this hook.
//
// This function is a no-op if called on a nil Hook.
func (h *Hook) Patch(spec *ebpf.CollectionSpec, hookMapSymbol string) error {
if h == nil {
return nil
}
return spec.RewriteMaps(map[string]*ebpf.Map{
hookMapSymbol: h.hookMap,
})
}