| 1 |
|
| 2 |
|
| 3 |
package link |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"slices" |
| 8 |
|
| 9 |
"github.com/cilium/ebpf" |
| 10 |
"github.com/cilium/ebpf/internal/sys" |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
type QueryOptions struct { |
| 15 |
|
| 16 |
|
| 17 |
Target int |
| 18 |
|
| 19 |
Attach ebpf.AttachType |
| 20 |
|
| 21 |
QueryFlags uint32 |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
type QueryResult struct { |
| 26 |
|
| 27 |
Programs []AttachedProgram |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
Revision uint64 |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
func (qr *QueryResult) HaveLinkInfo() bool { |
| 37 |
return slices.ContainsFunc(qr.Programs, |
| 38 |
func(ap AttachedProgram) bool { |
| 39 |
_, ok := ap.LinkID() |
| 40 |
return ok |
| 41 |
}, |
| 42 |
) |
| 43 |
} |
| 44 |
|
| 45 |
type AttachedProgram struct { |
| 46 |
ID ebpf.ProgramID |
| 47 |
linkID ID |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
func (ap *AttachedProgram) LinkID() (ID, bool) { |
| 55 |
return ap.linkID, ap.linkID != 0 |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
func QueryPrograms(opts QueryOptions) (*QueryResult, error) { |
| 65 |
|
| 66 |
attr := sys.ProgQueryAttr{ |
| 67 |
TargetFdOrIfindex: uint32(opts.Target), |
| 68 |
AttachType: sys.AttachType(opts.Attach), |
| 69 |
QueryFlags: opts.QueryFlags, |
| 70 |
} |
| 71 |
err := sys.ProgQuery(&attr) |
| 72 |
if err != nil { |
| 73 |
if haveFeatErr := haveProgQuery(); haveFeatErr != nil { |
| 74 |
return nil, fmt.Errorf("query programs: %w", haveFeatErr) |
| 75 |
} |
| 76 |
return nil, fmt.Errorf("query programs: %w", err) |
| 77 |
} |
| 78 |
if attr.Count == 0 { |
| 79 |
return &QueryResult{Revision: attr.Revision}, nil |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
haveLinkIDs := attr.Revision != 0 |
| 85 |
|
| 86 |
count := attr.Count |
| 87 |
progIds := make([]ebpf.ProgramID, count) |
| 88 |
attr = sys.ProgQueryAttr{ |
| 89 |
TargetFdOrIfindex: uint32(opts.Target), |
| 90 |
AttachType: sys.AttachType(opts.Attach), |
| 91 |
QueryFlags: opts.QueryFlags, |
| 92 |
Count: count, |
| 93 |
ProgIds: sys.SlicePointer(progIds), |
| 94 |
} |
| 95 |
|
| 96 |
var linkIds []ID |
| 97 |
if haveLinkIDs { |
| 98 |
linkIds = make([]ID, count) |
| 99 |
attr.LinkIds = sys.SlicePointer(linkIds) |
| 100 |
} |
| 101 |
|
| 102 |
if err := sys.ProgQuery(&attr); err != nil { |
| 103 |
return nil, fmt.Errorf("query programs: %w", err) |
| 104 |
} |
| 105 |
|
| 106 |
|
| 107 |
var programs []AttachedProgram |
| 108 |
for i, id := range progIds[:attr.Count] { |
| 109 |
ap := AttachedProgram{ID: id} |
| 110 |
if haveLinkIDs { |
| 111 |
ap.linkID = linkIds[i] |
| 112 |
} |
| 113 |
programs = append(programs, ap) |
| 114 |
} |
| 115 |
|
| 116 |
return &QueryResult{programs, attr.Revision}, nil |
| 117 |
} |