Skip to content

Commit

Permalink
Refactor code of attaching skb-tracking kprobe
Browse files Browse the repository at this point in the history
Hide the attaching details of tracking skb from `main.go`.

Signed-off-by: Leon Hwang <hffilwlqm@gmail.com>
  • Loading branch information
Asphaltt authored and brb committed Jun 17, 2024
1 parent e064545 commit 2c0afa8
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 29 deletions.
61 changes: 61 additions & 0 deletions internal/pwru/skb_tracker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: Apache-2.0
/* Copyright 2024 Authors of Cilium */

package pwru

import (
"errors"
"log"
"os"

"github.com/cilium/ebpf"
"github.com/cilium/ebpf/link"
)

type skbTracker struct {
links []link.Link
}

func (t *skbTracker) Detach() {
for _, l := range t.links {
_ = l.Close()
}
t.links = nil
}

func TrackSkb(coll *ebpf.Collection, haveFexit, trackSkbClone bool) *skbTracker {
var t skbTracker

kp, err := link.Kprobe("kfree_skbmem", coll.Programs["kprobe_skb_lifetime_termination"], nil)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatalf("Opening kprobe kfree_skbmem: %s\n", err)
} else {
log.Printf("Warn: kfree_skbmem not found, pwru is likely to mismatch skb due to lack of skb lifetime management\n")
return &t
}
} else {
t.links = append(t.links, kp)
}

if haveFexit && trackSkbClone {
progs := []*ebpf.Program{
coll.Programs["fexit_skb_clone"],
coll.Programs["fexit_skb_copy"],
}
for _, prog := range progs {
fexit, err := link.AttachTracing(link.TracingOptions{
Program: prog,
})
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatalf("Opening tracing(%s): %s\n", prog, err)
}
} else {
t.links = append(t.links, fexit)
}
}
}

return &t
}
31 changes: 2 additions & 29 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,35 +198,8 @@ func main() {
}

if flags.FilterTrackSkb || flags.FilterTrackSkbByStackid {
kp, err := link.Kprobe("kfree_skbmem", coll.Programs["kprobe_skb_lifetime_termination"], nil)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatalf("Opening kprobe kfree_skbmem: %s\n", err)
} else {
log.Printf("Warn: kfree_skbmem not found, pwru is likely to mismatch skb due to lack of skb lifetime management\n")
}
} else {
defer kp.Close()
}
}

if haveFexit && flags.FilterTrackSkb {
progs := []*ebpf.Program{
coll.Programs["fexit_skb_clone"],
coll.Programs["fexit_skb_copy"],
}
for _, prog := range progs {
fexit, err := link.AttachTracing(link.TracingOptions{
Program: prog,
})
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatalf("Opening tracing(%s): %s\n", prog, err)
}
} else {
defer fexit.Close()
}
}
t := pwru.TrackSkb(coll, haveFexit, flags.FilterTrackSkb)
defer t.Detach()
}

if len(flags.FilterNonSkbFuncs) > 0 {
Expand Down

0 comments on commit 2c0afa8

Please sign in to comment.