Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build on darwin: move linux-specific tracer code to tracer_linux.go #53

Merged
merged 2 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion ebpf/bpf_bpfeb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion ebpf/bpf_bpfel.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

171 changes: 1 addition & 170 deletions ebpf/tracer.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,6 @@
//go:build linux

package ebpf

import (
"bufio"
"context"
"errors"
"fmt"
"os"
"strings"

"github.com/cilium/ebpf"
"github.com/cilium/ebpf/btf"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/perf"
"github.com/cilium/ebpf/rlimit"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/sirupsen/logrus"
)

var ErrCgroup2NotMounted = errors.New("cgroup2 not mounted")
import "github.com/sirupsen/logrus"

type Config struct {
QueueSize int
Expand All @@ -43,152 +23,3 @@ type Tracer struct {
cfg Config
events chan DNSEvent
}

func (t *Tracer) Run(ctx context.Context) error {
// Allow the current process to lock memory for eBPF resources.
if err := rlimit.RemoveMemlock(); err != nil {
return err
}

t.log.Debug("running")
defer t.log.Debug("stopping")

objs := bpfObjects{}
var customBTF *btf.Spec
if t.cfg.CustomBTFFilePath != "" {
t.log.Debugf("loading custom btf from path %q", t.cfg.CustomBTFFilePath)
spec, err := btf.LoadSpec(t.cfg.CustomBTFFilePath)
if err != nil {
return err
}
customBTF = spec
}

// Load pre-compiled programs and maps into the kernel.
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
Maps: ebpf.MapOptions{},
Programs: ebpf.ProgramOptions{
KernelTypes: customBTF,
},
MapReplacements: nil,
}); err != nil {
return fmt.Errorf("loading objects: %w", err)
}
defer objs.Close()

// Get the first-mounted cgroupv2 path.
cgroupPath, err := detectCgroupPath()
if errors.Is(err, ErrCgroup2NotMounted) {
if err := mountCgroup2(); err != nil {
return fmt.Errorf("cgroup2 not mounted and failed to mount manually: %w", err)
}
cgroupPath, err = detectCgroupPath()
}
if err != nil {
return err
}

t.log.Debugf("using cgroup2 at %q", cgroupPath)

l, err := link.AttachCgroup(link.CgroupOptions{
Path: cgroupPath,
Attach: ebpf.AttachCGroupInetIngress,
Program: objs.CgroupIngress,
})
if err != nil {
return fmt.Errorf("attaching cgroup: %w", err)
}
defer l.Close()

reader, err := perf.NewReader(objs.Events, 1024)
if err != nil {
return err
}

for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}

record, err := reader.Read()
if err != nil {
return err
}

if len(record.RawSample) < 4 {
t.log.Warnf("skipping too small event: %d bytes", len(record.RawSample))
continue
}

// First 4 bytes now reserved for payload size. See net_event_context in types.h for full structure.
event, err := parseEvent(record.RawSample[4:])
if err != nil {
t.log.Errorf("parsing event: %v", err)
continue
}

select {
case t.events <- event:
default:
t.log.Warn("dropping event, queue is full")
continue
}
}
}

func (t *Tracer) Events() <-chan DNSEvent {
return t.events
}

func IsKernelBTFAvailable() bool {
_, err := os.Stat("/sys/kernel/btf/vmlinux")
return err == nil
}

func parseEvent(data []byte) (DNSEvent, error) {
packet := gopacket.NewPacket(
data,
layers.LayerTypeIPv4,
gopacket.Default,
)

var res DNSEvent
if packet == nil {
return res, errors.New("parsing packet")
}

appLayer := packet.ApplicationLayer()
if appLayer == nil {
return res, errors.New("layer L7 is missing")
}

dns, ok := appLayer.(*layers.DNS)
if !ok {
return res, fmt.Errorf("expected dns layer, actual type %T", appLayer)
}

return DNSEvent{
Questions: dns.Questions,
Answers: dns.Answers,
}, nil
}

func detectCgroupPath() (string, error) {
f, err := os.Open("/proc/mounts")
if err != nil {
return "", err
}
defer f.Close()

scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) >= 3 && fields[2] == "cgroup2" {
return fields[1], nil
}
}

return "", ErrCgroup2NotMounted
}
171 changes: 171 additions & 0 deletions ebpf/tracer_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
//go:build linux

