Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix(gpu): correct CUDA eBPF launch decoding and kernel names (#1423)

cherrycoveb74453428793
diff --git a/opentelemetry-gpu-collector/README.md b/opentelemetry-gpu-collector/README.md
index f549dbc5..8112133e 100644
--- a/opentelemetry-gpu-collector/README.md
+++ b/opentelemetry-gpu-collector/README.md
@@ -273,12 +273,14 @@ On by default on Linux. Discovers `libcudart` from install paths and `/proc/*/ma
Attaches uprobes/uretprobes to `libcudart.so*` to intercept:
- `cudaLaunchKernel` — kernel name, grid/block dimensions, stream, shared mem
+- `__cudaGetKernel` (CUDA 13+) — maps opaque `cudaKernel_t` handles back to ELF host functions for stable kernel names
- `cudaMalloc` / `cudaFree` — allocation size
- `cudaMemcpy` / `cudaMemcpyAsync` — sync memcpy closes device-wide spans; async records bytes
- `cudaStreamSynchronize` / `cudaDeviceSynchronize` — stream-sync occupancy spans
- `cudaSetDevice` — per-thread device attribution
Events flow through a BPF ring buffer to Go userspace. Activity counters export with `process.pid`; the stream-sync occupancy engine emits `process.gpu.core.usage` / `process.gpu.sm_active` (model estimates, not hardware SM occupancy).
+Kernel symbols are resolved from the target process's executable mappings with PIE/ASLR load bias applied. Unresolvable symbols use the bounded `unknown` label rather than process-specific virtual addresses.
## Contributing
diff --git a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c
index 3dc9d40d..008d4ded 100644
--- a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c
+++ b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c
@@ -37,6 +37,36 @@ struct {
__type(value, __u64);
} cuda_malloc_size_cache SEC(".maps");
+// CUDA 13 lazily converts the ELF host-function pointer into an opaque
+// cudaKernel_t via __cudaGetKernel, then passes that handle to
+// cudaLaunchKernel. Retain the relationship so userspace can still resolve a
+// stable, human-readable ELF symbol. Older CUDA versions continue to pass the
+// host-function pointer directly and do not use these maps.
+struct cuda_get_kernel_args_t {
+ __u64 out_ptr;
+ __u64 host_func;
+};
+
+struct cuda_kernel_handle_key_t {
+ __u32 pid;
+ __u32 pad;
+ __u64 handle;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_LRU_HASH);
+ __uint(max_entries, 1024);
+ __type(key, __u64);
+ __type(value, struct cuda_get_kernel_args_t);
+} cuda_get_kernel_cache SEC(".maps");
+
+struct {
+ __uint(type, BPF_MAP_TYPE_LRU_HASH);
+ __uint(max_entries, 65536);
+ __type(key, struct cuda_kernel_handle_key_t);
+ __type(value, __u64);
+} cuda_kernel_handles SEC(".maps");
+
static __always_inline void fill_header(struct cuda_event_header_t *hdr, __u8 type, __u64 stream_id) {
__u64 pid_tgid = bpf_get_current_pid_tgid();
hdr->type = type;
@@ -62,21 +92,24 @@ int handle_cuda_launch(struct pt_regs *ctx) {
__u32 shared = 0;
#if defined(__TARGET_ARCH_x86)
- // After dim3 packing: r8=args, r9=sharedMem, stream on stack at SP+8.
- // Read r9 directly — PT_REGS_PARM6 can fail to inline with some libbpf
- // headers and surfaces as "unsatisfied program reference" at load time.
- shared = (__u32)ctx->r9;
- bpf_probe_read_user(&stream, sizeof(stream), (void *)(ctx->sp + 8));
-
+ // SysV AMD64 splits each 12-byte dim3 aggregate into two eightbytes:
+ // rdi=func, rsi/rdx=gridDim, rcx/r8=blockDim, r9=args,
+ // [sp+8]=sharedMem, [sp+16]=stream.
__u64 grid_xy = PT_REGS_PARM2(ctx);
+ __u64 grid_z = PT_REGS_PARM3(ctx);
+ __u64 block_xy = PT_REGS_PARM4(ctx);
+ __u64 block_z = PT_REGS_PARM5(ctx);
+ __u64 shared64 = 0;
+ bpf_probe_read_user(&shared64, sizeof(shared64), (void *)(ctx->sp + 8));
+ bpf_probe_read_user(&stream, sizeof(stream), (void *)(ctx->sp + 16));
+ shared = (__u32)shared64;
+
ev->grid_x = grid_xy & 0xFFFFFFFF;
ev->grid_y = grid_xy >> 32;
- __u64 grid_z_block_x = PT_REGS_PARM3(ctx);
- ev->grid_z = grid_z_block_x & 0xFFFFFFFF;
- ev->block_x = grid_z_block_x >> 32;
- __u64 block_yz = PT_REGS_PARM4(ctx);
- ev->block_y = block_yz & 0xFFFFFFFF;
- ev->block_z = block_yz >> 32;
+ ev->grid_z = grid_z & 0xFFFFFFFF;
+ ev->block_x = block_xy & 0xFFFFFFFF;
+ ev->block_y = block_xy >> 32;
+ ev->block_z = block_z & 0xFFFFFFFF;
#elif defined(__TARGET_ARCH_arm64)
// AAPCS64: func=x0, grid=x1/x2, block=x3/x4, args=x5, shared=x6, stream=x7
{
@@ -98,7 +131,14 @@ int handle_cuda_launch(struct pt_regs *ctx) {
#endif
fill_header(&ev->hdr, EVENT_GPU_KERNEL_LAUNCH, stream);
- ev->kern_func_off = PT_REGS_PARM1(ctx);
+ __u64 kernel = PT_REGS_PARM1(ctx);
+ struct cuda_kernel_handle_key_t kernel_key = {
+ .pid = ev->hdr.pid,
+ .pad = 0,
+ .handle = kernel,
+ };
+ __u64 *host_func = bpf_map_lookup_elem(&cuda_kernel_handles, &kernel_key);
+ ev->kern_func_off = host_func ? *host_func : kernel;
ev->shared_mem_bytes = shared;
ev->pad = 0;
@@ -106,6 +146,43 @@ int handle_cuda_launch(struct pt_regs *ctx) {
return 0;
}
+SEC("uprobe/__cudaGetKernel")
+int handle_cuda_get_kernel_enter(struct pt_regs *ctx) {
+ __u64 pid_tgid = bpf_get_current_pid_tgid();
+ struct cuda_get_kernel_args_t args = {
+ .out_ptr = PT_REGS_PARM1(ctx),
+ .host_func = PT_REGS_PARM2(ctx),
+ };
+ bpf_map_update_elem(&cuda_get_kernel_cache, &pid_tgid, &args, BPF_ANY);
+ return 0;
+}
+
+SEC("uretprobe/__cudaGetKernel")
+int handle_cuda_get_kernel_exit(struct pt_regs *ctx) {
+ __u64 pid_tgid = bpf_get_current_pid_tgid();
+ struct cuda_get_kernel_args_t *args =
+ bpf_map_lookup_elem(&cuda_get_kernel_cache, &pid_tgid);
+ if (!args)
+ return 0;
+
+ // cudaSuccess is zero. On success, *out_ptr contains the opaque handle
+ // subsequently supplied as cudaLaunchKernel's first argument.
+ if ((__s64)PT_REGS_RC(ctx) == 0 && args->out_ptr && args->host_func) {
+ __u64 handle = 0;
+ if (bpf_probe_read_user(&handle, sizeof(handle), (void *)args->out_ptr) == 0 && handle) {
+ struct cuda_kernel_handle_key_t key = {
+ .pid = pid_tgid >> 32,
+ .pad = 0,
+ .handle = handle,
+ };
+ bpf_map_update_elem(&cuda_kernel_handles, &key, &args->host_func, BPF_ANY);
+ }
+ }
+
+ bpf_map_delete_elem(&cuda_get_kernel_cache, &pid_tgid);
+ return 0;
+}
+
SEC("uprobe/cudaMalloc")
int handle_cuda_malloc_enter(struct pt_regs *ctx) {
__u64 pid_tgid = bpf_get_current_pid_tgid();
diff --git a/opentelemetry-gpu-collector/internal/ebpf/symbols.go b/opentelemetry-gpu-collector/internal/ebpf/symbols.go
index 888b897e..26b24e61 100644
--- a/opentelemetry-gpu-collector/internal/ebpf/symbols.go
+++ b/opentelemetry-gpu-collector/internal/ebpf/symbols.go
@@ -31,7 +31,21 @@ type symbolEntry struct {
type symbolTable struct {
entries []symbolEntry
- base uint64
+ loaded []addressRange
+}
+
+type addressRange struct {
+ start uint64
+ end uint64
+}
+
+type procMapEntry struct {
+ addrRange string
+ start uint64
+ end uint64
+ offset uint64
+ perms string
+ path string
}
func NewSymbolResolver(logger *slog.Logger) *SymbolResolver {
@@ -46,35 +60,62 @@ const maxSymbolCachePIDs = 512
// Resolve looks up the symbol name for a given PID and virtual address.
func (sr *SymbolResolver) Resolve(pid uint32, addr uint64) string {
sr.mu.RLock()
- st, ok := sr.cache[pid]
+ st := sr.cache[pid]
+ if st != nil {
+ if name := st.lookup(addr); name != "" {
+ sr.mu.RUnlock()
+ return demangleName(name)
+ }
+ if st.covers(addr) {
+ sr.mu.RUnlock()
+ return ""
+ }
+ }
sr.mu.RUnlock()
+ entries, mapped, ok := sr.loadSymbolsForAddress(pid, addr)
if !ok {
- st = sr.loadSymbols(pid)
- sr.mu.Lock()
+ return ""
+ }
+
+ sr.mu.Lock()
+ st = sr.cache[pid]
+ if st == nil {
if len(sr.cache) >= maxSymbolCachePIDs {
// Drop an arbitrary entry; process churn is rare relative to launches.
- for k := range sr.cache {
- delete(sr.cache, k)
+ for cachedPID := range sr.cache {
+ delete(sr.cache, cachedPID)
break
}
}
+ st = &symbolTable{}
sr.cache[pid] = st
- sr.mu.Unlock()
}
-
- if st == nil {
- return fmt.Sprintf("0x%x", addr)
+ if !st.covers(addr) {
+ st.entries = append(st.entries, entries...)
+ st.loaded = append(st.loaded, mapped)
+ sort.Slice(st.entries, func(i, j int) bool {
+ return st.entries[i].addr < st.entries[j].addr
+ })
}
-
name := st.lookup(addr)
+ sr.mu.Unlock()
+
if name == "" {
- return fmt.Sprintf("0x%x", addr)
+ return ""
}
-
return demangleName(name)
}
+func (st *symbolTable) covers(addr uint64) bool {
+ for _, r := range st.loaded {
+ if addr >= r.start && addr < r.end {
+ return true
+ }
+ }
+ return false
+}
+
func (st *symbolTable) lookup(addr uint64) string {
if len(st.entries) == 0 {
return ""
@@ -93,89 +134,110 @@ func (st *symbolTable) lookup(addr uint64) string {
if entry.size > 0 && addr >= entry.addr+entry.size {
return ""
}
+ if entry.size == 0 && addr != entry.addr {
+ return ""
+ }
return entry.name
}
-// loadSymbols parses /proc/<pid>/maps to find CUDA-relevant libraries
-// and loads their ELF symbol tables.
-func (sr *SymbolResolver) loadSymbols(pid uint32) *symbolTable {
+// loadSymbolsForAddress finds the executable mapping containing addr and loads
+// symbols only from that ELF image. cudaLaunchKernel's func pointer commonly
+// targets a host stub in the application executable or a user extension, not
+// libcudart itself.
+func (sr *SymbolResolver) loadSymbolsForAddress(pid uint32, addr uint64) ([]symbolEntry, addressRange, bool) {
mapsPath := fmt.Sprintf("/proc/%d/maps", pid)
f, err := os.Open(mapsPath)
if err != nil {
sr.logger.Debug("cannot read process maps", "pid", pid, "error", err)
- return nil
+ return nil, addressRange{}, false
}
defer f.Close()
- st := &symbolTable{}
- seen := make(map[string]bool)
-
scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 16*1024), 256*1024)
for scanner.Scan() {
- line := scanner.Text()
- fields := strings.Fields(line)
- if len(fields) < 6 {
+ mapping, ok := parseProcMapEntry(scanner.Text())
+ if !ok || addr < mapping.start || addr >= mapping.end {
continue
}
-
- path := fields[5]
- if !isCUDARelevant(path) || seen[path] {
- continue
+ mapped := addressRange{start: mapping.start, end: mapping.end}
+ // Non-executable / anonymous mappings are a permanent miss for symbol
+ // resolution — cache the range so we do not re-parse maps every launch.
+ if !strings.Contains(mapping.perms, "x") || mapping.path == "" || mapping.path[0] != '/' {
+ return nil, mapped, true
}
- seen[path] = true
- baseAddr := parseMapBase(fields[0])
// Prefer the file as seen by the target process (other mount namespaces).
- libPath := resolveMappedLib(int(pid), fields[0], path)
+ libPath := resolveMappedLib(int(pid), mapping.addrRange, mapping.path)
if libPath == "" {
- continue
+ // Transient: mount-namespace view or path may appear on a later launch.
+ return nil, addressRange{}, false
}
- symbols := loadELFSymbols(libPath)
- for _, sym := range symbols {
- st.entries = append(st.entries, symbolEntry{
- addr: baseAddr + sym.addr,
- size: sym.size,
- name: sym.name,
- })
+ entries, ok := loadELFSymbols(libPath, mapping.start, mapping.offset)
+ if !ok {
+ // Transient: ELF open / PT_LOAD bias failed; retry on the next resolve.
+ return nil, addressRange{}, false
}
+ // Successful parse (possibly zero symbols for a stripped binary).
+ return entries, mapped, true
}
- sort.Slice(st.entries, func(i, j int) bool {
- return st.entries[i].addr < st.entries[j].addr
- })
-
- return st
+ return nil, addressRange{}, false
}
-func isCUDARelevant(path string) bool {
- if path == "" || path[0] != '/' {
- return false
+func parseProcMapEntry(line string) (procMapEntry, bool) {
+ fields := strings.Fields(line)
+ if len(fields) < 6 {
+ return procMapEntry{}, false
}
- base := strings.ToLower(path)
- return strings.Contains(base, "libcudart") ||
- strings.Contains(base, "libtorch_cuda") ||
- strings.Contains(base, "vllm") ||
- strings.Contains(base, "ggml")
-}
-func parseMapBase(addrRange string) uint64 {
- parts := strings.Split(addrRange, "-")
- if len(parts) < 1 {
- return 0
+ bounds := strings.SplitN(fields[0], "-", 2)
+ if len(bounds) != 2 {
+ return procMapEntry{}, false
+ }
+ start, err := strconv.ParseUint(bounds[0], 16, 64)
+ if err != nil {
+ return procMapEntry{}, false
+ }
+ end, err := strconv.ParseUint(bounds[1], 16, 64)
+ if err != nil || end <= start {
+ return procMapEntry{}, false
}
- v, _ := strconv.ParseUint(parts[0], 16, 64)
- return v
+ offset, err := strconv.ParseUint(fields[2], 16, 64)
+ if err != nil {
+ return procMapEntry{}, false
+ }
+ path := strings.Join(fields[5:], " ")
+ path = strings.TrimSuffix(path, " (deleted)")
+ return procMapEntry{
+ addrRange: fields[0],
+ start: start,
+ end: end,
+ offset: offset,
+ perms: fields[1],
+ path: path,
+ }, true
}
-func loadELFSymbols(path string) []symbolEntry {
+// loadELFSymbols parses function symbols from path. ok is false when the ELF
+// cannot be opened or no PT_LOAD segment matches the mapping (caller must not
+// cache that as a permanent miss). ok is true with a possibly empty slice when
+// the ELF was parsed successfully (e.g. stripped binary with no STT_FUNC).
+func loadELFSymbols(path string, mapStart, mapOffset uint64) ([]symbolEntry, bool) {
f, err := elf.Open(path)
if err != nil {
- return nil
+ return nil, false
}
defer f.Close()
- var entries []symbolEntry
+ loadBias, ok := elfLoadBias(f, mapStart, mapOffset)
+ if !ok {
+ return nil, false
+ }
+
+ entries := make([]symbolEntry, 0)
+ seen := make(map[string]struct{})
// Try .symtab first, then .dynsym
for _, loader := range []func() ([]elf.Symbol, error){f.Symbols, f.DynamicSymbols} {
@@ -190,15 +252,49 @@ func loadELFSymbols(path string) []symbolEntry {
if elf.ST_TYPE(s.Info) != elf.STT_FUNC {
continue
}
+ key := fmt.Sprintf("%x:%s", s.Value, s.Name)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
entries = append(entries, symbolEntry{
- addr: s.Value,
+ addr: loadBias + s.Value,
size: s.Size,
name: s.Name,
})
}
}
- return entries
+ return entries, true
+}
+
+func elfLoadBias(f *elf.File, mapStart, mapOffset uint64) (uint64, bool) {
+ pageSize := uint64(os.Getpagesize())
+ alignDown := func(v uint64) uint64 {
+ return v & ^(pageSize - 1)
+ }
+ alignUp := func(v uint64) uint64 {
+ return (v + pageSize - 1) & ^(pageSize - 1)
+ }
+
+ for _, prog := range f.Progs {
+ if prog.Type != elf.PT_LOAD {
+ continue
+ }
+ segmentOffset := alignDown(prog.Off)
+ segmentEnd := alignUp(prog.Off + prog.Filesz)
+ if mapOffset < segmentOffset || mapOffset >= segmentEnd {
+ continue
+ }
+ segmentVaddr := alignDown(prog.Vaddr)
+ virtualAtMapping := segmentVaddr + (mapOffset - segmentOffset)
+ if mapStart < virtualAtMapping {
+ return 0, false
+ }
+ return mapStart - virtualAtMapping, true
+ }
+
+ return 0, false
}
// demangleName attempts to demangle a C++ mangled name.
diff --git a/opentelemetry-gpu-collector/internal/ebpf/symbols_test.go b/opentelemetry-gpu-collector/internal/ebpf/symbols_test.go
new file mode 100644
index 00000000..f7c9ebbf
--- /dev/null
+++ b/opentelemetry-gpu-collector/internal/ebpf/symbols_test.go
@@ -0,0 +1,155 @@
+//go:build linux && (amd64 || arm64)
+
+package ebpf
+
+import (
+ "debug/elf"
+ "io"
+ "log/slog"
+ "testing"
+)
+
+func TestParseProcMapEntry(t *testing.T) {
+ line := "5d21d95ed000-5d21d95ef000 r-xp 00002000 103:02 289296 /opt/gpu demo (deleted)"
+ got, ok := parseProcMapEntry(line)
+ if !ok {
+ t.Fatal("parseProcMapEntry returned false")
+ }
+ if got.start != 0x5d21d95ed000 || got.end != 0x5d21d95ef000 {
+ t.Fatalf("range = %#x-%#x", got.start, got.end)
+ }
+ if got.offset != 0x2000 {
+ t.Fatalf("offset = %#x, want 0x2000", got.offset)
+ }
+ if got.perms != "r-xp" {
+ t.Fatalf("perms = %q", got.perms)
+ }
+ if got.path != "/opt/gpu demo" {
+ t.Fatalf("path = %q", got.path)
+ }
+}
+
+func TestELFLoadBiasPIEAndExecutable(t *testing.T) {
+ const (
+ mapOffset = 0x2000
+ imageBase = 0x5d21d95eb000
+ )
+
+ pie := &elf.File{Progs: []*elf.Prog{{
+ ProgHeader: elf.ProgHeader{
+ Type: elf.PT_LOAD,
+ Off: mapOffset,
+ Vaddr: mapOffset,
+ Filesz: 0x2000,
+ },
+ }}}
+ bias, ok := elfLoadBias(pie, imageBase+mapOffset, mapOffset)
+ if !ok || bias != imageBase {
+ t.Fatalf("PIE load bias = %#x, %v; want %#x, true", bias, ok, imageBase)
+ }
+
+ executable := &elf.File{Progs: []*elf.Prog{{
+ ProgHeader: elf.ProgHeader{
+ Type: elf.PT_LOAD,
+ Off: mapOffset,
+ Vaddr: 0x402000,
+ Filesz: 0x2000,
+ },
+ }}}
+ bias, ok = elfLoadBias(executable, 0x402000, mapOffset)
+ if !ok || bias != 0 {
+ t.Fatalf("ET_EXEC-style load bias = %#x, %v; want 0, true", bias, ok)
+ }
+}
+
+func TestELFLoadBiasRejectsInvalidMappings(t *testing.T) {
+ file := &elf.File{Progs: []*elf.Prog{{
+ ProgHeader: elf.ProgHeader{
+ Type: elf.PT_LOAD,
+ Off: 0x2000,
+ Vaddr: 0x402000,
+ Filesz: 0x2000,
+ },
+ }}}
+
+ tests := []struct {
+ name string
+ mapStart uint64
+ mapOffset uint64
+ }{
+ {
+ name: "offset outside load segments",
+ mapStart: 0x405000,
+ mapOffset: 0x5000,
+ },
+ {
+ name: "mapping starts below segment address",
+ mapStart: 0x401000,
+ mapOffset: 0x2000,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if bias, ok := elfLoadBias(file, tt.mapStart, tt.mapOffset); ok {
+ t.Fatalf("elfLoadBias() = %#x, true; want false", bias)
+ }
+ })
+ }
+}
+
+func TestSymbolTableLookupAndCoveredMiss(t *testing.T) {
+ st := &symbolTable{
+ entries: []symbolEntry{
+ {addr: 0x1100, size: 0x20, name: "sized"},
+ {addr: 0x1200, size: 0, name: "exact-only"},
+ },
+ loaded: []addressRange{{start: 0x1000, end: 0x2000}},
+ }
+
+ if got := st.lookup(0x1110); got != "sized" {
+ t.Fatalf("lookup sized = %q", got)
+ }
+ if got := st.lookup(0x1200); got != "exact-only" {
+ t.Fatalf("lookup exact = %q", got)
+ }
+ if got := st.lookup(0x1201); got != "" {
+ t.Fatalf("zero-size symbol matched a range: %q", got)
+ }
+ if !st.covers(0x1800) || st.covers(0x2000) {
+ t.Fatal("address range coverage is incorrect")
+ }
+}
+
+func TestResolverMissDoesNotReturnASLRAddress(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ resolver := NewSymbolResolver(logger)
+ if got := resolver.Resolve(^uint32(0), 0xdeadbeef); got != "" {
+ t.Fatalf("Resolve miss = %q, want empty stable fallback", got)
+ }
+}
+
+func TestLoadELFSymbolsMissingFileIsTransient(t *testing.T) {
+ entries, ok := loadELFSymbols("/nonexistent/openlit-cuda-stub", 0x1000, 0)
+ if ok || entries != nil {
+ t.Fatalf("loadELFSymbols(missing) = %v, %v; want nil, false", entries, ok)
+ }
+}
+
+func TestResolveDoesNotCacheTransientMapMiss(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ resolver := NewSymbolResolver(logger)
+ pid := ^uint32(0)
+ addr := uint64(0xdeadbeef)
+
+ if got := resolver.Resolve(pid, addr); got != "" {
+ t.Fatalf("Resolve() = %q, want empty", got)
+ }
+
+ resolver.mu.RLock()
+ st := resolver.cache[pid]
+ resolver.mu.RUnlock()
+ if st != nil && st.covers(addr) {
+ t.Fatal("transient /proc maps miss must not mark the address range as covered")
+ }
+}
diff --git a/opentelemetry-gpu-collector/internal/ebpf/tracer.go b/opentelemetry-gpu-collector/internal/ebpf/tracer.go
index abb393d7..7980b216 100644
--- a/opentelemetry-gpu-collector/internal/ebpf/tracer.go
+++ b/opentelemetry-gpu-collector/internal/ebpf/tracer.go
@@ -75,6 +75,7 @@ func NewTracer(logger *slog.Logger, handler EventHandler) (*Tracer, error) {
stop: make(chan struct{}),
uprobes: map[string]*ebpf.Program{
"cudaLaunchKernel": objs.HandleCudaLaunch,
+ "__cudaGetKernel": objs.HandleCudaGetKernelEnter,
"cudaMalloc": objs.HandleCudaMallocEnter,
"cudaFree": objs.HandleCudaFree,
"cudaMemcpyAsync": objs.HandleCudaMemcpyAsync,
@@ -82,6 +83,7 @@ func NewTracer(logger *slog.Logger, handler EventHandler) (*Tracer, error) {
"cudaSetDevice": objs.HandleCudaSetDeviceEnter,
},
uretprobes: map[string]*ebpf.Program{
+ "__cudaGetKernel": objs.HandleCudaGetKernelExit,
"cudaMalloc": objs.HandleCudaMalloc,
"cudaMemcpy": objs.HandleCudaMemcpy,
"cudaStreamSynchronize": objs.HandleCudaStreamSync,
diff --git a/opentelemetry-gpu-collector/internal/ebpf/tracer_bpf_test.go b/opentelemetry-gpu-collector/internal/ebpf/tracer_bpf_test.go
new file mode 100644
index 00000000..25bd6ef0
--- /dev/null
+++ b/opentelemetry-gpu-collector/internal/ebpf/tracer_bpf_test.go
@@ -0,0 +1,30 @@
+//go:build linux && (amd64 || arm64)
+
+package ebpf
+
+import "testing"
+
+func TestGeneratedSpecIncludesCUDA13KernelHandleProbes(t *testing.T) {
+ spec, err := loadGpuevent()
+ if err != nil {
+ t.Fatalf("loadGpuevent() error = %v", err)
+ }
+
+ for _, name := range []string{
+ "handle_cuda_get_kernel_enter",
+ "handle_cuda_get_kernel_exit",
+ } {
+ if spec.Programs[name] == nil {
+ t.Errorf("generated BPF spec is missing program %q", name)
+ }
+ }
+
+ for _, name := range []string{
+ "cuda_get_kernel_cache",
+ "cuda_kernel_handles",
+ } {
+ if spec.Maps[name] == nil {
+ t.Errorf("generated BPF spec is missing map %q", name)
+ }
+ }
+}
diff --git a/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go b/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go
index df67a007..4078e004 100644
--- a/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go
+++ b/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go
@@ -275,6 +275,16 @@ func (em *EBPFMetrics) activityAttrs(pid, tid uint32, extra ...attribute.KeyValu
return metric.WithAttributes(attrs...)
}
+func kernelMetricName(e *gpuebpf.KernelLaunchEvent) string {
+ if e.KernelName != "" {
+ return e.KernelName
+ }
+ // Keep metric cardinality stable when an executable is stripped or
+ // otherwise unavailable. Raw ASLR addresses create new series after every
+ // process restart.
+ return "unknown"
+}
+
// HandleEvent processes a single CUDA event and records it as OTel metrics.
func (em *EBPFMetrics) HandleEvent(ev gpuebpf.CUDAEvent) {
ctx := context.Background()
@@ -286,10 +296,7 @@ func (em *EBPFMetrics) HandleEvent(ev gpuebpf.CUDAEvent) {
}
case *gpuebpf.KernelLaunchEvent:
- kernelName := e.KernelName
- if kernelName == "" {
- kernelName = fmt.Sprintf("0x%x", e.KernelAddr)
- }
+ kernelName := kernelMetricName(e)
attrs := em.activityAttrs(e.PID, e.TID, attribute.String("cuda.kernel.name", kernelName))
em.kernelLaunchCalls.Add(ctx, 1, attrs)
diff --git a/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go b/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go
index 569291f6..1da6171a 100644
--- a/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go
+++ b/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go
@@ -3,9 +3,21 @@ package export
import (
"testing"
+ gpuebpf "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/ebpf"
"github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"
)
+func TestKernelMetricNameUsesStableFallback(t *testing.T) {
+ event := &gpuebpf.KernelLaunchEvent{KernelAddr: 0x7fff12345678}
+ if got := kernelMetricName(event); got != "unknown" {
+ t.Fatalf("kernelMetricName() = %q, want unknown", got)
+ }
+ event.KernelName = "vector_add"
+ if got := kernelMetricName(event); got != "vector_add" {
+ t.Fatalf("kernelMetricName() = %q, want vector_add", got)
+ }
+}
+
func TestCUDADeviceTrackerSoleGPU(t *testing.T) {
devs := []gpu.Device{
&mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-a", Index: 0, Name: "A100"}},