package ebpf

import (
"bufio"
"context"
"errors"
"fmt"
"os"
"strings"

"github.com/cilium/ebpf"
"github.com/cilium/ebpf/btf"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/perf"
"github.com/cilium/ebpf/rlimit"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)

var ErrCgroup2NotMounted = errors.New("cgroup2 not mounted")

func (t *Tracer) Run(ctx context.Context) error {
// Allow the current process to lock memory for eBPF resources.
if err := rlimit.RemoveMemlock(); err != nil {
return err
}

t.log.Debug("running")
defer t.log.Debug("stopping")

objs := bpfObjects{}
var customBTF *btf.Spec
if t.cfg.CustomBTFFilePath != "" {
t.log.Debugf("loading custom btf from path %q", t.cfg.CustomBTFFilePath)
spec, err := btf.LoadSpec(t.cfg.CustomBTFFilePath)
if err != nil {
return err
}
customBTF = spec
}

// Load pre-compiled programs and maps into the kernel.
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
Maps: ebpf.MapOptions{},
Programs: ebpf.ProgramOptions{
KernelTypes: customBTF,
},
MapReplacements: nil,
}); err != nil {
return fmt.Errorf("loading objects: %w", err)
}
defer objs.Close()

// Get the first-mounted cgroupv2 path.
cgroupPath, err := detectCgroupPath()
if errors.Is(err, ErrCgroup2NotMounted) {
if err := mountCgroup2(); err != nil {
return fmt.Errorf("cgroup2 not mounted and failed to mount manually: %w", err)
}
cgroupPath, err = detectCgroupPath()
}
if err != nil {
return err
}

t.log.Debugf("using cgroup2 at %q", cgroupPath)

l, err := link.AttachCgroup(link.CgroupOptions{
Path: cgroupPath,
Attach: ebpf.AttachCGroupInetIngress,
Program: objs.CgroupIngress,
})
if err != nil {
return fmt.Errorf("attaching cgroup: %w", err)
}
defer l.Close()

reader, err := perf.NewReader(objs.Events, 1024)
if err != nil {
return err
}

for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}

record, err := reader.Read()
if err != nil {
return err
}

if len(record.RawSample) < 4 {
t.log.Warnf("skipping too small event: %d bytes", len(record.RawSample))
continue
}

// First 4 bytes now reserved for payload size. See net_event_context in types.h for full structure.
event, err := parseEvent(record.RawSample[4:])
if err != nil {
t.log.Errorf("parsing event: %v", err)
continue
}

select {
case t.events <- event:
default:
t.log.Warn("dropping event, queue is full")
continue
}
}
}

func (t *Tracer) Events() <-chan DNSEvent {
return t.events
}

func IsKernelBTFAvailable() bool {
_, err := os.Stat("/sys/kernel/btf/vmlinux")
return err == nil
}

func parseEvent(data []byte) (DNSEvent, error) {
packet := gopacket.NewPacket(
data,
layers.LayerTypeIPv4,
gopacket.Default,
)

var res DNSEvent
if packet == nil {
return res, errors.New("parsing packet")
}

appLayer := packet.ApplicationLayer()
if appLayer == nil {
return res, errors.New("layer L7 is missing")
}

dns, ok := appLayer.(*layers.DNS)
if !ok {
return res, fmt.Errorf("expected dns layer, actual type %T", appLayer)
}

return DNSEvent{
Questions: dns.Questions,
Answers: dns.Answers,
}, nil
}

func detectCgroupPath() (string, error) {
f, err := os.Open("/proc/mounts")
if err != nil {
return "", err
}
defer f.Close()

scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) >= 3 && fields[2] == "cgroup2" {
return fields[1], nil
}
}

return "", ErrCgroup2NotMounted
}
2 changes: 2 additions & 0 deletions ebpf/tracer_test.go → ebpf/tracer_linux_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//go:build linux

package ebpf

import (
Expand Down
19 changes: 19 additions & 0 deletions ebpf/tracer_nolinux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//go:build !linux

package ebpf

import (
"context"
)

func (t *Tracer) Run(ctx context.Context) error {
panic("not implemented on non-linux")
}

func (t *Tracer) Events() <-chan DNSEvent {
return t.events
}

func IsKernelBTFAvailable() bool {
return false
}