Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: Updates to collector (#1411)
Aman Agarwalf47bd11e7898
diff --git a/.cursor/rules/coding-agents-convention.mdc b/.cursor/rules/coding-agents-convention.mdcindex 15349181..2d0b5063 100644--- a/.cursor/rules/coding-agents-convention.mdc+++ b/.cursor/rules/coding-agents-convention.mdc@@ -199,6 +199,7 @@ Cursor sends payloads to our hook subcommand; we own the mapping. For full refer| `text` (assistant response) | `gen_ai.output.messages` | full mode only || `text` (thought) | `coding_agent.llm.thought.text` | full mode only || `duration_ms` | `coding_agent.llm.thought.duration_ms` | for thoughts |+| `input_tokens` / `output_tokens` / `cache_*_tokens` (on `stop`) | `gen_ai.usage.*_tokens` | Real counters only; stamp on `stop` + drain to session root at `sessionEnd`. Never invent from text. Cursor does not send USD — leave cost unset. || `tool_name` | `gen_ai.tool.name` | || `tool_use_id` | `gen_ai.tool.call.id` | || `tool_input` | `gen_ai.tool.call.arguments` | full mode only |diff --git a/.github/workflows/otel-gpu-collector-release.yml b/.github/workflows/otel-gpu-collector-release.ymlindex 45225312..0f31aba2 100644--- a/.github/workflows/otel-gpu-collector-release.yml+++ b/.github/workflows/otel-gpu-collector-release.yml@@ -119,8 +119,8 @@ jobs:GOOS: ${{ matrix.goos }}GOARCH: ${{ matrix.goarch }}GOARM: ${{ matrix.goarm }}- # Linux ships NVML via go-nvml (cgo+dlopen); darwin/windows have no- # NVML at all and fall through to the stub, so CGO is unnecessary.+ # Linux ships NVML via go-nvml (cgo+dlopen). Windows uses cgo-free+ # LoadLibrary(nvml.dll) + DXGI/PDH. Darwin has no GPU backends.CGO_ENABLED: ${{ matrix.goos == 'linux' && '1' || '0' }}CC: ${{ (matrix.goos == 'linux' && matrix.goarch == 'arm64') && 'aarch64-linux-gnu-gcc' || '' }}run: |diff --git a/.github/workflows/otel-gpu-collector-tests.yml b/.github/workflows/otel-gpu-collector-tests.ymlindex 928cb406..c14e75c1 100644--- a/.github/workflows/otel-gpu-collector-tests.yml+++ b/.github/workflows/otel-gpu-collector-tests.yml@@ -93,7 +93,7 @@ jobs:GOARCH: arm64run: go build ./...- - name: Cross-compile windows/amd64 (stub fallback)+ - name: Cross-compile windows/amd64 (GPU via NVML/DXGI/PDH, CGO=0)working-directory: opentelemetry-gpu-collectorenv:CGO_ENABLED: "0"diff --git a/README.md b/README.mdindex 7f6fc4a0..72f61ce6 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ This project proudly follows and maintains the [Semantic Conventions](https://gi-- 📈 **Analytics Dashboard**: Monitor your AI application's health and performance with detailed dashboards that track metrics, costs, and user interactions, providing a clear view of overall efficiency.+- 📈 **Analytics Dashboard**: Monitor your AI application's and GPUs health and performance with detailed dashboards that track metrics, costs, and user interactions, providing a clear view of overall efficiency.- 🔌 **OpenTelemetry-native Observability SDKs**: Vendor-neutral SDKs (Python, TypeScript, Go) to send traces and metrics to your existing observability tools.diff --git a/cli/internal/coding/hook/cursor/handle.go b/cli/internal/coding/hook/cursor/handle.goindex 9bb8377a..64207402 100644--- a/cli/internal/coding/hook/cursor/handle.go+++ b/cli/internal/coding/hook/cursor/handle.go@@ -12,7 +12,6 @@ import ("github.com/openlit/openlit/cli/internal/coding/detect""github.com/openlit/openlit/cli/internal/coding/git""github.com/openlit/openlit/cli/internal/coding/normalize"- "github.com/openlit/openlit/cli/internal/coding/pricing""github.com/openlit/openlit/cli/internal/coding/sessionstate""github.com/openlit/openlit/sdk/go/semconv")@@ -47,10 +46,10 @@ type cursorPayload struct {DurationMs int64 `json:"duration_ms"`// Token usage — Cursor ships these on afterAgentResponse and stop.- // Absent on older builds and- // on beforeSubmitPrompt; when present they are authoritative and- // supersede the char-heuristic estimate. Pointers so we can tell- // "missing" from an explicit zero.+ // Absent on older builds and on beforeSubmitPrompt. We only trust+ // these fields on `stop` (full-turn counts including tools ++ // cache); we never invent tokens from text length. Pointers so we+ // can tell "missing" from an explicit zero.InputTokens *int64 `json:"input_tokens"`OutputTokens *int64 `json:"output_tokens"`CacheReadTokens *int64 `json:"cache_read_tokens"`@@ -201,6 +200,11 @@ func handle(ctx context.Context, in normalize.Input) error {s.Duration = time.Duration(p.DurationMs) * time.Millisecond}s.Outcome = outcomeFromReason(p.Reason, p.FinalStatus)+ // Drain real token totals accumulated on each `stop`. Cursor+ // never sends USD; leave CostUSD at 0 rather than inventing+ // list-price estimates. Set on the session here so every+ // capture mode (not only minimal) gets session-root tokens.+ applyAccumulatedTokens(&s, sessionID, in.Vendor)return in.Emit.EmitSession(s)case "stop":@@ -208,8 +212,9 @@ func handle(ctx context.Context, in normalize.Input) error {// emit a small event so dashboards can count loop turns; the// authoritative session end span comes from sessionEnd.//- // When Cursor attaches token counts on stop, stamp them on the event so the UI can show- // authoritative usage even if afterAgentResponse omitted them.+ // Token accounting: stop is the only place we stamp usage.+ // Cursor's counts here cover the full turn (tools + cache).+ // We never invent tokens or USD — Cursor does not send cost.attrs := map[string]any{"coding_agent.client": in.Vendor,"coding_agent.hook.event": event,@@ -228,9 +233,8 @@ func handle(ctx context.Context, in normalize.Input) error {}if p.Model != "" {attrs["gen_ai.request.model"] = p.Model- rate := pricing.Lookup(p.Model)- attrs["gen_ai.usage.cost"] = rate.Cost(inTok, outTok, cacheRead, cacheWrite)}+ accumulateStopTokens(sessionID, in.Vendor, inTok, outTok)}return in.Emit.EmitEvent(normalize.EventEmission{SessionID: sessionID,@@ -246,16 +250,8 @@ func handle(ctx context.Context, in normalize.Input) error {return in.Emit.EmitLLMTurn(buildResponseTurn(in, p, sessionID))case "afterAgentThought":- // Reasoning / thinking text is real model output: the provider- // charged tokens for it just like for the final assistant- // message. Estimate output tokens from the thought text and- // run them through the same pricing path as a normal response- // turn — without this the session cost rolled-up at the UI- // level under-counts thinking-heavy models (Claude- // extended-thinking, GPT-5 reasoning) by a wide margin.- thoughtTokens := pricing.EstimateTokens(p.Text)- thoughtRate := pricing.Lookup(p.Model)- thoughtCost := thoughtRate.Cost(0, thoughtTokens, 0, 0)+ // Thought text only — Cursor does not expose separate thought+ // token counters. Full-turn usage lands on `stop`.return in.Emit.EmitLLMTurn(normalize.LLMTurn{SessionID: sessionID,ConversationID: p.ConversationID,@@ -265,9 +261,6 @@ func handle(ctx context.Context, in normalize.Input) error {EndedAt: time.Now(),ThoughtText: p.Text,ThoughtMs: p.DurationMs,- OutputTokens: thoughtTokens,- TotalTokens: thoughtTokens,- CostUSD: thoughtCost,})case "preToolUse":@@ -541,14 +534,8 @@ func buildPromptTurn(in normalize.Input, p cursorPayload, sessionID string) norm}}now := time.Now()- // beforeSubmitPrompt does not carry token counts (we observes- // the same). Stamp a char-heuristic input estimate so the prompt- // half isn't empty; cost for this half is the input-only estimate- // and acts as the fallback when afterAgentResponse/stop never- // report real usage.- inputTokens := pricing.EstimateTokens(p.Prompt)- rate := pricing.Lookup(p.Model)- cost := rate.Cost(inputTokens, 0, 0, 0)+ // Content / identity only. beforeSubmitPrompt never carries token+ // counts; we do not invent them. Full-turn usage lands on `stop`.return normalize.LLMTurn{SessionID: sessionID,ConversationID: p.ConversationID,@@ -560,39 +547,15 @@ func buildPromptTurn(in normalize.Input, p cursorPayload, sessionID string) normPrompt: p.Prompt,AttachmentPaths: paths,UserEmail: p.UserEmail,- InputTokens: inputTokens,- TotalTokens: inputTokens,- CostUSD: cost,}}func buildResponseTurn(in normalize.Input, p cursorPayload, sessionID string) normalize.LLMTurn {now := time.Now()- rate := pricing.Lookup(p.Model)-- // Prefer Cursor's real token fields when present (same source). These cover the full generation — input,- // output, and cache — so we bill the complete turn here.- //- // Cost note: the matching beforeSubmitPrompt span already billed- // an input-only estimate. To avoid double-counting input, we bill- // output + cache from the real counters here and still stamp the- // real input token count for accurate token dashboards. When real- // counters are absent we fall back to the char-heuristic on the- // response text (output only), same as before.- var (- inputTokens, outputTokens int64- cacheRead, cacheWrite int64- cost float64- )- if inTok, outTok, cr, cw, ok := realTokenUsage(p); ok {- inputTokens, outputTokens = inTok, outTok- cacheRead, cacheWrite = cr, cw- cost = rate.Cost(0, outputTokens, cacheRead, cacheWrite)- } else {- outputTokens = pricing.EstimateTokens(p.Text)- cost = rate.Cost(0, outputTokens, 0, 0)- }-+ // Content only. Even when Cursor attaches token fields here we+ // leave them off this span — stop's counts cover the full turn+ // (tools + cache) and stamping both would double-count under the+ // UI's sum(child gen_ai.usage.*) rollup.return normalize.LLMTurn{SessionID: sessionID,ConversationID: p.ConversationID,@@ -603,12 +566,6 @@ func buildResponseTurn(in normalize.Input, p cursorPayload, sessionID string) noEndedAt: now,Response: p.Text,AssistantMessageOnly: true,- InputTokens: inputTokens,- OutputTokens: outputTokens,- TotalTokens: inputTokens + outputTokens,- CacheReadTokens: cacheRead,- CacheCreationTokens: cacheWrite,- CostUSD: cost,}}@@ -634,6 +591,47 @@ func realTokenUsage(p cursorPayload) (input, output, cacheRead, cacheWrite int64return input, output, cacheRead, cacheWrite, true}+// accumulateStopTokens adds one stop's real token counts into the+// sessionstate cache so sessionEnd can stamp session-root totals.+func accumulateStopTokens(sessionID, vendor string, inTok, outTok int64) {+ if sessionID == "" {+ return+ }+ st := sessionstate.Load(sessionID, vendor)+ if st == nil {+ st = &sessionstate.State{}+ }+ if inTok > 0 {+ st.InputTokens += inTok+ }+ if outTok > 0 {+ st.OutputTokens += outTok+ }+ sessionstate.Save(sessionID, vendor, st)+}++// applyAccumulatedTokens copies stop-accumulated token totals onto the+// session-root struct. CostUSD stays 0 — Cursor never sends USD and we+// refuse to invent list-price estimates.+func applyAccumulatedTokens(s *normalize.Session, sessionID, vendor string) {+ if s == nil || sessionID == "" {+ return+ }+ st := sessionstate.Load(sessionID, vendor)+ if st == nil {+ return+ }+ if s.InputTokens == 0 && st.InputTokens > 0 {+ s.InputTokens = st.InputTokens+ }+ if s.OutputTokens == 0 && st.OutputTokens > 0 {+ s.OutputTokens = st.OutputTokens+ }+ if s.TotalTokens == 0 {+ s.TotalTokens = s.InputTokens + s.OutputTokens+ }+}+func buildToolCallSuccess(in normalize.Input, p cursorPayload, sessionID string) normalize.ToolCall {startedAt := time.Now().Add(-time.Duration(p.Duration) * time.Millisecond)return normalize.ToolCall{diff --git a/cli/internal/coding/hook/cursor/handle_test.go b/cli/internal/coding/hook/cursor/handle_test.goindex 4c16f623..1c90c32c 100644--- a/cli/internal/coding/hook/cursor/handle_test.go+++ b/cli/internal/coding/hook/cursor/handle_test.go@@ -212,18 +212,16 @@ func TestCursorSessionIDPrefersConversation(t *testing.T) {}}-// TestCursorAfterAgentResponsePrefersRealTokens:-// when Cursor ships input_tokens / output_tokens / cache_* on-// afterAgentResponse, those counters are authoritative and must beat-// the char-heuristic estimate derived from `text`.-func TestCursorAfterAgentResponsePrefersRealTokens(t *testing.T) {+// TestCursorAfterAgentResponseOmitsTokensEvenWhenPresent:+// afterAgentResponse is content-only. Token fields on the payload are+// ignored here so we do not double-count against stop's full-turn+// counters under the UI sum(child) rollup.+func TestCursorAfterAgentResponseOmitsTokensEvenWhenPresent(t *testing.T) {withIsolatedCache(t)em := &recordingEmitter{}in := inputBuilder(t, em)- // Long text would estimate to thousands of tokens; real counters- // below are tiny so a regression to the heuristic is obvious.longText := strings.Repeat("word ", 2000)if err := handle(context.Background(), in("afterAgentResponse", map[string]any{"hook_event_name": "afterAgentResponse",@@ -242,35 +240,31 @@ func TestCursorAfterAgentResponsePrefersRealTokens(t *testing.T) {t.Fatalf("expected one llm turn; got %d", len(em.llmTurns))}got := em.llmTurns[0]- if got.InputTokens != 1200 {- t.Errorf("InputTokens = %d, want 1200 (real payload)", got.InputTokens)+ if got.Response == "" {+ t.Errorf("expected response text to be preserved")}- if got.OutputTokens != 340 {- t.Errorf("OutputTokens = %d, want 340 (real payload)", got.OutputTokens)+ if got.InputTokens != 0 || got.OutputTokens != 0 || got.TotalTokens != 0 {+ t.Errorf("tokens on response turn = in=%d out=%d total=%d; want all 0 (stop owns usage)",+ got.InputTokens, got.OutputTokens, got.TotalTokens)}- if got.CacheReadTokens != 800 {- t.Errorf("CacheReadTokens = %d, want 800", got.CacheReadTokens)- }- if got.CacheCreationTokens != 100 {- t.Errorf("CacheCreationTokens = %d, want 100", got.CacheCreationTokens)- }- if got.TotalTokens != 1540 {- t.Errorf("TotalTokens = %d, want 1540", got.TotalTokens)+ if got.CacheReadTokens != 0 || got.CacheCreationTokens != 0 {+ t.Errorf("cache tokens on response turn = read=%d write=%d; want 0",+ got.CacheReadTokens, got.CacheCreationTokens)}- if got.CostUSD <= 0 {- t.Errorf("CostUSD = %v, want > 0 from real token pricing", got.CostUSD)+ if got.CostUSD != 0 {+ t.Errorf("CostUSD = %v, want 0 (Cursor never sends USD)", got.CostUSD)}}-// TestCursorAfterAgentResponseFallsBackToEstimate covers older Cursor-// builds that omit token fields — we still estimate from response text.-func TestCursorAfterAgentResponseFallsBackToEstimate(t *testing.T) {+// TestCursorAfterAgentResponseNoEstimate covers older Cursor builds+// that omit token fields — we must not invent tokens from text.+func TestCursorAfterAgentResponseNoEstimate(t *testing.T) {withIsolatedCache(t)em := &recordingEmitter{}in := inputBuilder(t, em)- text := "hello world from cursor" // short, deterministic estimate+ text := "hello world from cursor"if err := handle(context.Background(), in("afterAgentResponse", map[string]any{"hook_event_name": "afterAgentResponse","conversation_id": "convo-2",@@ -283,19 +277,17 @@ func TestCursorAfterAgentResponseFallsBackToEstimate(t *testing.T) {t.Fatalf("expected one llm turn; got %d", len(em.llmTurns))}got := em.llmTurns[0]- if got.InputTokens != 0 {- t.Errorf("InputTokens = %d, want 0 when no real counters", got.InputTokens)+ if got.InputTokens != 0 || got.OutputTokens != 0 || got.TotalTokens != 0 {+ t.Errorf("tokens = in=%d out=%d total=%d; want all 0 when usage absent",+ got.InputTokens, got.OutputTokens, got.TotalTokens)}- if got.OutputTokens <= 0 {- t.Errorf("OutputTokens = %d, want estimated > 0", got.OutputTokens)- }- if got.CacheReadTokens != 0 || got.CacheCreationTokens != 0 {- t.Errorf("cache tokens should be 0 on estimate path; got read=%d write=%d",- got.CacheReadTokens, got.CacheCreationTokens)+ if got.CostUSD != 0 {+ t.Errorf("CostUSD = %v, want 0", got.CostUSD)}}-// TestCursorStopStampsRealTokenAttrs ensures stop surfaces token counters on the loop event.+// TestCursorStopStampsRealTokenAttrs ensures stop surfaces token+// counters on the loop event and never invents USD cost.func TestCursorStopStampsRealTokenAttrs(t *testing.T) {withIsolatedCache(t)@@ -328,8 +320,67 @@ func TestCursorStopStampsRealTokenAttrs(t *testing.T) {if attrs["gen_ai.usage.cache.read_input_tokens"] != int64(200) {t.Errorf("cache read attr = %v, want 200", attrs["gen_ai.usage.cache.read_input_tokens"])}- if attrs["gen_ai.usage.cost"] == nil {- t.Errorf("expected gen_ai.usage.cost on stop when model + tokens present")+ if attrs["gen_ai.usage.cache.creation_input_tokens"] != int64(50) {+ t.Errorf("cache write attr = %v, want 50", attrs["gen_ai.usage.cache.creation_input_tokens"])+ }+ if _, ok := attrs["gen_ai.usage.cost"]; ok {+ t.Errorf("gen_ai.usage.cost must be absent on Cursor stop; got %v", attrs["gen_ai.usage.cost"])+ }+}++// TestCursorStopAccumulatesIntoSessionEnd verifies multiple stop+// turns sum into session-root token totals with CostUSD left at 0.+func TestCursorStopAccumulatesIntoSessionEnd(t *testing.T) {+ withIsolatedCache(t)++ em := &recordingEmitter{}+ in := inputBuilder(t, em)++ stops := []struct {+ in, out int64+ }{+ {500, 100},+ {800, 200},+ }+ for i, s := range stops {+ if err := handle(context.Background(), in("stop", map[string]any{+ "hook_event_name": "stop",+ "conversation_id": "convo-accum",+ "status": "completed",+ "loop_count": i + 1,+ "model": "composer-2.5",+ "input_tokens": s.in,+ "output_tokens": s.out,+ })); err != nil {+ t.Fatalf("stop %d: %v", i, err)+ }+ }++ if err := handle(context.Background(), in("sessionEnd", map[string]any{+ "hook_event_name": "sessionEnd",+ "conversation_id": "convo-accum",+ "reason": "completed",+ "final_status": "completed",+ "duration_ms": int64(12000),+ "model": "composer-2.5",+ })); err != nil {+ t.Fatalf("sessionEnd: %v", err)+ }+ if len(em.sessions) != 1 {+ t.Fatalf("expected one session emission; got %d", len(em.sessions))+ }+ got := em.sessions[0]+ if got.InputTokens != 1300 {+ t.Errorf("InputTokens = %d, want 1300 (500+800)", got.InputTokens)+ }+ if got.OutputTokens != 300 {+ t.Errorf("OutputTokens = %d, want 300 (100+200)", got.OutputTokens)+ }+ if got.TotalTokens != 1600 {+ t.Errorf("TotalTokens = %d, want 1600", got.TotalTokens)+ }+ if got.CostUSD != 0 {+ t.Errorf("CostUSD = %v, want 0", got.CostUSD)}}diff --git a/docs/latest/gpu-collector/configuration.mdx b/docs/latest/gpu-collector/configuration.mdxindex 8e5744f1..4a41c1c1 100644--- a/docs/latest/gpu-collector/configuration.mdx+++ b/docs/latest/gpu-collector/configuration.mdx@@ -14,9 +14,100 @@ The collector is configured entirely via environment variables. All variables fo| `OTEL_EXPORTER_OTLP_HEADERS` | | Auth headers in `key=val,key2=val2` format || `OTEL_EXPORTER_OTLP_PROTOCOL` | `grpc` | `grpc` or `http/protobuf` || `OTEL_SERVICE_NAME` | `default` | Service name attached to all metrics |-| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment=default` | Resource attributes in `key=val,key=val` format |-| `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric polling interval in **milliseconds** |-| `OTEL_GPU_EBPF_ENABLED` | `false` | Enable eBPF CUDA kernel tracing (Linux only) |+| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment=default` | Resource attributes (`key=val,...`). Prefer setting `host.name`, `k8s.*`, `cloud.provider`, `host.type`, `cloud.region` here — overrides auto-detect. Org tags such as `team` or `datacenter` are not auto-detected; set them here. |+| `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric polling interval in **milliseconds**. For self-hosted LLM hosts, `15000` is recommended |+| `OTEL_GPU_EBPF_ENABLED` | `true` on Linux; `false` elsewhere | eBPF CUDA activity tracing + stream-sync occupancy (Linux/NVIDIA only). Discovers `libcudart` via FS + `/proc` maps (fleet-friendly with host PID). Soft-fails without caps; set `false` to disable |+| `OPENLIT_HOST_METRICS` | `true` | Collect system + collector-process host metrics. Set `false` for a GPU-only light footprint |+| `OTEL_GPU_PROCESS_CMDLINE` | `true` | Export truncated `process.command_line` on GPU process metrics |+| `OTEL_GPU_PROCESS_CMDLINE_MAX_LEN` | `512` | Max characters for `process.command_line` |+| `OTEL_GPU_ALLOCATED_UTIL_THRESHOLD` | `0.05` | Util threshold (0–1) used with process memory for `hw.gpu.allocated` |+| `OTEL_GPU_INTERCONNECT_ENABLED` | `true` | Export NVLink/XGMI interconnect throughput when available |+| `K8S_NODE_NAME` | | Kubernetes node name via downward API (`spec.nodeName`). Also accepts `OTEL_RESOURCE_ATTRIBUTES_NODE_NAME` (Operator) or legacy `NODE_NAME` |+| `K8S_CLUSTER_NAME` | | Explicit cluster name when cloud auto-detect fails (on-prem). Alias: `OPENLIT_K8S_CLUSTER_NAME`. Only applied in Kubernetes |+| `OPENLIT_K8S_NODE_LOOKUP` | `true` | When `false`, skip `GET /api/v1/nodes/$K8S_NODE_NAME` for instance-type / provider discovery |+| `OPENLIT_K8S_POD_RESOURCES` | `true` in K8s | Use kubelet PodResources socket; joins GPU UUID → `k8s.pod.name` / namespace / container |+| `OPENLIT_K8S_POD_LOOKUP` | `true` in K8s when `K8S_NODE_NAME` is set | List pods on this node via the Kubernetes API (needs `list` on pods) for UID/container-id joins |+| `POD_RESOURCES_SOCKET` | OS default | Override kubelet PodResources socket / named pipe path |+| `OPENLIT_CLOUD_DETECT` | `true` | When `false`, skip AWS/GCP/Azure IMDS probes (recommended on bare metal to avoid link-local timeouts) |++## Host, Kubernetes, and cloud identity++Resource attributes follow [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/resource/) for host, K8s, and cloud:++| Attribute | When set |+|---|---|+| `host.name` | Always (from `OTEL_RESOURCE_ATTRIBUTES`, or `K8S_NODE_NAME` → GCE hostname in K8s → OS hostname) |+| `k8s.node.name` | When a node env is set (`K8S_NODE_NAME` / Operator / legacy `NODE_NAME`) |+| `k8s.cluster.name` | In Kubernetes only: `K8S_CLUSTER_NAME` / `OTEL_RESOURCE_ATTRIBUTES` → GKE / AKS / EKS metadata |+| `cloud.provider` | Auto: K8s `Node.spec.providerID` → AWS/GCP/Azure IMDS → DMI vendor hint |+| `cloud.platform` | e.g. `aws_eks`, `gcp_kubernetes_engine`, `aws_ec2`, `azure_aks` |+| `host.type` | Instance type (e.g. `g4dn.xlarge`, `a2-highgpu-1g`, `Standard_NC6s_v3`) from node labels or IMDS |+| `cloud.region` / `cloud.availability_zone` | Topology labels or IMDS |+| `cloud.account.id` | AWS account / GCP project / Azure subscription when available |+| `host.id` | Cloud instance ID from providerID or IMDS |+| `openlit.host.type.source` | Which tier filled `host.type`: `k8s_label`, `imds`, or `dmi` |++**Discovery order** (later tiers only fill missing fields; never blocks startup; never emits `"unknown"`):++1. Explicit `OTEL_RESOURCE_ATTRIBUTES` (wins via SDK `WithFromEnv`)+2. Kubernetes Node `GET` (needs `get` on `nodes` + `K8S_NODE_NAME`) — OpenCost-style labels / providerID+3. Parallel AWS / GCP / Azure instance metadata (short timeout)+4. DMI `sys_vendor` hint for provider only++Use `cloud.provider` + `host.type` + `cloud.region` as join keys for future UI cost attribution. The collector does **not** compute prices.++Kubernetes is detected via `KUBERNETES_SERVICE_HOST`. On GKE, AKS, and EKS the cluster name is read from the instance metadata service (short timeout; failures are ignored). Self-managed clusters should set `k8s.cluster.name` via `OTEL_RESOURCE_ATTRIBUTES` or `K8S_CLUSTER_NAME`.++### Recommended Kubernetes DaemonSet (OTel-native)++```yaml+env:+ - name: K8S_NODE_NAME+ valueFrom:+ fieldRef:+ fieldPath: spec.nodeName+ - name: OTEL_RESOURCE_ATTRIBUTES+ value: "host.name=$(K8S_NODE_NAME),k8s.node.name=$(K8S_NODE_NAME)"+ - name: OTEL_EXPORTER_OTLP_ENDPOINT+ value: "http://otel-collector:4317"+ # Optional when cloud auto-detect is unavailable (on-prem / self-managed):+ # - name: K8S_CLUSTER_NAME+ # value: my-cluster+ # Or append to OTEL_RESOURCE_ATTRIBUTES:+ # ,k8s.cluster.name=my-cluster,cloud.provider=aws,host.type=g4dn.xlarge,cloud.region=us-east-1+```++If you only set `K8S_NODE_NAME` (without packing it into `OTEL_RESOURCE_ATTRIBUTES`), the collector still maps it to `host.name` and `k8s.node.name` automatically.++For K8s node label / providerID discovery, grant the DaemonSet ServiceAccount:++```yaml+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRole+metadata:+ name: otel-gpu-collector-node-get+rules:+ - apiGroups: [""]+ resources: ["nodes"]+ verbs: ["get"]+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRoleBinding+metadata:+ name: otel-gpu-collector-node-get+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: ClusterRole+ name: otel-gpu-collector-node-get+subjects:+ - kind: ServiceAccount+ name: otel-gpu-collector+ namespace: monitoring+```++<Note>+On EKS, pods without `hostNetwork` may fail IMDSv2 when the node `httpPutResponseHopLimit` is `1`. Prefer K8s node lookup (above), raise the hop limit to `2+`, or run with `hostNetwork: true`. Timeouts are soft-fail and do not stop the collector.+</Note>## Common configurations@@ -46,18 +137,21 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \./opentelemetry-gpu-collector```-### Enable eBPF CUDA tracing+### Disable eBPF CUDA tracing-Requires `CAP_BPF` + `CAP_PERFMON` (or root) and NVIDIA CUDA runtime.+On Linux, eBPF CUDA tracing is **on by default**. It discovers `libcudart` from the filesystem and from `/proc/*/maps` (no CUDA volume mount required when Docker `--pid=host` / Kubernetes `hostPID: true` is set). Soft-fails without `CAP_BPF` + `CAP_PERFMON` (or root). Containers typically also need `--ulimit memlock=-1:-1` so BPF maps can be created. Set `false` to skip:```bash-OTEL_GPU_EBPF_ENABLED=true \+OTEL_GPU_EBPF_ENABLED=false \OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \./opentelemetry-gpu-collector```+eBPF activity/occupancy is **NVIDIA/CUDA only**. AMD and Intel use the same host-PID process attribution for DRM fdinfo metrics; they do not need `libcudart`.+## Notes- `OTEL_METRIC_EXPORT_INTERVAL` is in **milliseconds** per the OTel spec. For a 30-second interval, set `30000`.- `deployment.environment` is extracted from `OTEL_RESOURCE_ATTRIBUTES` and attached as a resource attribute. Any key-value pairs in `OTEL_RESOURCE_ATTRIBUTES` are also forwarded to the OTel SDK resource via `resource.WithFromEnv()`.- If `OTEL_EXPORTER_OTLP_ENDPOINT` is not set, the collector starts but no metrics are exported. Check the logs for a warning.+- Auto-detected `host.name` / `k8s.*` attributes are logged at startup as `resolved resource identity`.diff --git a/docs/latest/gpu-collector/gpus/amd.mdx b/docs/latest/gpu-collector/gpus/amd.mdxindex 5247e9cf..7e561c67 100644--- a/docs/latest/gpu-collector/gpus/amd.mdx+++ b/docs/latest/gpu-collector/gpus/amd.mdx@@ -32,18 +32,22 @@ docker run -d \--name otel-gpu-collector \--device /dev/kfd:/dev/kfd \--device /dev/dri:/dev/dri \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 \ghcr.io/openlit/otel-gpu-collector:latest```+`--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+## Docker Compose```yamlservices:otel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: my-appOTEL_RESOURCE_ATTRIBUTES: deployment.environment=production@@ -71,6 +75,7 @@ spec:labels:app: otel-gpu-collectorspec:+ hostPID: truecontainers:- name: collectorimage: ghcr.io/openlit/otel-gpu-collector:latest@@ -87,12 +92,21 @@ spec:- name: sysmountPath: /sysreadOnly: true+ - name: dri+ mountPath: /dev/drivolumes:- name: syshostPath:path: /sys+ - name: dri+ hostPath:+ path: /dev/dri```+<Note>+Docker `--pid=host` (or Kubernetes `hostPID: true`) and `/dev/dri` are required for per-process GPU attribution via DRM fdinfo.+</Note>+---<CardGroup cols={2}>diff --git a/docs/latest/gpu-collector/gpus/intel.mdx b/docs/latest/gpu-collector/gpus/intel.mdxindex 96ab22e3..467d57b9 100644--- a/docs/latest/gpu-collector/gpus/intel.mdx+++ b/docs/latest/gpu-collector/gpus/intel.mdx@@ -32,18 +32,22 @@ Intel GPU support provides thermal, power, energy, and clock metrics. Utilizatiodocker run -d \--name otel-gpu-collector \--device /dev/dri:/dev/dri \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 \ghcr.io/openlit/otel-gpu-collector:latest```+`--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+## Docker Compose```yamlservices:otel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: my-appOTEL_RESOURCE_ATTRIBUTES: deployment.environment=production@@ -70,6 +74,7 @@ spec:labels:app: otel-gpu-collectorspec:+ hostPID: truecontainers:- name: collectorimage: ghcr.io/openlit/otel-gpu-collector:latest@@ -86,12 +91,21 @@ spec:- name: sysmountPath: /sysreadOnly: true+ - name: dri+ mountPath: /dev/drivolumes:- name: syshostPath:path: /sys+ - name: dri+ hostPath:+ path: /dev/dri```+<Note>+Docker `--pid=host` (or Kubernetes `hostPID: true`) and `/dev/dri` are required for per-process GPU attribution via DRM fdinfo.+</Note>+---<CardGroup cols={2}>diff --git a/docs/latest/gpu-collector/gpus/nvidia.mdx b/docs/latest/gpu-collector/gpus/nvidia.mdxindex 265bb7eb..c67eebb0 100644--- a/docs/latest/gpu-collector/gpus/nvidia.mdx+++ b/docs/latest/gpu-collector/gpus/nvidia.mdx@@ -21,7 +21,7 @@ The collector monitors NVIDIA GPUs via [NVML](https://developer.nvidia.com/nvidi| `hw.gpu.memory.usage` | Used VRAM (bytes) || `hw.gpu.memory.free` | Free VRAM (bytes) || `hw.gpu.temperature` | Die and memory temperature (°C) via `sensor` attribute |-| `hw.gpu.fan_speed` | Fan speed (RPM) |+| `hw.gpu.fan_speed` | Fan speed (RPM) — not emitted; NVML reports percent only || `hw.gpu.power.draw` | Current power draw (W) || `hw.gpu.power.limit` | Power cap (W) || `hw.gpu.energy.consumed` | Cumulative energy (J) |@@ -35,18 +35,22 @@ The collector monitors NVIDIA GPUs via [NVML](https://developer.nvidia.com/nvididocker run -d \--name otel-gpu-collector \--gpus all \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 \ghcr.io/openlit/otel-gpu-collector:latest```+`--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+## Docker Compose```yamlservices:otel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: my-appOTEL_RESOURCE_ATTRIBUTES: deployment.environment=production@@ -80,6 +84,7 @@ spec:labels:app: otel-gpu-collectorspec:+ hostPID: truetolerations:- key: nvidia.com/gpuoperator: Exists@@ -102,7 +107,7 @@ spec:```<Note>-The collector does not need privileged mode for NVML - just access to `libnvidia-ml.so`. eBPF tracing requires `CAP_BPF` + `CAP_PERFMON`.+The collector does not need privileged mode for NVML device metrics — just access to `libnvidia-ml.so`. Per-process attribution needs Docker `--pid=host` or Kubernetes `hostPID: true`. eBPF tracing / stream-sync occupancy requires `CAP_BPF` + `CAP_PERFMON` (or privileged) and raised memlock (`--ulimit memlock=-1:-1`).</Note>---diff --git a/docs/latest/gpu-collector/installation.mdx b/docs/latest/gpu-collector/installation.mdxindex 0b4e2eb5..2d8fe5d5 100644--- a/docs/latest/gpu-collector/installation.mdx+++ b/docs/latest/gpu-collector/installation.mdx@@ -12,6 +12,8 @@ The easiest way to run the collector. The image is published to GitHub Containerdocker pull ghcr.io/openlit/otel-gpu-collector:latest```+For per-process GPU attribution (cmdline, PID, zombie/`process.state`, owner), run with host PID namespace access: Docker `--pid=host`, Compose `pid: host`, or Kubernetes `hostPID: true`. Device-level `hw.gpu.*` metrics work without it.+### Tags| Tag | Description |@@ -43,7 +45,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \```<Note>-GPU metrics (NVML, sysfs) and eBPF tracing only work on Linux. On macOS and Windows the binary runs with host and process metrics only.+GPU device and process metrics work on **Linux and Windows** (NVIDIA via NVML; AMD/Intel via sysfs on Linux or DXGI+PDH on Windows). eBPF CUDA tracing and occupancy are **Linux only**. On macOS the binary runs with host and process metrics only.</Note>Verify the SHA256 checksum from the `SHA256SUMS.txt` file in the release:@@ -75,6 +77,100 @@ make build---+## Kubernetes DaemonSet++Run one collector per GPU node. Use the OpenTelemetry-recommended pattern: downward API → `K8S_NODE_NAME` → `OTEL_RESOURCE_ATTRIBUTES` with `host.name` and `k8s.node.name`. On GKE, AKS, and EKS the collector also auto-detects `k8s.cluster.name`, `cloud.provider`, and `host.type` (instance type) from the Kubernetes Node object and/or cloud metadata.++```yaml+apiVersion: v1+kind: ServiceAccount+metadata:+ name: otel-gpu-collector+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRole+metadata:+ name: otel-gpu-collector-node-get+rules:+ - apiGroups: [""]+ resources: ["nodes"]+ verbs: ["get"]+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRoleBinding+metadata:+ name: otel-gpu-collector-node-get+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: ClusterRole+ name: otel-gpu-collector-node-get+subjects:+ - kind: ServiceAccount+ name: otel-gpu-collector+ namespace: default # change to your namespace+---+apiVersion: apps/v1+kind: DaemonSet+metadata:+ name: otel-gpu-collector+spec:+ selector:+ matchLabels:+ app: otel-gpu-collector+ template:+ metadata:+ labels:+ app: otel-gpu-collector+ spec:+ serviceAccountName: otel-gpu-collector+ hostPID: true+ containers:+ - name: otel-gpu-collector+ image: ghcr.io/openlit/otel-gpu-collector:latest+ env:+ - name: K8S_NODE_NAME+ valueFrom:+ fieldRef:+ fieldPath: spec.nodeName+ - name: OTEL_SERVICE_NAME+ value: otel-gpu-collector+ - name: OTEL_RESOURCE_ATTRIBUTES+ value: "host.name=$(K8S_NODE_NAME),k8s.node.name=$(K8S_NODE_NAME)"+ - name: OTEL_EXPORTER_OTLP_ENDPOINT+ value: "http://otel-collector:4317"+ # Optional for on-prem / self-managed clusters:+ # - name: K8S_CLUSTER_NAME+ # value: my-cluster+ # eBPF CUDA tracing is on by default on Linux; set false to disable:+ # - name: OTEL_GPU_EBPF_ENABLED+ # value: "false"+ volumeMounts:+ - name: pod-resources+ mountPath: /var/lib/kubelet/pod-resources+ readOnly: true+ # AMD/Intel DRM:+ # - name: dri+ # mountPath: /dev/dri+ securityContext:+ capabilities:+ add: ["SYS_ADMIN"] # or privileged / CAP_BPF+CAP_PERFMON for eBPF+ volumes:+ - name: pod-resources+ hostPath:+ path: /var/lib/kubelet/pod-resources+ # - name: dri+ # hostPath:+ # path: /dev/dri+```++<Note>+`hostPID: true` (same role as Docker `--pid=host`) is required for per-process and per-pod GPU attribution so the collector can see workload PIDs under `/proc`. Without it, device-level `hw.gpu.*` metrics still work. The `nodes/get` ClusterRole enables OpenCost-style `host.type` / `cloud.provider` discovery from node labels without relying on IMDS (helpful when EKS hop limit is 1).+</Note>++See [Configuration](/latest/gpu-collector/configuration) for identity env vars and detection order.++---+## Upgrade### Docker@@ -120,11 +216,13 @@ rm /usr/local/bin/opentelemetry-gpu-collector- Check logs: `docker logs otel-gpu-collector` for `"discovered GPU"` entries</Accordion><Accordion title="eBPF tracing not working">- - Confirm `OTEL_GPU_EBPF_ENABLED=true` is set+ - On Linux it is enabled by default; confirm it is not disabled via `OTEL_GPU_EBPF_ENABLED=false`- Check kernel version: `uname -r` (requires 5.8+)- The process needs `CAP_BPF` and `CAP_PERFMON`, or run as root- - For Docker: add `--privileged` or `--cap-add CAP_BPF --cap-add CAP_PERFMON`- - Verify `libcudart.so` is present on the host: `ldconfig -p | grep cudart`+ - For Docker: `--cap-add CAP_BPF --cap-add CAP_PERFMON`, `--pid=host`, and `--ulimit memlock=-1:-1` (BPF maps need locked memory; no CUDA mount needed)+ - For Kubernetes: `hostPID: true` plus BPF capabilities (or `SYS_ADMIN`); raise memlock if map create returns EPERM+ - If no CUDA process is running yet, the collector rescans `/proc` every 30s+ - Verify a workload has loaded cudart: `grep libcudart /proc/*/maps 2>/dev/null | head`</Accordion><Accordion title="Connection refused / no data reaching backend">- Verify `OTEL_EXPORTER_OTLP_ENDPOINT` is reachable from the container: `curl http://<endpoint>/health`diff --git a/docs/latest/gpu-collector/metrics.mdx b/docs/latest/gpu-collector/metrics.mdxindex 1648961a..f48e5a50 100644--- a/docs/latest/gpu-collector/metrics.mdx+++ b/docs/latest/gpu-collector/metrics.mdx@@ -8,27 +8,41 @@ All metric names and attributes follow the [OpenTelemetry semantic conventions f## GPU Hardware Telemetry-Collected for each detected GPU on Linux. Availability depends on vendor and GPU model.+Collected for each detected GPU on **Linux and Windows**. Availability depends on vendor, OS, and GPU model.### Metrics| Metric | Type | Unit | Description | NVIDIA | AMD | Intel ||---|---|---|---|:---:|:---:|:---:|-| `hw.gpu.utilization` | Gauge | `1` | GPU compute/encoder/decoder utilization (0.0–1.0) | Yes | Yes | - |+| `hw.gpu.utilization` | Gauge | `1` | GPU compute/encoder/decoder utilization (0.0–1.0) | Yes | Yes | Yes* || `hw.gpu.memory.utilization` | Gauge | `1` | Memory controller utilization (0.0–1.0) | Yes | Yes | - |-| `hw.gpu.memory.limit` | UpDownCounter | `By` | Total GPU memory | Yes | Yes | - |-| `hw.gpu.memory.usage` | UpDownCounter | `By` | Used GPU memory | Yes | Yes | - |-| `hw.gpu.memory.free` | UpDownCounter | `By` | Free GPU memory | Yes | Yes | - |+| `hw.gpu.memory.limit` | UpDownCounter | `By` | Total GPU memory | Yes | Yes | Yes* |+| `hw.gpu.memory.usage` | UpDownCounter | `By` | Used GPU memory | Yes | Yes | Yes* |+| `hw.gpu.memory.free` | UpDownCounter | `By` | Free GPU memory | Yes | Yes | Yes* || `hw.gpu.temperature` | Gauge | `Cel` | Die or memory temperature | Yes | Yes | Yes |-| `hw.gpu.fan_speed` | Gauge | `{rpm}` | Fan speed | Yes | Yes | Yes* |+| `hw.gpu.fan_speed` | Gauge | `{rpm}` | Fan speed | -† | Yes | Yes* || `hw.gpu.power.draw` | Gauge | `W` | Current power draw | Yes | Yes | Yes || `hw.gpu.power.limit` | Gauge | `W` | Power limit/cap | Yes | Yes | Yes || `hw.gpu.energy.consumed` | Counter | `J` | Cumulative energy consumed | Yes | Yes | Yes || `hw.gpu.clock.graphics` | Gauge | `MHz` | Graphics/SM clock frequency | Yes | Yes | Yes* || `hw.gpu.clock.memory` | Gauge | `MHz` | Memory clock frequency | Yes | Yes | - |-| `hw.errors` | Counter | `{error}` | ECC and PCIe error count | Yes | - | - |+| `hw.gpu.up` | Gauge | `1` | `1` when the device was successfully scraped | Yes | Yes | Yes |+| `hw.gpu.allocated` | Gauge | `1` | `1` when process memory or util ≥ threshold | Yes | Yes | Yes |+| `hw.gpu.idle` | Gauge | `1` | Idle ratio (`1 - utilization`) when util known | Yes | Yes | Yes* |+| `hw.gpu.pcie.throughput` | Gauge | `By/s` | PCIe RX/TX throughput | Yes | Yes¶ | Soft‡ |+| `hw.gpu.interconnect.throughput` | Gauge | `By/s` | NVLink / XGMI aggregate throughput | Yes§ | Yes¶ | - |+| `hw.gpu.throttled` | Gauge | `1` | `1` when thermal/power throttle is active | Yes | Yes¶ | Yes* |+| `hw.errors` | Counter | `{error}` | ECC, PCIe, XID, and RAS error counts | Yes | Yes (RAS + PCIe replay¶) | - |-\* Intel fan speed requires Linux kernel 6.16+. Intel graphics clock requires the Xe driver.+\* Intel device util/VRAM/power/throttle/media use Level Zero Sysman when available (Linux/Windows); otherwise DRM/hwmon/PDH subset. Encoder/decoder util comes from media engine groups or Windows PDH VideoEncode/VideoDecode.++† NVIDIA NVML exposes fan speed as a percentage, not RPM, so `hw.gpu.fan_speed` is not emitted for NVIDIA.++‡ Soft-omitted when the vendor library/driver path does not expose the counter. Core util/memory/power still collect without those libraries. Windows AMD has no PCIe/XGMI throughput API (ADL).++§ NVLink on Linux and Windows NVIDIA when the GPU exposes enabled NVLink links (rates after the second sample).++¶ AMD Linux via `libamd_smi` (`amdsmi_get_gpu_pci_throughput`, `amdsmi_get_link_metrics`, `amdsmi_get_violation_status`) when present; soft-omitted on VMs/consumer cards without those counters. AMD media util (`MmActivity`) is exported as `hw.gpu.task=encoder` when the driver only exposes a combined VCN counter (decoder stays unset).### Attributes@@ -48,8 +62,13 @@ Additional per-metric attributes:|---|---|---|| `hw.gpu.utilization` | `hw.gpu.task` | `general`, `encoder`, `decoder` || `hw.gpu.temperature` | `sensor` | `die`, `memory` |-| `hw.errors` | `error.type` | `corrected`, `uncorrected`, `pcie_replay` |+| `hw.gpu.pcie.throughput` | `network.io.direction` | `receive`, `transmit` |+| `hw.gpu.interconnect.throughput` | `network.io.direction` | `receive`, `transmit` |+| `hw.gpu.interconnect.throughput` | `hw.gpu.interconnect.type` | `nvlink`, `xgmi`, `other` |+| `hw.gpu.throttled` | `hw.gpu.throttle_reasons` | comma-separated reason labels |+| `hw.errors` | `error.type` | `corrected`, `uncorrected`, `pcie_replay`, `xid`, `ras_corrected`, `ras_uncorrected` || `hw.errors` | `hw.type` | `gpu` |+| MIG devices | `gpu.mig.enabled`, `gpu.mig.device_id`, `gpu.parent.uuid`, `gpu.mig.instance_id`, `gpu.mig.profile` | Linux NVIDIA only (MIG is not available on Windows) |---@@ -93,14 +112,80 @@ Self-monitoring of the collector process. Follows the [OTel semantic conventions----## eBPF CUDA Metrics (opt-in)+## Per-process / per-pod GPU attribution-Enable with `OTEL_GPU_EBPF_ENABLED=true`. Requires Linux, `CAP_BPF` + `CAP_PERFMON` (or root), and an NVIDIA CUDA runtime (`libcudart.so`). Attaches uprobes to `cudaLaunchKernel`, `cudaMalloc`, and `cudaMemcpy`.+Collected on each scrape from NVML (NVIDIA) or DRM fdinfo (AMD/Intel). Requires host PID visibility — Docker `--pid=host` / Compose `pid: host`, or Kubernetes `hostPID: true` — so `/proc` shows workload PIDs. Without it, device-level `hw.gpu.*` metrics still work, but per-process cmdline, state (including zombies), and GPU process metrics will be missing or incomplete.++These attributes support views like zombie-process triage: filter `process.state == "zombie"` and show `process.command_line`, `process.pid`, `process.owner`, and `process.uptime` (age).++| Metric | Type | Unit | Description | NVIDIA | AMD | Intel |+|---|---|---|---|:---:|:---:|:---:|+| `process.gpu.memory.usage` | UpDownCounter | `By` | GPU memory used by a process on a device | Yes | Yes | Yes |+| `process.gpu.utilization` | Gauge | `1` | Per-process GPU utilization (0.0–1.0) | Yes | Yes | Yes |+| `process.uptime` | Gauge | `s` | Process uptime for GPU-attributed PIDs | Yes | Yes | Yes |++### Attributes++| Attribute | Description |+|---|---|+| `process.pid` | Host process ID |+| `process.executable.name` | Short name from `/proc/<pid>/comm` (or Windows image basename) |+| `process.command_line` | Truncated command line (see `OTEL_GPU_PROCESS_CMDLINE`) |+| `process.state` | `running`, `sleeping`, `zombie`, `stopped`, `dead`, `unknown` |+| `process.owner` / `process.owner.userid` | Username and UID/SID |+| `process.workload.kind` | `llm_inference`, `llm_training`, or `other` |+| `process.workload.framework` | `vllm`, `ollama`, `llama.cpp`, `sglang`, `tgi`, `triton`, `ray`, `pytorch`, `unknown` |+| `hw.id`, `hw.name`, `hw.vendor`, `gpu.index`, `gpu.pci_address` | Same device attrs as `hw.gpu.*` |+| `hw.gpu.task` | On utilization only: `general`, `encoder`, `decoder` |+| `k8s.pod.uid` | From cgroup path when present |+| `k8s.pod.name`, `k8s.namespace.name`, `k8s.container.name` | Via kubelet PodResources (GPU device join) and/or pod API lookup |+| `container.id` | Runtime container ID when resolvable |++<Note>+`process.start_time` is not exported as a metric attribute (cardinality). Use `process.uptime` for lifetime. On MIG devices, NVML often provides **memory only** (no per-process SM util). Process util may not sum to device util (time-slicing / sampling windows differ). Use `process.state == zombie` to find defunct processes still holding GPU contexts.+</Note>++---++## eBPF CUDA Metrics++Enable with `OTEL_GPU_EBPF_ENABLED` (on by default on Linux). Soft-fails without caps. Discovers `libcudart.so*` from common install paths **and** from `/proc/*/maps` (with Docker `--pid=host` / Kubernetes `hostPID: true`), so fleet DaemonSets do not need a CUDA toolkit mount. Attaches uprobes/uretprobes for launches, alloc/free, memcpy, stream/device sync, and `cudaSetDevice`. AMD/Intel do not use this path — their per-process metrics come from DRM fdinfo.++### Activity metrics| Metric | Type | Unit | Description | Attributes ||---|---|---|---|---|-| `gpu.kernel.launch.calls` | Counter | `{call}` | CUDA kernel launch count | `cuda.kernel.name` |-| `gpu.kernel.grid.size` | Histogram | `{thread}` | Total threads in grid per launch | `cuda.kernel.name` |-| `gpu.kernel.block.size` | Histogram | `{thread}` | Threads per block per launch | `cuda.kernel.name` |-| `gpu.memory.allocations` | Counter | `By` | Bytes allocated via cudaMalloc | |-| `gpu.memory.copies` | Histogram | `By` | Bytes per cudaMemcpy call | `cuda.memcpy.kind`={HostToHost,HostToDevice,DeviceToHost,DeviceToDevice} |+| `gpu.kernel.launch.calls` | Counter | `{call}` | CUDA kernel launch count | `process.pid`, `process.executable.name`, `cuda.kernel.name`, `hw.id` / `gpu.index` when known |+| `gpu.kernel.grid.size` | Histogram | `{thread}` | Total threads in grid per launch | same |+| `gpu.kernel.block.size` | Histogram | `{thread}` | Threads per block per launch | same |+| `gpu.kernel.shared_memory` | Histogram | `By` | Dynamic shared memory per launch (`cudaLaunchKernel` sharedMem) | same |+| `gpu.memory.allocations` | Counter | `By` | Bytes allocated via cudaMalloc | `process.pid`, `process.executable.name`, `hw.id` / `gpu.index` when known |+| `gpu.memory.copies` | Histogram | `By` | Bytes per cudaMemcpyAsync | `process.pid`, `cuda.memcpy.kind`, `hw.id` / `gpu.index` when known |++`hw.id` is set after `cudaSetDevice` for that thread, or immediately on single-GPU hosts. On multi-GPU hosts before `cudaSetDevice`, join via `process.pid` as before. **Linux/NVIDIA (CUDA) only** — same eBPF path for Kubernetes and non-Kubernetes when host PID is visible. AMD/Intel use device/process metrics via DRM fdinfo, not these kernel series.++### Stream-sync occupancy (Datadog-parity model)++These are **CPU-side model estimates**, not hardware SM occupancy (warps resident / max warps). Spans run from kernel launch to sync API return; thread-seconds are clamped to NVML CUDA core count and normalized so multi-process totals do not exceed device capacity.++| Metric | Type | Unit | Description |+|---|---|---|---|+| `process.gpu.core.usage` | Gauge | `{cores}` | Normalized avg CUDA cores from launch→sync thread-seconds |+| `process.gpu.sm_active` | Gauge | `1` | Fraction of interval with any launch→sync span for the process |+| `gpu.core.limit` | Gauge | `{cores}` | NVML CUDA core count |+| `gpu.sm_active` | Gauge | `1` | Device-wide union of launch→sync spans |++**Prefer** NVML `process.gpu.utilization` for sampled SM%. Use occupancy metrics when correlating with Datadog Agent stream-sync behavior or when NVML process util is unavailable.++**Known limits:** no GPU completion signal (late sync inflates usage); CUDA Graphs / unhooked launch paths under-report; sync `cudaMemcpy` and default-stream sync are treated as device-wide (legacy default-stream semantics).++---++## Capability matrix++| Feature | NVIDIA | AMD | Intel |+|---|:---:|:---:|:---:|+| Device `hw.gpu.*` | Yes | Yes | Partial |+| `process.gpu.memory.usage` / `utilization` | NVML | DRM fdinfo | DRM fdinfo |+| Pod UID on process metrics | cgroup | cgroup | cgroup |+| eBPF activity + occupancy | Yes (default on Linux) | — | — |diff --git a/docs/latest/gpu-collector/overview.mdx b/docs/latest/gpu-collector/overview.mdxindex 760c7b4f..664950ba 100644--- a/docs/latest/gpu-collector/overview.mdx+++ b/docs/latest/gpu-collector/overview.mdx@@ -10,7 +10,7 @@ It is fully configured via standard OpenTelemetry environment variables and foll## Goals* **OpenTelemetry-native** - uses standard `OTEL_*` env vars, exports via OTLP gRPC or HTTP to any OTel-compatible backend-* **Cross-vendor GPU support** - NVIDIA (NVML), AMD (sysfs/hwmon), and Intel (i915/Xe sysfs) from a single binary+* **Cross-vendor GPU support** - NVIDIA (NVML), AMD, and Intel on Linux and Windows from a single binary* **OTel semantic conventions** - `hw.gpu.*` metric names, `hw.id` / `hw.name` / `hw.vendor` attributes per spec* **Zero dependencies** - no DCGM, no Python, no CUDA toolkit needed at runtime for hardware metrics* **Resilient** - continues exporting host metrics even when no GPUs are present; retries GPU discovery every 30s@@ -19,23 +19,23 @@ It is fully configured via standard OpenTelemetry environment variables and foll<CardGroup cols={3}><Card title="GPU Hardware Telemetry" icon="microchip">- Utilization, memory, temperature, power draw, energy, clock speeds, ECC errors, PCIe errors - for NVIDIA, AMD, and Intel GPUs+ Utilization, memory, temperature, power, energy, clocks, PCIe/interconnect throughput, throttle, ECC/XID/RAS — NVIDIA, AMD, and Intel on Linux and Windows</Card>- <Card title="Host System Metrics" icon="server">- CPU utilization, memory usage, disk I/O, filesystem usage, and network I/O - on Linux, macOS, and Windows+ <Card title="Process + workload attribution" icon="user">+ Per-process VRAM/util plus cmdline, OS state (zombie), owner, uptime, and LLM framework labels (`vllm`, `ollama`, …). Kubernetes pod name/namespace via PodResources</Card><Card title="eBPF CUDA Tracing" icon="code">- Kernel launch counts, grid/block sizes, memory allocations, and memory copies - via uprobes on libcudart.so (opt-in, Linux only)+ Kernel launch counts, grid/block sizes, memory allocations, and memory copies via uprobes on libcudart (on by default on Linux; discovers libs from `/proc` with host PID — no CUDA mount)</Card></CardGroup>## GPU vendor support-| Vendor | Backend | Metrics available |+| Vendor | Linux | Windows ||---|---|---|-| **NVIDIA** | NVML via [go-nvml](https://github.com/NVIDIA/go-nvml) - loads `libnvidia-ml.so` at runtime | Utilization, memory, temperature, power, energy, clocks, ECC errors, PCIe errors, fan speed |-| **AMD** | sysfs + hwmon - zero external dependencies | Utilization, memory, temperature, power, energy, fan speed |-| **Intel** | sysfs + hwmon + DRM (i915/Xe driver) | Temperature, power draw/limit, cumulative energy, graphics clock, fan speed (kernel 6.16+) |+| **NVIDIA** | NVML (+ MIG, NVLink, XID events) | NVML (`nvml.dll`, NVLink) + PDH process attribution (MIG not available on Windows) |+| **AMD** | sysfs/hwmon/DRM + `libamd_smi` (PCIe/XGMI/throttle/RAS when present) | DXGI + PDH (incl. encode/decode) + ADL (util/temp/clocks/fan) |+| **Intel** | DRM/hwmon + Level Zero Sysman (util/VRAM/power/media) | DXGI + PDH (incl. encode/decode) + Level Zero Sysman |## Platform support@@ -43,8 +43,8 @@ It is fully configured via standard OpenTelemetry environment variables and foll|---|:---:|:---:|:---:|| System metrics (CPU, memory, disk, network) | Yes | Yes | Yes || Process metrics (CPU, memory, threads, FDs) | Yes | Yes | Yes |-| GPU metrics (NVIDIA, AMD, Intel) | Yes | - | - |-| eBPF CUDA tracing | Yes | - | - |+| GPU device + process metrics | Yes | - | Yes |+| eBPF CUDA tracing / occupancy | Yes | - | - |## How it works@@ -53,24 +53,20 @@ Host Metrics (all platforms via gopsutil)+-- CPU utilization, memory, disk I/O, filesystem, network+-- Process: self CPU, memory, threads, FDs, Go runtime-GPU Metrics (Linux only)- +-- PCI Bus Scan (/sys/bus/pci/devices/)- | +-- NVIDIA (0x10de) --> NVML backend- | +-- AMD (0x1002) --> sysfs/hwmon backend- | +-- Intel (0x8086) --> sysfs/hwmon + DRM backend- |- +-- [Optional: eBPF CUDA tracing via uprobes on libcudart.so]+GPU Metrics (Linux + Windows)+ +-- Linux: PCI scan → NVML / sysfs / DRM (+ eBPF CUDA, default on)+ +-- Windows: NVML.dll / DXGI + PDH (no eBPF)Export+-- OTel SDK --> OTLP gRPC/HTTP --> your OTel collector / backend```<Steps>- <Step title="Scans PCI bus">- On startup, the collector scans `/sys/bus/pci/devices/` for PCI class codes `0x0300` (VGA), `0x0302` (3D controller), and `0x0380` (display controller), identifying GPU vendor from the PCI vendor ID.+ <Step title="Discovers GPUs">+ On Linux, the collector scans `/sys/bus/pci/devices/` for GPU class codes. On Windows, it loads `nvml.dll` when present and enumerates adapters via DXGI.</Step><Step title="Initialises vendor backend">- Each detected GPU is handed to its vendor-specific backend. NVIDIA loads `libnvidia-ml.so` via NVML. AMD and Intel read directly from kernel sysfs/hwmon - no additional libraries needed.+ Each detected GPU is handed to its vendor-specific backend. NVIDIA uses NVML. Linux AMD/Intel read sysfs/hwmon; Windows AMD/Intel use DXGI memory totals and PDH for utilization and per-process attribution.</Step><Step title="Registers OTel instruments">Observable gauge and counter instruments are registered with the OTel SDK meter. On each collection tick, the SDK calls back into the collector to read fresh values from each GPU.diff --git a/docs/latest/gpu-collector/quickstart.mdx b/docs/latest/gpu-collector/quickstart.mdxindex 635a95d3..bd1cb0e0 100644--- a/docs/latest/gpu-collector/quickstart.mdx+++ b/docs/latest/gpu-collector/quickstart.mdx@@ -40,12 +40,13 @@ In this guide you'll pull the collector Docker image, point it at your OTel backdocker run -d \--name otel-gpu-collector \--gpus all \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \ghcr.io/openlit/otel-gpu-collector:latest```- Requires the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) on the host.+ Requires the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) on the host. `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).</Tab><Tab title="AMD GPU">```bash@@ -53,23 +54,26 @@ In this guide you'll pull the collector Docker image, point it at your OTel back--name otel-gpu-collector \--device /dev/kfd:/dev/kfd \--device /dev/dri:/dev/dri \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \ghcr.io/openlit/otel-gpu-collector:latest```+ `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).</Tab><Tab title="Intel GPU">```bashdocker run -d \--name otel-gpu-collector \--device /dev/dri:/dev/dri \+ --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=production' \-e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \ghcr.io/openlit/otel-gpu-collector:latest```- Requires Linux kernel 5.10+ with the i915 or Xe driver.+ Requires Linux kernel 5.10+ with the i915 or Xe driver. `--pid=host` is required for per-process GPU attribution.</Tab><Tab title="Host metrics only">```bash@@ -115,6 +119,7 @@ Add the collector as a service alongside your existing stack:services:otel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: my-appOTEL_RESOURCE_ATTRIBUTES: deployment.environment=production@@ -131,6 +136,8 @@ services:restart: always```+`pid: host` (Docker `--pid=host`) is required so the collector can see host workload PIDs under `/proc` for per-process GPU metrics, cmdline, and zombie detection.+---<CardGroup cols={2}>diff --git a/docs/latest/sdk/integrations/amd-gpu.mdx b/docs/latest/sdk/integrations/amd-gpu.mdxindex 37f76f42..6fa5f57a 100644--- a/docs/latest/sdk/integrations/amd-gpu.mdx+++ b/docs/latest/sdk/integrations/amd-gpu.mdx@@ -49,7 +49,7 @@ OpenLIT uses OpenTelemetry to help you monitor AMD GPUs. This includes trackingHere's a quick example showing how to run the container with the required environment variables:```sh- docker run --gpus all \+ docker run --gpus all --pid=host \-e OTEL_SERVICE_NAME='chatbot' \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=staging' \-e OTEL_EXPORTER_OTLP_ENDPOINT="YOUR_OTEL_ENDPOINT" \@@ -57,6 +57,8 @@ OpenLIT uses OpenTelemetry to help you monitor AMD GPUs. This includes trackingghcr.io/openlit/otel-gpu-collector:latest```+ `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+For more advanced configurations of the collector, visit the [OTel GPU Collector repository](https://github.com/openlit/openlit/tree/main/opentelemetry-gpu-collector/).**Note:** If you've deployed **OpenLIT** using [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml), make sure to use the host's IP address or add OTel GPU Collector to the [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml):@@ -67,6 +69,7 @@ OpenLIT uses OpenTelemetry to help you monitor AMD GPUs. This includes tracking```yamlotel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: 'chatbot'OTEL_RESOURCE_ATTRIBUTES: 'deployment.environment=staging'diff --git a/docs/latest/sdk/integrations/intel-gpu.mdx b/docs/latest/sdk/integrations/intel-gpu.mdxindex 5c0519c3..2f50c134 100644--- a/docs/latest/sdk/integrations/intel-gpu.mdx+++ b/docs/latest/sdk/integrations/intel-gpu.mdx@@ -66,6 +66,7 @@ Intel GPU support requires Linux with the **i915** or **Xe** kernel driver (kern```shdocker run \--device /dev/dri:/dev/dri \+ --pid=host \-e OTEL_SERVICE_NAME='my-app' \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=staging' \-e OTEL_EXPORTER_OTLP_ENDPOINT="YOUR_OTEL_ENDPOINT" \@@ -73,6 +74,8 @@ Intel GPU support requires Linux with the **i915** or **Xe** kernel driver (kernghcr.io/openlit/otel-gpu-collector:latest```+ `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+For more advanced configurations of the collector, visit the [OTel GPU Collector repository](https://github.com/openlit/openlit/tree/main/opentelemetry-gpu-collector/).**Note:** If you've deployed **OpenLIT** using [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml), make sure to use the host's IP address or add OTel GPU Collector to the [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml):@@ -83,6 +86,7 @@ Intel GPU support requires Linux with the **i915** or **Xe** kernel driver (kern```yamlotel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: 'my-app'OTEL_RESOURCE_ATTRIBUTES: 'deployment.environment=staging'diff --git a/docs/latest/sdk/integrations/nvidia-gpu.mdx b/docs/latest/sdk/integrations/nvidia-gpu.mdxindex 0af44ff0..064082c6 100644--- a/docs/latest/sdk/integrations/nvidia-gpu.mdx+++ b/docs/latest/sdk/integrations/nvidia-gpu.mdx@@ -49,7 +49,7 @@ OpenLIT uses OpenTelemetry to help you monitor NVIDIA GPUs. This includes trackiHere's a quick example showing how to run the container with the required environment variables:```sh- docker run --gpus all \+ docker run --gpus all --pid=host \-e OTEL_SERVICE_NAME='chatbot' \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=staging' \-e OTEL_EXPORTER_OTLP_ENDPOINT="YOUR_OTEL_ENDPOINT" \@@ -57,6 +57,8 @@ OpenLIT uses OpenTelemetry to help you monitor NVIDIA GPUs. This includes trackighcr.io/openlit/otel-gpu-collector:latest```+ `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+For more advanced configurations of the collector, visit the [OTel GPU Collector repository](https://github.com/openlit/openlit/tree/main/opentelemetry-gpu-collector/).**Note:** If you've deployed **OpenLIT** using [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml), make sure to use the host's IP address or add OTel GPU Collector to the [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml):@@ -67,6 +69,7 @@ OpenLIT uses OpenTelemetry to help you monitor NVIDIA GPUs. This includes tracki```yamlotel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: 'chatbot'OTEL_RESOURCE_ATTRIBUTES: 'deployment.environment=staging'diff --git a/docs/snippets/quickstart-gpu.mdx b/docs/snippets/quickstart-gpu.mdxindex 9c12f2c3..ed8da588 100644--- a/docs/snippets/quickstart-gpu.mdx+++ b/docs/snippets/quickstart-gpu.mdx@@ -235,13 +235,15 @@Here's a quick example showing how to run the container with the required environment variables:```sh- docker run --gpus all \+ docker run --gpus all --pid=host \-e OTEL_SERVICE_NAME='chatbot' \-e OTEL_RESOURCE_ATTRIBUTES='deployment.environment=staging' \-e OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:4318" \ghcr.io/openlit/otel-gpu-collector:latest```+ `--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie state).+For more advanced configurations of the collector, visit the [OTel GPU Collector repository](https://github.com/openlit/openlit/tree/main/opentelemetry-gpu-collector/).**Note:** If you've deployed **OpenLIT** using [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml), make sure to use the host's IP address or add OTel GPU Collector to the [Docker Compose](https://github.com/openlit/openlit/blob/main/docker-compose.yml):@@ -252,6 +254,7 @@```yamlotel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: 'chatbot'OTEL_RESOURCE_ATTRIBUTES: 'deployment.environment=staging'diff --git a/opentelemetry-gpu-collector/README.md b/opentelemetry-gpu-collector/README.mdindex c1ae366f..3c567501 100644--- a/opentelemetry-gpu-collector/README.md+++ b/opentelemetry-gpu-collector/README.md@@ -16,7 +16,7 @@ OpenTelemetry GPU Collector</h1></div>-A high-performance host and GPU metrics collector written in Go. Exports host-level system metrics (CPU, memory, disk, network), process metrics, DCGM-style GPU hardware telemetry, and optional eBPF-based CUDA kernel tracing — all via OpenTelemetry (OTLP).+A high-performance host and GPU metrics collector written in Go. Exports host-level system metrics (CPU, memory, disk, network), process metrics, DCGM-style GPU hardware telemetry, and eBPF-based CUDA kernel tracing (on by default on Linux) — all via OpenTelemetry (OTLP).Metric names and attributes follow the [OpenTelemetry semantic conventions for hardware](https://opentelemetry.io/docs/specs/semconv/hardware/gpu/) and [system metrics](https://opentelemetry.io/docs/specs/semconv/system/).@@ -26,8 +26,14 @@ Metric names and attributes follow the [OpenTelemetry semantic conventions for h- **OTel semantic conventions** — `hw.gpu.*` metric names, `hw.id` / `hw.name` / `hw.vendor` attributes- **Host metrics** — CPU utilization, memory, disk I/O, filesystem, network I/O (Linux, macOS, Windows)- **Process metrics** — self-process CPU, memory, threads, file descriptors, Go runtime stats-- **Cross-vendor GPU support** — NVIDIA (via NVML), AMD (via sysfs/hwmon), Intel (via sysfs/hwmon + DRM) on Linux-- **eBPF CUDA tracing** (opt-in) — kernel launch counts, grid/block sizes, memory allocations, memory copies+- **Cross-vendor GPU support** — NVIDIA (NVML), AMD, Intel on **Linux and Windows** (Windows: NVML / DXGI+PDH+ADL / Level Zero)+- **Fleet signals** — `hw.gpu.up`, `hw.gpu.allocated`, `hw.gpu.idle` for available vs active device aggregations+- **LLM process attribution** — cmdline, OS state (incl. zombie), owner, uptime, framework classification (`vllm`, `ollama`, …)+- **Kubernetes enrichment** — kubelet PodResources GPU→pod join (+ auto pod API when `K8S_NODE_NAME` is set)+- **PCIe / interconnect / health** — PCIe/NVLink/XGMI/throttle/XID/RAS when the driver exposes them (soft-omitted otherwise)+- **MIG devices** — NVIDIA MIG instances as first-class devices (**Linux only**; MIG is not available on Windows)+- **Encoder/decoder util** — NVIDIA NVENC/NVDEC; AMD/Intel via media engines or Windows PDH (AMD combined VCN → encoder only)+- **eBPF CUDA tracing** (on by default on Linux) — kernel launch counts, grid/block sizes, memory allocations, memory copies; soft-fails without caps/CUDA- **Lightweight** — single static binary, no Python dependencies- **Resilient** — stays alive on systems without GPUs, retries discovery every 30s@@ -37,12 +43,13 @@ Metric names and attributes follow the [OpenTelemetry semantic conventions for h|---|:---:|:---:|:---:|| System metrics (CPU, memory, disk, network) | Yes | Yes | Yes || Process metrics (CPU, memory, threads, FDs) | Yes | Yes | Yes |-| GPU metrics — NVIDIA (NVML) | Yes | — | — |-| GPU metrics — AMD (sysfs/hwmon) | Yes | — | — |-| GPU metrics — Intel (sysfs/hwmon) | Yes | — | — |-| eBPF CUDA tracing | Yes | — | — |+| GPU metrics — NVIDIA (NVML) | Yes | — | Yes |+| GPU metrics — AMD | Yes (sysfs) | — | Yes (DXGI+PDH) |+| GPU metrics — Intel | Yes (sysfs) | — | Yes (DXGI+PDH) |+| Per-process GPU memory / util | Yes | — | Yes (PDH) |+| eBPF CUDA tracing / occupancy | Yes | — | — |-On macOS/Windows the collector runs with host and process metrics only. GPU discovery is skipped gracefully. On Linux without GPUs, the collector retries discovery every 30 seconds while still exporting host metrics.+On macOS the collector runs with host and process metrics only (no discrete GPU APIs). On Windows and Linux, GPU discovery retries every 30 seconds when no devices are found while still exporting host metrics. eBPF CUDA tracing and stream-sync occupancy remain Linux-only.## Architecture@@ -51,13 +58,16 @@ Host Metrics (all platforms via gopsutil)+-- CPU utilization, memory, disk I/O, filesystem, network+-- Process: self CPU, memory, threads, FDs, Go runtime-GPU Metrics (Linux only)- +-- PCI Bus Scan (/sys/bus/pci/devices/)- | +-- NVIDIA (0x10de) --> NVML backend (go-nvml / libnvidia-ml.so)- | +-- AMD (0x1002) --> sysfs/hwmon backend (zero dependencies)- | +-- Intel (0x8086) --> sysfs/hwmon + DRM backend+GPU Metrics (Linux + Windows)+ +-- Linux: PCI Bus Scan (/sys/bus/pci/devices/)+ | +-- NVIDIA (0x10de) --> NVML (go-nvml / libnvidia-ml.so)+ | +-- AMD (0x1002) --> sysfs/hwmon+ | +-- Intel (0x8086) --> sysfs/hwmon + DRM+ | +-- [Optional: eBPF CUDA tracing via uprobes on libcudart.so]|- +-- [Optional: eBPF CUDA tracing via uprobes on libcudart.so]+ +-- Windows: NVML (nvml.dll) + DXGI enum + PDH GPU Engine/Process Memory+ +-- NVIDIA --> nvml.dll device metrics; PDH process attribution+ +-- AMD/Intel --> DXGI memory + PDH util/process (no eBPF)Export+-- OTel SDK --> OTLP gRPC/HTTP --> your OTel collector / backend@@ -68,27 +78,32 @@ Export### Prerequisites- An OpenTelemetry-compatible backend (e.g., OpenLIT, Grafana, Datadog)-- For GPU metrics: Linux with NVIDIA/AMD/Intel GPU drivers installed-- For eBPF tracing: Linux kernel 5.8+ with `CAP_BPF` + `CAP_PERFMON` (or root)+- For GPU metrics: Linux or Windows with NVIDIA/AMD/Intel GPU drivers installed+ - Windows NVIDIA: `nvml.dll` (shipped with the driver)+ - Windows AMD/Intel: DXGI + Performance Counters (PDH); thermals/power may be limited vs Linux sysfs+- For eBPF tracing: Linux kernel 5.8+ with `CAP_BPF` + `CAP_PERFMON` (or root); Docker also needs `--ulimit memlock=-1:-1`### Docker```shdocker pull ghcr.io/openlit/otel-gpu-collector:latest-docker run --gpus all \+docker run --gpus all --pid=host \-e OTEL_SERVICE_NAME=my-app \-e OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production" \-e OTEL_EXPORTER_OTLP_ENDPOINT="http://otel-collector:4317" \ghcr.io/openlit/otel-gpu-collector:latest```+`--pid=host` is required for per-process GPU attribution (cmdline, PID, zombie/`process.state`, owner). Device-level `hw.gpu.*` metrics still work without it.+### Docker Compose```yamlservices:otel-gpu-collector:image: ghcr.io/openlit/otel-gpu-collector:latest+ pid: hostenvironment:OTEL_SERVICE_NAME: my-appOTEL_RESOURCE_ATTRIBUTES: "deployment.environment=production"@@ -137,15 +152,21 @@ All configuration uses standard OpenTelemetry environment variables.| `OTEL_EXPORTER_OTLP_HEADERS` | | Auth headers (`key=val,key2=val2`) || `OTEL_EXPORTER_OTLP_PROTOCOL` | `grpc` | `grpc` or `http/protobuf` || `OTEL_SERVICE_NAME` | `default` | Service name attached to all metrics |-| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment=default` | Resource attributes (`deployment.environment=prod,team=ml`) |+| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment=default` | Prefer `host.name`, `k8s.*`, `cloud.provider`, `host.type`, `cloud.region` here; overrides auto identity || `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric polling interval in **milliseconds** |-| `OTEL_GPU_EBPF_ENABLED` | `false` | Enable eBPF CUDA kernel tracing (Linux only) |+| `OTEL_GPU_EBPF_ENABLED` | `true` on Linux; `false` elsewhere | eBPF CUDA kernel tracing (Linux only). Soft-fails without caps/CUDA; set `false` to disable |+| `K8S_NODE_NAME` | | Downward API node name → also accepts Operator `OTEL_RESOURCE_ATTRIBUTES_NODE_NAME` or legacy `NODE_NAME` |+| `K8S_CLUSTER_NAME` | | Explicit cluster name (K8s only; on-prem when cloud detect fails) |+| `OPENLIT_K8S_NODE_LOOKUP` | `true` | Set `false` to skip Node API lookup for instance type / provider |+| `OPENLIT_CLOUD_DETECT` | `true` | Set `false` to skip AWS/GCP/Azure IMDS probes (avoids link-local timeouts on bare metal) |`deployment.environment` is read from `OTEL_RESOURCE_ATTRIBUTES` and defaults to `default` if not set.+The collector auto-attaches `host.name`, and when running in Kubernetes (`KUBERNETES_SERVICE_HOST` set) also `k8s.node.name` / `k8s.cluster.name`. It also discovers `cloud.provider`, `host.type` (instance type), and `cloud.region` via Node labels/`providerID` and/or AWS/GCP/Azure IMDS (join keys for future cost UIs — no pricing in the collector). Recommended DaemonSet: `K8S_NODE_NAME` + resource attrs, plus ClusterRole `get` on `nodes`.+## Metrics-### GPU Hardware Telemetry (Linux only)+### GPU Hardware Telemetry (Linux + Windows)Follows the [OTel semantic conventions for hardware metrics](https://opentelemetry.io/docs/specs/semconv/hardware/gpu/).@@ -157,7 +178,7 @@ Follows the [OTel semantic conventions for hardware metrics](https://opentelemet| `hw.gpu.memory.usage` | UpDownCounter | By | Used GPU memory | Yes | Yes | — || `hw.gpu.memory.free` | UpDownCounter | By | Free GPU memory | Yes | Yes | — || `hw.gpu.temperature` | Gauge | Cel | Temperature via `sensor=die\|memory` | Yes | Yes | Yes |-| `hw.gpu.fan_speed` | Gauge | {rpm} | Fan speed | Yes | Yes | Yes* |+| `hw.gpu.fan_speed` | Gauge | {rpm} | Fan speed | -† | Yes | Yes* || `hw.gpu.power.draw` | Gauge | W | Current power draw | Yes | Yes | Yes || `hw.gpu.power.limit` | Gauge | W | Power limit/cap | Yes | Yes | Yes || `hw.gpu.energy.consumed` | Counter | J | Cumulative energy consumed | Yes | Yes | Yes |@@ -167,6 +188,8 @@ Follows the [OTel semantic conventions for hardware metrics](https://opentelemet\* Intel support depends on driver (i915/Xe) and kernel version.+† NVIDIA NVML reports fan speed as a percentage, not RPM — `hw.gpu.fan_speed` is omitted for NVIDIA.+**Attributes on all GPU metrics:**| Attribute | Description | Example |@@ -218,38 +241,43 @@ Follows the [OTel semantic conventions for process metrics](https://opentelemetr| `process.runtime.go.goroutines` | Gauge | {goroutine} | Go goroutine count | || `process.runtime.go.mem.heap_alloc` | Gauge | By | Go heap memory allocated | |-### eBPF CUDA Tracing (opt-in, Linux only)+### eBPF CUDA Tracing (on by default on Linux)-Enable with `OTEL_GPU_EBPF_ENABLED=true`. Requires `CAP_BPF` + `CAP_PERFMON` or root, and NVIDIA CUDA runtime (`libcudart.so`).+On by default on Linux. Discovers `libcudart` from install paths and `/proc/*/maps` (use `--pid=host` / `hostPID: true` so containerized/fleet workloads are visible — no CUDA toolkit mount required). Soft-fails without `CAP_BPF` + `CAP_PERFMON` (or root). Docker/K8s: also raise memlock (`--ulimit memlock=-1:-1`). Set `OTEL_GPU_EBPF_ENABLED=false` to disable. AMD/Intel process metrics do not use eBPF.| Metric | Type | Unit | Description | Attributes ||---|---|---|---|---|-| `gpu.kernel.launch.calls` | Counter | {call} | CUDA kernel launch count | `cuda.kernel.name` |-| `gpu.kernel.grid.size` | Histogram | {thread} | Total threads in grid per launch | `cuda.kernel.name` |-| `gpu.kernel.block.size` | Histogram | {thread} | Threads per block per launch | `cuda.kernel.name` |-| `gpu.memory.allocations` | Counter | By | Bytes allocated via cudaMalloc | |+| `gpu.kernel.launch.calls` | Counter | {call} | CUDA kernel launch count | `cuda.kernel.name`, `hw.id` when known |+| `gpu.kernel.grid.size` | Histogram | {thread} | Total threads in grid per launch | `cuda.kernel.name`, `hw.id` when known |+| `gpu.kernel.block.size` | Histogram | {thread} | Threads per block per launch | `cuda.kernel.name`, `hw.id` when known |+| `gpu.kernel.shared_memory` | Histogram | By | Dynamic shared memory per launch | `cuda.kernel.name`, `hw.id` when known |+| `gpu.memory.allocations` | Counter | By | Bytes allocated via cudaMalloc | `hw.id` when known || `gpu.memory.copies` | Histogram | By | Bytes per cudaMemcpy | `cuda.memcpy.kind`={HostToHost,HostToDevice,DeviceToHost,DeviceToDevice} |## How It Works### Device Discovery-The collector scans `/sys/bus/pci/devices/` for PCI class codes `0x0300` (VGA), `0x0302` (3D controller), and `0x0380` (display controller), then maps the vendor ID:+**Linux:** scans `/sys/bus/pci/devices/` for PCI class codes `0x0300` / `0x0302` / `0x0380`, then maps vendor ID:| Vendor ID | Backend | Collected metrics ||---|---|---|-| `0x10de` (NVIDIA) | NVML via [go-nvml](https://github.com/NVIDIA/go-nvml) — loads `libnvidia-ml.so` at runtime | Utilization, memory, temperature, power, energy, clocks, ECC errors, PCIe errors, fan speed |-| `0x1002` (AMD) | sysfs + hwmon — zero external dependencies | Utilization, memory, temperature, power, energy, fan speed |-| `0x8086` (Intel) | sysfs + hwmon + DRM (i915/Xe driver) — requires Linux kernel 5.10+ | Temperature, power draw/limit, cumulative energy, graphics clock, fan speed (kernel 6.16+) |+| `0x10de` (NVIDIA) | NVML via [go-nvml](https://github.com/NVIDIA/go-nvml) — `libnvidia-ml.so` | Utilization, memory, temperature, power, energy, clocks, ECC, PCIe |+| `0x1002` (AMD) | sysfs + hwmon + DRM fdinfo | Utilization, memory, temperature, power, energy, fan, processes |+| `0x8086` (Intel) | sysfs + hwmon + DRM (i915/Xe) | Temperature, power, energy, clocks, fan*, processes |++**Windows:** NVIDIA via `nvml.dll` (LoadLibrary); AMD/Intel via DXGI adapter enum + PDH `\GPU Engine` / `\GPU Process Memory` for util and per-process attribution. eBPF CUDA tracing is not available on Windows.### eBPF CUDA Tracing-Attaches uprobes to `libcudart.so` to intercept:-- `cudaLaunchKernel` — kernel name, grid/block dimensions-- `cudaMalloc` — allocation size-- `cudaMemcpy` / `cudaMemcpyAsync` — copy size and direction+Attaches uprobes/uretprobes to `libcudart.so*` to intercept:+- `cudaLaunchKernel` — kernel name, grid/block dimensions, stream, shared mem+- `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, where kernel addresses are resolved to function names via ELF symbol tables.+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).## Contributing@@ -264,11 +292,12 @@ Join our [Slack](https://join.slack.com/t/openlit/shared_invite/zt-2etnfttwg-TjP| NVIDIA GPU hardware telemetry (NVML) | Done || AMD GPU hardware telemetry (sysfs/hwmon) | Done || Intel GPU hardware telemetry (sysfs/hwmon) | Done |-| eBPF CUDA kernel tracing | Done |+| Per-process GPU attribution (NVML + DRM fdinfo) | Done |+| eBPF CUDA activity + stream-sync occupancy | Done || OTel semantic convention compliance (`hw.gpu.*`) | Done || Prometheus `/metrics` endpoint | Planned || ROCm HIP tracing (AMD eBPF) | Planned |-| Per-process GPU utilization (DRM fdinfo) | Planned |+| CUDA Graph launch hooks | Planned |## Licensediff --git a/opentelemetry-gpu-collector/cmd/collector/main.go b/opentelemetry-gpu-collector/cmd/collector/main.goindex e6ba24a7..a195b386 100644--- a/opentelemetry-gpu-collector/cmd/collector/main.go+++ b/opentelemetry-gpu-collector/cmd/collector/main.go@@ -53,29 +53,37 @@ func run(logger *slog.Logger) error {}defer shutdownProvider()- // --- Host metrics (always-on, works on all platforms) ---- sysColl, err := hostmetrics.NewSystemCollector(provider, logger)- if err != nil {- logger.Warn("system metrics unavailable", "error", err)- }-- procColl, err := hostmetrics.NewProcessCollector(provider, logger)- if err != nil {- logger.Warn("process metrics unavailable", "error", err)+ // --- Host metrics (optional; default on for auto-collect) ---+ var sysColl *hostmetrics.SystemCollector+ var procColl *hostmetrics.ProcessCollector+ if cfg.HostMetricsEnabled {+ var err error+ sysColl, err = hostmetrics.NewSystemCollector(provider, logger)+ if err != nil {+ logger.Warn("system metrics unavailable", "error", err)+ }+ procColl, err = hostmetrics.NewProcessCollector(provider, logger)+ if err != nil {+ logger.Warn("process metrics unavailable", "error", err)+ }+ } else {+ logger.Info("host metrics disabled")}// --- GPU device discovery with retry ---var devices []gpu.Devicevar mc *export.MetricsCollectorvar ebpfTracer *gpuebpf.Tracer+ var occMetrics *export.OccupancyMetrics- // GPU discovery only makes sense on Linux (PCI sysfs, NVML, etc.)- gpuCapable := runtime.GOOS == "linux"+ // GPU discovery: Linux (PCI/sysfs/NVML) and Windows (NVML/DXGI/PDH).+ // macOS and others keep host/process metrics only.+ gpuCapable := runtime.GOOS == "linux" || runtime.GOOS == "windows"if gpuCapable {devices = tryDiscoverGPUs(logger)if len(devices) > 0 {- mc, ebpfTracer = setupCollectors(ctx, cfg, provider, devices, logger)+ mc, ebpfTracer, occMetrics = setupCollectors(ctx, cfg, provider, devices, logger)} else {logger.Warn("no GPUs discovered at startup; will retry periodically")}@@ -98,12 +106,16 @@ func run(logger *slog.Logger) error {if ebpfTracer != nil {ebpfTracer.Close()}+ if occMetrics != nil {+ occMetrics.Close()+ }if mc != nil {mc.Close()}for _, d := range devices {d.Close()}+ nvidia.ShutdownNVML()if sysColl != nil {sysColl.Close()}@@ -120,7 +132,7 @@ func run(logger *slog.Logger) error {logger.Info("retrying GPU discovery...")devices = tryDiscoverGPUs(logger)if len(devices) > 0 {- mc, ebpfTracer = setupCollectors(ctx, cfg, provider, devices, logger)+ mc, ebpfTracer, occMetrics = setupCollectors(ctx, cfg, provider, devices, logger)logger.Info("GPUs discovered on retry", "count", len(devices))}}@@ -150,51 +162,112 @@ func setupCollectors(provider *sdkmetric.MeterProvider,devices []gpu.Device,logger *slog.Logger,-) (*export.MetricsCollector, *gpuebpf.Tracer) {- mc, err := export.NewMetricsCollector(provider, devices, logger)+) (*export.MetricsCollector, *gpuebpf.Tracer, *export.OccupancyMetrics) {+ mc, err := export.NewMetricsCollector(provider, devices, logger, cfg)if err != nil {logger.Error("failed to create metrics collector", "error", err)- return nil, nil+ return nil, nil, nil}var ebpfTracer *gpuebpf.Tracer+ var occ *export.OccupancyMetricsif cfg.EBPFEnabled {- ebpfMetrics, err := export.NewEBPFMetrics(provider, logger)+ ebpfMetrics, err := export.NewEBPFMetrics(provider, devices, logger)if err != nil {logger.Warn("failed to create eBPF metrics instruments", "error", err)} else {- tracer, err := gpuebpf.NewTracer(logger, ebpfMetrics.HandleEvent)+ var handlers []gpuebpf.EventHandler+ handlers = append(handlers, ebpfMetrics.HandleEvent)++ occ, err = export.NewOccupancyMetrics(provider, devices, logger)+ if err != nil {+ logger.Warn("failed to create occupancy metrics", "error", err)+ occ = nil+ } else {+ handlers = append(handlers, occ.HandleEvent)+ }++ tracer, err := gpuebpf.NewTracer(logger, gpuebpf.MultiplexHandlers(handlers...))if err != nil {logger.Warn("eBPF CUDA tracing unavailable", "error", err)+ if occ != nil {+ occ.Close()+ occ = nil+ }} else {ebpfTracer = tracergo ebpfTracer.Run(ctx)- logger.Info("eBPF CUDA tracing started")+ logger.Info("eBPF CUDA tracing started (activity + stream-sync occupancy; /proc libcudart discovery)")}}}- return mc, ebpfTracer+ return mc, ebpfTracer, occ}-// discoverAllGPUs finds GPUs on the PCI bus and instantiates appropriate backends.+// discoverAllGPUs finds GPUs and instantiates appropriate backends.func discoverAllGPUs(logger *slog.Logger) ([]gpu.Device, error) {+ if runtime.GOOS == "windows" {+ return discoverAllGPUsWindows(logger)+ }+ return discoverAllGPUsLinux(logger)+}++// discoverAllGPUsWindows uses NVML + DXGI (no PCI sysfs).+func discoverAllGPUsWindows(logger *slog.Logger) ([]gpu.Device, error) {+ var allDevices []gpu.Device+ idx := 0++ nvDevices, err := nvidia.DiscoverDevices(logger)+ if err != nil {+ logger.Warn("NVIDIA discovery failed", "error", err)+ } else {+ for _, d := range nvDevices {+ allDevices = append(allDevices, d)+ idx+++ }+ }++ amdDevices, err := amd.DiscoverDevices(nil, idx, logger)+ if err != nil {+ logger.Warn("AMD discovery failed", "error", err)+ } else {+ for _, d := range amdDevices {+ allDevices = append(allDevices, d)+ idx+++ }+ }++ intelDevices, err := intel.DiscoverDevices(nil, idx, logger)+ if err != nil {+ logger.Warn("Intel discovery failed", "error", err)+ } else {+ for _, d := range intelDevices {+ allDevices = append(allDevices, d)+ }+ }++ return allDevices, nil+}++// discoverAllGPUsLinux finds GPUs on Linux. NVIDIA is tried via NVML even when+// PCI sysfs is incomplete (common in some containers). AMD/Intel use PCI addresses+// when available, with DRM/Level Zero fallbacks inside their discoverers.+func discoverAllGPUsLinux(logger *slog.Logger) ([]gpu.Device, error) {pciDevices, err := discovery.Discover(logger)if err != nil {- return nil, err+ logger.Debug("PCI discovery incomplete", "error", err)+ pciDevices = nil}var (allDevices []gpu.Device- nvidiaAddrs []stringamdAddrs []stringintelAddrs []string)for _, d := range pciDevices {switch d.Vendor {- case gpu.VendorNVIDIA:- nvidiaAddrs = append(nvidiaAddrs, d.Address)case gpu.VendorAMD:amdAddrs = append(amdAddrs, d.Address)case gpu.VendorIntel:@@ -204,41 +277,33 @@ func discoverAllGPUs(logger *slog.Logger) ([]gpu.Device, error) {idx := 0- // NVIDIA: use NVML for all NVIDIA GPUs at once- if len(nvidiaAddrs) > 0 {- nvDevices, err := nvidia.DiscoverDevices(logger)- if err != nil {- logger.Warn("NVIDIA discovery failed", "error", err)- } else {- for _, d := range nvDevices {- allDevices = append(allDevices, d)- idx++- }+ // Always attempt NVML — do not gate on PCI class scan.+ nvDevices, err := nvidia.DiscoverDevices(logger)+ if err != nil {+ logger.Warn("NVIDIA discovery failed", "error", err)+ } else {+ for _, d := range nvDevices {+ allDevices = append(allDevices, d)+ idx++}}- // AMD: use sysfs for each AMD GPU- if len(amdAddrs) > 0 {- amdDevices, err := amd.DiscoverDevices(amdAddrs, idx, logger)- if err != nil {- logger.Warn("AMD discovery failed", "error", err)- } else {- for _, d := range amdDevices {- allDevices = append(allDevices, d)- idx++- }+ amdDevices, err := amd.DiscoverDevices(amdAddrs, idx, logger)+ if err != nil {+ logger.Warn("AMD discovery failed", "error", err)+ } else {+ for _, d := range amdDevices {+ allDevices = append(allDevices, d)+ idx++}}- // Intel: use sysfs for each Intel GPU- if len(intelAddrs) > 0 {- intelDevices, err := intel.DiscoverDevices(intelAddrs, idx, logger)- if err != nil {- logger.Warn("Intel discovery failed", "error", err)- } else {- for _, d := range intelDevices {- allDevices = append(allDevices, d)- }+ intelDevices, err := intel.DiscoverDevices(intelAddrs, idx, logger)+ if err != nil {+ logger.Warn("Intel discovery failed", "error", err)+ } else {+ for _, d := range intelDevices {+ allDevices = append(allDevices, d)}}diff --git a/opentelemetry-gpu-collector/go.mod b/opentelemetry-gpu-collector/go.modindex 96b5b440..d6cb8fb9 100644--- a/opentelemetry-gpu-collector/go.mod+++ b/opentelemetry-gpu-collector/go.mod@@ -3,40 +3,43 @@ module github.com/openlit/openlit/opentelemetry-gpu-collectorgo 1.25.0require (+ github.com/Microsoft/go-winio v0.6.2github.com/NVIDIA/go-nvml v0.13.0-1github.com/cilium/ebpf v0.21.0+ github.com/ebitengine/purego v0.10.0github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0fgithub.com/shirou/gopsutil/v4 v4.26.3+ github.com/tklauser/go-sysconf v0.3.16go.opentelemetry.io/otel v1.43.0go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0go.opentelemetry.io/otel/metric v1.43.0go.opentelemetry.io/otel/sdk v1.43.0go.opentelemetry.io/otel/sdk/metric v1.43.0+ golang.org/x/sys v0.45.0+ google.golang.org/grpc v1.80.0+ k8s.io/kubelet v0.32.3)require (github.com/cenkalti/backoff/v5 v5.0.3 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirect- github.com/ebitengine/purego v0.10.0 // indirectgithub.com/go-logr/logr v1.4.3 // indirectgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/go-ole/go-ole v1.2.6 // indirect+ github.com/gogo/protobuf v1.3.2 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirectgithub.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirectgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect- github.com/tklauser/go-sysconf v0.3.16 // indirectgithub.com/tklauser/numcpus v0.11.0 // indirectgithub.com/yusufpapurcu/wmi v1.2.4 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirectgo.opentelemetry.io/otel/trace v1.43.0 // indirectgo.opentelemetry.io/proto/otlp v1.10.0 // indirectgolang.org/x/net v0.55.0 // indirect- golang.org/x/sys v0.45.0 // indirectgolang.org/x/text v0.37.0 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect- google.golang.org/grpc v1.80.0 // indirectgoogle.golang.org/protobuf v1.36.11 // indirect)diff --git a/opentelemetry-gpu-collector/go.sum b/opentelemetry-gpu-collector/go.sumindex dad07ce9..53841b77 100644--- a/opentelemetry-gpu-collector/go.sum+++ b/opentelemetry-gpu-collector/go.sum@@ -1,3 +1,5 @@+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/NVIDIA/go-nvml v0.13.0-1 h1:OLX8Jq3dONuPOQPC7rndB6+iDmDakw0XTYgzMxObkEw=github.com/NVIDIA/go-nvml v0.13.0-1/go.mod h1:+KNA7c7gIBH7SKSJ1ntlwkfN80zdx8ovl4hrK3LmPt4=github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=@@ -19,6 +21,8 @@ github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6 h1:teYtXy9B7y5lHTp8V9KPxpYRAVA7dozigQcMiBust1s=github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=@@ -34,6 +38,8 @@ github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLgithub.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=github.com/jsimonetti/rtnetlink/v2 v2.0.1 h1:xda7qaHDSVOsADNouv7ukSuicKZO7GgVUCXxpaIEIlM=github.com/jsimonetti/rtnetlink/v2 v2.0.1/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsTKP1pqKLUTVCvToE=+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=@@ -58,6 +64,8 @@ github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYIgithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=@@ -78,17 +86,41 @@ go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=@@ -101,3 +133,5 @@ google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNgoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+k8s.io/kubelet v0.32.3 h1:B9HzW4yB67flx8tN2FYuDwZvxnmK3v5EjxxFvOYjmc8=+k8s.io/kubelet v0.32.3/go.mod h1:yyAQSCKC+tjSlaFw4HQG7Jein+vo+GeKBGdXdQGvL1U=diff --git a/opentelemetry-gpu-collector/internal/config/config.go b/opentelemetry-gpu-collector/internal/config/config.goindex 6eb79150..78abf130 100644--- a/opentelemetry-gpu-collector/internal/config/config.go+++ b/opentelemetry-gpu-collector/internal/config/config.go@@ -2,6 +2,7 @@ package configimport ("os"+ "runtime""strconv""strings""time"@@ -12,16 +13,42 @@ type Config struct {ServiceName stringCollectionInterval time.DurationEBPFEnabled bool+ HostMetricsEnabled bool++ ProcessCmdline bool+ ProcessCmdlineMaxLen int+ AllocatedUtilThreshold float64+ K8sPodLookup bool // in-cluster API (auto on when NODE_NAME set in K8s)+ K8sPodResources bool // kubelet PodResources socket (default true in K8s)+ InterconnectEnabled bool}func Load() *Config {+ inK8s := os.Getenv("KUBERNETES_SERVICE_HOST") != ""+ nodeName := os.Getenv("K8S_NODE_NAME")+ if nodeName == "" {+ nodeName = os.Getenv("NODE_NAME")+ }+ // Pod API lookup auto-enables in-cluster when the node name is known.+ defaultPodLookup := inK8s && nodeName != ""+ // eBPF is Linux-only; default on there (soft-fails without BPF caps; CUDA+ // libs are discovered via FS + /proc maps). Off on Windows/macOS.+ defaultEBPF := runtime.GOOS == "linux"cfg := &Config{ServiceName: envOrDefault("OTEL_SERVICE_NAME", "default"),// OTEL_METRIC_EXPORT_INTERVAL is in milliseconds per the OTel spec.// OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, and// OTEL_EXPORTER_OTLP_PROTOCOL are read directly by the OTel SDK exporters.CollectionInterval: parseIntervalMS(os.Getenv("OTEL_METRIC_EXPORT_INTERVAL"), 60*time.Second),- EBPFEnabled: parseBool(envOrDefault("OTEL_GPU_EBPF_ENABLED", "false")),+ EBPFEnabled: parseBool(envOrDefault("OTEL_GPU_EBPF_ENABLED", strconv.FormatBool(defaultEBPF))),+ HostMetricsEnabled: parseBool(envOrDefault("OPENLIT_HOST_METRICS", "true")),++ ProcessCmdline: parseBool(envOrDefault("OTEL_GPU_PROCESS_CMDLINE", "true")),+ ProcessCmdlineMaxLen: parseInt(envOrDefault("OTEL_GPU_PROCESS_CMDLINE_MAX_LEN", "512"), 512),+ AllocatedUtilThreshold: parseFloat(envOrDefault("OTEL_GPU_ALLOCATED_UTIL_THRESHOLD", "0.05"), 0.05),+ K8sPodLookup: parseBool(envOrDefault("OPENLIT_K8S_POD_LOOKUP", strconv.FormatBool(defaultPodLookup))),+ K8sPodResources: parseBool(envOrDefault("OPENLIT_K8S_POD_RESOURCES", strconv.FormatBool(inK8s))),+ InterconnectEnabled: parseBool(envOrDefault("OTEL_GPU_INTERCONNECT_ENABLED", "true")),}// deployment.environment comes from OTEL_RESOURCE_ATTRIBUTES per the OTel spec.@@ -54,6 +81,22 @@ func parseBool(s string) bool {return b}+func parseInt(s string, fallback int) int {+ v, err := strconv.Atoi(s)+ if err != nil || v <= 0 {+ return fallback+ }+ return v+}++func parseFloat(s string, fallback float64) float64 {+ v, err := strconv.ParseFloat(s, 64)+ if err != nil || v < 0 {+ return fallback+ }+ return v+}+// parseResourceAttr extracts a specific key from OTEL_RESOURCE_ATTRIBUTES format// "key1=val1,key2=val2".func parseResourceAttr(raw, key, fallback string) string {diff --git a/opentelemetry-gpu-collector/internal/config/config_test.go b/opentelemetry-gpu-collector/internal/config/config_test.goindex 46947421..26611627 100644--- a/opentelemetry-gpu-collector/internal/config/config_test.go+++ b/opentelemetry-gpu-collector/internal/config/config_test.go@@ -1,6 +1,7 @@package configimport (+ "runtime""testing""time")@@ -66,8 +67,9 @@ func TestLoadDefaults(t *testing.T) {if cfg.CollectionInterval != 60*time.Second {t.Errorf("CollectionInterval = %v, want %v", cfg.CollectionInterval, 60*time.Second)}- if cfg.EBPFEnabled {- t.Error("EBPFEnabled should be false by default")+ wantEBPF := runtime.GOOS == "linux"+ if cfg.EBPFEnabled != wantEBPF {+ t.Errorf("EBPFEnabled = %v, want %v (default for %s)", cfg.EBPFEnabled, wantEBPF, runtime.GOOS)}if cfg.Environment != "default" {t.Errorf("Environment = %q, want %q", cfg.Environment, "default")@@ -95,3 +97,12 @@ func TestLoadFromEnv(t *testing.T) {t.Errorf("Environment = %q, want %q", cfg.Environment, "production")}}++func TestLoadEBPFDisabled(t *testing.T) {+ t.Setenv("OTEL_GPU_EBPF_ENABLED", "false")++ cfg := Load()+ if cfg.EBPFEnabled {+ t.Error("EBPFEnabled should be false when OTEL_GPU_EBPF_ENABLED=false")+ }+}diff --git a/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_linux.go b/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_linux.gonew file mode 100644index 00000000..250a17b1--- /dev/null+++ b/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_linux.go@@ -0,0 +1,16 @@+//go:build linux++package cudaoccupancy++import "golang.org/x/sys/unix"++// monotonicNowNs returns CLOCK_MONOTONIC nanoseconds, matching bpf_ktime_get_ns()+// (excludes suspend time). Must not use wall-clock UnixNano — that is a different+// domain and makes every occupancy interval clamp to empty.+func monotonicNowNs() uint64 {+ var ts unix.Timespec+ if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil {+ return 0+ }+ return uint64(ts.Sec)*1e9 + uint64(ts.Nsec)+}diff --git a/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_other.go b/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_other.gonew file mode 100644index 00000000..bc1b6658--- /dev/null+++ b/opentelemetry-gpu-collector/internal/cudaoccupancy/clock_other.go@@ -0,0 +1,11 @@+//go:build !linux++package cudaoccupancy++import "time"++// monotonicNowNs is a wall-clock fallback for non-Linux unit tests.+// Production occupancy runs only with Linux eBPF; tests inject nowFn.+func monotonicNowNs() uint64 {+ return uint64(time.Now().UnixNano())+}diff --git a/opentelemetry-gpu-collector/internal/cudaoccupancy/engine.go b/opentelemetry-gpu-collector/internal/cudaoccupancy/engine.gonew file mode 100644index 00000000..189720be--- /dev/null+++ b/opentelemetry-gpu-collector/internal/cudaoccupancy/engine.go@@ -0,0 +1,596 @@+// Package cudaoccupancy implements Datadog-parity CUDA stream-sync occupancy.+//+// This is a CPU-side model: spans run from kernel launch to sync API return,+// not true hardware SM occupancy. See package docs and metrics descriptions.+package cudaoccupancy++import (+ "sort"+ "sync"+ "time"+)++const (+ DefaultMaxActiveStreams = 100+ DefaultMaxKernelLaunches = 1000+ DefaultMaxPendingKernelSpans = 1000+ DefaultStreamInactiveTimeout = 30 * time.Second+)++// KernelLaunch is one cudaLaunchKernel (or cuLaunchKernel) observation.+type KernelLaunch struct {+ PID uint32+ TID uint32+ StreamID uint64+ DeviceUUID string+ KtimeNs uint64+ GridX, GridY, GridZ uint32+ BlockX, BlockY, BlockZ uint32+}++// SyncEvent closes spans on a stream (or all streams on a device when DeviceWide).+type SyncEvent struct {+ PID uint32+ TID uint32+ StreamID uint64+ DeviceUUID string+ KtimeNs uint64+ DeviceWide bool+}++// SetDeviceEvent records cudaSetDevice success for (pid, tid).+type SetDeviceEvent struct {+ PID uint32+ TID uint32+ DeviceIdx int+ DeviceUUID string+ KtimeNs uint64+}++// ProcessStats is one interval's occupancy for a process on a device.+type ProcessStats struct {+ PID uint32+ DeviceUUID string+ UsedCores float64 // normalized+ ActiveTime float64 // 0..1 fraction of interval+ RawUsedCores float64+}++// DeviceStats is device-wide active time for an interval.+type DeviceStats struct {+ DeviceUUID string+ ActiveTime float64 // 0..1+ CoreLimit float64+}++// FlushResult is emitted by Engine.GetAndFlush.+type FlushResult struct {+ Processes []ProcessStats+ Devices []DeviceStats+}++type kernelSpan struct {+ startKtime uint64+ endKtime uint64+ avgThreadCount uint64+ numKernels uint64+}++type streamKey struct {+ pid uint32+ streamID uint64+ gpuUUID string // for default stream (streamID==0)+}++type streamHandler struct {+ key streamKey+ gpuUUID string+ pid uint32+ launches []KernelLaunch+ pending []*kernelSpan+ lastEventKtimeNs uint64+ ended bool+}++type aggregatorKey struct {+ pid uint32+ gpuUUID string+}++type aggregator struct {+ deviceMaxThreads uint64+ lastCheckKtime uint64+ measuredIntervalNs int64+ totalThreadSecondsUsed float64+ activeIntervals [][2]uint64+ isActive bool+}++// Engine is the Datadog-style stream occupancy engine.+type Engine struct {+ mu sync.Mutex++ streams map[streamKey]*streamHandler+ globalStreams map[streamKey]*streamHandler // stream_id==0 keyed by pid+uuid+ aggregators map[aggregatorKey]*aggregator++ // tid -> last cudaSetDevice UUID+ threadDevice map[uint64]string // pid<<32|tid+ deviceCores map[string]uint64 // uuid -> core count+ deviceIndex map[int]string // cuda device index -> uuid++ lastFlushKtime uint64+ nowFn func() uint64++ maxActiveStreams int+ maxKernelLaunches int+ maxPendingSpans int+ inactiveTimeoutNs uint64++ RejectedStreams uint64+ RejectedSpans uint64+ ForcedSyncs uint64+}++// NewEngine creates an occupancy engine. deviceCores maps GPU UUID -> CUDA core count.+func NewEngine(deviceCores map[string]uint64) *Engine {+ cores := deviceCores+ if cores == nil {+ cores = map[string]uint64{}+ }+ return &Engine{+ streams: make(map[streamKey]*streamHandler),+ globalStreams: make(map[streamKey]*streamHandler),+ aggregators: make(map[aggregatorKey]*aggregator),+ threadDevice: make(map[uint64]string),+ deviceCores: cores,+ deviceIndex: make(map[int]string),+ nowFn: monotonicNowNs,+ maxActiveStreams: DefaultMaxActiveStreams,+ maxKernelLaunches: DefaultMaxKernelLaunches,+ maxPendingSpans: DefaultMaxPendingKernelSpans,+ inactiveTimeoutNs: uint64(DefaultStreamInactiveTimeout.Nanoseconds()),+ }+}++// SetDeviceIndexUUID maps a CUDA device index to a GPU UUID (from NVML discovery).+func (e *Engine) SetDeviceIndexUUID(idx int, uuid string) {+ e.mu.Lock()+ defer e.mu.Unlock()+ e.deviceIndex[idx] = uuid+ if _, ok := e.deviceCores[uuid]; !ok {+ e.deviceCores[uuid] = 0+ }+}++func threadKey(pid, tid uint32) uint64 {+ return uint64(pid)<<32 | uint64(tid)+}++// HandleSetDevice records the active device for a thread.+func (e *Engine) HandleSetDevice(ev SetDeviceEvent) {+ e.mu.Lock()+ defer e.mu.Unlock()+ uuid := ev.DeviceUUID+ if uuid == "" {+ uuid = e.deviceIndex[ev.DeviceIdx]+ }+ if uuid == "" {+ return+ }+ e.threadDevice[threadKey(ev.PID, ev.TID)] = uuid+}++// HandleLaunch buffers a kernel launch on its stream.+func (e *Engine) HandleLaunch(ev KernelLaunch) {+ e.mu.Lock()+ defer e.mu.Unlock()++ uuid := ev.DeviceUUID+ if uuid == "" {+ uuid = e.threadDevice[threadKey(ev.PID, ev.TID)]+ }+ if uuid == "" {+ // Fallback: first known device+ for _, u := range e.deviceIndex {+ uuid = u+ break+ }+ }+ if uuid == "" {+ uuid = "unknown"+ }+ ev.DeviceUUID = uuid++ h := e.getOrCreateStream(ev.PID, ev.StreamID, uuid, ev.KtimeNs)+ if h == nil {+ return+ }+ h.lastEventKtimeNs = ev.KtimeNs+ h.launches = append(h.launches, ev)+ if len(h.launches) >= e.maxKernelLaunches {+ e.ForcedSyncs+++ e.markSynchronization(h, ev.KtimeNs+1)+ }+}++// HandleSync closes spans for a stream or all streams on a device.+func (e *Engine) HandleSync(ev SyncEvent) {+ e.mu.Lock()+ defer e.mu.Unlock()++ uuid := ev.DeviceUUID+ if uuid == "" {+ uuid = e.threadDevice[threadKey(ev.PID, ev.TID)]+ }++ if ev.DeviceWide || ev.StreamID == 0 {+ e.fanOutDeviceSync(ev.PID, uuid, ev.KtimeNs)+ return+ }+ key := streamKey{pid: ev.PID, streamID: ev.StreamID}+ h := e.streams[key]+ if h == nil {+ return+ }+ h.lastEventKtimeNs = ev.KtimeNs+ e.markSynchronization(h, ev.KtimeNs)+}++func (e *Engine) fanOutDeviceSync(pid uint32, uuid string, ts uint64) {+ if uuid == "" {+ uuid = e.threadDevice[threadKey(pid, 0)]+ }+ // No cudaSetDevice yet: close all streams for this PID so launches still complete.+ if uuid == "" {+ for _, h := range e.globalStreams {+ if h.pid == pid {+ h.lastEventKtimeNs = ts+ e.markSynchronization(h, ts)+ }+ }+ for _, h := range e.streams {+ if h.pid == pid {+ h.lastEventKtimeNs = ts+ e.markSynchronization(h, ts)+ }+ }+ return+ }+ gkey := streamKey{pid: pid, streamID: 0, gpuUUID: uuid}+ if h := e.globalStreams[gkey]; h != nil {+ h.lastEventKtimeNs = ts+ e.markSynchronization(h, ts)+ }+ for _, h := range e.streams {+ if h.pid == pid && h.gpuUUID == uuid {+ h.lastEventKtimeNs = ts+ e.markSynchronization(h, ts)+ }+ }+}++const maxGlobalActiveStreams = 1000 // hard cap across all PIDs++func (e *Engine) getOrCreateStream(pid uint32, streamID uint64, uuid string, ts uint64) *streamHandler {+ if streamID == 0 {+ key := streamKey{pid: pid, streamID: 0, gpuUUID: uuid}+ if h := e.globalStreams[key]; h != nil {+ return h+ }+ if e.activeStreamCountForPID(pid) >= e.maxActiveStreams || e.activeStreamCount() >= maxGlobalActiveStreams {+ e.RejectedStreams+++ return nil+ }+ h := &streamHandler{key: key, gpuUUID: uuid, pid: pid, lastEventKtimeNs: ts}+ e.globalStreams[key] = h+ return h+ }+ key := streamKey{pid: pid, streamID: streamID}+ if h := e.streams[key]; h != nil {+ return h+ }+ if e.activeStreamCountForPID(pid) >= e.maxActiveStreams || e.activeStreamCount() >= maxGlobalActiveStreams {+ e.RejectedStreams+++ return nil+ }+ h := &streamHandler{key: key, gpuUUID: uuid, pid: pid, lastEventKtimeNs: ts}+ e.streams[key] = h+ return h+}++func (e *Engine) activeStreamCount() int {+ return len(e.streams) + len(e.globalStreams)+}++func (e *Engine) activeStreamCountForPID(pid uint32) int {+ n := 0+ for _, h := range e.streams {+ if h.pid == pid {+ n+++ }+ }+ for _, h := range e.globalStreams {+ if h.pid == pid {+ n+++ }+ }+ return n+}++func (e *Engine) markSynchronization(h *streamHandler, ts uint64) {+ span := buildKernelSpan(h.launches, ts)+ if span != nil {+ if len(h.pending) >= e.maxPendingSpans {+ e.RejectedSpans+++ } else {+ h.pending = append(h.pending, span)+ }+ }+ // Keep launches at/after ts (Datadog uses >=)+ kept := h.launches[:0]+ for _, l := range h.launches {+ if l.KtimeNs >= ts {+ kept = append(kept, l)+ }+ }+ h.launches = kept+}++func buildKernelSpan(launches []KernelLaunch, maxTime uint64) *kernelSpan {+ if len(launches) == 0 {+ return nil+ }+ span := &kernelSpan{+ startKtime: ^uint64(0),+ endKtime: maxTime,+ }+ var sumThreads uint64+ for _, l := range launches {+ if l.KtimeNs >= maxTime {+ continue+ }+ if l.KtimeNs < span.startKtime {+ span.startKtime = l.KtimeNs+ }+ grid := uint64(l.GridX) * uint64(l.GridY) * uint64(l.GridZ)+ block := uint64(l.BlockX) * uint64(l.BlockY) * uint64(l.BlockZ)+ sumThreads += grid * block+ span.numKernels+++ }+ if span.numKernels == 0 {+ return nil+ }+ span.avgThreadCount = sumThreads / span.numKernels+ return span+}++// GetAndFlush aggregates spans since the last flush and returns normalized stats.+func (e *Engine) GetAndFlush() FlushResult {+ e.mu.Lock()+ defer e.mu.Unlock()++ now := e.nowFn()+ if e.lastFlushKtime == 0 {+ e.lastFlushKtime = now+ // Still collect open spans with end=now for first interval baseline+ }+ intervalNs := int64(now - e.lastFlushKtime)+ if intervalNs <= 0 {+ intervalNs = 1+ }++ // Reset aggregator activity+ for _, agg := range e.aggregators {+ agg.isActive = false+ agg.totalThreadSecondsUsed = 0+ agg.activeIntervals = agg.activeIntervals[:0]+ agg.lastCheckKtime = e.lastFlushKtime+ agg.measuredIntervalNs = intervalNs+ }++ deviceIntervals := make(map[string][][2]uint64)++ consume := func(h *streamHandler) {+ // Snapshot open span+ if open := buildKernelSpan(h.launches, now); open != nil {+ e.feedSpan(h, open, deviceIntervals, intervalNs)+ }+ for _, span := range h.pending {+ e.feedSpan(h, span, deviceIntervals, intervalNs)+ }+ h.pending = h.pending[:0]+ }++ for _, h := range e.streams {+ consume(h)+ }+ for _, h := range e.globalStreams {+ consume(h)+ }++ // Normalize process cores+ rawByDevice := make(map[string]float64)+ for key, agg := range e.aggregators {+ if !agg.isActive {+ continue+ }+ raw := agg.getAverageCoreUsage()+ rawByDevice[key.gpuUUID] += raw+ }++ factors := make(map[string]float64)+ for uuid, total := range rawByDevice {+ cores := float64(e.deviceCores[uuid])+ if cores <= 0 {+ cores = total // no clamp info+ }+ if total > cores && cores > 0 {+ factors[uuid] = total / cores+ } else {+ factors[uuid] = 1+ }+ }++ var result FlushResult+ for key, agg := range e.aggregators {+ if !agg.isActive {+ continue+ }+ raw := agg.getAverageCoreUsage()+ factor := factors[key.gpuUUID]+ if factor < 1 {+ factor = 1+ }+ active := agg.getActiveTimeFrac()+ result.Processes = append(result.Processes, ProcessStats{+ PID: key.pid,+ DeviceUUID: key.gpuUUID,+ UsedCores: raw / factor,+ ActiveTime: active,+ RawUsedCores: raw,+ })+ }++ for uuid, intervals := range deviceIntervals {+ activeNs := MergeIntervals(intervals)+ frac := float64(activeNs) / float64(intervalNs)+ if frac > 1 {+ frac = 1+ }+ result.Devices = append(result.Devices, DeviceStats{+ DeviceUUID: uuid,+ ActiveTime: frac,+ CoreLimit: float64(e.deviceCores[uuid]),+ })+ }++ e.lastFlushKtime = now+ e.cleanupInactive(now)+ return result+}++func (e *Engine) feedSpan(h *streamHandler, span *kernelSpan, deviceIntervals map[string][][2]uint64, intervalNs int64) {+ key := aggregatorKey{pid: h.pid, gpuUUID: h.gpuUUID}+ agg := e.aggregators[key]+ if agg == nil {+ agg = &aggregator{deviceMaxThreads: e.deviceCores[h.gpuUUID]}+ e.aggregators[key] = agg+ }+ if agg.deviceMaxThreads == 0 {+ agg.deviceMaxThreads = e.deviceCores[h.gpuUUID]+ }+ agg.lastCheckKtime = e.lastFlushKtime+ agg.measuredIntervalNs = intervalNs+ agg.isActive = true+ agg.processKernelSpan(span)++ start := span.startKtime+ end := span.endKtime+ if start < e.lastFlushKtime {+ start = e.lastFlushKtime+ }+ intervalEnd := e.lastFlushKtime + uint64(intervalNs)+ if end > intervalEnd {+ end = intervalEnd+ }+ if start < end {+ deviceIntervals[h.gpuUUID] = append(deviceIntervals[h.gpuUUID], [2]uint64{start, end})+ }+}++func (agg *aggregator) processKernelSpan(span *kernelSpan) {+ tsStart := span.startKtime+ tsEnd := span.endKtime+ if agg.lastCheckKtime > tsStart {+ tsStart = agg.lastCheckKtime+ }+ intervalEnd := agg.lastCheckKtime + uint64(agg.measuredIntervalNs)+ if tsEnd > intervalEnd {+ tsEnd = intervalEnd+ }+ if tsEnd <= tsStart {+ return+ }+ durationSec := float64(tsEnd-tsStart) / 1e9+ activeThreads := span.avgThreadCount+ if agg.deviceMaxThreads > 0 && activeThreads > agg.deviceMaxThreads {+ activeThreads = agg.deviceMaxThreads+ }+ agg.totalThreadSecondsUsed += durationSec * float64(activeThreads)+ agg.activeIntervals = append(agg.activeIntervals, [2]uint64{tsStart, tsEnd})+}++func (agg *aggregator) getAverageCoreUsage() float64 {+ if agg.measuredIntervalNs == 0 {+ return 0+ }+ intervalSecs := float64(agg.measuredIntervalNs) / 1e9+ return agg.totalThreadSecondsUsed / intervalSecs+}++func (agg *aggregator) getActiveTimeFrac() float64 {+ if agg.measuredIntervalNs <= 0 {+ return 0+ }+ activeNs := MergeIntervals(agg.activeIntervals)+ frac := float64(activeNs) / float64(agg.measuredIntervalNs)+ if frac > 1 {+ frac = 1+ }+ return frac+}++func (e *Engine) cleanupInactive(now uint64) {+ livePIDs := make(map[uint32]struct{})+ for key, h := range e.streams {+ if h.lastEventKtimeNs > 0 && now > h.lastEventKtimeNs && now-h.lastEventKtimeNs > e.inactiveTimeoutNs {+ delete(e.streams, key)+ continue+ }+ livePIDs[h.pid] = struct{}{}+ }+ for key, h := range e.globalStreams {+ if h.lastEventKtimeNs > 0 && now > h.lastEventKtimeNs && now-h.lastEventKtimeNs > e.inactiveTimeoutNs {+ delete(e.globalStreams, key)+ continue+ }+ livePIDs[h.pid] = struct{}{}+ }+ // Drop aggregators and thread→device entries for PIDs with no live streams.+ for key := range e.aggregators {+ if _, ok := livePIDs[key.pid]; !ok {+ delete(e.aggregators, key)+ }+ }+ for tk := range e.threadDevice {+ pid := uint32(tk >> 32)+ if _, ok := livePIDs[pid]; !ok {+ delete(e.threadDevice, tk)+ }+ }+}++// MergeIntervals unions overlapping [start,end) intervals and returns total covered ns.+func MergeIntervals(intervals [][2]uint64) uint64 {+ if len(intervals) == 0 {+ return 0+ }+ sort.Slice(intervals, func(i, j int) bool {+ return intervals[i][0] < intervals[j][0]+ })+ var total uint64+ curStart, curEnd := intervals[0][0], intervals[0][1]+ for i := 1; i < len(intervals); i++ {+ if intervals[i][0] <= curEnd {+ if intervals[i][1] > curEnd {+ curEnd = intervals[i][1]+ }+ } else {+ total += curEnd - curStart+ curStart, curEnd = intervals[i][0], intervals[i][1]+ }+ }+ total += curEnd - curStart+ return total+}diff --git a/opentelemetry-gpu-collector/internal/cudaoccupancy/engine_test.go b/opentelemetry-gpu-collector/internal/cudaoccupancy/engine_test.gonew file mode 100644index 00000000..0bdd0803--- /dev/null+++ b/opentelemetry-gpu-collector/internal/cudaoccupancy/engine_test.go@@ -0,0 +1,191 @@+package cudaoccupancy++import "testing"++func TestMergeIntervals(t *testing.T) {+ if got := MergeIntervals(nil); got != 0 {+ t.Fatalf("empty: %d", got)+ }+ got := MergeIntervals([][2]uint64{{10, 20}, {15, 25}, {30, 40}})+ // union [10,25)+[30,40) = 15+10 = 25+ if got != 25 {+ t.Fatalf("got %d want 25", got)+ }+}++func TestBuildKernelSpanAvgThreads(t *testing.T) {+ launches := []KernelLaunch{+ {KtimeNs: 100, GridX: 2, GridY: 1, GridZ: 1, BlockX: 32, BlockY: 1, BlockZ: 1},+ {KtimeNs: 200, GridX: 1, GridY: 1, GridZ: 1, BlockX: 32, BlockY: 1, BlockZ: 1},+ }+ span := buildKernelSpan(launches, 1000)+ if span == nil || span.numKernels != 2 {+ t.Fatalf("span=%+v", span)+ }+ // (64 + 32) / 2 = 48+ if span.avgThreadCount != 48 {+ t.Fatalf("avg=%d", span.avgThreadCount)+ }+ if span.endKtime != 1000 || span.startKtime != 100 {+ t.Fatalf("times start=%d end=%d", span.startKtime, span.endKtime)+ }+}++func TestCoreUsageClampAndNormalize(t *testing.T) {+ e := NewEngine(map[string]uint64{"gpu-a": 50})+ // Control time+ var now uint64 = 1_000_000_000 // 1s+ e.nowFn = func() uint64 { return now }+ e.lastFlushKtime = 0++ // First flush establishes baseline+ _ = e.GetAndFlush()++ // Launch 100 threads at t=1s, sync at t=2s, flush at t=3s (2s window from last flush)+ now = 1_000_000_000+ e.HandleLaunch(KernelLaunch{+ PID: 1, StreamID: 1, DeviceUUID: "gpu-a", KtimeNs: now,+ GridX: 100, GridY: 1, GridZ: 1, BlockX: 1, BlockY: 1, BlockZ: 1,+ })+ now = 2_000_000_000+ e.HandleSync(SyncEvent{PID: 1, StreamID: 1, DeviceUUID: "gpu-a", KtimeNs: now})++ now = 3_000_000_000 // interval = 2s from first flush end (~1s)+ // After first GetAndFlush, lastFlush was ~1s. Wait — first call set lastFlush=1s.+ // Actually first GetAndFlush at now=1s set lastFlush=1s.+ // Second at now=3s → interval 2s. Span [1s,2s] clamped → 1s * min(100,50) = 50 thread-seconds+ // UsedCores_raw = 50 / 2 = 25+ res := e.GetAndFlush()+ if len(res.Processes) != 1 {+ t.Fatalf("processes: %+v", res.Processes)+ }+ p := res.Processes[0]+ if p.RawUsedCores < 24 || p.RawUsedCores > 26 {+ t.Fatalf("raw cores=%v want ~25", p.RawUsedCores)+ }+ if p.UsedCores > p.RawUsedCores+0.01 {+ t.Fatalf("normalized should be <= raw: %v vs %v", p.UsedCores, p.RawUsedCores)+ }+}++func TestMultiProcessNormalization(t *testing.T) {+ e := NewEngine(map[string]uint64{"gpu-a": 100})+ var now uint64 = 1_000_000_000+ e.nowFn = func() uint64 { return now }+ _ = e.GetAndFlush()++ // Two processes each claim 80 cores for full 1s interval+ now = 2_000_000_000+ for _, pid := range []uint32{1, 2} {+ e.HandleLaunch(KernelLaunch{+ PID: pid, StreamID: uint64(pid), DeviceUUID: "gpu-a", KtimeNs: 1_000_000_000,+ GridX: 80, GridY: 1, GridZ: 1, BlockX: 1, BlockY: 1, BlockZ: 1,+ })+ e.HandleSync(SyncEvent{PID: pid, StreamID: uint64(pid), DeviceUUID: "gpu-a", KtimeNs: 2_000_000_000})+ }+ res := e.GetAndFlush()+ var sum float64+ for _, p := range res.Processes {+ sum += p.UsedCores+ }+ if sum > 100.01 {+ t.Fatalf("sum UsedCores=%v exceeds core limit 100", sum)+ }+ if len(res.Processes) != 2 {+ t.Fatalf("want 2 processes, got %+v", res.Processes)+ }+}++func TestDeviceSyncFanOut(t *testing.T) {+ e := NewEngine(map[string]uint64{"gpu-a": 64})+ var now uint64 = 100+ e.nowFn = func() uint64 { return now }+ _ = e.GetAndFlush()++ e.HandleLaunch(KernelLaunch{+ PID: 7, StreamID: 42, DeviceUUID: "gpu-a", KtimeNs: 100,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 32, BlockY: 1, BlockZ: 1,+ })+ e.HandleLaunch(KernelLaunch{+ PID: 7, StreamID: 43, DeviceUUID: "gpu-a", KtimeNs: 100,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 32, BlockY: 1, BlockZ: 1,+ })+ now = 200+ e.HandleSync(SyncEvent{PID: 7, DeviceUUID: "gpu-a", KtimeNs: 200, DeviceWide: true})++ now = 300+ res := e.GetAndFlush()+ if len(res.Processes) != 1 {+ t.Fatalf("got %+v", res.Processes)+ }+ if res.Processes[0].ActiveTime <= 0 {+ t.Fatalf("expected positive active time: %+v", res.Processes[0])+ }+}++func TestDeviceSyncWithoutSetDevice(t *testing.T) {+ e := NewEngine(map[string]uint64{"gpu-a": 64})+ var now uint64 = 100+ e.nowFn = func() uint64 { return now }+ _ = e.GetAndFlush()++ e.HandleLaunch(KernelLaunch{+ PID: 9, StreamID: 1, DeviceUUID: "gpu-a", KtimeNs: 100,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 16, BlockY: 1, BlockZ: 1,+ })+ now = 200+ // Empty UUID + DeviceWide: must still close spans for the PID.+ e.HandleSync(SyncEvent{PID: 9, KtimeNs: 200, DeviceWide: true})++ now = 300+ res := e.GetAndFlush()+ if len(res.Processes) != 1 {+ t.Fatalf("got %+v", res.Processes)+ }+}++func TestStreamLimitIsPerPID(t *testing.T) {+ e := NewEngine(map[string]uint64{"gpu-a": 64})+ e.maxActiveStreams = 2+ var now uint64 = 1+ e.nowFn = func() uint64 { return now }++ for sid := uint64(1); sid <= 2; sid++ {+ e.HandleLaunch(KernelLaunch{+ PID: 1, StreamID: sid, DeviceUUID: "gpu-a", KtimeNs: now,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 1, BlockY: 1, BlockZ: 1,+ })+ }+ e.HandleLaunch(KernelLaunch{+ PID: 1, StreamID: 3, DeviceUUID: "gpu-a", KtimeNs: now,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 1, BlockY: 1, BlockZ: 1,+ })+ if e.RejectedStreams == 0 {+ t.Fatal("expected reject for PID 1 over limit")+ }+ before := e.RejectedStreams+ e.HandleLaunch(KernelLaunch{+ PID: 2, StreamID: 1, DeviceUUID: "gpu-a", KtimeNs: now,+ GridX: 1, GridY: 1, GridZ: 1, BlockX: 1, BlockY: 1, BlockZ: 1,+ })+ if e.RejectedStreams != before {+ t.Fatal("PID 2 should not share PID 1 stream quota")+ }+}++func TestUint64ThreadProduct(t *testing.T) {+ // Large grid that would overflow uint32 if multiplied wrongly+ launches := []KernelLaunch{{+ KtimeNs: 1,+ GridX: 1 << 20, GridY: 1 << 10, GridZ: 1,+ BlockX: 256, BlockY: 1, BlockZ: 1,+ }}+ span := buildKernelSpan(launches, 10)+ if span == nil {+ t.Fatal("nil span")+ }+ want := uint64(1<<20) * uint64(1<<10) * 256+ if span.avgThreadCount != want {+ t.Fatalf("got %d want %d", span.avgThreadCount, want)+ }+}diff --git a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.cindex 3d4c368a..3dc9d40d 100644--- a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c+++ b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.c@@ -1,4 +1,4 @@-// GPU event eBPF probes for CUDA runtime interception.+// GPU event eBPF probes for CUDA runtime interception (stream-sync occupancy).// License: Apache-2.0//go:build ignore@@ -15,50 +15,42 @@ struct {__uint(max_entries, 1 << 24); // 16 MB} gpu_events SEC(".maps");-// Capture settings (toggled via map).+// Entry caches for uretprobes (keyed by pid_tgid).struct {- __uint(type, BPF_MAP_TYPE_ARRAY);- __uint(max_entries, 1);- __type(key, __u32);- __type(value, __u32);-} capture_config SEC(".maps");--static __always_inline struct pid_info_t get_pid_info() {- struct pid_info_t pi = {};+ __uint(type, BPF_MAP_TYPE_LRU_HASH);+ __uint(max_entries, 1024);+ __type(key, __u64);+ __type(value, __u64);+} cuda_sync_cache SEC(".maps");++struct {+ __uint(type, BPF_MAP_TYPE_LRU_HASH);+ __uint(max_entries, 1024);+ __type(key, __u64);+ __type(value, __s32);+} cuda_set_device_cache SEC(".maps");++struct {+ __uint(type, BPF_MAP_TYPE_LRU_HASH);+ __uint(max_entries, 1024);+ __type(key, __u64);+ __type(value, __u64);+} cuda_malloc_size_cache 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();- pi.host_pid = pid_tgid >> 32;- pi.user_pid = pid_tgid >> 32;-- struct task_struct *task = (struct task_struct *)bpf_get_current_task();- if (task) {- struct nsproxy *ns;- bpf_probe_read_kernel(&ns, sizeof(ns), &task->nsproxy);- if (ns) {- struct pid_namespace *pidns;- bpf_probe_read_kernel(&pidns, sizeof(pidns), &ns->pid_ns_for_children);- if (pidns) {- unsigned int level;- bpf_probe_read_kernel(&level, sizeof(level), &pidns->level);- pi.ns = level;- }- }- }- return pi;+ hdr->type = type;+ hdr->pad0 = 0;+ hdr->device_idx = DEVICE_IDX_UNKNOWN;+ hdr->pid = pid_tgid >> 32;+ hdr->tid = (__u32)pid_tgid;+ hdr->pad1 = 0;+ hdr->stream_id = stream_id;+ hdr->ktime_ns = bpf_ktime_get_ns();}-// uprobe/cudaLaunchKernel intercepts CUDA kernel launches.-// Signature: cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim,-// dim3 blockDim, void **args, size_t sharedMem, cudaStream_t stream)-//-// dim3 is a 12-byte struct of three uint32 values. The way it is passed in-// registers at the libcudart entry point differs by target architecture, so-// the decoder is split per __TARGET_ARCH_* macro (auto-defined by bpf2go).-//-// `stream` is intentionally not decoded here — it is the 6th argument and on-// both ABIs it spills past the registers covered by libbpf's PT_REGS_PARMn-// macros (x86_64: stack; arm64: x7). Userspace does not consume the field-// today, so we keep the wire layout but zero the value to avoid reading-// arbitrary stack bytes inside the BPF program.+// cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,+// void **args, size_t sharedMem, cudaStream_t stream)SEC("uprobe/cudaLaunchKernel")int handle_cuda_launch(struct pt_regs *ctx) {struct gpu_kernel_launch_t *ev;@@ -66,20 +58,16 @@ int handle_cuda_launch(struct pt_regs *ctx) {if (!ev)return 0;- ev->flags = EVENT_GPU_KERNEL_LAUNCH;- ev->pid_info = get_pid_info();- ev->stream = 0;-- // arg0: const void *func (kernel function pointer)- ev->kern_func_off = PT_REGS_PARM1(ctx);+ __u64 stream = 0;+ __u32 shared = 0;#if defined(__TARGET_ARCH_x86)- // x86_64 System V: dim3 (12 bytes) is decomposed into 3 uint32 fields and- // packed two-per-register across rsi/rdx/rcx, as observed in libcudart- // CUDA 11.x–12.x (gcc/clang). With func consuming rdi:- // rsi (PARM2): gridDim.x | gridDim.y- // rdx (PARM3): gridDim.z | blockDim.x- // rcx (PARM4): blockDim.y | blockDim.z+ // 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));+__u64 grid_xy = PT_REGS_PARM2(ctx);ev->grid_x = grid_xy & 0xFFFFFFFF;ev->grid_y = grid_xy >> 32;@@ -90,13 +78,13 @@ int handle_cuda_launch(struct pt_regs *ctx) {ev->block_y = block_yz & 0xFFFFFFFF;ev->block_z = block_yz >> 32;#elif defined(__TARGET_ARCH_arm64)- // AArch64 AAPCS64 (§6.4.2): each dim3 (12 bytes, rounded to 16) occupies- // two consecutive 64-bit GPRs and tail padding is NOT merged with the- // next argument. With func consuming x0:- // x1 (PARM2): gridDim.x | gridDim.y- // x2 (PARM3): gridDim.z | (pad)- // x3 (PARM4): blockDim.x | blockDim.y- // x4 (PARM5): blockDim.z | (pad)+ // AAPCS64: func=x0, grid=x1/x2, block=x3/x4, args=x5, shared=x6, stream=x7+ {+ struct user_pt_regs *regs = (struct user_pt_regs *)ctx;+ shared = (__u32)regs->regs[6];+ stream = regs->regs[7];+ }+__u64 grid_xy = PT_REGS_PARM2(ctx);ev->grid_x = grid_xy & 0xFFFFFFFF;ev->grid_y = grid_xy >> 32;@@ -109,45 +97,173 @@ int handle_cuda_launch(struct pt_regs *ctx) {#error "cudaLaunchKernel argument decoding not implemented for this architecture"#endif- // Capture user-space stack trace- bpf_get_stack(ctx, ev->ustack, sizeof(ev->ustack), BPF_F_USER_STACK);+ fill_header(&ev->hdr, EVENT_GPU_KERNEL_LAUNCH, stream);+ ev->kern_func_off = PT_REGS_PARM1(ctx);+ ev->shared_mem_bytes = shared;+ ev->pad = 0;bpf_ringbuf_submit(ev, 0);return 0;}-// uprobe/cudaMalloc intercepts GPU memory allocations.-// Signature: cudaError_t cudaMalloc(void **devPtr, size_t size)SEC("uprobe/cudaMalloc")+int handle_cuda_malloc_enter(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __u64 size = PT_REGS_PARM2(ctx);+ bpf_map_update_elem(&cuda_malloc_size_cache, &pid_tgid, &size, BPF_ANY);+ return 0;+}++SEC("uretprobe/cudaMalloc")int handle_cuda_malloc(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __u64 *sizep = bpf_map_lookup_elem(&cuda_malloc_size_cache, &pid_tgid);+ if (!sizep)+ return 0;+ __u64 size = *sizep;+ bpf_map_delete_elem(&cuda_malloc_size_cache, &pid_tgid);++ long ret = (long)PT_REGS_RC(ctx);+ if (ret != 0)+ return 0;+struct gpu_malloc_t *ev;ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);if (!ev)return 0;+ fill_header(&ev->hdr, EVENT_GPU_MALLOC, 0);+ ev->size = size;+ bpf_ringbuf_submit(ev, 0);+ return 0;+}- ev->flags = EVENT_GPU_MALLOC;- ev->pid_info = get_pid_info();- ev->size = PT_REGS_PARM2(ctx);-+SEC("uprobe/cudaFree")+int handle_cuda_free(struct pt_regs *ctx) {+ struct gpu_malloc_t *ev;+ ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);+ if (!ev)+ return 0;+ fill_header(&ev->hdr, EVENT_GPU_FREE, 0);+ ev->size = 0;bpf_ringbuf_submit(ev, 0);return 0;}-// uprobe/cudaMemcpy intercepts GPU memory copy operations.-// Signature: cudaError_t cudaMemcpyAsync(void *dst, const void *src,-// size_t count, enum cudaMemcpyKind kind, cudaStream_t stream)-SEC("uprobe/cudaMemcpy")+// Synchronous cudaMemcpy → treat completion as device-wide sync (Datadog parity).+SEC("uretprobe/cudaMemcpy")int handle_cuda_memcpy(struct pt_regs *ctx) {- struct gpu_memcpy_t *ev;+ long ret = (long)PT_REGS_RC(ctx);+ if (ret != 0)+ return 0;++ struct gpu_sync_t *ev;ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);if (!ev)return 0;+ fill_header(&ev->hdr, EVENT_GPU_SYNC_DEVICE, 0);+ bpf_ringbuf_submit(ev, 0);+ return 0;+}- ev->flags = EVENT_GPU_MEMCPY;- ev->pid_info = get_pid_info();+// Also count async memcpy bytes without closing spans.+SEC("uprobe/cudaMemcpyAsync")+int handle_cuda_memcpy_async(struct pt_regs *ctx) {+ struct gpu_memcpy_t *ev;+ ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);+ if (!ev)+ return 0;+ __u64 stream = 0;+#if defined(__TARGET_ARCH_x86)+ stream = PT_REGS_PARM5(ctx);+#elif defined(__TARGET_ARCH_arm64)+ stream = PT_REGS_PARM5(ctx);+#endif+ fill_header(&ev->hdr, EVENT_GPU_MEMCPY, stream);ev->size = PT_REGS_PARM3(ctx);ev->kind = (__u8)PT_REGS_PARM4(ctx);+ bpf_ringbuf_submit(ev, 0);+ return 0;+}+SEC("uprobe/cudaStreamSynchronize")+int handle_cuda_stream_sync_enter(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __u64 stream = PT_REGS_PARM1(ctx);+ bpf_map_update_elem(&cuda_sync_cache, &pid_tgid, &stream, BPF_ANY);+ return 0;+}++SEC("uretprobe/cudaStreamSynchronize")+int handle_cuda_stream_sync(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __u64 *streamp = bpf_map_lookup_elem(&cuda_sync_cache, &pid_tgid);+ if (!streamp)+ return 0;+ __u64 stream = *streamp;+ bpf_map_delete_elem(&cuda_sync_cache, &pid_tgid);++ long ret = (long)PT_REGS_RC(ctx);+ if (ret != 0)+ return 0;++ struct gpu_sync_t *ev;+ ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);+ if (!ev)+ return 0;++ // Default stream (0) synchronizes with other streams → device-wide.+ if (stream == 0)+ fill_header(&ev->hdr, EVENT_GPU_SYNC_DEVICE, 0);+ else+ fill_header(&ev->hdr, EVENT_GPU_SYNC, stream);+ bpf_ringbuf_submit(ev, 0);+ return 0;+}++SEC("uretprobe/cudaDeviceSynchronize")+int handle_cuda_device_sync(struct pt_regs *ctx) {+ long ret = (long)PT_REGS_RC(ctx);+ if (ret != 0)+ return 0;++ struct gpu_sync_t *ev;+ ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);+ if (!ev)+ return 0;+ fill_header(&ev->hdr, EVENT_GPU_SYNC_DEVICE, 0);+ bpf_ringbuf_submit(ev, 0);+ return 0;+}++SEC("uprobe/cudaSetDevice")+int handle_cuda_set_device_enter(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __s32 device = (__s32)PT_REGS_PARM1(ctx);+ bpf_map_update_elem(&cuda_set_device_cache, &pid_tgid, &device, BPF_ANY);+ return 0;+}++SEC("uretprobe/cudaSetDevice")+int handle_cuda_set_device(struct pt_regs *ctx) {+ __u64 pid_tgid = bpf_get_current_pid_tgid();+ __s32 *devp = bpf_map_lookup_elem(&cuda_set_device_cache, &pid_tgid);+ if (!devp)+ return 0;+ __s32 device = *devp;+ bpf_map_delete_elem(&cuda_set_device_cache, &pid_tgid);++ long ret = (long)PT_REGS_RC(ctx);+ if (ret != 0)+ return 0;++ struct gpu_set_device_t *ev;+ ev = bpf_ringbuf_reserve(&gpu_events, sizeof(*ev), 0);+ if (!ev)+ return 0;+ fill_header(&ev->hdr, EVENT_GPU_SET_DEVICE, 0);+ ev->hdr.device_idx = (__u16)device;+ ev->device = device;+ ev->pad = 0;bpf_ringbuf_submit(ev, 0);return 0;}diff --git a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.h b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.hindex 6e4da5a0..2bdeb8cc 100644--- a/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.h+++ b/opentelemetry-gpu-collector/internal/ebpf/bpf/gpuevent.h@@ -1,32 +1,39 @@-// GPU event eBPF data structures.+// GPU event eBPF data structures — stream-sync occupancy wire format.// License: Apache-2.0#ifndef __GPUEVENT_H__#define __GPUEVENT_H__-#define MAX_STACK_DEPTH 128-#define MAX_KERNEL_ARGS 16--// Event type flags (stored in first byte).+// Event type (first byte of every event).#define EVENT_GPU_KERNEL_LAUNCH 1#define EVENT_GPU_MALLOC 2#define EVENT_GPU_MEMCPY 3+#define EVENT_GPU_SYNC 4+#define EVENT_GPU_SYNC_DEVICE 5+#define EVENT_GPU_SET_DEVICE 6+#define EVENT_GPU_FREE 7-// cudaMemcpyKind enum values.#define CUDA_MEMCPY_HOST_TO_HOST 0#define CUDA_MEMCPY_HOST_TO_DEVICE 1#define CUDA_MEMCPY_DEVICE_TO_HOST 2#define CUDA_MEMCPY_DEVICE_TO_DEVICE 3-struct pid_info_t {- __u32 host_pid;- __u32 user_pid;- __u32 ns;+#define DEVICE_IDX_UNKNOWN 0xffff++// Shared header (32 bytes). All events start with this layout.+struct cuda_event_header_t {+ __u8 type;+ __u8 pad0;+ __u16 device_idx; // CUDA device index when known; DEVICE_IDX_UNKNOWN otherwise+ __u32 pid; // host tgid+ __u32 tid; // host tid+ __u32 pad1;+ __u64 stream_id;+ __u64 ktime_ns;};struct gpu_kernel_launch_t {- __u8 flags;- struct pid_info_t pid_info;+ struct cuda_event_header_t hdr;__u64 kern_func_off;__u32 grid_x;__u32 grid_y;@@ -34,22 +41,30 @@ struct gpu_kernel_launch_t {__u32 block_x;__u32 block_y;__u32 block_z;- __u64 stream;- __u64 args[MAX_KERNEL_ARGS];- __u64 ustack[MAX_STACK_DEPTH];+ __u32 shared_mem_bytes;+ __u32 pad;};struct gpu_malloc_t {- __u8 flags;- struct pid_info_t pid_info;+ struct cuda_event_header_t hdr;__u64 size;};struct gpu_memcpy_t {- __u8 flags;- __u8 kind;- struct pid_info_t pid_info;+ struct cuda_event_header_t hdr;__u64 size;+ __u8 kind;+ __u8 pad[7];+};++struct gpu_sync_t {+ struct cuda_event_header_t hdr;+};++struct gpu_set_device_t {+ struct cuda_event_header_t hdr;+ __s32 device;+ __u32 pad;};#endif /* __GPUEVENT_H__ */diff --git a/opentelemetry-gpu-collector/internal/ebpf/discover.go b/opentelemetry-gpu-collector/internal/ebpf/discover.gonew file mode 100644index 00000000..5023fa87--- /dev/null+++ b/opentelemetry-gpu-collector/internal/ebpf/discover.go@@ -0,0 +1,267 @@+//go:build linux && (amd64 || arm64)++package ebpf++import (+ "bufio"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+)++// findCudaLibs finds libcudart shared libraries to attach uprobes to.+//+// Discovery order (deduped by inode):+// 1. Filesystem candidates / globs (host install layouts, LD_LIBRARY_PATH, CUDA_HOME)+// 2. /proc/*/maps — fleet-friendly: with host PID visibility (Docker --pid=host /+// Kubernetes hostPID), finds whatever libcudart GPU workloads actually loaded,+// including copies only visible inside other containers via /proc/<pid>/map_files+// or /proc/<pid>/root.+//+// eBPF CUDA probes are NVIDIA/CUDA-only. AMD/Intel process GPU metrics use DRM+// fdinfo/NVML alternatives and do not need libcudart.+func findCudaLibs() []string {+ seenPath := make(map[string]struct{})+ seenInode := make(map[string]struct{})+ var out []string+ add := func(path string) {+ if path == "" {+ return+ }+ fi, err := os.Stat(path)+ if err != nil {+ return+ }+ // Keep /proc/*/map_files/* paths as-is: EvalSymlinks can rewrite them to a+ // container-local pathname that resolves to a *different* host inode.+ resolved := path+ if !isProcMapFilesPath(path) {+ if r, err := filepath.EvalSymlinks(path); err == nil {+ resolved = r+ }+ }+ if _, ok := seenPath[resolved]; ok {+ return+ }+ if sys, ok := fi.Sys().(*syscall.Stat_t); ok {+ key := inodeKey(sys.Dev, sys.Ino)+ if _, ok := seenInode[key]; ok {+ return+ }+ seenInode[key] = struct{}{}+ }+ seenPath[resolved] = struct{}{}+ out = append(out, resolved)+ }++ for _, path := range findCudaLibsFromFS() {+ add(path)+ }+ for _, path := range findCudaLibsFromProc() {+ add(path)+ }+ return out+}++func isProcMapFilesPath(path string) bool {+ // /proc/<pid>/map_files/<start>-<end>+ return strings.HasPrefix(path, "/proc/") && strings.Contains(path, "/map_files/")+}++func inodeKey(dev, ino uint64) string {+ return fmt.Sprintf("%d:%d", dev, ino)+}++func findCudaLibsFromFS() []string {+ var out []string+ add := func(path string) {+ if path == "" {+ return+ }+ if _, err := os.Stat(path); err == nil {+ out = append(out, path)+ }+ }++ candidates := []string{+ "/usr/local/cuda/lib64/libcudart.so",+ "/usr/lib/x86_64-linux-gnu/libcudart.so",+ "/usr/lib/aarch64-linux-gnu/libcudart.so",+ "/usr/lib64/libcudart.so",+ "/usr/lib/libcudart.so",+ }+ if ldPath := os.Getenv("LD_LIBRARY_PATH"); ldPath != "" {+ for _, dir := range strings.Split(ldPath, ":") {+ candidates = append(candidates, filepath.Join(dir, "libcudart.so"))+ }+ }+ if cudaHome := os.Getenv("CUDA_HOME"); cudaHome != "" {+ candidates = append(candidates,+ filepath.Join(cudaHome, "lib64", "libcudart.so"),+ filepath.Join(cudaHome, "lib", "libcudart.so"),+ filepath.Join(cudaHome, "targets", "x86_64-linux", "lib", "libcudart.so"),+ filepath.Join(cudaHome, "targets", "aarch64-linux", "lib", "libcudart.so"),+ )+ }+ for _, path := range candidates {+ add(path)+ }++ globs := []string{+ "/usr/local/cuda*/lib64/libcudart.so*",+ "/usr/local/cuda*/targets/*/lib/libcudart.so*",+ "/usr/lib/x86_64-linux-gnu/libcudart.so*",+ "/usr/lib/aarch64-linux-gnu/libcudart.so*",+ "/usr/local/lib/python*/dist-packages/nvidia/cuda_runtime/lib/libcudart.so*",+ "/usr/lib/python*/site-packages/nvidia/cuda_runtime/lib/libcudart.so*",+ "/opt/conda/lib/libcudart.so*",+ "/opt/conda/lib/python*/site-packages/nvidia/cuda_runtime/lib/libcudart.so*",+ }+ for _, g := range globs {+ matches, _ := filepath.Glob(g)+ for _, m := range matches {+ base := filepath.Base(m)+ // Skip linker scripts / static archives accidentally matched by globs.+ if !strings.Contains(base, ".so") || strings.HasSuffix(base, ".a") {+ continue+ }+ out = append(out, m)+ }+ }+ return out+}++// findCudaLibsFromProc scans host process maps for loaded libcudart copies.+// Keeps cost low: skips kernel threads, and only fully parses map lines that+// mention libcudart (most processes have none).+func findCudaLibsFromProc() []string {+ entries, err := os.ReadDir("/proc")+ if err != nil {+ return nil+ }++ seenInode := make(map[string]struct{})+ var out []string++ for _, ent := range entries {+ if !ent.IsDir() {+ continue+ }+ pid, err := strconv.Atoi(ent.Name())+ if err != nil || pid <= 0 {+ continue+ }+ // Kernel threads have an empty cmdline; skip before opening maps.+ if !isUserspacePID(pid) {+ continue+ }+ for _, path := range cudaLibsForPID(pid) {+ fi, err := os.Stat(path)+ if err != nil {+ continue+ }+ if sys, ok := fi.Sys().(*syscall.Stat_t); ok {+ key := inodeKey(sys.Dev, sys.Ino)+ if _, ok := seenInode[key]; ok {+ continue+ }+ seenInode[key] = struct{}{}+ }+ out = append(out, path)+ }+ }+ return out+}++func isUserspacePID(pid int) bool {+ data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))+ return err == nil && len(data) > 0+}++func cudaLibsForPID(pid int) []string {+ mapsPath := fmt.Sprintf("/proc/%d/maps", pid)+ f, err := os.Open(mapsPath)+ if err != nil {+ return nil+ }+ defer f.Close()++ var out []string+ seen := make(map[string]struct{})+ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 0, 16*1024), 256*1024)+ for scanner.Scan() {+ line := scanner.Text()+ // Cheap reject: almost all map lines are unrelated.+ if !strings.Contains(line, "libcudart") {+ continue+ }+ addrRange, path, ok := parseMapsLibLine(line)+ if !ok || !isCudartPath(path) {+ continue+ }+ resolved := resolveMappedLib(pid, addrRange, path)+ if resolved == "" {+ continue+ }+ if _, ok := seen[resolved]; ok {+ continue+ }+ seen[resolved] = struct{}{}+ out = append(out, resolved)+ }+ return out+}++// parseMapsLibLine extracts the address range and pathname from a /proc/pid/maps line.+func parseMapsLibLine(line string) (addrRange, path string, ok bool) {+ fields := strings.Fields(line)+ if len(fields) < 6 {+ return "", "", false+ }+ // fields[1] permissions — prefer executable mappings for .so attach.+ perms := fields[1]+ if !strings.Contains(perms, "x") {+ return "", "", false+ }+ path = fields[5]+ // Pathnames can contain spaces; join remaining fields. Also strip " (deleted)".+ if len(fields) > 6 {+ path = strings.Join(fields[5:], " ")+ }+ path = strings.TrimSuffix(path, " (deleted)")+ if path == "" || path[0] != '/' {+ return "", "", false+ }+ return fields[0], path, true+}++func isCudartPath(path string) bool {+ base := strings.ToLower(filepath.Base(path))+ return strings.Contains(base, "libcudart.so")+}++// resolveMappedLib opens the library as seen by pid (cross mount-namespace).+// Prefer /proc/<pid>/map_files/<range> itself — that path always refers to the+// inode the process has mapped. Do not EvalSymlinks it to a container pathname+// that may collide with a different host file.+func resolveMappedLib(pid int, addrRange, path string) string {+ mapFile := fmt.Sprintf("/proc/%d/map_files/%s", pid, addrRange)+ if _, err := os.Stat(mapFile); err == nil {+ return mapFile+ }++ rootPath := fmt.Sprintf("/proc/%d/root%s", pid, path)+ if _, err := os.Stat(rootPath); err == nil {+ return rootPath+ }++ // Same mount namespace as the collector (bare metal / host binary).+ if _, err := os.Stat(path); err == nil {+ return path+ }+ return ""+}diff --git a/opentelemetry-gpu-collector/internal/ebpf/discover_test.go b/opentelemetry-gpu-collector/internal/ebpf/discover_test.gonew file mode 100644index 00000000..90108e53--- /dev/null+++ b/opentelemetry-gpu-collector/internal/ebpf/discover_test.go@@ -0,0 +1,96 @@+//go:build linux && (amd64 || arm64)++package ebpf++import (+ "testing"+ "time"+)++func TestParseMapsLibLine(t *testing.T) {+ tests := []struct {+ line string+ wantAddr string+ wantPath string+ wantOK bool+ }{+ {+ line: "7f8a2c000000-7f8a2c200000 r-xp 00000000 08:01 12345 /usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudart.so.11.0",+ wantAddr: "7f8a2c000000-7f8a2c200000",+ wantPath: "/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudart.so.11.0",+ wantOK: true,+ },+ {+ line: "7f8a2c000000-7f8a2c200000 r-xp 00000000 08:01 12345 /usr/local/cuda/lib64/libcudart.so.11.0 (deleted)",+ wantAddr: "7f8a2c000000-7f8a2c200000",+ wantPath: "/usr/local/cuda/lib64/libcudart.so.11.0",+ wantOK: true,+ },+ {+ line: "7f8a2c000000-7f8a2c200000 r--p 00000000 08:01 12345 /usr/local/cuda/lib64/libcudart.so",+ wantOK: false, // not executable+ },+ {+ line: "7f8a2c000000-7f8a2c200000 r-xp 00000000 08:01 12345 [vdso]",+ wantOK: false,+ },+ {+ line: "incomplete",+ wantOK: false,+ },+ }+ for _, tt := range tests {+ addr, path, ok := parseMapsLibLine(tt.line)+ if ok != tt.wantOK {+ t.Fatalf("parseMapsLibLine(%q) ok=%v want %v", tt.line, ok, tt.wantOK)+ }+ if !tt.wantOK {+ continue+ }+ if addr != tt.wantAddr || path != tt.wantPath {+ t.Fatalf("parseMapsLibLine(%q) = (%q,%q), want (%q,%q)", tt.line, addr, path, tt.wantAddr, tt.wantPath)+ }+ }+}++func TestCudaRescanInterval(t *testing.T) {+ if got := cudaRescanInterval(false); got != 30*time.Second {+ t.Fatalf("waiting interval = %v, want 30s", got)+ }+ if got := cudaRescanInterval(true); got != 5*time.Minute {+ t.Fatalf("attached interval = %v, want 5m", got)+ }+}++func TestIsProcMapFilesPath(t *testing.T) {+ if !isProcMapFilesPath("/proc/1/map_files/7f-8f") {+ t.Fatal("expected map_files path")+ }+ if isProcMapFilesPath("/usr/local/cuda/lib64/libcudart.so") {+ t.Fatal("plain path should not match")+ }+}++func TestIsCudartPath(t *testing.T) {+ yes := []string{+ "/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudart.so.11.0",+ "/usr/local/cuda/lib64/libcudart.so",+ "/opt/conda/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12",+ }+ no := []string{+ "/usr/lib/libcuda.so.1",+ "/usr/local/cuda/lib64/libcudart_static.a",+ "/usr/lib/libamdhip64.so",+ "",+ }+ for _, p := range yes {+ if !isCudartPath(p) {+ t.Errorf("isCudartPath(%q) = false, want true", p)+ }+ }+ for _, p := range no {+ if isCudartPath(p) {+ t.Errorf("isCudartPath(%q) = true, want false", p)+ }+ }+}diff --git a/opentelemetry-gpu-collector/internal/ebpf/symbols.go b/opentelemetry-gpu-collector/internal/ebpf/symbols.goindex 9e67e1e6..888b897e 100644--- a/opentelemetry-gpu-collector/internal/ebpf/symbols.go+++ b/opentelemetry-gpu-collector/internal/ebpf/symbols.go@@ -41,6 +41,8 @@ func NewSymbolResolver(logger *slog.Logger) *SymbolResolver {}}+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()@@ -50,6 +52,13 @@ func (sr *SymbolResolver) Resolve(pid uint32, addr uint64) string {if !ok {st = sr.loadSymbols(pid)sr.mu.Lock()+ 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)+ break+ }+ }sr.cache[pid] = stsr.mu.Unlock()}@@ -117,7 +126,12 @@ func (sr *SymbolResolver) loadSymbols(pid uint32) *symbolTable {seen[path] = truebaseAddr := parseMapBase(fields[0])- symbols := loadELFSymbols(path)+ // Prefer the file as seen by the target process (other mount namespaces).+ libPath := resolveMappedLib(int(pid), fields[0], path)+ if libPath == "" {+ continue+ }+ symbols := loadELFSymbols(libPath)for _, sym := range symbols {st.entries = append(st.entries, symbolEntry{addr: baseAddr + sym.addr,diff --git a/opentelemetry-gpu-collector/internal/ebpf/tracer.go b/opentelemetry-gpu-collector/internal/ebpf/tracer.goindex 37ef5ab6..abb393d7 100644--- a/opentelemetry-gpu-collector/internal/ebpf/tracer.go+++ b/opentelemetry-gpu-collector/internal/ebpf/tracer.go@@ -9,17 +9,17 @@ import ("fmt""log/slog""os"- "path/filepath"- "strings""sync""sync/atomic"+ "syscall"+ "time""github.com/cilium/ebpf""github.com/cilium/ebpf/link""github.com/cilium/ebpf/ringbuf"+ "github.com/cilium/ebpf/rlimit")-// tracer.sh picks the bpf2go target arches from the host arch.//go:generate ./tracer.sh// Tracer manages eBPF programs for CUDA runtime interception.@@ -31,18 +31,31 @@ type Tracer struct {handler EventHandlersymbols *SymbolResolverrunning atomic.Bool+ closed atomic.Boolwg sync.WaitGroup+ dropped atomic.Uint64++ mu sync.Mutex+ attachedInode map[string]struct{} // successfully attached, or permanently skipped+ uprobes map[string]*ebpf.Program+ uretprobes map[string]*ebpf.Program+ stop chan struct{}+ runStarted bool}-// NewTracer loads eBPF programs and attaches uprobes to libcudart.so.+// NewTracer loads eBPF programs and attaches uprobes to CUDA libraries.+// Libraries are discovered from the filesystem and from /proc/*/maps (fleet-friendly+// with host PID visibility). If none are present yet, the tracer still starts and+// periodically rescans so late-starting CUDA workloads are picked up.func NewTracer(logger *slog.Logger, handler EventHandler) (*Tracer, error) {- cudaLib := findCudaLib()- if cudaLib == "" {- return nil, fmt.Errorf("libcudart.so not found; CUDA runtime is not installed")+ // BPF maps count against RLIMIT_MEMLOCK on kernels < 5.11 (and still can in+ // some container configs). Raise/remove the limit when permitted.+ if err := rlimit.RemoveMemlock(); err != nil {+ logger.Warn("could not raise RLIMIT_MEMLOCK; eBPF map load may fail",+ "error", err,+ "hint", "Docker: --ulimit memlock=-1:-1 (and CAP_BPF/CAP_PERFMON); Kubernetes: add securityContext.ulimits or privileged")}- logger.Info("found CUDA runtime library", "path", cudaLib)-spec, err := loadGpuevent()if err != nil {return nil, fmt.Errorf("loading eBPF spec: %w", err)@@ -54,59 +67,212 @@ func NewTracer(logger *slog.Logger, handler EventHandler) (*Tracer, error) {}t := &Tracer{- logger: logger,- objs: objs,- handler: handler,- symbols: NewSymbolResolver(logger),+ logger: logger,+ objs: objs,+ handler: handler,+ symbols: NewSymbolResolver(logger),+ attachedInode: make(map[string]struct{}),+ stop: make(chan struct{}),+ uprobes: map[string]*ebpf.Program{+ "cudaLaunchKernel": objs.HandleCudaLaunch,+ "cudaMalloc": objs.HandleCudaMallocEnter,+ "cudaFree": objs.HandleCudaFree,+ "cudaMemcpyAsync": objs.HandleCudaMemcpyAsync,+ "cudaStreamSynchronize": objs.HandleCudaStreamSyncEnter,+ "cudaSetDevice": objs.HandleCudaSetDeviceEnter,+ },+ uretprobes: map[string]*ebpf.Program{+ "cudaMalloc": objs.HandleCudaMalloc,+ "cudaMemcpy": objs.HandleCudaMemcpy,+ "cudaStreamSynchronize": objs.HandleCudaStreamSync,+ "cudaDeviceSynchronize": objs.HandleCudaDeviceSync,+ "cudaSetDevice": objs.HandleCudaSetDevice,+ },}- ex, err := link.OpenExecutable(cudaLib)+ n := t.attachNewCudaLibs()+ if n == 0 {+ logger.Info("no CUDA runtime found yet; rescanning /proc for libcudart (Docker --pid=host / Kubernetes hostPID recommended)")+ }++ t.reader, err = ringbuf.NewReader(objs.GpuEvents)if err != nil {- t.Close()- return nil, fmt.Errorf("opening %s: %w", cudaLib, err)+ // Do not call Close()/wg.Wait() here — Run has not started. Free BPF objs only.+ t.closed.Store(true)+ close(t.stop)+ objs.Close()+ t.objs = nil+ return nil, fmt.Errorf("creating ring buffer reader: %w", err)}- probes := map[string]*ebpf.Program{- "cudaLaunchKernel": objs.HandleCudaLaunch,- "cudaMalloc": objs.HandleCudaMalloc,- "cudaMemcpy": objs.HandleCudaMemcpy,- "cudaMemcpyAsync": objs.HandleCudaMemcpy,+ return t, nil+}++// attachNewCudaLibs discovers libcudart copies and attaches probes to new inodes.+// Returns the number of libraries newly attached.+func (t *Tracer) attachNewCudaLibs() int {+ if t.closed.Load() {+ return 0+ }+ libs := findCudaLibs()+ attached := 0+ for _, cudaLib := range libs {+ if t.attachCudaLib(cudaLib) {+ attached+++ }+ }+ return attached+}++func (t *Tracer) attachCudaLib(cudaLib string) bool {+ if t.closed.Load() {+ return false+ }+ fi, err := os.Stat(cudaLib)+ if err != nil {+ return false+ }+ var key string+ if sys, ok := fi.Sys().(*syscall.Stat_t); ok {+ key = fmt.Sprintf("%d:%d", sys.Dev, sys.Ino)+ } else {+ key = cudaLib+ }++ // Reserve the inode under the lock so concurrent rescans cannot double-attach.+ t.mu.Lock()+ if _, ok := t.attachedInode[key]; ok {+ t.mu.Unlock()+ return false+ }+ t.attachedInode[key] = struct{}{}+ t.mu.Unlock()++ unreserve := func() {+ t.mu.Lock()+ delete(t.attachedInode, key)+ t.mu.Unlock()+ }++ t.logger.Info("attaching CUDA probes", "path", cudaLib)+ ex, err := link.OpenExecutable(cudaLib)+ if err != nil {+ t.logger.Warn("opening CUDA lib failed", "path", cudaLib, "error", err)+ unreserve() // transient (e.g. process exited); allow retry+ return false}- for sym, prog := range probes {+ var newLinks []link.Link+ for sym, prog := range t.uprobes {+ if prog == nil {+ continue+ }l, err := ex.Uprobe(sym, prog, nil)if err != nil {- logger.Warn("failed to attach uprobe", "symbol", sym, "error", err)+ t.logger.Warn("failed to attach uprobe", "symbol", sym, "path", cudaLib, "error", err)continue}- t.links = append(t.links, l)- logger.Info("attached uprobe", "symbol", sym)+ newLinks = append(newLinks, l)+ t.logger.Info("attached uprobe", "symbol", sym, "path", cudaLib)+ }+ for sym, prog := range t.uretprobes {+ if prog == nil {+ continue+ }+ l, err := ex.Uretprobe(sym, prog, nil)+ if err != nil {+ t.logger.Warn("failed to attach uretprobe", "symbol", sym, "path", cudaLib, "error", err)+ continue+ }+ newLinks = append(newLinks, l)+ t.logger.Info("attached uretprobe", "symbol", sym, "path", cudaLib)}- if len(t.links) == 0 {- t.Close()- return nil, fmt.Errorf("no uprobes attached; CUDA symbols not found in %s", cudaLib)+ if len(newLinks) == 0 {+ // Keep inode reserved to avoid log spam every rescan on stripped/non-CUDA .so.+ t.logger.Warn("no CUDA symbols attached; skipping further attempts for this library", "path", cudaLib)+ return false}- t.reader, err = ringbuf.NewReader(objs.GpuEvents)- if err != nil {- t.Close()- return nil, fmt.Errorf("creating ring buffer reader: %w", err)+ if t.closed.Load() {+ for _, l := range newLinks {+ l.Close()+ }+ return false}- return t, nil+ t.mu.Lock()+ t.links = append(t.links, newLinks...)+ t.mu.Unlock()+ return true}-// Run starts reading events from the ring buffer. Blocks until ctx is cancelled.+func (t *Tracer) hasAttachedProbes() bool {+ t.mu.Lock()+ defer t.mu.Unlock()+ return len(t.links) > 0+}++// cudaRescanInterval keeps discovery snappy until the first attach, then backs+// off so fleet nodes are not full-/proc-scanned every 30s forever.+func cudaRescanInterval(hasProbes bool) time.Duration {+ if hasProbes {+ return 5 * time.Minute+ }+ return 30 * time.Second+}++// Dropped returns approximate count of events that failed ringbuf reserve (not+// directly visible from userspace; reserved for future BPF stats map).+func (t *Tracer) Dropped() uint64 { return t.dropped.Load() }++// Run starts reading events from the ring buffer. Blocks until ctx is cancelled+// or Close is called.func (t *Tracer) Run(ctx context.Context) {+ t.mu.Lock()+ if t.closed.Load() {+ t.mu.Unlock()+ return+ }+ t.wg.Add(2) // this goroutine + rescan+ t.runStarted = truet.running.Store(true)- t.wg.Add(1)+ t.mu.Unlock()defer t.wg.Done()+ go func() {+ defer t.wg.Done()+ // Fast while waiting for the first libcudart; back off once attached so+ // steady-state /proc scans stay cheap on busy nodes.+ interval := 30 * time.Second+ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.stop:+ return+ case <-ticker.C:+ n := t.attachNewCudaLibs()+ if n > 0 {+ t.logger.Info("attached CUDA probes after /proc rescan", "libraries", n)+ }+ next := cudaRescanInterval(t.hasAttachedProbes())+ if next != interval {+ interval = next+ ticker.Reset(interval)+ }+ }+ }+ }()+for {select {case <-ctx.Done():return+ case <-t.stop:+ returndefault:}@@ -115,6 +281,9 @@ func (t *Tracer) Run(ctx context.Context) {if errors.Is(err, ringbuf.ErrClosed) {return}+ if t.closed.Load() {+ return+ }t.logger.Warn("ring buffer read error", "error", err)continue}@@ -132,113 +301,136 @@ func (t *Tracer) processRecord(data []byte) {switch eventType {case EventTypeKernelLaunch:t.processKernelLaunch(data)- case EventTypeMalloc:- t.processMalloc(data)+ case EventTypeMalloc, EventTypeFree:+ t.processMalloc(data, eventType)case EventTypeMemcpy:t.processMemcpy(data)+ case EventTypeSync, EventTypeSyncDevice:+ t.processSync(data, eventType == EventTypeSyncDevice)+ case EventTypeSetDevice:+ t.processSetDevice(data)default:t.logger.Debug("unknown GPU event type", "type", eventType)}}+func parseHeader(data []byte) (eventMeta, bool) {+ // cuda_event_header_t: type(1)+pad(1)+device_idx(2)+pid(4)+tid(4)+pad(4)+stream(8)+ktime(8) = 32+ if len(data) < 32 {+ return eventMeta{}, false+ }+ return eventMeta{+ PID: binary.LittleEndian.Uint32(data[4:8]),+ TID: binary.LittleEndian.Uint32(data[8:12]),+ DeviceIdx: binary.LittleEndian.Uint16(data[2:4]),+ StreamID: binary.LittleEndian.Uint64(data[16:24]),+ KtimeNs: binary.LittleEndian.Uint64(data[24:32]),+ }, true+}+func (t *Tracer) processKernelLaunch(data []byte) {- // Parse the gpu_kernel_launch_t struct.- // Layout: flags(1) + pad(3) + pid_info(12) + kern_func_off(8) + grid(12) + block(12) + ...- if len(data) < 48 {+ // header(32) + kern(8) + grid(12) + block(12) + shared(4) + pad(4) = 72+ if len(data) < 72 {return}-- ev := &KernelLaunchEvent{}- ev.PID = binary.LittleEndian.Uint32(data[4:8])- ev.KernelAddr = binary.LittleEndian.Uint64(data[16:24])- ev.GridX = binary.LittleEndian.Uint32(data[24:28])- ev.GridY = binary.LittleEndian.Uint32(data[28:32])- ev.GridZ = binary.LittleEndian.Uint32(data[32:36])- ev.BlockX = binary.LittleEndian.Uint32(data[36:40])- ev.BlockY = binary.LittleEndian.Uint32(data[40:44])- ev.BlockZ = binary.LittleEndian.Uint32(data[44:48])-+ meta, ok := parseHeader(data)+ if !ok {+ return+ }+ ev := &KernelLaunchEvent{eventMeta: meta}+ ev.KernelAddr = binary.LittleEndian.Uint64(data[32:40])+ ev.GridX = binary.LittleEndian.Uint32(data[40:44])+ ev.GridY = binary.LittleEndian.Uint32(data[44:48])+ ev.GridZ = binary.LittleEndian.Uint32(data[48:52])+ ev.BlockX = binary.LittleEndian.Uint32(data[52:56])+ ev.BlockY = binary.LittleEndian.Uint32(data[56:60])+ ev.BlockZ = binary.LittleEndian.Uint32(data[60:64])+ ev.SharedMemBytes = binary.LittleEndian.Uint32(data[64:68])ev.KernelName = t.symbols.Resolve(ev.PID, ev.KernelAddr)-t.handler(ev)}-func (t *Tracer) processMalloc(data []byte) {- // gpu_malloc_t: flags(1) + pad(3) + pid_info(12) + size(8) = 24 bytes- if len(data) < 24 {+func (t *Tracer) processMalloc(data []byte, typ uint8) {+ if len(data) < 40 {return}-- ev := &MallocEvent{}- ev.PID = binary.LittleEndian.Uint32(data[4:8])- ev.Size = binary.LittleEndian.Uint64(data[16:24])-+ meta, ok := parseHeader(data)+ if !ok {+ return+ }+ if typ == EventTypeFree {+ t.handler(&FreeEvent{eventMeta: meta})+ return+ }+ ev := &MallocEvent{eventMeta: meta}+ ev.Size = binary.LittleEndian.Uint64(data[32:40])t.handler(ev)}func (t *Tracer) processMemcpy(data []byte) {- if len(data) < 24 {+ if len(data) < 48 {return}-- ev := &MemcpyEvent{}- ev.Kind = data[1]- ev.PID = binary.LittleEndian.Uint32(data[4:8])- ev.Size = binary.LittleEndian.Uint64(data[16:24])-+ meta, ok := parseHeader(data)+ if !ok {+ return+ }+ ev := &MemcpyEvent{eventMeta: meta}+ ev.Size = binary.LittleEndian.Uint64(data[32:40])+ ev.Kind = data[40]t.handler(ev)}-// Close detaches all probes and frees resources.-func (t *Tracer) Close() {- if t.reader != nil {- t.reader.Close()+func (t *Tracer) processSync(data []byte, deviceWide bool) {+ meta, ok := parseHeader(data)+ if !ok {+ return}- for _, l := range t.links {- l.Close()+ t.handler(&SyncEvent{eventMeta: meta, DeviceWide: deviceWide})+}++func (t *Tracer) processSetDevice(data []byte) {+ if len(data) < 40 {+ return}- if t.objs != nil {- t.objs.Close()+ meta, ok := parseHeader(data)+ if !ok {+ return}- t.wg.Wait()+ ev := &SetDeviceEvent{eventMeta: meta}+ ev.Device = int32(binary.LittleEndian.Uint32(data[32:36]))+ t.handler(ev)}-// findCudaLib searches for libcudart.so in common locations.-func findCudaLib() string {- candidates := []string{- "/usr/local/cuda/lib64/libcudart.so",- "/usr/lib/x86_64-linux-gnu/libcudart.so",- "/usr/lib/aarch64-linux-gnu/libcudart.so",- "/usr/lib64/libcudart.so",- "/usr/lib/libcudart.so",+// Close detaches all probes and frees resources.+// Safe to call before Run. Callers should cancel the Run context first when active.+func (t *Tracer) Close() {+ t.mu.Lock()+ if t.closed.Load() {+ t.mu.Unlock()+ return}+ t.closed.Store(true)+ close(t.stop)+ started := t.runStarted+ t.mu.Unlock()- // Also check LD_LIBRARY_PATH- if ldPath := os.Getenv("LD_LIBRARY_PATH"); ldPath != "" {- for _, dir := range strings.Split(ldPath, ":") {- candidates = append(candidates, filepath.Join(dir, "libcudart.so"))- }+ if t.reader != nil {+ t.reader.Close()}-- // Check CUDA_HOME- if cudaHome := os.Getenv("CUDA_HOME"); cudaHome != "" {- candidates = append(candidates,- filepath.Join(cudaHome, "lib64", "libcudart.so"),- filepath.Join(cudaHome, "lib", "libcudart.so"),- )+ if started {+ t.wg.Wait()}- for _, path := range candidates {- if _, err := os.Stat(path); err == nil {- return path- }+ t.mu.Lock()+ links := t.links+ t.links = nil+ t.mu.Unlock()+ for _, l := range links {+ l.Close()}-- // Try to find via /etc/ld.so.cache by searching /usr/local/cuda*/lib64/- matches, _ := filepath.Glob("/usr/local/cuda*/lib64/libcudart.so")- if len(matches) > 0 {- return matches[len(matches)-1]+ if t.objs != nil {+ t.objs.Close()+ t.objs = nil}-- return ""}diff --git a/opentelemetry-gpu-collector/internal/ebpf/types.go b/opentelemetry-gpu-collector/internal/ebpf/types.goindex 9e19c7d4..9b49ae2c 100644--- a/opentelemetry-gpu-collector/internal/ebpf/types.go+++ b/opentelemetry-gpu-collector/internal/ebpf/types.go@@ -5,41 +5,86 @@ const (EventTypeKernelLaunch = 1EventTypeMalloc = 2EventTypeMemcpy = 3+ EventTypeSync = 4+ EventTypeSyncDevice = 5+ EventTypeSetDevice = 6+ EventTypeFree = 7)// CUDAEvent is the common interface for parsed ring buffer events.type CUDAEvent interface {EventType() uint8+ ProcessPID() uint32+}++type eventMeta struct {+ PID uint32+ TID uint32+ StreamID uint64+ KtimeNs uint64+ DeviceIdx uint16 // 0xffff = unknown}type KernelLaunchEvent struct {- PID uint32- KernelAddr uint64- GridX uint32- GridY uint32- GridZ uint32- BlockX uint32- BlockY uint32- BlockZ uint32- KernelName string+ eventMeta+ KernelAddr uint64+ GridX uint32+ GridY uint32+ GridZ uint32+ BlockX uint32+ BlockY uint32+ BlockZ uint32+ SharedMemBytes uint32+ KernelName string}-func (e *KernelLaunchEvent) EventType() uint8 { return EventTypeKernelLaunch }+func (e *KernelLaunchEvent) EventType() uint8 { return EventTypeKernelLaunch }+func (e *KernelLaunchEvent) ProcessPID() uint32 { return e.PID }type MallocEvent struct {- PID uint32+ eventMetaSize uint64}-func (e *MallocEvent) EventType() uint8 { return EventTypeMalloc }+func (e *MallocEvent) EventType() uint8 { return EventTypeMalloc }+func (e *MallocEvent) ProcessPID() uint32 { return e.PID }type MemcpyEvent struct {- PID uint32+ eventMetaSize uint64Kind uint8}-func (e *MemcpyEvent) EventType() uint8 { return EventTypeMemcpy }+func (e *MemcpyEvent) EventType() uint8 { return EventTypeMemcpy }+func (e *MemcpyEvent) ProcessPID() uint32 { return e.PID }++type SyncEvent struct {+ eventMeta+ DeviceWide bool+}++func (e *SyncEvent) EventType() uint8 {+ if e.DeviceWide {+ return EventTypeSyncDevice+ }+ return EventTypeSync+}+func (e *SyncEvent) ProcessPID() uint32 { return e.PID }++type SetDeviceEvent struct {+ eventMeta+ Device int32+}++func (e *SetDeviceEvent) EventType() uint8 { return EventTypeSetDevice }+func (e *SetDeviceEvent) ProcessPID() uint32 { return e.PID }++type FreeEvent struct {+ eventMeta+}++func (e *FreeEvent) EventType() uint8 { return EventTypeFree }+func (e *FreeEvent) ProcessPID() uint32 { return e.PID }// MemcpyKindString returns a human-readable string for cudaMemcpyKind.func MemcpyKindString(kind uint8) string {@@ -59,3 +104,14 @@ func MemcpyKindString(kind uint8) string {// EventHandler is called for each parsed CUDA event.type EventHandler func(CUDAEvent)++// MultiplexHandlers returns a handler that fans out to all given handlers.+func MultiplexHandlers(handlers ...EventHandler) EventHandler {+ return func(ev CUDAEvent) {+ for _, h := range handlers {+ if h != nil {+ h(ev)+ }+ }+ }+}diff --git a/opentelemetry-gpu-collector/internal/ebpf/types_test.go b/opentelemetry-gpu-collector/internal/ebpf/types_test.goindex 65b5f6cb..9784e4c1 100644--- a/opentelemetry-gpu-collector/internal/ebpf/types_test.go+++ b/opentelemetry-gpu-collector/internal/ebpf/types_test.go@@ -61,4 +61,7 @@ func TestCUDAEventInterface(t *testing.T) {var _ CUDAEvent = (*KernelLaunchEvent)(nil)var _ CUDAEvent = (*MallocEvent)(nil)var _ CUDAEvent = (*MemcpyEvent)(nil)+ var _ CUDAEvent = (*SyncEvent)(nil)+ var _ CUDAEvent = (*SetDeviceEvent)(nil)+ var _ CUDAEvent = (*FreeEvent)(nil)}diff --git a/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go b/opentelemetry-gpu-collector/internal/export/ebpfmetrics.goindex 7947b662..df67a007 100644--- a/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go+++ b/opentelemetry-gpu-collector/internal/export/ebpfmetrics.go@@ -4,29 +4,38 @@ import ("context""fmt""log/slog"+ "math"+ "strconv""sync"+ "time""go.opentelemetry.io/otel/attribute""go.opentelemetry.io/otel/metric"sdkmetric "go.opentelemetry.io/otel/sdk/metric"gpuebpf "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/ebpf"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procname"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/workload")// EBPFMetrics records eBPF CUDA tracing events as OTel metrics.type EBPFMetrics struct {logger *slog.Logger- mu sync.Mutex- kernelLaunchCalls metric.Int64Counter- kernelGridSize metric.Float64Histogram- kernelBlockSize metric.Float64Histogram- memoryAllocations metric.Int64Counter- memoryCopies metric.Float64Histogram+ kernelLaunchCalls metric.Int64Counter+ kernelGridSize metric.Float64Histogram+ kernelBlockSize metric.Float64Histogram+ kernelSharedMemory metric.Float64Histogram+ memoryAllocations metric.Int64Counter+ memoryCopies metric.Float64Histogram++ devices *cudaDeviceTracker}// NewEBPFMetrics creates OTel instruments for eBPF CUDA event metrics.-func NewEBPFMetrics(provider *sdkmetric.MeterProvider, logger *slog.Logger) (*EBPFMetrics, error) {+// devices is used to map cudaSetDevice indices → hw.id / gpu.index when known.+func NewEBPFMetrics(provider *sdkmetric.MeterProvider, devices []gpu.Device, logger *slog.Logger) (*EBPFMetrics, error) {meter := provider.Meter("otelcol.gpu.ebpf",metric.WithInstrumentationVersion("1.0.0"),)@@ -55,9 +64,17 @@ func NewEBPFMetrics(provider *sdkmetric.MeterProvider, logger *slog.Logger) (*EBreturn nil, fmt.Errorf("creating gpu.kernel.block.size: %w", err)}+ sharedMem, err := meter.Float64Histogram("gpu.kernel.shared_memory",+ metric.WithDescription("Dynamic shared memory requested per CUDA kernel launch (cudaLaunchKernel sharedMem)"),+ metric.WithUnit("By"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating gpu.kernel.shared_memory: %w", err)+ }+memAlloc, err := meter.Int64Counter("gpu.memory.allocations",metric.WithDescription("Total bytes allocated via cudaMalloc"),- metric.WithUnit("bytes"),+ metric.WithUnit("By"),)if err != nil {return nil, fmt.Errorf("creating gpu.memory.allocations: %w", err)@@ -65,34 +82,215 @@ func NewEBPFMetrics(provider *sdkmetric.MeterProvider, logger *slog.Logger) (*EBmemCopies, err := meter.Float64Histogram("gpu.memory.copies",metric.WithDescription("Bytes copied per cudaMemcpy operation"),- metric.WithUnit("bytes"),+ metric.WithUnit("By"),)if err != nil {return nil, fmt.Errorf("creating gpu.memory.copies: %w", err)}return &EBPFMetrics{- logger: logger,- kernelLaunchCalls: kernelCalls,- kernelGridSize: gridSize,- kernelBlockSize: blockSize,- memoryAllocations: memAlloc,- memoryCopies: memCopies,+ logger: logger,+ kernelLaunchCalls: kernelCalls,+ kernelGridSize: gridSize,+ kernelBlockSize: blockSize,+ kernelSharedMemory: sharedMem,+ memoryAllocations: memAlloc,+ memoryCopies: memCopies,+ devices: newCUDADeviceTracker(devices),}, nil}+// cudaDeviceTracker maps cudaSetDevice(index) onto NVML device identity so+// activity metrics can carry hw.id / gpu.index for device-scoped dashboards.+type cudaDeviceTracker struct {+ mu sync.Mutex++ indexUUID map[int]string+ indexName map[int]string+ threadDev map[uint64]int // pid<<32|tid → CUDA device index+ soleIndex int // set when exactly one NVIDIA device; else -1+}++const threadDevMaxSize = 8192++func newCUDADeviceTracker(devices []gpu.Device) *cudaDeviceTracker {+ t := &cudaDeviceTracker{+ indexUUID: make(map[int]string),+ indexName: make(map[int]string),+ threadDev: make(map[uint64]int),+ soleIndex: -1,+ }+ n := 0+ sole := -1+ for _, d := range devices {+ info := d.Info()+ if info.Vendor != gpu.VendorNVIDIA || info.UUID == "" {+ continue+ }+ t.indexUUID[info.Index] = info.UUID+ t.indexName[info.Index] = info.Name+ sole = info.Index+ n+++ }+ if n == 1 {+ t.soleIndex = sole+ }+ return t+}++func threadDeviceKey(pid, tid uint32) uint64 {+ return uint64(pid)<<32 | uint64(tid)+}++func (t *cudaDeviceTracker) noteSetDevice(pid, tid uint32, deviceIdx int) {+ if t == nil || deviceIdx < 0 {+ return+ }+ t.mu.Lock()+ defer t.mu.Unlock()+ if _, ok := t.indexUUID[deviceIdx]; !ok {+ return+ }+ if len(t.threadDev) >= threadDevMaxSize {+ // Bound memory on long-lived nodes with high thread churn.+ n := 0+ for k := range t.threadDev {+ delete(t.threadDev, k)+ n+++ if n >= threadDevMaxSize/2 {+ break+ }+ }+ }+ t.threadDev[threadDeviceKey(pid, tid)] = deviceIdx+}++// deviceAttrs returns hw.id / gpu.index / hw.name when the thread (or sole GPU) is known.+func (t *cudaDeviceTracker) deviceAttrs(pid, tid uint32) []attribute.KeyValue {+ if t == nil {+ return nil+ }+ t.mu.Lock()+ defer t.mu.Unlock()++ idx, ok := t.threadDev[threadDeviceKey(pid, tid)]+ if !ok {+ if t.soleIndex < 0 {+ return nil+ }+ idx = t.soleIndex+ }+ uuid := t.indexUUID[idx]+ if uuid == "" {+ return nil+ }+ attrs := []attribute.KeyValue{+ attribute.String("hw.id", uuid),+ attribute.Int("gpu.index", idx),+ }+ if name := t.indexName[idx]; name != "" {+ attrs = append(attrs, attribute.String("hw.name", name))+ }+ return attrs+}++type pidAttrCacheEntry struct {+ attrs []attribute.KeyValue+ expires time.Time+}++var (+ pidAttrMu sync.Mutex+ pidAttrCache = make(map[uint32]pidAttrCacheEntry)+)++const (+ pidAttrTTL = 5 * time.Second+ pidAttrMaxSize = 4096+)++func cachedPIDAttrs(pid uint32) []attribute.KeyValue {+ now := time.Now()+ pidAttrMu.Lock()+ if e, ok := pidAttrCache[pid]; ok && now.Before(e.expires) {+ attrs := e.attrs+ pidAttrMu.Unlock()+ return attrs+ }+ pidAttrMu.Unlock()++ attrs := []attribute.KeyValue{+ attribute.String("process.pid", strconv.FormatUint(uint64(pid), 10)),+ }+ if pid <= math.MaxInt32 {+ pid32 := int32(pid)+ attrs = append(attrs, attribute.String("process.executable.name", procname.ExecutableName(pid32)))+ if pod, ok := workload.ResolvePod(pid32); ok {+ if pod.PodUID != "" {+ attrs = append(attrs, attribute.String("k8s.pod.uid", pod.PodUID))+ }+ if pod.PodName != "" {+ attrs = append(attrs, attribute.String("k8s.pod.name", pod.PodName))+ }+ if pod.Namespace != "" {+ attrs = append(attrs, attribute.String("k8s.namespace.name", pod.Namespace))+ }+ }+ }++ pidAttrMu.Lock()+ if len(pidAttrCache) >= pidAttrMaxSize {+ // Drop expired entries; if still full, clear half.+ for k, e := range pidAttrCache {+ if now.After(e.expires) {+ delete(pidAttrCache, k)+ }+ }+ if len(pidAttrCache) >= pidAttrMaxSize {+ n := 0+ for k := range pidAttrCache {+ delete(pidAttrCache, k)+ n+++ if n >= pidAttrMaxSize/2 {+ break+ }+ }+ }+ }+ pidAttrCache[pid] = pidAttrCacheEntry{attrs: attrs, expires: now.Add(pidAttrTTL)}+ pidAttrMu.Unlock()+ return attrs+}++func (em *EBPFMetrics) activityAttrs(pid, tid uint32, extra ...attribute.KeyValue) metric.MeasurementOption {+ base := cachedPIDAttrs(pid)+ var dev []attribute.KeyValue+ if em.devices != nil {+ dev = em.devices.deviceAttrs(pid, tid)+ }+ attrs := make([]attribute.KeyValue, 0, len(base)+len(dev)+len(extra))+ attrs = append(attrs, base...)+ attrs = append(attrs, dev...)+ attrs = append(attrs, extra...)+ return metric.WithAttributes(attrs...)+}+// HandleEvent processes a single CUDA event and records it as OTel metrics.-// This is the EventHandler passed to the eBPF Tracer.func (em *EBPFMetrics) HandleEvent(ev gpuebpf.CUDAEvent) {ctx := context.Background()switch e := ev.(type) {+ case *gpuebpf.SetDeviceEvent:+ if em.devices != nil {+ em.devices.noteSetDevice(e.PID, e.TID, int(e.Device))+ }+case *gpuebpf.KernelLaunchEvent:kernelName := e.KernelNameif kernelName == "" {kernelName = fmt.Sprintf("0x%x", e.KernelAddr)}- attrs := metric.WithAttributes(attribute.String("cuda.kernel.name", kernelName))+ attrs := em.activityAttrs(e.PID, e.TID, attribute.String("cuda.kernel.name", kernelName))em.kernelLaunchCalls.Add(ctx, 1, attrs)@@ -102,13 +300,14 @@ func (em *EBPFMetrics) HandleEvent(ev gpuebpf.CUDAEvent) {blockTotal := float64(e.BlockX) * float64(e.BlockY) * float64(e.BlockZ)em.kernelBlockSize.Record(ctx, blockTotal, attrs)+ em.kernelSharedMemory.Record(ctx, float64(e.SharedMemBytes), attrs)+case *gpuebpf.MallocEvent:- em.memoryAllocations.Add(ctx, int64(e.Size))+ em.memoryAllocations.Add(ctx, int64(e.Size), em.activityAttrs(e.PID, e.TID))case *gpuebpf.MemcpyEvent:- attrs := metric.WithAttributes(+ em.memoryCopies.Record(ctx, float64(e.Size), em.activityAttrs(e.PID, e.TID,attribute.String("cuda.memcpy.kind", gpuebpf.MemcpyKindString(e.Kind)),- )- em.memoryCopies.Record(ctx, float64(e.Size), attrs)+ ))}}diff --git a/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go b/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.gonew file mode 100644index 00000000..569291f6--- /dev/null+++ b/opentelemetry-gpu-collector/internal/export/ebpfmetrics_test.go@@ -0,0 +1,87 @@+package export++import (+ "testing"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+)++func TestCUDADeviceTrackerSoleGPU(t *testing.T) {+ devs := []gpu.Device{+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-a", Index: 0, Name: "A100"}},+ }+ tr := newCUDADeviceTracker(devs)+ attrs := tr.deviceAttrs(1, 2)+ if len(attrs) < 2 {+ t.Fatalf("expected sole-GPU attrs, got %#v", attrs)+ }+ m := map[string]string{}+ for _, a := range attrs {+ m[string(a.Key)] = a.Value.Emit()+ }+ if m["hw.id"] != "gpu-a" {+ t.Fatalf("hw.id = %q", m["hw.id"])+ }+}++func TestCUDADeviceTrackerMultiGPUNeedsSetDevice(t *testing.T) {+ devs := []gpu.Device{+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-a", Index: 0, Name: "A100"}},+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-b", Index: 1, Name: "A100"}},+ }+ tr := newCUDADeviceTracker(devs)+ if attrs := tr.deviceAttrs(1, 2); len(attrs) != 0 {+ t.Fatalf("expected no attrs before SetDevice, got %#v", attrs)+ }+ tr.noteSetDevice(1, 2, 1)+ attrs := tr.deviceAttrs(1, 2)+ m := map[string]string{}+ for _, a := range attrs {+ m[string(a.Key)] = a.Value.Emit()+ }+ if m["hw.id"] != "gpu-b" {+ t.Fatalf("hw.id = %q, want gpu-b", m["hw.id"])+ }+ if m["gpu.index"] != "1" {+ t.Fatalf("gpu.index = %q, want 1", m["gpu.index"])+ }+}++func TestCUDADeviceTrackerIgnoresUnknownIndex(t *testing.T) {+ devs := []gpu.Device{+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-a", Index: 0}},+ }+ tr := newCUDADeviceTracker(devs)+ tr.noteSetDevice(1, 2, 9) // unknown CUDA index — ignored+ attrs := tr.deviceAttrs(1, 2)+ if len(attrs) == 0 {+ t.Fatal("sole GPU should still attribute")+ }+}++func TestCUDADeviceTrackerBoundsThreadMap(t *testing.T) {+ devs := []gpu.Device{+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-a", Index: 0}},+ &mockDevice{info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA, UUID: "gpu-b", Index: 1}},+ }+ tr := newCUDADeviceTracker(devs)+ // Force eviction path without allocating 8k entries in the test by+ // temporarily shrinking via filling past the cap with a local override.+ // We call noteSetDevice enough times that len exceeds threadDevMaxSize after+ // pre-seeding — use a smaller loop by filling the map directly then noting.+ for i := 0; i < threadDevMaxSize; i++ {+ tr.threadDev[uint64(i)] = 0+ }+ tr.noteSetDevice(42, 7, 1)+ if len(tr.threadDev) > threadDevMaxSize {+ t.Fatalf("threadDev grew unbounded: %d", len(tr.threadDev))+ }+ attrs := tr.deviceAttrs(42, 7)+ m := map[string]string{}+ for _, a := range attrs {+ m[string(a.Key)] = a.Value.Emit()+ }+ if m["hw.id"] != "gpu-b" {+ t.Fatalf("after eviction, latest SetDevice should stick; hw.id=%q", m["hw.id"])+ }+}diff --git a/opentelemetry-gpu-collector/internal/export/metrics.go b/opentelemetry-gpu-collector/internal/export/metrics.goindex c4fad0ce..b2bd9df1 100644--- a/opentelemetry-gpu-collector/internal/export/metrics.go+++ b/opentelemetry-gpu-collector/internal/export/metrics.go@@ -4,35 +4,47 @@ import ("context""fmt""log/slog"+ "strconv"+ "time""go.opentelemetry.io/otel/attribute""go.opentelemetry.io/otel/metric"sdkmetric "go.opentelemetry.io/otel/sdk/metric"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/config""github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/classify"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procinfo"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/workload")// MetricsCollector registers OTel observable instruments that poll GPU devices on each collection cycle.type MetricsCollector struct {devices []gpu.Devicelogger *slog.Logger+ cfg *config.Config+ pods *workload.Enricherreg []metric.Registration}// NewMetricsCollector creates all GPU metric instruments and registers callbacks.// Metric names and attributes follow the OpenTelemetry semantic conventions for hardware:// https://opentelemetry.io/docs/specs/semconv/hardware/gpu/-func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Device, logger *slog.Logger) (*MetricsCollector, error) {+func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Device, logger *slog.Logger, cfg *config.Config) (*MetricsCollector, error) {+ if cfg == nil {+ cfg = config.Load()+ }mc := &MetricsCollector{devices: devices,logger: logger,+ cfg: cfg,+ pods: workload.NewEnricher(cfg, logger),}meter := provider.Meter("otelcol.gpu.collector",metric.WithInstrumentationVersion("1.0.0"),)- // hw.gpu.utilization — general + encoder + decoder via hw.gpu.task attributegpuUtilization, err := meter.Float64ObservableGauge("hw.gpu.utilization",metric.WithDescription("GPU utilization"),metric.WithUnit("1"),@@ -41,7 +53,6 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.gpu.utilization: %w", err)}- // hw.gpu.memory.utilizationmemUtilization, err := meter.Float64ObservableGauge("hw.gpu.memory.utilization",metric.WithDescription("GPU memory utilization"),metric.WithUnit("1"),@@ -50,7 +61,6 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.gpu.memory.utilization: %w", err)}- // hw.gpu.memory.limit — total memorymemLimit, err := meter.Int64ObservableUpDownCounter("hw.gpu.memory.limit",metric.WithDescription("Total GPU memory"),metric.WithUnit("By"),@@ -59,7 +69,6 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.gpu.memory.limit: %w", err)}- // hw.gpu.memory.usage — used memorymemUsage, err := meter.Int64ObservableUpDownCounter("hw.gpu.memory.usage",metric.WithDescription("Used GPU memory"),metric.WithUnit("By"),@@ -68,7 +77,6 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.gpu.memory.usage: %w", err)}- // hw.errors — ECC and PCIe errorshwErrors, err := meter.Int64ObservableCounter("hw.errors",metric.WithDescription("GPU hardware error count"),metric.WithUnit("{error}"),@@ -77,7 +85,6 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.errors: %w", err)}- // Custom metrics not covered by the spectemperature, err := meter.Float64ObservableGauge("hw.gpu.temperature",metric.WithDescription("GPU temperature"),metric.WithUnit("Cel"),@@ -142,21 +149,101 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn nil, fmt.Errorf("creating hw.gpu.clock.memory: %w", err)}+ gpuUp, err := meter.Float64ObservableGauge("hw.gpu.up",+ metric.WithDescription("1 when the GPU was successfully scraped"),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.up: %w", err)+ }++ gpuAllocated, err := meter.Float64ObservableGauge("hw.gpu.allocated",+ metric.WithDescription("1 when the GPU has process memory or util above threshold"),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.allocated: %w", err)+ }++ gpuIdle, err := meter.Float64ObservableGauge("hw.gpu.idle",+ metric.WithDescription("Idle ratio (1 - utilization) when utilization is known"),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.idle: %w", err)+ }++ pcieThroughput, err := meter.Float64ObservableGauge("hw.gpu.pcie.throughput",+ metric.WithDescription("PCIe throughput"),+ metric.WithUnit("By/s"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.pcie.throughput: %w", err)+ }++ interconnectThroughput, err := meter.Float64ObservableGauge("hw.gpu.interconnect.throughput",+ metric.WithDescription("GPU interconnect throughput (NVLink/XGMI)"),+ metric.WithUnit("By/s"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.interconnect.throughput: %w", err)+ }++ throttled, err := meter.Float64ObservableGauge("hw.gpu.throttled",+ metric.WithDescription("1 when clock throttle reasons are active"),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating hw.gpu.throttled: %w", err)+ }++ procMemUsage, err := meter.Int64ObservableUpDownCounter("process.gpu.memory.usage",+ metric.WithDescription("GPU memory used by a process on a device"),+ metric.WithUnit("By"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating process.gpu.memory.usage: %w", err)+ }++ procUtil, err := meter.Float64ObservableGauge("process.gpu.utilization",+ metric.WithDescription("Per-process GPU utilization (sampled; 0.0–1.0)"),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating process.gpu.utilization: %w", err)+ }++ procUptime, err := meter.Float64ObservableGauge("process.uptime",+ metric.WithDescription("Process uptime in seconds for GPU-attributed processes"),+ metric.WithUnit("s"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating process.uptime: %w", err)+ }+reg, err := meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {for _, dev := range mc.devices {+ if err := ctx.Err(); err != nil {+ return err+ }+ info := dev.Info()+ attrs := deviceAttrs(info)+snap, err := dev.Collect()if err != nil {- mc.logger.Warn("collection failed", "gpu", dev.Info().Index, "error", err)+ mc.logger.Warn("collection failed", "gpu", info.Index, "error", err)+ o.ObserveFloat64(gpuUp, 0, metric.WithAttributeSet(attrs))continue}- info := dev.Info()- attrs := deviceAttrs(info)+ o.ObserveFloat64(gpuUp, 1, metric.WithAttributeSet(attrs))if snap.Utilization != nil {generalAttrs := attribute.NewSet(append(attrs.ToSlice(), attribute.String("hw.gpu.task", "general"))...)o.ObserveFloat64(gpuUtilization, *snap.Utilization/100.0, metric.WithAttributeSet(generalAttrs))+ idle := 1.0 - clamp01(*snap.Utilization/100.0)+ o.ObserveFloat64(gpuIdle, idle, metric.WithAttributeSet(attrs))}if snap.EncoderUtilization != nil {encAttrs := attribute.NewSet(append(attrs.ToSlice(), attribute.String("hw.gpu.task", "encoder"))...)@@ -232,6 +319,109 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Device)...)o.ObserveInt64(hwErrors, *snap.ECCDoubleBit, metric.WithAttributeSet(uncorrAttrs))}+ if snap.XIDErrors != nil {+ xidAttrs := attribute.NewSet(append(attrs.ToSlice(),+ attribute.String("hw.type", "gpu"),+ attribute.String("error.type", "xid"),+ )...)+ o.ObserveInt64(hwErrors, *snap.XIDErrors, metric.WithAttributeSet(xidAttrs))+ }+ if snap.RASCE != nil {+ a := attribute.NewSet(append(attrs.ToSlice(),+ attribute.String("hw.type", "gpu"),+ attribute.String("error.type", "ras_corrected"),+ )...)+ o.ObserveInt64(hwErrors, *snap.RASCE, metric.WithAttributeSet(a))+ }+ if snap.RASUE != nil {+ a := attribute.NewSet(append(attrs.ToSlice(),+ attribute.String("hw.type", "gpu"),+ attribute.String("error.type", "ras_uncorrected"),+ )...)+ o.ObserveInt64(hwErrors, *snap.RASUE, metric.WithAttributeSet(a))+ }++ if snap.PCIeRxBytesPerSec != nil {+ rx := attribute.NewSet(append(attrs.ToSlice(), attribute.String("network.io.direction", "receive"))...)+ o.ObserveFloat64(pcieThroughput, *snap.PCIeRxBytesPerSec, metric.WithAttributeSet(rx))+ }+ if snap.PCIeTxBytesPerSec != nil {+ tx := attribute.NewSet(append(attrs.ToSlice(), attribute.String("network.io.direction", "transmit"))...)+ o.ObserveFloat64(pcieThroughput, *snap.PCIeTxBytesPerSec, metric.WithAttributeSet(tx))+ }++ if mc.cfg.InterconnectEnabled {+ icType := snap.InterconnectType+ if icType == "" {+ icType = "other"+ }+ if snap.InterconnectRxBytesPerSec != nil {+ rx := attribute.NewSet(append(attrs.ToSlice(),+ attribute.String("network.io.direction", "receive"),+ attribute.String("hw.gpu.interconnect.type", icType),+ )...)+ o.ObserveFloat64(interconnectThroughput, *snap.InterconnectRxBytesPerSec, metric.WithAttributeSet(rx))+ }+ if snap.InterconnectTxBytesPerSec != nil {+ tx := attribute.NewSet(append(attrs.ToSlice(),+ attribute.String("network.io.direction", "transmit"),+ attribute.String("hw.gpu.interconnect.type", icType),+ )...)+ o.ObserveFloat64(interconnectThroughput, *snap.InterconnectTxBytesPerSec, metric.WithAttributeSet(tx))+ }+ }++ if snap.Throttled != nil {+ thAttrs := attrs.ToSlice()+ if snap.ThrottleReasons != nil && *snap.ThrottleReasons != "" {+ thAttrs = append(thAttrs, attribute.String("hw.gpu.throttle_reasons", *snap.ThrottleReasons))+ }+ o.ObserveFloat64(throttled, *snap.Throttled, metric.WithAttributeSet(attribute.NewSet(thAttrs...)))+ }++ procs, err := dev.CollectProcesses()+ if err != nil {+ mc.logger.Debug("CollectProcesses failed", "gpu", info.Index, "error", err)+ procs = nil+ }++ allocated := 0.0+ thresh := mc.cfg.AllocatedUtilThreshold+ if snap.Utilization != nil && *snap.Utilization/100.0 >= thresh {+ allocated = 1.0+ }+ procInfoCache := make(map[int32]procinfo.Info, len(procs))+ podCache := make(map[int32]workload.PodInfo, len(procs))+ for i := range procs {+ enrichProcess(mc.cfg, &procs[i], mc.pods, info.UUID, procInfoCache, podCache)+ if procs[i].MemoryBytes != nil && *procs[i].MemoryBytes > 0 {+ allocated = 1.0+ }+ }+ o.ObserveFloat64(gpuAllocated, allocated, metric.WithAttributeSet(attrs))++ for _, pu := range procs {+ pattrs := mc.attrsForProcess(info, pu, podCache)+ base := pattrs.ToSlice()+ if pu.MemoryBytes != nil {+ o.ObserveInt64(procMemUsage, *pu.MemoryBytes, metric.WithAttributeSet(pattrs))+ }+ if pu.Utilization != nil {+ general := attribute.NewSet(append(append([]attribute.KeyValue{}, base...), attribute.String("hw.gpu.task", "general"))...)+ o.ObserveFloat64(procUtil, *pu.Utilization, metric.WithAttributeSet(general))+ }+ if pu.EncoderUtil != nil {+ enc := attribute.NewSet(append(append([]attribute.KeyValue{}, base...), attribute.String("hw.gpu.task", "encoder"))...)+ o.ObserveFloat64(procUtil, *pu.EncoderUtil, metric.WithAttributeSet(enc))+ }+ if pu.DecoderUtil != nil {+ dec := attribute.NewSet(append(append([]attribute.KeyValue{}, base...), attribute.String("hw.gpu.task", "decoder"))...)+ o.ObserveFloat64(procUtil, *pu.DecoderUtil, metric.WithAttributeSet(dec))+ }+ if !pu.StartTime.IsZero() {+ o.ObserveFloat64(procUptime, time.Since(pu.StartTime).Seconds(), metric.WithAttributeSet(pattrs))+ }+ }}return nil},@@ -241,6 +431,9 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.DevicepowerDraw, powerLimit, energyConsumed,clockGraphics, clockMemory,hwErrors,+ gpuUp, gpuAllocated, gpuIdle,+ pcieThroughput, interconnectThroughput, throttled,+ procMemUsage, procUtil, procUptime,)if err != nil {return nil, fmt.Errorf("registering callback: %w", err)@@ -250,21 +443,149 @@ func NewMetricsCollector(provider *sdkmetric.MeterProvider, devices []gpu.Devicereturn mc, nil}+func enrichProcess(cfg *config.Config, pu *gpu.ProcessUsage, pods *workload.Enricher, deviceID string, cache map[int32]procinfo.Info, podCache map[int32]workload.PodInfo) {+ info, ok := cache[pu.PID]+ if !ok {+ info = procinfo.Lookup(pu.PID)+ cache[pu.PID] = info+ }+ if cfg.ProcessCmdline && info.CommandLine != "" {+ pu.CommandLine = truncate(info.CommandLine, cfg.ProcessCmdlineMaxLen)+ }+ pu.UserID = info.UserID+ pu.Username = info.Username+ pu.State = info.State+ pu.StartTime = info.StartTime++ // Classify from full cmdline; attribute export may use a truncated copy.+ cl := classify.FromProcess(pu.ExecutableName, info.CommandLine)+ pu.WorkloadKind = cl.Kind+ pu.WorkloadFramework = cl.Framework++ if pods != nil {+ if pod, ok := pods.Resolve(pu.PID, deviceID); ok {+ podCache[pu.PID] = pod+ if pu.ContainerID == "" && pod.ContainerID != "" {+ pu.ContainerID = pod.ContainerID+ }+ }+ }+}++func truncate(s string, max int) string {+ if max <= 0 || len(s) <= max {+ return s+ }+ return s[:max]+}++func clamp01(v float64) float64 {+ if v < 0 {+ return 0+ }+ if v > 1 {+ return 1+ }+ return v+}+// Close unregisters all metric callbacks.func (mc *MetricsCollector) Close() {for _, r := range mc.reg {_ = r.Unregister()}+ if mc.pods != nil {+ mc.pods.Close()+ }}// deviceAttrs returns the standard hw.* attribute set for a GPU device.-// hw.id is required; hw.name, hw.vendor are recommended by the spec.func deviceAttrs(info gpu.DeviceInfo) attribute.Set {- return attribute.NewSet(+ attrs := []attribute.KeyValue{attribute.String("hw.id", info.UUID),attribute.String("hw.name", info.Name),attribute.String("hw.vendor", string(info.Vendor)),attribute.Int("gpu.index", info.Index),attribute.String("gpu.pci_address", info.PCIAddress),- )+ }+ if info.IsMIG {+ attrs = append(attrs,+ attribute.Bool("gpu.mig.enabled", true),+ attribute.String("gpu.mig.device_id", info.MIGDeviceID),+ attribute.String("gpu.parent.uuid", info.ParentUUID),+ )+ if info.MIGInstanceID >= 0 {+ attrs = append(attrs, attribute.Int("gpu.mig.instance_id", info.MIGInstanceID))+ }+ if info.MIGProfileName != "" {+ attrs = append(attrs, attribute.String("gpu.mig.profile", info.MIGProfileName))+ }+ }+ return attribute.NewSet(attrs...)+}++func processAttrs(info gpu.DeviceInfo, pu gpu.ProcessUsage) attribute.Set {+ attrs := []attribute.KeyValue{+ attribute.String("hw.id", info.UUID),+ attribute.String("hw.name", info.Name),+ attribute.String("hw.vendor", string(info.Vendor)),+ attribute.Int("gpu.index", info.Index),+ attribute.String("gpu.pci_address", info.PCIAddress),+ attribute.String("process.pid", strconv.FormatInt(int64(pu.PID), 10)),+ attribute.String("process.executable.name", pu.ExecutableName),+ }+ if pu.CommandLine != "" {+ attrs = append(attrs, attribute.String("process.command_line", pu.CommandLine))+ }+ if pu.State != "" {+ attrs = append(attrs, attribute.String("process.state", pu.State))+ }+ if pu.UserID != "" {+ attrs = append(attrs, attribute.String("process.owner.userid", pu.UserID))+ }+ if pu.Username != "" {+ attrs = append(attrs, attribute.String("process.owner", pu.Username))+ }+ // process.start_time is intentionally omitted from metric attributes (high+ // cardinality). process.uptime already covers process lifetime.+ if pu.WorkloadKind != "" {+ attrs = append(attrs, attribute.String("process.workload.kind", pu.WorkloadKind))+ }+ if pu.WorkloadFramework != "" {+ attrs = append(attrs, attribute.String("process.workload.framework", pu.WorkloadFramework))+ }+ if pu.ContainerID != "" {+ attrs = append(attrs, attribute.String("container.id", pu.ContainerID))+ }+ return attribute.NewSet(attrs...)+}++// processAttrsWithPod merges pod enrichment into process attributes.+func processAttrsWithPod(info gpu.DeviceInfo, pu gpu.ProcessUsage, pod workload.PodInfo) attribute.Set {+ set := processAttrs(info, pu)+ base := set.ToSlice()+ if pod.PodUID != "" {+ base = append(base, attribute.String("k8s.pod.uid", pod.PodUID))+ }+ if pod.PodName != "" {+ base = append(base, attribute.String("k8s.pod.name", pod.PodName))+ }+ if pod.Namespace != "" {+ base = append(base, attribute.String("k8s.namespace.name", pod.Namespace))+ }+ if pod.ContainerName != "" {+ base = append(base, attribute.String("k8s.container.name", pod.ContainerName))+ }+ if pod.ContainerID != "" && pu.ContainerID == "" {+ base = append(base, attribute.String("container.id", pod.ContainerID))+ }+ return attribute.NewSet(base...)+}++// Used by callback — resolve pod and build attrs.+func (mc *MetricsCollector) attrsForProcess(info gpu.DeviceInfo, pu gpu.ProcessUsage, podCache map[int32]workload.PodInfo) attribute.Set {+ if pod, ok := podCache[pu.PID]; ok {+ return processAttrsWithPod(info, pu, pod)+ }+ return processAttrs(info, pu)}diff --git a/opentelemetry-gpu-collector/internal/export/metrics_test.go b/opentelemetry-gpu-collector/internal/export/metrics_test.goindex 6e041fcf..41fe2b0a 100644--- a/opentelemetry-gpu-collector/internal/export/metrics_test.go+++ b/opentelemetry-gpu-collector/internal/export/metrics_test.go@@ -10,17 +10,21 @@ import ("github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu")+func (m *mockDevice) Info() gpu.DeviceInfo { return m.info }+func (m *mockDevice) Collect() (*gpu.Snapshot, error) { return m.snapshot, m.err }+func (m *mockDevice) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return m.processes, nil+}+func (m *mockDevice) Close() {}+// mockDevice implements gpu.Device for testing without real hardware.type mockDevice struct {- info gpu.DeviceInfo- snapshot *gpu.Snapshot- err error+ info gpu.DeviceInfo+ snapshot *gpu.Snapshot+ processes []gpu.ProcessUsage+ err error}-func (m *mockDevice) Info() gpu.DeviceInfo { return m.info }-func (m *mockDevice) Collect() (*gpu.Snapshot, error) { return m.snapshot, m.err }-func (m *mockDevice) Close() {}-func ptr[T any](v T) *T { return &v }func TestNewMetricsCollectorRegisters(t *testing.T) {@@ -57,7 +61,7 @@ func TestNewMetricsCollectorRegisters(t *testing.T) {}logger := slog.Default()- mc, err := NewMetricsCollector(provider, []gpu.Device{dev}, logger)+ mc, err := NewMetricsCollector(provider, []gpu.Device{dev}, logger, nil)if err != nil {t.Fatalf("NewMetricsCollector() error = %v", err)}@@ -100,6 +104,9 @@ func TestNewMetricsCollectorRegisters(t *testing.T) {"hw.gpu.clock.graphics","hw.gpu.clock.memory","hw.errors",+ "hw.gpu.up",+ "hw.gpu.allocated",+ "hw.gpu.idle",}for _, name := range wantMetrics {if !reported[name] {@@ -108,11 +115,67 @@ func TestNewMetricsCollectorRegisters(t *testing.T) {}}+func TestProcessGPUMetrics(t *testing.T) {+ reader := metric.NewManualReader()+ provider := metric.NewMeterProvider(metric.WithReader(reader))+ defer provider.Shutdown(t.Context())++ mem := int64(1024 * 1024)+ util := 0.42+ dev := &mockDevice{+ info: gpu.DeviceInfo{+ Vendor: gpu.VendorNVIDIA,+ Index: 0,+ Name: "Test GPU",+ UUID: "GPU-test-uuid-0000",+ PCIAddress: "0000:01:00.0",+ },+ snapshot: &gpu.Snapshot{+ Utilization: ptr(10.0),+ },+ processes: []gpu.ProcessUsage{{+ PID: 4242,+ ExecutableName: "python",+ MemoryBytes: &mem,+ Utilization: &util,+ }},+ }++ mc, err := NewMetricsCollector(provider, []gpu.Device{dev}, slog.Default(), nil)+ if err != nil {+ t.Fatalf("NewMetricsCollector: %v", err)+ }+ defer mc.Close()++ var rm metricdata.ResourceMetrics+ if err := reader.Collect(t.Context(), &rm); err != nil {+ t.Fatalf("Collect: %v", err)+ }++ foundMem, foundUtil := false, false+ for _, sm := range rm.ScopeMetrics {+ if sm.Scope.Name != "otelcol.gpu.collector" {+ continue+ }+ for _, m := range sm.Metrics {+ switch m.Name {+ case "process.gpu.memory.usage":+ foundMem = true+ case "process.gpu.utilization":+ foundUtil = true+ }+ }+ }+ if !foundMem || !foundUtil {+ t.Fatalf("process metrics missing: mem=%v util=%v", foundMem, foundUtil)+ }+}+func TestNewMetricsCollectorNoDevices(t *testing.T) {provider := metric.NewMeterProvider()defer provider.Shutdown(t.Context())- mc, err := NewMetricsCollector(provider, nil, slog.Default())+ mc, err := NewMetricsCollector(provider, nil, slog.Default(), nil)if err != nil {t.Fatalf("NewMetricsCollector() with no devices error = %v", err)}@@ -123,7 +186,7 @@ func TestMetricsCollectorCloseIdempotent(t *testing.T) {provider := metric.NewMeterProvider()defer provider.Shutdown(t.Context())- mc, err := NewMetricsCollector(provider, nil, slog.Default())+ mc, err := NewMetricsCollector(provider, nil, slog.Default(), nil)if err != nil {t.Fatalf("NewMetricsCollector() error = %v", err)}diff --git a/opentelemetry-gpu-collector/internal/export/occupancy.go b/opentelemetry-gpu-collector/internal/export/occupancy.gonew file mode 100644index 00000000..85979f52--- /dev/null+++ b/opentelemetry-gpu-collector/internal/export/occupancy.go@@ -0,0 +1,243 @@+package export++import (+ "context"+ "fmt"+ "log/slog"+ "math"+ "strconv"+ "sync"++ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/metric"+ sdkmetric "go.opentelemetry.io/otel/sdk/metric"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/cudaoccupancy"+ gpuebpf "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/ebpf"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procname"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/workload"+)++// OccupancyMetrics exports Datadog-parity stream-sync occupancy gauges.+// These are model estimates (launch→sync), not hardware SM occupancy.+type OccupancyMetrics struct {+ logger *slog.Logger+ engine *cudaoccupancy.Engine+ reg metric.Registration++ mu sync.Mutex+ lastProcesses []cudaoccupancy.ProcessStats+ lastDevices []cudaoccupancy.DeviceStats+ prevPIDs map[string]struct{} // uuid|pid seen last flush — zero-on-leave+}++// NewOccupancyMetrics wires an occupancy engine to OTel observable gauges.+func NewOccupancyMetrics(+ provider *sdkmetric.MeterProvider,+ devices []gpu.Device,+ logger *slog.Logger,+) (*OccupancyMetrics, error) {+ cores := make(map[string]uint64)+ for _, d := range devices {+ info := d.Info()+ if info.Vendor != gpu.VendorNVIDIA {+ continue+ }+ if info.CoreCount > 0 {+ cores[info.UUID] = uint64(info.CoreCount)+ }+ }+ engine := cudaoccupancy.NewEngine(cores)+ for _, d := range devices {+ info := d.Info()+ if info.Vendor == gpu.VendorNVIDIA {+ engine.SetDeviceIndexUUID(info.Index, info.UUID)+ }+ }++ om := &OccupancyMetrics{+ logger: logger,+ engine: engine,+ prevPIDs: make(map[string]struct{}),+ }++ meter := provider.Meter("otelcol.gpu.occupancy",+ metric.WithInstrumentationVersion("1.0.0"),+ )++ coreUsage, err := meter.Float64ObservableGauge("process.gpu.core.usage",+ metric.WithDescription("Model estimate of average CUDA cores used by a process (launch→sync thread-seconds, multi-process normalized). Not hardware SM occupancy."),+ metric.WithUnit("{cores}"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating process.gpu.core.usage: %w", err)+ }++ procSMActive, err := meter.Float64ObservableGauge("process.gpu.sm_active",+ metric.WithDescription("Model estimate: fraction of the interval with any launch→sync span for this process (0–1). Not hardware SM occupancy."),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating process.gpu.sm_active: %w", err)+ }++ coreLimit, err := meter.Float64ObservableGauge("gpu.core.limit",+ metric.WithDescription("NVML CUDA core count for the device"),+ metric.WithUnit("{cores}"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating gpu.core.limit: %w", err)+ }++ devSMActive, err := meter.Float64ObservableGauge("gpu.sm_active",+ metric.WithDescription("Model estimate: fraction of the interval with any launch→sync span on the device (0–1). Not hardware SM occupancy."),+ metric.WithUnit("1"),+ )+ if err != nil {+ return nil, fmt.Errorf("creating gpu.sm_active: %w", err)+ }++ reg, err := meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {+ res := om.engine.GetAndFlush()+ om.mu.Lock()+ defer om.mu.Unlock()++ seen := make(map[string]struct{})+ for _, p := range res.Processes {+ key := p.DeviceUUID + "|" + strconv.FormatUint(uint64(p.PID), 10)+ seen[key] = struct{}{}+ attrs := occupancyProcessAttrs(p.PID, p.DeviceUUID, devices)+ o.ObserveFloat64(coreUsage, p.UsedCores, metric.WithAttributeSet(attrs))+ o.ObserveFloat64(procSMActive, p.ActiveTime, metric.WithAttributeSet(attrs))+ }+ // Zero-on-leave+ for key := range om.prevPIDs {+ if _, ok := seen[key]; ok {+ continue+ }+ uuid, pidStr, _ := splitKey(key)+ pid64, _ := strconv.ParseUint(pidStr, 10, 32)+ attrs := occupancyProcessAttrs(uint32(pid64), uuid, devices)+ o.ObserveFloat64(coreUsage, 0, metric.WithAttributeSet(attrs))+ o.ObserveFloat64(procSMActive, 0, metric.WithAttributeSet(attrs))+ }+ om.prevPIDs = seen+ om.lastProcesses = res.Processes+ om.lastDevices = res.Devices++ emittedDev := make(map[string]bool)+ for _, d := range res.Devices {+ emittedDev[d.DeviceUUID] = true+ attrs := occupancyDeviceAttrs(d.DeviceUUID, devices)+ o.ObserveFloat64(devSMActive, d.ActiveTime, metric.WithAttributeSet(attrs))+ if d.CoreLimit > 0 {+ o.ObserveFloat64(coreLimit, d.CoreLimit, metric.WithAttributeSet(attrs))+ }+ }+ for _, d := range devices {+ info := d.Info()+ if info.Vendor != gpu.VendorNVIDIA || emittedDev[info.UUID] {+ continue+ }+ attrs := occupancyDeviceAttrs(info.UUID, devices)+ if info.CoreCount > 0 {+ o.ObserveFloat64(coreLimit, float64(info.CoreCount), metric.WithAttributeSet(attrs))+ }+ }+ return nil+ }, coreUsage, procSMActive, coreLimit, devSMActive)+ if err != nil {+ return nil, fmt.Errorf("registering occupancy callback: %w", err)+ }+ om.reg = reg+ return om, nil+}++func splitKey(key string) (uuid, pid string, ok bool) {+ for i := len(key) - 1; i >= 0; i-- {+ if key[i] == '|' {+ return key[:i], key[i+1:], true+ }+ }+ return "", "", false+}++func occupancyProcessAttrs(pid uint32, uuid string, devices []gpu.Device) attribute.Set {+ attrs := []attribute.KeyValue{+ attribute.String("hw.id", uuid),+ attribute.String("process.pid", strconv.FormatUint(uint64(pid), 10)),+ }+ // procname/workload APIs take int32; skip lookups for PIDs that would truncate.+ if pid <= math.MaxInt32 {+ pid32 := int32(pid)+ attrs = append(attrs, attribute.String("process.executable.name", procname.ExecutableName(pid32)))+ if pod, ok := workload.ResolvePod(pid32); ok && pod.PodUID != "" {+ attrs = append(attrs, attribute.String("k8s.pod.uid", pod.PodUID))+ }+ }+ for _, d := range devices {+ info := d.Info()+ if info.UUID == uuid {+ attrs = append(attrs,+ attribute.String("hw.name", info.Name),+ attribute.String("hw.vendor", string(info.Vendor)),+ attribute.Int("gpu.index", info.Index),+ attribute.String("gpu.pci_address", info.PCIAddress),+ )+ break+ }+ }+ return attribute.NewSet(attrs...)+}++func occupancyDeviceAttrs(uuid string, devices []gpu.Device) attribute.Set {+ attrs := []attribute.KeyValue{attribute.String("hw.id", uuid)}+ for _, d := range devices {+ info := d.Info()+ if info.UUID == uuid {+ attrs = append(attrs,+ attribute.String("hw.name", info.Name),+ attribute.String("hw.vendor", string(info.Vendor)),+ attribute.Int("gpu.index", info.Index),+ attribute.String("gpu.pci_address", info.PCIAddress),+ )+ break+ }+ }+ return attribute.NewSet(attrs...)+}++// HandleEvent feeds CUDA events into the occupancy engine.+func (om *OccupancyMetrics) HandleEvent(ev gpuebpf.CUDAEvent) {+ switch e := ev.(type) {+ case *gpuebpf.KernelLaunchEvent:+ om.engine.HandleLaunch(cudaoccupancy.KernelLaunch{+ PID: e.PID, TID: e.TID, StreamID: e.StreamID, KtimeNs: e.KtimeNs,+ GridX: e.GridX, GridY: e.GridY, GridZ: e.GridZ,+ BlockX: e.BlockX, BlockY: e.BlockY, BlockZ: e.BlockZ,+ })+ case *gpuebpf.SyncEvent:+ om.engine.HandleSync(cudaoccupancy.SyncEvent{+ PID: e.PID, TID: e.TID, StreamID: e.StreamID, KtimeNs: e.KtimeNs,+ DeviceWide: e.DeviceWide,+ })+ case *gpuebpf.SetDeviceEvent:+ om.engine.HandleSetDevice(cudaoccupancy.SetDeviceEvent{+ PID: e.PID, TID: e.TID, DeviceIdx: int(e.Device), KtimeNs: e.KtimeNs,+ })+ case *gpuebpf.MemcpyEvent:+ // Sync memcpy already emits SyncDevice from BPF; async memcpy does not close spans.+ _ = e+ }+}++// Engine exposes the underlying engine for tests.+func (om *OccupancyMetrics) Engine() *cudaoccupancy.Engine { return om.engine }++// Close unregisters callbacks.+func (om *OccupancyMetrics) Close() {+ if om.reg != nil {+ _ = om.reg.Unregister()+ }+}diff --git a/opentelemetry-gpu-collector/internal/export/otel.go b/opentelemetry-gpu-collector/internal/export/otel.goindex 4d1d32b4..3d327cd5 100644--- a/opentelemetry-gpu-collector/internal/export/otel.go+++ b/opentelemetry-gpu-collector/internal/export/otel.go@@ -15,6 +15,7 @@ import ("go.opentelemetry.io/otel/sdk/resource""github.com/openlit/openlit/opentelemetry-gpu-collector/internal/config"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/identity")type slogErrorHandler struct{ logger *slog.Logger }@@ -28,10 +29,14 @@ func (h *slogErrorHandler) Handle(err error) {func NewMeterProvider(ctx context.Context, cfg *config.Config, logger *slog.Logger) (*metric.MeterProvider, func(), error) {otel.SetErrorHandler(&slogErrorHandler{logger: logger})+ _, identityAttrs := identity.Detect(ctx, logger)+res, err := resource.New(ctx,- resource.WithHost(),resource.WithOS(),- resource.WithFromEnv(), // picks up OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME+ // Auto host.name / k8s.node.name / k8s.cluster.name (Datadog-like detection).+ resource.WithAttributes(identityAttrs...),+ // Explicit OTEL_RESOURCE_ATTRIBUTES / OTEL_SERVICE_NAME override auto identity.+ resource.WithFromEnv(),resource.WithAttributes(attribute.String("service.name", cfg.ServiceName),attribute.String("deployment.environment", cfg.Environment),diff --git a/opentelemetry-gpu-collector/internal/gpu/adlx/adlx_windows.go b/opentelemetry-gpu-collector/internal/gpu/adlx/adlx_windows.gonew file mode 100644index 00000000..f5395f6d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/adlx/adlx_windows.go@@ -0,0 +1,156 @@+//go:build windows++package adlx++import (+ "fmt"+ "sync"+ "unsafe"++ "golang.org/x/sys/windows"+)++// Metrics is a point-in-time AMD GPU sample.+type Metrics struct {+ Utilization *float64 // 0-100+ TemperatureC *float64+ ClockMHz *float64+ VRAMClockMHz *float64+ FanRPM *float64+ PowerWatts *float64+}++var (+ initOnce sync.Once+ initErr error+ adlDLL *windows.LazyDLL++ adlCreate *windows.LazyProc+ adlDestroy *windows.LazyProc+ adlAdapterNumberOfAdapters *windows.LazyProc+ adlOverdrive5CurrentActivity *windows.LazyProc+ adlOverdrive5Temperature *windows.LazyProc+ adlOverdrive5FanSpeed *windows.LazyProc+ context uintptr+ mallocCB uintptr++ kernel32 = windows.NewLazySystemDLL("kernel32.dll")+ heapAlloc = kernel32.NewProc("HeapAlloc")+ getHeap = kernel32.NewProc("GetProcessHeap")+)++type adlActivity struct {+ Size int32+ EngineClock int32+ MemoryClock int32+ Vddc int32+ ActivityPercent int32+ CurrentBusSpeed int32+ CurrentBusLanes int32+ MaximumBusLanes int32+ Reserved int32+}++type adlTemperature struct {+ Size int32+ Temperature int32+}++type adlFanSpeedValue struct {+ Size int32+ SpeedType int32+ FanSpeed int32+ Flags int32+}++func adlMalloc(size int32) uintptr {+ if size <= 0 {+ return 0+ }+ heap, _, _ := getHeap.Call()+ p, _, _ := heapAlloc.Call(heap, 0, uintptr(size))+ return p+}++// Init loads ADL2 from the AMD driver.+func Init() error {+ initOnce.Do(func() {+ adlDLL = windows.NewLazyDLL("atiadlxx.dll")+ if err := adlDLL.Load(); err != nil {+ adlDLL = windows.NewLazyDLL("atiadlxy.dll")+ if err2 := adlDLL.Load(); err2 != nil {+ initErr = fmt.Errorf("load ADL: %v / %v", err, err2)+ return+ }+ }+ adlCreate = adlDLL.NewProc("ADL2_Main_Control_Create")+ adlDestroy = adlDLL.NewProc("ADL2_Main_Control_Destroy")+ adlAdapterNumberOfAdapters = adlDLL.NewProc("ADL2_Adapter_NumberOfAdapters_Get")+ adlOverdrive5CurrentActivity = adlDLL.NewProc("ADL2_Overdrive5_CurrentActivity_Get")+ adlOverdrive5Temperature = adlDLL.NewProc("ADL2_Overdrive5_Temperature_Get")+ adlOverdrive5FanSpeed = adlDLL.NewProc("ADL2_Overdrive5_FanSpeed_Get")++ mallocCB = windows.NewCallback(adlMalloc)+ const adlOK = 0+ r, _, _ := adlCreate.Call(mallocCB, 1, uintptr(unsafe.Pointer(&context)))+ if r != adlOK {+ initErr = fmt.Errorf("ADL2_Main_Control_Create: %d", r)+ context = 0+ return+ }+ })+ return initErr+}++// Available reports whether ADL initialized.+func Available() bool {+ return Init() == nil && context != 0+}++// Collect returns metrics for adapter index (0-based among ADL adapters).+func Collect(index int) (Metrics, bool) {+ if !Available() {+ return Metrics{}, false+ }+ var num int32+ if r, _, _ := adlAdapterNumberOfAdapters.Call(context, uintptr(unsafe.Pointer(&num))); r != 0 || num <= 0 {+ return Metrics{}, false+ }+ if index < 0 || index >= int(num) {+ return Metrics{}, false+ }+ idx := int32(index)+ m := Metrics{}+ var act adlActivity+ act.Size = int32(unsafe.Sizeof(act))+ if r, _, _ := adlOverdrive5CurrentActivity.Call(context, uintptr(idx), uintptr(unsafe.Pointer(&act))); r == 0 {+ u := float64(act.ActivityPercent)+ m.Utilization = &u+ clk := float64(act.EngineClock) / 100.0+ m.ClockMHz = &clk+ mclk := float64(act.MemoryClock) / 100.0+ m.VRAMClockMHz = &mclk+ }+ var temp adlTemperature+ temp.Size = int32(unsafe.Sizeof(temp))+ if r, _, _ := adlOverdrive5Temperature.Call(context, uintptr(idx), 0, uintptr(unsafe.Pointer(&temp))); r == 0 {+ t := float64(temp.Temperature) / 1000.0+ m.TemperatureC = &t+ }+ var fan adlFanSpeedValue+ fan.Size = int32(unsafe.Sizeof(fan))+ fan.SpeedType = 1+ if r, _, _ := adlOverdrive5FanSpeed.Call(context, uintptr(idx), 0, uintptr(unsafe.Pointer(&fan))); r == 0 {+ f := float64(fan.FanSpeed)+ m.FanRPM = &f+ }+ return m, m.Utilization != nil || m.TemperatureC != nil || m.ClockMHz != nil || m.FanRPM != nil+}++// Close releases ADL.+func Close() {+ if context != 0 && adlDestroy != nil {+ _, _, _ = adlDestroy.Call(context)+ context = 0+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amd/amd.go b/opentelemetry-gpu-collector/internal/gpu/amd/amd_linux.gosimilarity index 70%rename from opentelemetry-gpu-collector/internal/gpu/amd/amd.gorename to opentelemetry-gpu-collector/internal/gpu/amd/amd_linux.goindex 0ccc4185..a5e0318f 100644--- a/opentelemetry-gpu-collector/internal/gpu/amd/amd.go+++ b/opentelemetry-gpu-collector/internal/gpu/amd/amd_linux.go@@ -1,3 +1,5 @@+//go:build linux+package amdimport (@@ -9,6 +11,8 @@ import ("strings""github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/amdsmi"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/drmfdinfo")const (@@ -18,19 +22,18 @@ const (// Device implements gpu.Device for AMD GPUs via sysfs/hwmon.type Device struct {- info gpu.DeviceInfo- drmPath string // e.g. /sys/class/drm/card0/device- hwmonPath string // e.g. /sys/class/hwmon/hwmon3- logger *slog.Logger+ info gpu.DeviceInfo+ drmPath string // e.g. /sys/class/drm/card0/device+ hwmonPath string // e.g. /sys/class/hwmon/hwmon3+ vendorIndex int // 0-based among AMD devices (for amdsmi)+ logger *slog.Logger}// DiscoverDevices scans sysfs for AMD GPU DRM cards and resolves their hwmon paths.+// When pciAddresses is empty, all amdgpu DRM cards are discovered (PCI-less fallback).func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger) ([]*Device, error) {- if len(pciAddresses) == 0 {- return nil, nil- }-addrSet := make(map[string]bool, len(pciAddresses))+ filter := len(pciAddresses) > 0for _, a := range pciAddresses {addrSet[strings.ToLower(a)] = true}@@ -42,6 +45,7 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)var devices []*Deviceidx := startIndex+ vendorIdx := 0for _, entry := range entries {name := entry.Name()@@ -56,7 +60,7 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)continue}- if !addrSet[strings.ToLower(pciAddr)] {+ if filter && !addrSet[strings.ToLower(pciAddr)] {continue}@@ -90,11 +94,13 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)PCIAddress: pciAddr,DriverVersion: driverVersion,},- drmPath: devPath,- hwmonPath: hwmon,- logger: logger.With("gpu", idx, "vendor", "amd"),+ drmPath: devPath,+ hwmonPath: hwmon,+ vendorIndex: vendorIdx,+ logger: logger.With("gpu", idx, "vendor", "amd"),})idx+++ vendorIdx++}return devices, nil@@ -125,6 +131,9 @@ func (d *Device) Collect() (*gpu.Snapshot, error) {}if s.MemoryTotalBytes != nil && s.MemoryUsedBytes != nil {free := *s.MemoryTotalBytes - *s.MemoryUsedBytes+ if free < 0 {+ free = 0+ }s.MemoryFreeBytes = &free}@@ -132,6 +141,54 @@ func (d *Device) Collect() (*gpu.Snapshot, error) {d.collectHwmon(s)}+ if m, ok := amdsmi.Collect(d.vendorIndex); ok {+ if m.Utilization != nil && s.Utilization == nil {+ s.Utilization = m.Utilization+ }+ if m.PowerWatts != nil && s.PowerDrawWatts == nil {+ s.PowerDrawWatts = m.PowerWatts+ }+ if m.TemperatureC != nil && s.TemperatureGPU == nil {+ s.TemperatureGPU = m.TemperatureC+ }+ if m.MemoryTotal != nil && s.MemoryTotalBytes == nil {+ s.MemoryTotalBytes = m.MemoryTotal+ }+ if m.MemoryUsed != nil && s.MemoryUsedBytes == nil {+ s.MemoryUsedBytes = m.MemoryUsed+ }+ if m.PCIeRxBytesPerSec != nil {+ s.PCIeRxBytesPerSec = m.PCIeRxBytesPerSec+ }+ if m.PCIeTxBytesPerSec != nil {+ s.PCIeTxBytesPerSec = m.PCIeTxBytesPerSec+ }+ if m.PCIeReplayErrors != nil {+ s.PCIeReplayErrors = m.PCIeReplayErrors+ }+ if m.InterconnectRxBytesPerSec != nil {+ s.InterconnectRxBytesPerSec = m.InterconnectRxBytesPerSec+ s.InterconnectType = "xgmi"+ }+ if m.InterconnectTxBytesPerSec != nil {+ s.InterconnectTxBytesPerSec = m.InterconnectTxBytesPerSec+ s.InterconnectType = "xgmi"+ }+ if m.ThrottleReasons != nil {+ s.ThrottleReasons = m.ThrottleReasons+ }+ if m.Throttled != nil {+ s.Throttled = m.Throttled+ }+ if m.EncoderUtilization != nil {+ s.EncoderUtilization = m.EncoderUtilization+ }+ }+ if ce, ue := amdsmi.CollectRAS(d.drmPath); ce != nil || ue != nil {+ s.RASCE = ce+ s.RASUE = ue+ }+return s, nil}@@ -186,6 +243,10 @@ func (d *Device) collectHwmon(s *gpu.Snapshot) {func (d *Device) Close() {}+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return drmfdinfo.Shared().CollectForPCI(d.info.PCIAddress, map[string]bool{"amdgpu": true})+}+// findHwmonForDevice locates the hwmon directory associated with a DRM device path.func findHwmonForDevice(drmDevicePath string) string {hwmonDir := filepath.Join(drmDevicePath, "hwmon")diff --git a/opentelemetry-gpu-collector/internal/gpu/amd/amd_stub.go b/opentelemetry-gpu-collector/internal/gpu/amd/amd_stub.gonew file mode 100644index 00000000..baa0651a--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amd/amd_stub.go@@ -0,0 +1,30 @@+//go:build !linux && !windows++package amd++import (+ "fmt"+ "log/slog"+ "runtime"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+)++type Device struct {+ info gpu.DeviceInfo+}++func (d *Device) Info() gpu.DeviceInfo { return d.info }+func (d *Device) Collect() (*gpu.Snapshot, error) { return nil, errUnsupported() }+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return nil, errUnsupported()+}+func (d *Device) Close() {}++func DiscoverDevices(_ []string, _ int, _ *slog.Logger) ([]*Device, error) {+ return nil, errUnsupported()+}++func errUnsupported() error {+ return fmt.Errorf("AMD GPU monitoring requires linux or windows (current: %s/%s)", runtime.GOOS, runtime.GOARCH)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amd/amd_windows.go b/opentelemetry-gpu-collector/internal/gpu/amd/amd_windows.gonew file mode 100644index 00000000..ac3027f7--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amd/amd_windows.go@@ -0,0 +1,121 @@+//go:build windows++package amd++import (+ "fmt"+ "log/slog"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/adlx"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/windxg"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/winpdh"+)++// Device implements gpu.Device for AMD GPUs on Windows via DXGI + PDH + ADL.+type Device struct {+ info gpu.DeviceInfo+ adapter windxg.Adapter+ luidKey string+ vendorIndex int // 0-based among AMD adapters (for ADL)+ logger *slog.Logger+}++// DiscoverDevices discovers AMD adapters via DXGI.+// pciAddresses is ignored on Windows (DXGI enumeration replaces PCI sysfs).+func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger) ([]*Device, error) {+ adapters, err := windxg.EnumAdapters()+ if err != nil {+ return nil, err+ }+ var devices []*Device+ idx := startIndex+ vendorIdx := 0+ for _, a := range adapters {+ if a.VendorID != windxg.VendorAMD {+ continue+ }+ uuid := a.LUIDKey+ pci := fmt.Sprintf("dxgi:%04X:%04X", a.VendorID, a.DeviceID)+ logger.Info("discovered AMD GPU", "name", a.Name, "luid", a.LUIDKey)+ devices = append(devices, &Device{+ info: gpu.DeviceInfo{+ Vendor: gpu.VendorAMD,+ Index: idx,+ Name: a.Name,+ UUID: uuid,+ PCIAddress: pci,+ },+ adapter: a,+ luidKey: a.LUIDKey,+ vendorIndex: vendorIdx,+ logger: logger.With("gpu", idx, "vendor", "amd"),+ })+ idx+++ vendorIdx+++ }+ return devices, nil+}++func (d *Device) Info() gpu.DeviceInfo { return d.info }++func (d *Device) Collect() (*gpu.Snapshot, error) {+ s := &gpu.Snapshot{}+ total := int64(d.adapter.DedicatedVideoMemory)+ if total > 0 {+ s.MemoryTotalBytes = &total+ }+ if au, ok := winpdh.AdapterSnapshot(d.luidKey); ok {+ if au.HasUtil {+ u := au.Util * 100+ s.Utilization = &u+ }+ if au.HasEnc {+ e := au.EncoderUtil * 100+ s.EncoderUtilization = &e+ }+ if au.HasDec {+ dec := au.DecoderUtil * 100+ s.DecoderUtilization = &dec+ }+ if au.HasMemory {+ used := au.MemoryUsed+ s.MemoryUsedBytes = &used+ if total > 0 {+ free := total - used+ if free < 0 {+ free = 0+ }+ s.MemoryFreeBytes = &free+ }+ }+ }+ // Enrich with ADL using vendor-local index (not global gpu.index).+ if m, ok := adlx.Collect(d.vendorIndex); ok {+ if m.Utilization != nil {+ s.Utilization = m.Utilization+ }+ if m.TemperatureC != nil {+ s.TemperatureGPU = m.TemperatureC+ }+ if m.ClockMHz != nil {+ s.ClockGraphicsMHz = m.ClockMHz+ }+ if m.VRAMClockMHz != nil {+ s.ClockMemoryMHz = m.VRAMClockMHz+ }+ if m.FanRPM != nil {+ s.FanSpeedRPM = m.FanRPM+ }+ if m.PowerWatts != nil {+ s.PowerDrawWatts = m.PowerWatts+ }+ }+ return s, nil+}++func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return winpdh.CollectForLUID(d.luidKey)+}++func (d *Device) Close() {}diff --git a/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_linux.go b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_linux.gonew file mode 100644index 00000000..5addcce8--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_linux.go@@ -0,0 +1,391 @@+//go:build linux++// Package amdsmi wraps AMD SMI (libamd_smi) for XGMI, RAS, and PCIe metrics.+package amdsmi++import (+ "fmt"+ "strings"+ "sync"+ "time"++ "github.com/ebitengine/purego"+)++const (+ amdsmiLinkTypeXGMI = 2+ amdsmiMaxXGMIPhysicalLinks = 64+ amdsmiUnsupportedUint8 = 0xff+)++// Metrics holds AMD SMI device extras beyond sysfs.+type Metrics struct {+ PCIeRxBytesPerSec *float64+ PCIeTxBytesPerSec *float64+ PCIeReplayErrors *int64+ InterconnectRxBytesPerSec *float64+ InterconnectTxBytesPerSec *float64+ RASCE *int64+ RASUE *int64+ ThrottleReasons *string+ Throttled *float64+ PowerWatts *float64+ TemperatureC *float64+ Utilization *float64+ // EncoderUtilization is media/VCN activity (%) when only a combined counter exists.+ EncoderUtilization *float64+ MemoryTotal *int64+ MemoryUsed *int64+}++type lib struct {+ handle uintptr++ amdsmiInit func(uint64) int32+ amdsmiShut func() int32+ getProcessorHandles func(*uint32, *uintptr) int32+ getPowerInfo func(uintptr, *amdsmiPowerInfo) int32+ getTempMetric func(uintptr, int32, int32, *int64) int32+ getGpuActivity func(uintptr, *amdsmiActivity) int32+ getVramUsage func(uintptr, *amdsmiVram) int32+ getGpuMetrics func(uintptr, *amdsmiGpuMetrics) int32+ getPciThroughput func(uintptr, *uint64, *uint64, *uint64) int32+ getPciReplay func(uintptr, *uint64) int32+ getLinkMetrics func(uintptr, *amdsmiLinkMetrics) int32+ getViolationStatus func(uintptr, *amdsmiViolationStatus) int32+}++type amdsmiPowerInfo struct {+ CurrentSocketPower uint32+ _pad [60]byte+}++type amdsmiActivity struct {+ GfxActivity uint32+ UmcActivity uint32+ MmActivity uint32+}++type amdsmiVram struct {+ VramTotal uint64+ VramUsed uint64+}++// Layout is version-sensitive; we only read fields we need after size check.+type amdsmiGpuMetrics struct {+ CommonHeader struct {+ StructureSize uint16+ FormatRevision uint8+ ContentRevision uint8+ }+ _pad0 [100]byte+}++// amdsmi_link_metrics_t — see ROCm amdsmi.h+type amdsmiLinkEntry struct {+ BDF uint64+ BitRate uint32+ MaxBandwidth uint32+ LinkType uint32+ _ uint32+ ReadKB uint64+ WriteKB uint64+ Reserved uint64+}++type amdsmiLinkMetrics struct {+ NumLinks uint32+ _ uint32+ Links [amdsmiMaxXGMIPhysicalLinks]amdsmiLinkEntry+ Reserved [7]uint64+}++// Truncated + oversized pad so newer MI3x fields can be written safely.+type amdsmiViolationStatus struct {+ ReferenceTimestamp uint64+ ViolationTimestamp uint64+ AccCounter uint64+ AccProchot uint64+ AccPpt uint64+ AccSocket uint64+ AccVr uint64+ AccHbm uint64+ AccGfxClk uint64+ PerProchot uint64+ PerPpt uint64+ PerSocket uint64+ PerVr uint64+ PerHbm uint64+ PerGfxClk uint64+ ActiveProchot uint8+ ActivePpt uint8+ ActiveSocket uint8+ ActiveVr uint8+ ActiveHbm uint8+ ActiveGfxClk uint8+ _ [2]byte+ // Remaining driver 1.8+ fields (XCP×XCC arrays) — keep large enough.+ _rest [8 * 1024]byte+}++type xgmiPrev struct {+ readKB uint64+ writeKB uint64+ at time.Time+}++var (+ once sync.Once+ l *lib+ errL error++ handlesMu sync.Mutex+ cachedHandles []uintptr++ xgmiMu sync.Mutex+ xgmiPrevByIndex = map[int]*xgmiPrev{}+)++// Init loads libamd_smi.+func Init() error {+ once.Do(func() {+ for _, name := range []string{"libamd_smi.so", "libamd_smi.so.1"} {+ h, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL)+ if err != nil {+ continue+ }+ l = &lib{handle: h}+ bind := func(name string, fptr any) {+ sym, err := purego.Dlsym(h, name)+ if err != nil {+ return+ }+ purego.RegisterFunc(fptr, sym)+ }+ bind("amdsmi_init", &l.amdsmiInit)+ bind("amdsmi_shut_down", &l.amdsmiShut)+ bind("amdsmi_get_processor_handles", &l.getProcessorHandles)+ bind("amdsmi_get_power_info", &l.getPowerInfo)+ bind("amdsmi_get_temp_metric", &l.getTempMetric)+ bind("amdsmi_get_gpu_activity", &l.getGpuActivity)+ bind("amdsmi_get_gpu_vram_usage", &l.getVramUsage)+ bind("amdsmi_get_gpu_metrics_info", &l.getGpuMetrics)+ bind("amdsmi_get_gpu_pci_throughput", &l.getPciThroughput)+ bind("amdsmi_get_gpu_pci_replay_counter", &l.getPciReplay)+ bind("amdsmi_get_link_metrics", &l.getLinkMetrics)+ bind("amdsmi_get_violation_status", &l.getViolationStatus)+ if l.amdsmiInit == nil || l.getProcessorHandles == nil {+ errL = fmt.Errorf("amdsmi required symbols missing")+ l = nil+ return+ }+ // AMDSMI_INIT_AMD_GPUS = 1 << 0 typically; try 0 for all.+ if rc := l.amdsmiInit(1); rc != 0 {+ if rc2 := l.amdsmiInit(0); rc2 != 0 {+ errL = fmt.Errorf("amdsmi_init: %d", rc)+ l = nil+ return+ }+ }+ return+ }+ errL = fmt.Errorf("libamd_smi not found")+ })+ return errL+}++// Available reports whether AMD SMI loaded.+func Available() bool {+ return Init() == nil && l != nil+}++// Collect returns AMD SMI metrics for processor index.+func Collect(index int) (Metrics, bool) {+ if !Available() || l.getProcessorHandles == nil {+ return Metrics{}, false+ }+ handlesMu.Lock()+ if cachedHandles == nil {+ var n uint32+ if l.getProcessorHandles(&n, nil) != 0 || n == 0 {+ handlesMu.Unlock()+ return Metrics{}, false+ }+ handles := make([]uintptr, n)+ if l.getProcessorHandles(&n, &handles[0]) != 0 {+ handlesMu.Unlock()+ return Metrics{}, false+ }+ cachedHandles = handles+ }+ handles := cachedHandles+ handlesMu.Unlock()++ if index < 0 || index >= len(handles) {+ return Metrics{}, false+ }+ h := handles[index]+ m := Metrics{}++ if l.getPowerInfo != nil {+ var pi amdsmiPowerInfo+ if l.getPowerInfo(h, &pi) == 0 && pi.CurrentSocketPower > 0 {+ p := float64(pi.CurrentSocketPower)+ m.PowerWatts = &p+ }+ }+ if l.getTempMetric != nil {+ // AMDSMI_TEMPERATURE_TYPE_EDGE = 0, CURRENT = 0+ var t int64+ if l.getTempMetric(h, 0, 0, &t) == 0 {+ tc := float64(t)+ m.TemperatureC = &tc+ }+ }+ if l.getGpuActivity != nil {+ var a amdsmiActivity+ if l.getGpuActivity(h, &a) == 0 {+ u := float64(a.GfxActivity)+ m.Utilization = &u+ // Combined media/VCN — encoder only when value looks like a percent.+ if a.MmActivity <= 100 {+ enc := float64(a.MmActivity)+ m.EncoderUtilization = &enc+ }+ }+ }+ if l.getVramUsage != nil {+ var v amdsmiVram+ if l.getVramUsage(h, &v) == 0 && v.VramTotal > 0 {+ tot := int64(v.VramTotal)+ used := v.VramUsed+ if used > v.VramTotal {+ used = v.VramTotal+ }+ u := int64(used)+ m.MemoryTotal = &tot+ m.MemoryUsed = &u+ }+ }++ if l.getPciThroughput != nil {+ var sent, recv, maxPkt uint64+ if l.getPciThroughput(h, &sent, &recv, &maxPkt) == 0 {+ // API returns bytes transferred in the last ~1 second.+ tx := float64(sent)+ rx := float64(recv)+ m.PCIeTxBytesPerSec = &tx+ m.PCIeRxBytesPerSec = &rx+ }+ }+ if l.getPciReplay != nil {+ var counter uint64+ if l.getPciReplay(h, &counter) == 0 {+ v := int64(counter)+ m.PCIeReplayErrors = &v+ }+ }++ collectXGMI(index, h, &m)+ collectThrottle(h, &m)++ ok := m.PowerWatts != nil || m.TemperatureC != nil || m.Utilization != nil || m.MemoryTotal != nil ||+ m.PCIeRxBytesPerSec != nil || m.InterconnectRxBytesPerSec != nil || m.Throttled != nil ||+ m.EncoderUtilization != nil || m.PCIeReplayErrors != nil+ return m, ok+}++func collectXGMI(index int, h uintptr, m *Metrics) {+ if l.getLinkMetrics == nil {+ return+ }+ var lm amdsmiLinkMetrics+ if l.getLinkMetrics(h, &lm) != 0 {+ return+ }+ var readKB, writeKB uint64+ var n int+ maxN := int(lm.NumLinks)+ if maxN > amdsmiMaxXGMIPhysicalLinks {+ maxN = amdsmiMaxXGMIPhysicalLinks+ }+ for i := 0; i < maxN; i++ {+ link := lm.Links[i]+ if link.LinkType != amdsmiLinkTypeXGMI {+ continue+ }+ readKB += link.ReadKB+ writeKB += link.WriteKB+ n+++ }+ if n == 0 {+ return+ }+ now := time.Now()+ xgmiMu.Lock()+ prev := xgmiPrevByIndex[index]+ if prev != nil && !prev.at.IsZero() {+ dt := now.Sub(prev.at).Seconds()+ if dt > 0 && readKB >= prev.readKB && writeKB >= prev.writeKB {+ if rx, tx, ok := XGMIRateBytesPerSec(prev.readKB, prev.writeKB, readKB, writeKB, dt); ok {+ m.InterconnectRxBytesPerSec = &rx+ m.InterconnectTxBytesPerSec = &tx+ }+ }+ }+ xgmiPrevByIndex[index] = &xgmiPrev{readKB: readKB, writeKB: writeKB, at: now}+ xgmiMu.Unlock()+}++func collectThrottle(h uintptr, m *Metrics) {+ if l.getViolationStatus == nil {+ return+ }+ var vs amdsmiViolationStatus+ if l.getViolationStatus(h, &vs) != 0 {+ return+ }+ parts := make([]string, 0, 6)+ active := false+ check := func(v uint8, name string) {+ if v == amdsmiUnsupportedUint8 {+ return+ }+ if v != 0 {+ active = true+ parts = append(parts, name)+ }+ }+ check(vs.ActiveProchot, "prochot")+ check(vs.ActivePpt, "ppt_power")+ check(vs.ActiveSocket, "socket_thermal")+ check(vs.ActiveVr, "vr_thermal")+ check(vs.ActiveHbm, "hbm_thermal")+ check(vs.ActiveGfxClk, "gfx_clk_limit")++ // If all active flags unsupported, soft-omit.+ if vs.ActiveProchot == amdsmiUnsupportedUint8 &&+ vs.ActivePpt == amdsmiUnsupportedUint8 &&+ vs.ActiveSocket == amdsmiUnsupportedUint8 &&+ vs.ActiveVr == amdsmiUnsupportedUint8 &&+ vs.ActiveHbm == amdsmiUnsupportedUint8 &&+ vs.ActiveGfxClk == amdsmiUnsupportedUint8 {+ return+ }++ th := 0.0+ if active {+ th = 1.0+ }+ m.Throttled = &th+ label := "none"+ if len(parts) > 0 {+ label = strings.Join(parts, ",")+ }+ m.ThrottleReasons = &label+}++// CollectRAS reads RAS UE/CE from sysfs for a DRM device path.+func CollectRAS(drmDevicePath string) (ce, ue *int64) {+ return readRAS(drmDevicePath)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate.go b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate.gonew file mode 100644index 00000000..69e4209a--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate.go@@ -0,0 +1,11 @@+package amdsmi++// XGMIRateBytesPerSec converts cumulative KB deltas to By/s.+func XGMIRateBytesPerSec(prevReadKB, prevWriteKB, curReadKB, curWriteKB uint64, dtSec float64) (rx, tx float64, ok bool) {+ if dtSec <= 0 || curReadKB < prevReadKB || curWriteKB < prevWriteKB {+ return 0, 0, false+ }+ return float64(curReadKB-prevReadKB) * 1024.0 / dtSec,+ float64(curWriteKB-prevWriteKB) * 1024.0 / dtSec,+ true+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate_test.go b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate_test.gonew file mode 100644index 00000000..ee67ba90--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amdsmi/amdsmi_rate_test.go@@ -0,0 +1,19 @@+package amdsmi++import "testing"++func TestXGMIRateBytesPerSec(t *testing.T) {+ rx, tx, ok := XGMIRateBytesPerSec(100, 200, 1100, 2200, 1.0)+ if !ok {+ t.Fatal("expected ok")+ }+ if rx != 1000*1024 || tx != 2000*1024 {+ t.Fatalf("rx=%v tx=%v", rx, tx)+ }+ if _, _, ok := XGMIRateBytesPerSec(100, 200, 50, 2200, 1.0); ok {+ t.Fatal("underflow should fail")+ }+ if _, _, ok := XGMIRateBytesPerSec(100, 200, 1100, 2200, 0); ok {+ t.Fatal("zero dt should fail")+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux.go b/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux.gonew file mode 100644index 00000000..b9cc4aee--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux.go@@ -0,0 +1,64 @@+//go:build linux++package amdsmi++import (+ "os"+ "path/filepath"+ "strconv"+ "strings"+)++func readRAS(drmDevicePath string) (ce, ue *int64) {+ rasDir := filepath.Join(drmDevicePath, "ras")+ entries, err := os.ReadDir(rasDir)+ if err != nil {+ return nil, nil+ }+ var ceSum, ueSum int64+ var hasCE, hasUE bool+ for _, e := range entries {+ name := e.Name()+ data, err := os.ReadFile(filepath.Join(rasDir, name))+ if err != nil {+ continue+ }+ // Files often contain "ue: N\nce: M" or similar.+ for _, line := range strings.Split(string(data), "\n") {+ line = strings.TrimSpace(strings.ToLower(line))+ if strings.HasPrefix(line, "ue:") || strings.HasPrefix(line, "ue ") {+ if v, ok := parseTrailingInt(line); ok {+ ueSum += v+ hasUE = true+ }+ }+ if strings.HasPrefix(line, "ce:") || strings.HasPrefix(line, "ce ") {+ if v, ok := parseTrailingInt(line); ok {+ ceSum += v+ hasCE = true+ }+ }+ }+ }+ if hasCE {+ ce = &ceSum+ }+ if hasUE {+ ue = &ueSum+ }+ return ce, ue+}++func parseTrailingInt(line string) (int64, bool) {+ fields := strings.FieldsFunc(line, func(r rune) bool {+ return r == ':' || r == ' ' || r == '\t'+ })+ if len(fields) == 0 {+ return 0, false+ }+ v, err := strconv.ParseInt(fields[len(fields)-1], 10, 64)+ if err != nil {+ return 0, false+ }+ return v, true+}diff --git a/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux_test.go b/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux_test.gonew file mode 100644index 00000000..697f0917--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/amdsmi/ras_linux_test.go@@ -0,0 +1,19 @@+//go:build linux++package amdsmi++import "testing"++func TestParseTrailingInt(t *testing.T) {+ v, ok := parseTrailingInt("ue: 12")+ if !ok || v != 12 {+ t.Fatalf("got %v %v", v, ok)+ }+}++func TestReadRASEmpty(t *testing.T) {+ ce, ue := CollectRAS("/nonexistent/path")+ if ce != nil || ue != nil {+ t.Fatalf("expected nil, got %v %v", ce, ue)+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/classify/classify.go b/opentelemetry-gpu-collector/internal/gpu/classify/classify.gonew file mode 100644index 00000000..69bbca76--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/classify/classify.go@@ -0,0 +1,45 @@+// Package classify detects LLM-related workload frameworks from process identity.+package classify++import "strings"++// Result is the classification of a GPU process.+type Result struct {+ Kind string // llm_inference | llm_training | other+ Framework string // vllm | ollama | llama.cpp | sglang | tgi | triton | ray | pytorch | unknown+}++type rule struct {+ substr string+ framework string+ kind string+}++// Ordered from more specific to less specific.+var rules = []rule{+ {"ray::", "ray", "llm_inference"},+ {"vllm", "vllm", "llm_inference"},+ {"ollama", "ollama", "llm_inference"},+ {"llama-server", "llama.cpp", "llm_inference"},+ {"llama.cpp", "llama.cpp", "llm_inference"},+ {"llama_cpp", "llama.cpp", "llm_inference"},+ {"text-generation-launcher", "tgi", "llm_inference"},+ {"text-generation-server", "tgi", "llm_inference"},+ {"sglang", "sglang", "llm_inference"},+ {"tritonserver", "triton", "llm_inference"},+ {"torchrun", "pytorch", "llm_training"},+ {"pytorch", "pytorch", "llm_training"},+ {"transformers.trainer", "pytorch", "llm_training"},+ {"deepspeed", "pytorch", "llm_training"},+}++// FromProcess classifies using executable name and command line (case-insensitive).+func FromProcess(exe, cmdline string) Result {+ hay := strings.ToLower(exe + " " + cmdline)+ for _, r := range rules {+ if strings.Contains(hay, r.substr) {+ return Result{Kind: r.kind, Framework: r.framework}+ }+ }+ return Result{Kind: "other", Framework: "unknown"}+}diff --git a/opentelemetry-gpu-collector/internal/gpu/classify/classify_test.go b/opentelemetry-gpu-collector/internal/gpu/classify/classify_test.gonew file mode 100644index 00000000..5a85a292--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/classify/classify_test.go@@ -0,0 +1,23 @@+package classify++import "testing"++func TestFromProcess(t *testing.T) {+ cases := []struct {+ exe, cmd string+ kind, fw string+ }{+ {"python", "python -m vllm.entrypoints.openai.api_server", "llm_inference", "vllm"},+ {"ollama", "/usr/local/bin/ollama serve", "llm_inference", "ollama"},+ {"llama-server", "./llama-server -m model.gguf", "llm_inference", "llama.cpp"},+ {"python", "ray::ServeReplica:app1:VLLMDeployment", "llm_inference", "ray"},+ {"torchrun", "torchrun train.py", "llm_training", "pytorch"},+ {"bash", "sleep 10", "other", "unknown"},+ }+ for _, c := range cases {+ got := FromProcess(c.exe, c.cmd)+ if got.Kind != c.kind || got.Framework != c.fw {+ t.Errorf("FromProcess(%q,%q)=%+v want kind=%s fw=%s", c.exe, c.cmd, got, c.kind, c.fw)+ }+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner.go b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner.gonew file mode 100644index 00000000..106317db--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner.go@@ -0,0 +1,401 @@+// Package drmfdinfo scans DRM client usage stats from /proc/<pid>/fdinfo.+// Spec: https://docs.kernel.org/gpu/drm-usage-stats.html+package drmfdinfo++import (+ "bufio"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procname"+)++// Client aggregates one DRM client's memory and engine busy counters.+type Client struct {+ PID int32+ PCIAddress string+ Driver string+ ClientID string+ MemoryBy int64+ // EngineNs maps engine name (e.g. "gfx", "render") to cumulative busy ns.+ EngineNs map[string]uint64+}++// Scanner walks /proc for DRM fdinfo clients and computes utilization deltas.+type Scanner struct {+ mu sync.Mutex+ prev map[string]engineSample // key: pid|pci|engine++ // clientsCache avoids a full /proc walk per GPU device within one scrape.+ clientsCache []Client+ clientsCacheAt time.Time+}++type engineSample struct {+ ns uint64+ wall time.Time+}++// clientsCacheTTL is long enough to cover one metrics callback with multiple+// AMD/Intel devices, short enough that consecutive scrapes still re-scan.+const clientsCacheTTL = time.Second++func NewScanner() *Scanner {+ return &Scanner{prev: make(map[string]engineSample)}+}++func engineKey(pid int32, pci, engine string) string {+ return fmt.Sprintf("%d|%s|%s", pid, strings.ToLower(pci), engine)+}++// CollectForPCI returns ProcessUsage for clients on the given PCI address+// whose drm-driver matches one of allowedDrivers (e.g. "amdgpu", "i915", "xe").+func (s *Scanner) CollectForPCI(pciAddress string, allowedDrivers map[string]bool) ([]gpu.ProcessUsage, error) {+ clients, err := s.cachedClients()+ if err != nil {+ return nil, err+ }++ now := time.Now()+ pciLower := strings.ToLower(pciAddress)++ type agg struct {+ mem int64+ engines map[string]uint64+ }+ byPID := make(map[int32]*agg)++ for _, c := range clients {+ if !allowedDrivers[c.Driver] {+ continue+ }+ if strings.ToLower(c.PCIAddress) != pciLower {+ continue+ }+ a := byPID[c.PID]+ if a == nil {+ a = &agg{engines: make(map[string]uint64)}+ byPID[c.PID] = a+ }+ a.mem += c.MemoryBy+ for eng, ns := range c.EngineNs {+ a.engines[eng] += ns+ }+ }++ s.mu.Lock()+ defer s.mu.Unlock()++ seenKeys := make(map[string]struct{}, len(byPID)*2)+ out := make([]gpu.ProcessUsage, 0, len(byPID))+ for pid, a := range byPID {+ pu := gpu.ProcessUsage{+ PID: pid,+ ExecutableName: procname.ExecutableName(pid),+ }+ if a.mem > 0 {+ mem := a.mem+ pu.MemoryBytes = &mem+ }++ primary := pickPrimaryEngine(a.engines)+ if primary != "" {+ key := engineKey(pid, pciLower, primary)+ curr := a.engines[primary]+ if prev, ok := s.prev[key]; ok && curr >= prev.ns {+ wallDelta := now.Sub(prev.wall).Seconds()+ if wallDelta > 0 {+ util := float64(curr-prev.ns) / (wallDelta * 1e9)+ if util > 1 {+ util = 1+ }+ if util < 0 {+ util = 0+ }+ pu.Utilization = &util+ }+ }+ }++ for eng, ns := range a.engines {+ k := engineKey(pid, pciLower, eng)+ s.prev[k] = engineSample{ns: ns, wall: now}+ seenKeys[k] = struct{}{}+ }++ out = append(out, pu)+ }++ // Rebuild prev entries for this PCI so departed clients do not grow forever.+ for k := range s.prev {+ if !strings.Contains(k, "|"+pciLower+"|") {+ continue+ }+ if _, ok := seenKeys[k]; !ok {+ delete(s.prev, k)+ }+ }++ return out, nil+}++func (s *Scanner) cachedClients() ([]Client, error) {+ s.mu.Lock()+ if s.clientsCache != nil && time.Since(s.clientsCacheAt) < clientsCacheTTL {+ c := s.clientsCache+ s.mu.Unlock()+ return c, nil+ }+ s.mu.Unlock()++ clients, err := ScanClients()+ if err != nil {+ return nil, err+ }++ s.mu.Lock()+ s.clientsCache = clients+ s.clientsCacheAt = time.Now()+ s.mu.Unlock()+ return clients, nil+}++func pickPrimaryEngine(engines map[string]uint64) string {+ preferred := []string{"gfx", "graphics", "compute", "render", "rcs"}+ for _, p := range preferred {+ for name := range engines {+ if strings.EqualFold(name, p) || strings.HasPrefix(strings.ToLower(name), p) {+ return name+ }+ }+ }+ // fallback: max busy absolute+ var best string+ var bestNs uint64+ for name, ns := range engines {+ if ns >= bestNs {+ bestNs = ns+ best = name+ }+ }+ return best+}++// ScanClients walks /proc for open DRM fds and parses fdinfo.+func ScanClients() ([]Client, error) {+ procEntries, err := os.ReadDir("/proc")+ if err != nil {+ return nil, err+ }++ seen := make(map[string]struct{}) // pid|client-id|pci+ var out []Client++ for _, pe := range procEntries {+ if !pe.IsDir() {+ continue+ }+ pid64, err := strconv.ParseInt(pe.Name(), 10, 32)+ if err != nil {+ continue+ }+ pid := int32(pid64)+ fdDir := filepath.Join("/proc", pe.Name(), "fd")+ fds, err := os.ReadDir(fdDir)+ if err != nil {+ continue // EACCES / gone+ }+ for _, fd := range fds {+ link, err := os.Readlink(filepath.Join(fdDir, fd.Name()))+ if err != nil {+ continue+ }+ if !strings.HasPrefix(link, "/dev/dri/") {+ continue+ }+ infoPath := filepath.Join("/proc", pe.Name(), "fdinfo", fd.Name())+ c, ok := parseFdinfo(infoPath, pid)+ if !ok {+ continue+ }+ dedup := fmt.Sprintf("%d|%s|%s", pid, c.ClientID, strings.ToLower(c.PCIAddress))+ if c.ClientID != "" {+ if _, exists := seen[dedup]; exists {+ continue+ }+ seen[dedup] = struct{}{}+ }+ out = append(out, c)+ }+ }+ return out, nil+}++func parseFdinfo(path string, pid int32) (Client, bool) {+ f, err := os.Open(path)+ if err != nil {+ return Client{}, false+ }+ defer f.Close()++ c := Client{+ PID: pid,+ EngineNs: make(map[string]uint64),+ }+ hasDRM := false+ var memCandidates []memCandidate+ sc := bufio.NewScanner(f)+ for sc.Scan() {+ line := sc.Text()+ key, val, ok := strings.Cut(line, ":")+ if !ok {+ continue+ }+ key = strings.TrimSpace(key)+ val = strings.TrimSpace(val)+ switch {+ case key == "drm-driver":+ c.Driver = val+ hasDRM = true+ case key == "drm-pdev":+ c.PCIAddress = val+ hasDRM = true+ case key == "drm-client-id":+ c.ClientID = val+ case strings.HasPrefix(key, "drm-engine-"):+ name := strings.TrimPrefix(key, "drm-engine-")+ ns, err := parseBusyNs(val)+ if err == nil {+ c.EngineNs[name] = ns+ hasDRM = true+ }+ default:+ if rank, ok := memoryKeyRank(key); ok {+ if b, ok := parseMemBytes(val); ok {+ memCandidates = append(memCandidates, memCandidate{rank: rank, bytes: b})+ hasDRM = true+ }+ }+ }+ }+ if !hasDRM || c.PCIAddress == "" {+ return Client{}, false+ }+ c.MemoryBy = pickMemoryBytes(memCandidates)+ return c, true+}++type memCandidate struct {+ rank int+ bytes int64+}++// memoryKeyRank prefers a single non-overlapping memory key so we do not+// double-count vram + resident + total from the same client.+// Lower rank wins. Unknown overlapping keys are ignored.+func memoryKeyRank(key string) (int, bool) {+ k := strings.ToLower(key)+ switch {+ case k == "drm-total-memory" || strings.HasSuffix(k, "-total-memory"):+ return 1, true+ case strings.Contains(k, "memory-vram") && !strings.Contains(k, "resident"):+ return 2, true+ case k == "drm-memory-vram":+ return 2, true+ case strings.Contains(k, "resident-vram") || k == "drm-resident-memory":+ return 3, true+ case strings.HasPrefix(k, "drm-memory-") && !strings.Contains(k, "shared"):+ return 4, true+ default:+ return 0, false+ }+}++func pickMemoryBytes(cands []memCandidate) int64 {+ if len(cands) == 0 {+ return 0+ }+ bestRank := cands[0].rank+ var sum int64+ for _, c := range cands {+ if c.rank < bestRank {+ bestRank = c.rank+ }+ }+ for _, c := range cands {+ if c.rank == bestRank {+ sum += c.bytes+ }+ }+ return sum+}++// parseBusyNs accepts "123 ns" or bare integer nanoseconds.+func parseBusyNs(val string) (uint64, error) {+ val = strings.TrimSpace(val)+ val = strings.TrimSuffix(val, "ns")+ val = strings.TrimSpace(val)+ return strconv.ParseUint(val, 10, 64)+}++// parseMemBytes accepts "123 KiB", "4 MiB", or bare bytes.+func parseMemBytes(val string) (int64, bool) {+ fields := strings.Fields(val)+ if len(fields) == 0 {+ return 0, false+ }+ n, err := strconv.ParseFloat(fields[0], 64)+ if err != nil {+ return 0, false+ }+ mult := float64(1)+ if len(fields) > 1 {+ switch strings.ToLower(fields[1]) {+ case "kib":+ mult = 1024+ case "mib":+ mult = 1024 * 1024+ case "gib":+ mult = 1024 * 1024 * 1024+ case "b", "bytes":+ mult = 1+ }+ }+ return int64(n * mult), true+}++// BuildPCIMap maps lowercase PCI addresses from DRM card/render sysfs nodes.+func BuildPCIMap() map[string]string {+ out := make(map[string]string)+ entries, err := os.ReadDir("/sys/class/drm")+ if err != nil {+ return out+ }+ for _, e := range entries {+ name := e.Name()+ if !(strings.HasPrefix(name, "card") || strings.HasPrefix(name, "render")) {+ continue+ }+ if strings.Contains(name, "-") {+ continue+ }+ devPath := filepath.Join("/sys/class/drm", name, "device")+ uevent, err := os.ReadFile(filepath.Join(devPath, "uevent"))+ if err != nil {+ continue+ }+ for _, line := range strings.Split(string(uevent), "\n") {+ if strings.HasPrefix(line, "PCI_SLOT_NAME=") {+ pci := strings.TrimPrefix(line, "PCI_SLOT_NAME=")+ out[strings.ToLower(pci)] = pci+ }+ }+ }+ return out+}diff --git a/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner_test.go b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner_test.gonew file mode 100644index 00000000..12af656f--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/scanner_test.go@@ -0,0 +1,89 @@+package drmfdinfo++import (+ "os"+ "path/filepath"+ "testing"+)++func TestParseBusyNs(t *testing.T) {+ ns, err := parseBusyNs("12345 ns")+ if err != nil || ns != 12345 {+ t.Fatalf("got %d %v", ns, err)+ }+ ns, err = parseBusyNs("99")+ if err != nil || ns != 99 {+ t.Fatalf("got %d %v", ns, err)+ }+}++func TestParseMemBytes(t *testing.T) {+ b, ok := parseMemBytes("4 MiB")+ if !ok || b != 4*1024*1024 {+ t.Fatalf("got %d %v", b, ok)+ }+ b, ok = parseMemBytes("512 KiB")+ if !ok || b != 512*1024 {+ t.Fatalf("got %d %v", b, ok)+ }+}++func TestParseFdinfoFixture(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "fdinfo")+ content := `pos: 0+flags: 02100002+mnt_id: 19+ino: 123+drm-driver: amdgpu+drm-pdev: 0000:03:00.0+drm-client-id: 42+drm-engine-gfx: 1000 ns+drm-memory-vram: 8 MiB+`+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatal(err)+ }+ c, ok := parseFdinfo(path, 1234)+ if !ok {+ t.Fatal("expected parse ok")+ }+ if c.Driver != "amdgpu" || c.PCIAddress != "0000:03:00.0" || c.ClientID != "42" {+ t.Fatalf("unexpected client: %+v", c)+ }+ if c.EngineNs["gfx"] != 1000 {+ t.Fatalf("engine ns: %v", c.EngineNs)+ }+ if c.MemoryBy != 8*1024*1024 {+ t.Fatalf("memory: %d", c.MemoryBy)+ }+}++func TestParseFdinfoMemoryNoDoubleCount(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "fdinfo")+ content := `drm-driver: amdgpu+drm-pdev: 0000:03:00.0+drm-client-id: 1+drm-total-memory: 10 MiB+drm-memory-vram: 8 MiB+drm-resident-memory: 8 MiB+`+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatal(err)+ }+ c, ok := parseFdinfo(path, 1)+ if !ok {+ t.Fatal("expected parse ok")+ }+ if c.MemoryBy != 10*1024*1024 {+ t.Fatalf("expected total-memory only, got %d", c.MemoryBy)+ }+}++func TestPickPrimaryEngine(t *testing.T) {+ got := pickPrimaryEngine(map[string]uint64{"video": 9, "gfx": 1})+ if got != "gfx" {+ t.Fatalf("got %s", got)+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/shared.go b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/shared.gonew file mode 100644index 00000000..186bd756--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/drmfdinfo/shared.go@@ -0,0 +1,18 @@+package drmfdinfo++import "sync"++var (+ sharedMu sync.Mutex+ sharedScanner *Scanner+)++// Shared returns a process-wide Scanner so AMD/Intel devices share delta state.+func Shared() *Scanner {+ sharedMu.Lock()+ defer sharedMu.Unlock()+ if sharedScanner == nil {+ sharedScanner = NewScanner()+ }+ return sharedScanner+}diff --git a/opentelemetry-gpu-collector/internal/gpu/gpu.go b/opentelemetry-gpu-collector/internal/gpu/gpu.goindex 18138579..09ec8d87 100644--- a/opentelemetry-gpu-collector/internal/gpu/gpu.go+++ b/opentelemetry-gpu-collector/internal/gpu/gpu.go@@ -1,5 +1,7 @@package gpu+import "time"+// Vendor identifies the GPU manufacturer.type Vendor string@@ -18,6 +20,16 @@ type DeviceInfo struct {UUID stringPCIAddress stringDriverVersion string+ // CoreCount is the NVML CUDA core count when known (NVIDIA). Used by the+ // eBPF stream-sync occupancy model for process.gpu.core.usage normalization.+ CoreCount int++ // MIG identity (NVIDIA only). Empty when not a MIG instance.+ IsMIG bool+ ParentUUID string // physical GPU UUID when IsMIG+ MIGDeviceID string // MIG UUID+ MIGInstanceID int // GPU instance id; -1 if unknown+ MIGProfileName string}// Snapshot holds a point-in-time reading of all GPU metrics.@@ -46,11 +58,56 @@ type Snapshot struct {PCIeReplayErrors *int64 // cumulative PCIe replay counterECCSingleBit *int64 // correctable ECC errorsECCDoubleBit *int64 // uncorrectable ECC errors++ // PCIe throughput (bytes/sec). Soft-nil when unsupported.+ PCIeRxBytesPerSec *float64+ PCIeTxBytesPerSec *float64++ // Interconnect (NVLink / XGMI / Xe-Link) aggregate throughput.+ InterconnectRxBytesPerSec *float64+ InterconnectTxBytesPerSec *float64+ InterconnectType string // nvlink | xgmi | other; empty if unknown++ // ThrottleReasons is a stable string label (e.g. "sw_thermal,hw_thermal") when known.+ ThrottleReasons *string+ // Throttled is 1 when any throttle reason is active, 0 when explicitly not.+ Throttled *float64++ // XID / RAS critical error cumulative counters when available.+ XIDErrors *int64+ RASUE *int64 // uncorrectable RAS+ RASCE *int64 // correctable RAS+}++// ProcessUsage holds per-process GPU memory and utilization for one device.+// Nil pointer fields indicate the metric is unavailable for this process.+type ProcessUsage struct {+ PID int32+ ExecutableName string+ MemoryBytes *int64+ Utilization *float64 // 0..1 primary compute/render util+ EncoderUtil *float64+ DecoderUtil *float64++ // OS process metadata (filled by export enrichment; backends may leave empty).+ CommandLine string+ UserID string+ Username string+ StartTime time.Time // zero if unknown+ State string // running, sleeping, zombie, stopped, dead, unknown+ ContainerID string++ // Workload classification from cmdline/exe (export layer).+ WorkloadKind string // llm_inference | llm_training | other+ WorkloadFramework string // vllm | ollama | ...}// Device is the interface that all vendor GPU backends implement.type Device interface {Info() DeviceInfoCollect() (*Snapshot, error)+ // CollectProcesses returns processes currently using this GPU.+ // Returns an empty slice (not an error) when unsupported or none are found.+ CollectProcesses() ([]ProcessUsage, error)Close()}diff --git a/opentelemetry-gpu-collector/internal/gpu/igcl/igcl_windows.go b/opentelemetry-gpu-collector/internal/gpu/igcl/igcl_windows.gonew file mode 100644index 00000000..947156f3--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/igcl/igcl_windows.go@@ -0,0 +1,19 @@+//go:build windows++package igcl++import (+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/levelzero"+)++// Metrics aliases Level Zero Sysman metrics (IGCL/ControlLib path uses the same loader on Windows).+type Metrics = levelzero.Metrics++// Init loads Level Zero Sysman.+func Init() error { return levelzero.Init() }++// Available reports Sysman availability.+func Available() bool { return levelzero.Available() }++// CollectByIndex scrapes Intel GPU metrics for device index.+func CollectByIndex(index int) (Metrics, bool) { return levelzero.Collect(index) }diff --git a/opentelemetry-gpu-collector/internal/gpu/intel/intel.go b/opentelemetry-gpu-collector/internal/gpu/intel/intel_linux.gosimilarity index 69%rename from opentelemetry-gpu-collector/internal/gpu/intel/intel.gorename to opentelemetry-gpu-collector/internal/gpu/intel/intel_linux.goindex a04ef1b9..57fbded1 100644--- a/opentelemetry-gpu-collector/internal/gpu/intel/intel.go+++ b/opentelemetry-gpu-collector/internal/gpu/intel/intel_linux.go@@ -1,3 +1,5 @@+//go:build linux+package intelimport (@@ -9,6 +11,8 @@ import ("strings""github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/drmfdinfo"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/levelzero")const (@@ -18,19 +22,18 @@ const (// Device implements gpu.Device for Intel GPUs via sysfs/hwmon/DRM.type Device struct {- info gpu.DeviceInfo- drmPath string // e.g. /sys/class/drm/card0/device- hwmonPath string- logger *slog.Logger+ info gpu.DeviceInfo+ drmPath string // e.g. /sys/class/drm/card0/device+ hwmonPath string+ vendorIndex int // 0-based among Intel devices (for Level Zero)+ logger *slog.Logger}// DiscoverDevices scans sysfs for Intel GPU DRM cards driven by i915 or xe.+// When pciAddresses is empty, all i915/xe DRM cards are discovered (PCI-less fallback).func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger) ([]*Device, error) {- if len(pciAddresses) == 0 {- return nil, nil- }-addrSet := make(map[string]bool, len(pciAddresses))+ filter := len(pciAddresses) > 0for _, a := range pciAddresses {addrSet[strings.ToLower(a)] = true}@@ -42,6 +45,7 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)var devices []*Deviceidx := startIndex+ vendorIdx := 0for _, entry := range entries {name := entry.Name()@@ -56,7 +60,7 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)continue}- if !addrSet[strings.ToLower(pciAddr)] {+ if filter && !addrSet[strings.ToLower(pciAddr)] {continue}@@ -87,11 +91,13 @@ func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger)PCIAddress: pciAddr,DriverVersion: driverName,},- drmPath: devPath,- hwmonPath: hwmon,- logger: logger.With("gpu", idx, "vendor", "intel"),+ drmPath: devPath,+ hwmonPath: hwmon,+ vendorIndex: vendorIdx,+ logger: logger.With("gpu", idx, "vendor", "intel"),})idx+++ vendorIdx++}return devices, nil@@ -114,6 +120,46 @@ func (d *Device) Collect() (*gpu.Snapshot, error) {d.collectHwmon(s)}+ if m, ok := levelzero.Collect(d.vendorIndex); ok {+ if m.Utilization != nil {+ s.Utilization = m.Utilization+ }+ if m.MemoryTotal != nil {+ s.MemoryTotalBytes = m.MemoryTotal+ }+ if m.MemoryUsed != nil {+ s.MemoryUsedBytes = m.MemoryUsed+ if s.MemoryTotalBytes != nil {+ free := *s.MemoryTotalBytes - *m.MemoryUsed+ if free < 0 {+ free = 0+ }+ s.MemoryFreeBytes = &free+ }+ }+ if m.TemperatureC != nil && s.TemperatureGPU == nil {+ s.TemperatureGPU = m.TemperatureC+ }+ if m.PowerWatts != nil && s.PowerDrawWatts == nil {+ s.PowerDrawWatts = m.PowerWatts+ }+ if m.ClockMHz != nil && s.ClockGraphicsMHz == nil {+ s.ClockGraphicsMHz = m.ClockMHz+ }+ if m.Throttled != nil {+ s.Throttled = m.Throttled+ }+ if m.ThrottleReasons != nil {+ s.ThrottleReasons = m.ThrottleReasons+ }+ if m.EncoderUtilization != nil {+ s.EncoderUtilization = m.EncoderUtilization+ }+ if m.DecoderUtilization != nil {+ s.DecoderUtilization = m.DecoderUtilization+ }+ }+return s, nil}@@ -152,6 +198,13 @@ func (d *Device) collectHwmon(s *gpu.Snapshot) {func (d *Device) Close() {}+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return drmfdinfo.Shared().CollectForPCI(d.info.PCIAddress, map[string]bool{+ "i915": true,+ "xe": true,+ })+}+func findHwmonForDevice(drmDevicePath string) string {hwmonDir := filepath.Join(drmDevicePath, "hwmon")entries, err := os.ReadDir(hwmonDir)diff --git a/opentelemetry-gpu-collector/internal/gpu/intel/intel_stub.go b/opentelemetry-gpu-collector/internal/gpu/intel/intel_stub.gonew file mode 100644index 00000000..126b2bae--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/intel/intel_stub.go@@ -0,0 +1,30 @@+//go:build !linux && !windows++package intel++import (+ "fmt"+ "log/slog"+ "runtime"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+)++type Device struct {+ info gpu.DeviceInfo+}++func (d *Device) Info() gpu.DeviceInfo { return d.info }+func (d *Device) Collect() (*gpu.Snapshot, error) { return nil, errUnsupported() }+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return nil, errUnsupported()+}+func (d *Device) Close() {}++func DiscoverDevices(_ []string, _ int, _ *slog.Logger) ([]*Device, error) {+ return nil, errUnsupported()+}++func errUnsupported() error {+ return fmt.Errorf("Intel GPU monitoring requires linux or windows (current: %s/%s)", runtime.GOOS, runtime.GOARCH)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/intel/intel_windows.go b/opentelemetry-gpu-collector/internal/gpu/intel/intel_windows.gonew file mode 100644index 00000000..e5ca930b--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/intel/intel_windows.go@@ -0,0 +1,143 @@+//go:build windows++package intel++import (+ "fmt"+ "log/slog"+ "strings"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/igcl"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/windxg"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/winpdh"+)++// Device implements gpu.Device for Intel GPUs on Windows via DXGI + PDH + Level Zero Sysman.+type Device struct {+ info gpu.DeviceInfo+ adapter windxg.Adapter+ luidKey string+ vendorIndex int+ logger *slog.Logger+}++// DiscoverDevices discovers Intel adapters via DXGI.+func DiscoverDevices(pciAddresses []string, startIndex int, logger *slog.Logger) ([]*Device, error) {+ adapters, err := windxg.EnumAdapters()+ if err != nil {+ return nil, err+ }+ var devices []*Device+ idx := startIndex+ vendorIdx := 0+ for _, a := range adapters {+ if a.VendorID != windxg.VendorIntel {+ continue+ }+ lower := strings.ToLower(a.Name)+ if strings.Contains(lower, "microsoft") || strings.Contains(lower, "basic") {+ continue+ }+ uuid := a.LUIDKey+ pci := fmt.Sprintf("dxgi:%04X:%04X", a.VendorID, a.DeviceID)+ logger.Info("discovered Intel GPU", "name", a.Name, "luid", a.LUIDKey)+ devices = append(devices, &Device{+ info: gpu.DeviceInfo{+ Vendor: gpu.VendorIntel,+ Index: idx,+ Name: a.Name,+ UUID: uuid,+ PCIAddress: pci,+ },+ adapter: a,+ luidKey: a.LUIDKey,+ vendorIndex: vendorIdx,+ logger: logger.With("gpu", idx, "vendor", "intel"),+ })+ idx+++ vendorIdx+++ }+ return devices, nil+}++func (d *Device) Info() gpu.DeviceInfo { return d.info }++func (d *Device) Collect() (*gpu.Snapshot, error) {+ s := &gpu.Snapshot{}+ total := int64(d.adapter.DedicatedVideoMemory)+ if total > 0 {+ s.MemoryTotalBytes = &total+ }+ if au, ok := winpdh.AdapterSnapshot(d.luidKey); ok {+ if au.HasUtil {+ u := au.Util * 100+ s.Utilization = &u+ }+ if au.HasEnc {+ e := au.EncoderUtil * 100+ s.EncoderUtilization = &e+ }+ if au.HasDec {+ dec := au.DecoderUtil * 100+ s.DecoderUtilization = &dec+ }+ if au.HasMemory {+ used := au.MemoryUsed+ s.MemoryUsedBytes = &used+ if total > 0 {+ free := total - used+ if free < 0 {+ free = 0+ }+ s.MemoryFreeBytes = &free+ }+ }+ }+ if m, ok := igcl.CollectByIndex(d.vendorIndex); ok {+ if m.Utilization != nil {+ s.Utilization = m.Utilization+ }+ if m.MemoryTotal != nil {+ s.MemoryTotalBytes = m.MemoryTotal+ }+ if m.MemoryUsed != nil {+ s.MemoryUsedBytes = m.MemoryUsed+ if s.MemoryTotalBytes != nil {+ free := *s.MemoryTotalBytes - *m.MemoryUsed+ if free < 0 {+ free = 0+ }+ s.MemoryFreeBytes = &free+ }+ }+ if m.TemperatureC != nil {+ s.TemperatureGPU = m.TemperatureC+ }+ if m.PowerWatts != nil {+ s.PowerDrawWatts = m.PowerWatts+ }+ if m.ClockMHz != nil {+ s.ClockGraphicsMHz = m.ClockMHz+ }+ if m.Throttled != nil {+ s.Throttled = m.Throttled+ }+ if m.ThrottleReasons != nil {+ s.ThrottleReasons = m.ThrottleReasons+ }+ if m.EncoderUtilization != nil && s.EncoderUtilization == nil {+ s.EncoderUtilization = m.EncoderUtilization+ }+ if m.DecoderUtilization != nil && s.DecoderUtilization == nil {+ s.DecoderUtilization = m.DecoderUtilization+ }+ }+ return s, nil+}++func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return winpdh.CollectForLUID(d.luidKey)+}++func (d *Device) Close() {}diff --git a/opentelemetry-gpu-collector/internal/gpu/levelzero/levelzero.go b/opentelemetry-gpu-collector/internal/gpu/levelzero/levelzero.gonew file mode 100644index 00000000..77762c4b--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/levelzero/levelzero.go@@ -0,0 +1,366 @@+// Package levelzero reads Intel GPU metrics via oneAPI Level Zero Sysman.+package levelzero++import (+ "sync"+)++// Metrics is a Sysman sample for one device.+type Metrics struct {+ Utilization *float64 // 0-100 engine activity+ EncoderUtilization *float64 // 0-100 media encode / combined media+ DecoderUtilization *float64 // 0-100 media decode when split+ MemoryTotal *int64+ MemoryUsed *int64+ TemperatureC *float64+ PowerWatts *float64+ ClockMHz *float64+ ThrottleReasons *string+ Throttled *float64+}++const (+ zesStructureTypeEngineProperties = 0x5+ zesStructureTypeFreqState = 0x1b+ zesStructureTypeMemState = 0x1e++ zesEngineGroupAll = 0+ zesEngineGroupComputeAll = 1+ zesEngineGroupMediaAll = 2+ zesEngineGroupComputeSingle = 4+ zesEngineGroupRenderSingle = 5+ zesEngineGroupMediaDecodeSingle = 6+ zesEngineGroupMediaEncodeSingle = 7+ zesEngineGroupMediaEnhanceSingle = 9+ zesEngineGroup3DSingle = 10+ zesEngineGroup3DRenderComputeAll = 11+ zesEngineGroupRenderAll = 12+ zesEngineGroup3DAll = 13+ zesEngineGroupMediaCodecSingle = 14+)++type lib struct {+ zeInit func(uint32) int32+ zeDriverGet func(*uint32, *uintptr) int32+ zeDeviceGet func(uintptr, *uint32, *uintptr) int32+ zesInit func(uint32) int32+ zesDeviceEnumTemperatureSensors func(uintptr, *uint32, *uintptr) int32+ zesTemperatureGetState func(uintptr, *float64) int32+ zesDeviceEnumPowerDomains func(uintptr, *uint32, *uintptr) int32+ zesPowerGetEnergyCounter func(uintptr, *zesEnergy) int32+ zesDeviceEnumMemoryModules func(uintptr, *uint32, *uintptr) int32+ zesMemoryGetState func(uintptr, *zesMemState) int32+ zesDeviceEnumEngineGroups func(uintptr, *uint32, *uintptr) int32+ zesEngineGetActivity func(uintptr, *zesEngineStats) int32+ zesEngineGetProperties func(uintptr, *zesEngineProps) int32+ zesDeviceEnumFrequencyDomains func(uintptr, *uint32, *uintptr) int32+ zesFrequencyGetState func(uintptr, *zesFreqState) int32+}++// zes_power_energy_counter_t+type zesEnergy struct {+ Energy uint64+ Timestamp uint64+}++// zes_mem_state_t — stype/pNext/health/free/size (Go inserts ABI padding).+type zesMemState struct {+ Stype uint32+ PNext uintptr+ Health uint32+ Free uint64+ Size uint64+}++// zes_engine_stats_t+type zesEngineStats struct {+ ActiveTime uint64+ Timestamp uint64+}++// zes_engine_properties_t+type zesEngineProps struct {+ Stype uint32+ PNext uintptr+ Type uint32+ OnSubdevice uint8+ _ [3]byte+ SubdeviceId uint32+}++// zes_freq_state_t+type zesFreqState struct {+ Stype uint32+ PNext uintptr+ CurrentVoltage float64+ Request float64+ Tdp float64+ Efficient float64+ Actual float64+ ThrottleReasons uint32+}++type devicePrev struct {+ engines map[uintptr]zesEngineStats+ power map[uintptr]zesEnergy+}++var (+ once sync.Once+ l *lib+ errL error++ prevByDev = map[uintptr]*devicePrev{}+ mu sync.Mutex++ devicesMu sync.Mutex+ cachedDevices []uintptr+)++// Available reports whether Sysman can be used.+func Available() bool {+ return Init() == nil && l != nil+}++func prevFor(dev uintptr) *devicePrev {+ p, ok := prevByDev[dev]+ if !ok {+ p = &devicePrev{+ engines: make(map[uintptr]zesEngineStats),+ power: make(map[uintptr]zesEnergy),+ }+ prevByDev[dev] = p+ }+ return p+}++func listDevices() []uintptr {+ devicesMu.Lock()+ defer devicesMu.Unlock()+ if cachedDevices != nil {+ return cachedDevices+ }+ var driverCount uint32+ if rc := l.zeDriverGet(&driverCount, nil); rc != 0 || driverCount == 0 {+ return nil+ }+ drivers := make([]uintptr, driverCount)+ if rc := l.zeDriverGet(&driverCount, &drivers[0]); rc != 0 {+ return nil+ }+ var all []uintptr+ for _, drv := range drivers {+ var n uint32+ if rc := l.zeDeviceGet(drv, &n, nil); rc != 0 || n == 0 {+ continue+ }+ devs := make([]uintptr, n)+ if rc := l.zeDeviceGet(drv, &n, &devs[0]); rc != 0 {+ continue+ }+ all = append(all, devs...)+ }+ cachedDevices = all+ return cachedDevices+}++// Collect returns metrics for the deviceIndex-th Level Zero device.+func Collect(deviceIndex int) (Metrics, bool) {+ if !Available() {+ return Metrics{}, false+ }+ allDevices := listDevices()+ if deviceIndex < 0 || deviceIndex >= len(allDevices) {+ return Metrics{}, false+ }+ dev := allDevices[deviceIndex]+ m := Metrics{}++ if l.zesDeviceEnumMemoryModules != nil && l.zesMemoryGetState != nil {+ var n uint32+ if l.zesDeviceEnumMemoryModules(dev, &n, nil) == 0 && n > 0 {+ mods := make([]uintptr, n)+ if l.zesDeviceEnumMemoryModules(dev, &n, &mods[0]) == 0 {+ var total, free uint64+ for _, mod := range mods {+ var st zesMemState+ st.Stype = zesStructureTypeMemState+ if l.zesMemoryGetState(mod, &st) == 0 {+ total += st.Size+ free += st.Free+ }+ }+ if total > 0 {+ t := int64(total)+ m.MemoryTotal = &t+ used := total+ if free <= total {+ used = total - free+ }+ u := int64(used)+ m.MemoryUsed = &u+ }+ }+ }+ }++ if l.zesDeviceEnumTemperatureSensors != nil && l.zesTemperatureGetState != nil {+ var n uint32+ if l.zesDeviceEnumTemperatureSensors(dev, &n, nil) == 0 && n > 0 {+ sensors := make([]uintptr, n)+ if l.zesDeviceEnumTemperatureSensors(dev, &n, &sensors[0]) == 0 {+ var temp float64+ if l.zesTemperatureGetState(sensors[0], &temp) == 0 {+ m.TemperatureC = &temp+ }+ }+ }+ }++ if l.zesDeviceEnumFrequencyDomains != nil && l.zesFrequencyGetState != nil {+ var n uint32+ if l.zesDeviceEnumFrequencyDomains(dev, &n, nil) == 0 && n > 0 {+ doms := make([]uintptr, n)+ if l.zesDeviceEnumFrequencyDomains(dev, &n, &doms[0]) == 0 {+ var st zesFreqState+ st.Stype = zesStructureTypeFreqState+ if l.zesFrequencyGetState(doms[0], &st) == 0 {+ if st.Actual >= 0 {+ m.ClockMHz = &st.Actual+ }+ if st.ThrottleReasons != 0 {+ t := 1.0+ m.Throttled = &t+ r := "hw_throttle"+ m.ThrottleReasons = &r+ } else {+ t := 0.0+ m.Throttled = &t+ }+ }+ }+ }+ }++ if l.zesDeviceEnumEngineGroups != nil && l.zesEngineGetActivity != nil {+ var n uint32+ if l.zesDeviceEnumEngineGroups(dev, &n, nil) == 0 && n > 0 {+ engs := make([]uintptr, n)+ if l.zesDeviceEnumEngineGroups(dev, &n, &engs[0]) == 0 {+ type bucket struct{ active, time uint64 }+ var genAll, genSingle, enc, dec, media bucket+ var hasGenAll, hasEnc, hasDec bool+ seen := make(map[uintptr]struct{}, len(engs))+ mu.Lock()+ p := prevFor(dev)+ for _, eng := range engs {+ var st zesEngineStats+ if l.zesEngineGetActivity(eng, &st) != 0 {+ continue+ }+ seen[eng] = struct{}{}+ var dActive, dTime uint64+ if prev, ok := p.engines[eng]; ok &&+ st.Timestamp > prev.Timestamp &&+ st.ActiveTime >= prev.ActiveTime {+ dActive = st.ActiveTime - prev.ActiveTime+ dTime = st.Timestamp - prev.Timestamp+ }+ p.engines[eng] = st+ if dTime == 0 {+ continue+ }+ engType := uint32(zesEngineGroupAll)+ if l.zesEngineGetProperties != nil {+ var props zesEngineProps+ props.Stype = zesStructureTypeEngineProperties+ if l.zesEngineGetProperties(eng, &props) == 0 {+ engType = props.Type+ }+ }+ switch engType {+ case zesEngineGroupAll, zesEngineGroupComputeAll,+ zesEngineGroup3DRenderComputeAll, zesEngineGroupRenderAll, zesEngineGroup3DAll:+ hasGenAll = true+ genAll.active += dActive+ genAll.time += dTime+ case zesEngineGroupComputeSingle, zesEngineGroupRenderSingle, zesEngineGroup3DSingle:+ genSingle.active += dActive+ genSingle.time += dTime+ case zesEngineGroupMediaEncodeSingle:+ hasEnc = true+ enc.active += dActive+ enc.time += dTime+ case zesEngineGroupMediaDecodeSingle:+ hasDec = true+ dec.active += dActive+ dec.time += dTime+ case zesEngineGroupMediaAll, zesEngineGroupMediaEnhanceSingle, zesEngineGroupMediaCodecSingle:+ media.active += dActive+ media.time += dTime+ }+ }+ for k := range p.engines {+ if _, ok := seen[k]; !ok {+ delete(p.engines, k)+ }+ }+ mu.Unlock()++ utilBucket := genSingle+ if hasGenAll {+ utilBucket = genAll+ }+ if utilBucket.time > 0 {+ u := 100.0 * float64(utilBucket.active) / float64(utilBucket.time)+ m.Utilization = &u+ }+ if hasEnc && enc.time > 0 {+ e := 100.0 * float64(enc.active) / float64(enc.time)+ m.EncoderUtilization = &e+ } else if !hasEnc && media.time > 0 {+ // Combined media → encoder only (do not invent decoder).+ e := 100.0 * float64(media.active) / float64(media.time)+ m.EncoderUtilization = &e+ }+ if hasDec && dec.time > 0 {+ d := 100.0 * float64(dec.active) / float64(dec.time)+ m.DecoderUtilization = &d+ }+ }+ }+ }++ if l.zesDeviceEnumPowerDomains != nil && l.zesPowerGetEnergyCounter != nil {+ var n uint32+ if l.zesDeviceEnumPowerDomains(dev, &n, nil) == 0 && n > 0 {+ doms := make([]uintptr, n)+ if l.zesDeviceEnumPowerDomains(dev, &n, &doms[0]) == 0 {+ var en zesEnergy+ if l.zesPowerGetEnergyCounter(doms[0], &en) == 0 {+ mu.Lock()+ p := prevFor(dev)+ prev, ok := p.power[doms[0]]+ p.power[doms[0]] = en+ for k := range p.power {+ if k != doms[0] {+ delete(p.power, k)+ }+ }+ mu.Unlock()+ if ok && en.Timestamp > prev.Timestamp && en.Energy >= prev.Energy {+ dt := float64(en.Timestamp-prev.Timestamp) / 1e6+ if dt > 0 {+ pw := (float64(en.Energy-prev.Energy) / 1e6) / dt+ m.PowerWatts = &pw+ }+ }+ }+ }+ }+ }++ ok := m.Utilization != nil || m.EncoderUtilization != nil || m.DecoderUtilization != nil ||+ m.MemoryTotal != nil || m.TemperatureC != nil || m.PowerWatts != nil || m.ClockMHz != nil || m.Throttled != nil+ return m, ok+}diff --git a/opentelemetry-gpu-collector/internal/gpu/levelzero/load_unix.go b/opentelemetry-gpu-collector/internal/gpu/levelzero/load_unix.gonew file mode 100644index 00000000..54918d83--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/levelzero/load_unix.go@@ -0,0 +1,68 @@+//go:build linux || darwin || freebsd || netbsd++package levelzero++import (+ "fmt"+ "os"++ "github.com/ebitengine/purego"+)++// Init loads Level Zero on Unix.+func Init() error {+ once.Do(func() {+ h, err := purego.Dlopen("libze_loader.so.1", purego.RTLD_NOW|purego.RTLD_GLOBAL)+ if err != nil {+ h, err = purego.Dlopen("libze_loader.so", purego.RTLD_NOW|purego.RTLD_GLOBAL)+ }+ if err != nil {+ errL = fmt.Errorf("dlopen libze_loader: %w", err)+ return+ }+ nl := &lib{}+ bind := func(name string, fptr any) {+ sym, err := purego.Dlsym(h, name)+ if err != nil {+ return+ }+ purego.RegisterFunc(fptr, sym)+ }+ bind("zeInit", &nl.zeInit)+ bind("zeDriverGet", &nl.zeDriverGet)+ bind("zeDeviceGet", &nl.zeDeviceGet)+ bind("zesInit", &nl.zesInit)+ bind("zesDeviceEnumTemperatureSensors", &nl.zesDeviceEnumTemperatureSensors)+ bind("zesTemperatureGetState", &nl.zesTemperatureGetState)+ bind("zesDeviceEnumPowerDomains", &nl.zesDeviceEnumPowerDomains)+ bind("zesPowerGetEnergyCounter", &nl.zesPowerGetEnergyCounter)+ bind("zesDeviceEnumMemoryModules", &nl.zesDeviceEnumMemoryModules)+ bind("zesMemoryGetState", &nl.zesMemoryGetState)+ bind("zesDeviceEnumEngineGroups", &nl.zesDeviceEnumEngineGroups)+ bind("zesEngineGetActivity", &nl.zesEngineGetActivity)+ bind("zesEngineGetProperties", &nl.zesEngineGetProperties)+ bind("zesDeviceEnumFrequencyDomains", &nl.zesDeviceEnumFrequencyDomains)+ bind("zesFrequencyGetState", &nl.zesFrequencyGetState)+ if nl.zeInit == nil || nl.zeDriverGet == nil || nl.zeDeviceGet == nil {+ errL = fmt.Errorf("level zero symbols missing")+ return+ }+ // ze device handles are valid for zes* when Sysman is enabled via env+ // (legacy) and/or explicit zesInit.+ if os.Getenv("ZES_ENABLE_SYSMAN") == "" {+ _ = os.Setenv("ZES_ENABLE_SYSMAN", "1")+ }+ if rc := nl.zeInit(0); rc != 0 {+ errL = fmt.Errorf("zeInit: %d", rc)+ return+ }+ if nl.zesInit != nil {+ if rc := nl.zesInit(0); rc != 0 {+ // Non-fatal: some loaders only need ZES_ENABLE_SYSMAN + zeInit.+ _ = rc+ }+ }+ l = nl+ })+ return errL+}diff --git a/opentelemetry-gpu-collector/internal/gpu/levelzero/load_windows.go b/opentelemetry-gpu-collector/internal/gpu/levelzero/load_windows.gonew file mode 100644index 00000000..a5e84db4--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/levelzero/load_windows.go@@ -0,0 +1,65 @@+//go:build windows++package levelzero++import (+ "fmt"+ "os"+ "syscall"++ "github.com/ebitengine/purego"+ "golang.org/x/sys/windows"+)++// Init loads Level Zero on Windows via ze_loader.dll.+func Init() error {+ once.Do(func() {+ h, err := windows.LoadLibrary("ze_loader.dll")+ if err != nil {+ errL = fmt.Errorf("LoadLibrary ze_loader.dll: %w", err)+ return+ }+ nl := &lib{}+ bind := func(name string, fptr any) {+ addr, err := windows.GetProcAddress(h, name)+ if err != nil {+ return+ }+ purego.RegisterFunc(fptr, uintptr(addr))+ }+ bind("zeInit", &nl.zeInit)+ bind("zeDriverGet", &nl.zeDriverGet)+ bind("zeDeviceGet", &nl.zeDeviceGet)+ bind("zesInit", &nl.zesInit)+ bind("zesDeviceEnumTemperatureSensors", &nl.zesDeviceEnumTemperatureSensors)+ bind("zesTemperatureGetState", &nl.zesTemperatureGetState)+ bind("zesDeviceEnumPowerDomains", &nl.zesDeviceEnumPowerDomains)+ bind("zesPowerGetEnergyCounter", &nl.zesPowerGetEnergyCounter)+ bind("zesDeviceEnumMemoryModules", &nl.zesDeviceEnumMemoryModules)+ bind("zesMemoryGetState", &nl.zesMemoryGetState)+ bind("zesDeviceEnumEngineGroups", &nl.zesDeviceEnumEngineGroups)+ bind("zesEngineGetActivity", &nl.zesEngineGetActivity)+ bind("zesEngineGetProperties", &nl.zesEngineGetProperties)+ bind("zesDeviceEnumFrequencyDomains", &nl.zesDeviceEnumFrequencyDomains)+ bind("zesFrequencyGetState", &nl.zesFrequencyGetState)+ if nl.zeInit == nil || nl.zeDriverGet == nil || nl.zeDeviceGet == nil {+ errL = fmt.Errorf("level zero symbols missing")+ _ = windows.FreeLibrary(h)+ return+ }+ if os.Getenv("ZES_ENABLE_SYSMAN") == "" {+ _ = os.Setenv("ZES_ENABLE_SYSMAN", "1")+ }+ if rc := nl.zeInit(0); rc != 0 {+ errL = fmt.Errorf("zeInit: %d", rc)+ _ = windows.FreeLibrary(h)+ return+ }+ if nl.zesInit != nil {+ _ = nl.zesInit(0)+ }+ l = nl+ _ = syscall.Handle(h)+ })+ return errL+}diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/extended_linux.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/extended_linux.gonew file mode 100644index 00000000..2632b255--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/extended_linux.go@@ -0,0 +1,103 @@+//go:build linux && (amd64 || arm64) && cgo++package nvidia++import (+ "strings"+ "sync/atomic"+ "time"++ "github.com/NVIDIA/go-nvml/pkg/nvml"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+)++func collectExtended(d *Device, s *gpu.Snapshot) {+ // PCIe throughput: NVML returns KB/s.+ if rx, ret := d.handle.GetPcieThroughput(nvml.PCIE_UTIL_RX_BYTES); ret == nvml.SUCCESS {+ v := float64(rx) * 1024.0+ s.PCIeRxBytesPerSec = &v+ }+ if tx, ret := d.handle.GetPcieThroughput(nvml.PCIE_UTIL_TX_BYTES); ret == nvml.SUCCESS {+ v := float64(tx) * 1024.0+ s.PCIeTxBytesPerSec = &v+ }++ if reasons, ret := d.handle.GetCurrentClocksThrottleReasons(); ret == nvml.SUCCESS {+ label := throttleLabel(reasons)+ s.ThrottleReasons = &label+ th := 0.0+ // Idle-only is not "throttled" for LLM health; treat thermal/power as throttled.+ if reasons&(nvml.ClocksThrottleReasonSwThermalSlowdown|+ nvml.ClocksThrottleReasonHwThermalSlowdown|+ nvml.ClocksThrottleReasonHwSlowdown|+ nvml.ClocksThrottleReasonSwPowerCap|+ nvml.ClocksThrottleReasonHwPowerBrakeSlowdown) != 0 {+ th = 1.0+ }+ s.Throttled = &th+ }++ collectNvLink(d, s)++ if xid := atomic.LoadInt64(&d.xidCount); xid > 0 {+ v := xid+ s.XIDErrors = &v+ }+}++func collectNvLink(d *Device, s *gpu.Snapshot) {+ var rxTotal, txTotal uint64+ var links int+ now := time.Now()+ for link := 0; link < 18; link++ {+ state, ret := d.handle.GetNvLinkState(link)+ if ret != nvml.SUCCESS || state != nvml.FEATURE_ENABLED {+ continue+ }+ rx, tx, ret := d.handle.GetNvLinkUtilizationCounter(link, 0)+ if ret != nvml.SUCCESS {+ continue+ }+ rxTotal += rx+ txTotal += tx+ links+++ }+ if links == 0 {+ return+ }+ s.InterconnectType = "nvlink"+ if !d.nvlinkLast.IsZero() {+ dt := now.Sub(d.nvlinkLast).Seconds()+ if dt > 0 && rxTotal >= d.nvlinkRxPrev && txTotal >= d.nvlinkTxPrev {+ rxRate := float64(rxTotal-d.nvlinkRxPrev) / dt+ txRate := float64(txTotal-d.nvlinkTxPrev) / dt+ s.InterconnectRxBytesPerSec = &rxRate+ s.InterconnectTxBytesPerSec = &txRate+ }+ }+ d.nvlinkRxPrev = rxTotal+ d.nvlinkTxPrev = txTotal+ d.nvlinkLast = now+}++func throttleLabel(reasons uint64) string {+ var parts []string+ add := func(bit uint64, name string) {+ if reasons&bit != 0 {+ parts = append(parts, name)+ }+ }+ add(nvml.ClocksThrottleReasonGpuIdle, "gpu_idle")+ add(nvml.ClocksThrottleReasonApplicationsClocksSetting, "apps_clocks")+ add(nvml.ClocksThrottleReasonSwPowerCap, "sw_power_cap")+ add(nvml.ClocksThrottleReasonHwSlowdown, "hw_slowdown")+ add(nvml.ClocksThrottleReasonSyncBoost, "sync_boost")+ add(nvml.ClocksThrottleReasonSwThermalSlowdown, "sw_thermal")+ add(nvml.ClocksThrottleReasonHwThermalSlowdown, "hw_thermal")+ add(nvml.ClocksThrottleReasonHwPowerBrakeSlowdown, "hw_power_brake")+ add(nvml.ClocksThrottleReasonDisplayClockSetting, "display_clock")+ if len(parts) == 0 {+ return "none"+ }+ return strings.Join(parts, ",")+}diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia.goindex c0f96777..c111e88f 100644--- a/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia.go+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia.go@@ -6,37 +6,65 @@ import ("fmt""log/slog""sync"+ "time""github.com/NVIDIA/go-nvml/pkg/nvml""github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procname")var (- initOnce sync.Once+ initMu sync.Mutex+ initDone boolinitErr error)// InitNVML initializes the NVML library. Safe to call multiple times.+// Failed inits are retried on later calls so a transient driver miss during+// early DaemonSet start does not permanently disable discovery.func InitNVML() error {- initOnce.Do(func() {- ret := nvml.Init()- if ret != nvml.SUCCESS {- initErr = fmt.Errorf("nvml.Init: %s", nvml.ErrorString(ret))- }- })- return initErr+ initMu.Lock()+ defer initMu.Unlock()+ if initDone && initErr == nil {+ return nil+ }+ ret := nvml.Init()+ if ret != nvml.SUCCESS {+ initDone = false+ initErr = fmt.Errorf("nvml.Init: %s", nvml.ErrorString(ret))+ return initErr+ }+ initDone = true+ initErr = nil+ return nil}// ShutdownNVML shuts down the NVML library.func ShutdownNVML() {- nvml.Shutdown()+ initMu.Lock()+ defer initMu.Unlock()+ if initDone {+ nvml.Shutdown()+ }+ initDone = false+ initErr = nil}// Device implements gpu.Device for NVIDIA GPUs via NVML.type Device struct {- handle nvml.Device- info gpu.DeviceInfo- logger *slog.Logger+ handle nvml.Device+ info gpu.DeviceInfo+ logger *slog.Logger+ lastUtilTimestamp uint64+ migMemoryOnlyLogged bool++ nvlinkRxPrev uint64+ nvlinkTxPrev uint64+ nvlinkLast time.Time+ xidCount int64+ eventSet nvml.EventSet+ closed int32+ xidDone chan struct{}}// DiscoverDevices returns all NVIDIA GPUs detected by NVML.@@ -56,6 +84,7 @@ func DiscoverDevices(logger *slog.Logger) ([]*Device, error) {}devices := make([]*Device, 0, count)+ idx := 0for i := 0; i < count; i++ {handle, ret := nvml.DeviceGetHandleByIndex(i)if ret != nvml.SUCCESS {@@ -66,19 +95,68 @@ func DiscoverDevices(logger *slog.Logger) ([]*Device, error) {name, _ := handle.GetName()uuid, _ := handle.GetUUID()pciInfo, _ := handle.GetPciInfo()+ coreCount := 0+ if cores, ret := handle.GetNumGpuCores(); ret == nvml.SUCCESS {+ coreCount = cores+ }- devices = append(devices, &Device{+ parent := &Device{handle: handle,info: gpu.DeviceInfo{Vendor: gpu.VendorNVIDIA,- Index: i,+ Index: idx,Name: name,UUID: uuid,PCIAddress: pciAddressString(pciInfo),DriverVersion: driverVersion,+ CoreCount: coreCount,},- logger: logger.With("gpu", i, "vendor", "nvidia"),- })+ logger: logger.With("gpu", idx, "vendor", "nvidia"),+ }+ idx+++ parent.startXIDWatcher(parent.logger)+ devices = append(devices, parent)++ // Enumerate MIG instances as first-class devices when enabled.+ current, pending, ret := handle.GetMigMode()+ if ret == nvml.SUCCESS && current == nvml.DEVICE_MIG_ENABLE {+ _ = pending+ maxMig, ret := handle.GetMaxMigDeviceCount()+ if ret != nvml.SUCCESS {+ continue+ }+ for mi := 0; mi < maxMig; mi++ {+ migHandle, ret := handle.GetMigDeviceHandleByIndex(mi)+ if ret != nvml.SUCCESS {+ continue+ }+ migName, _ := migHandle.GetName()+ migUUID, _ := migHandle.GetUUID()+ giID := -1+ if id, ret := migHandle.GetGpuInstanceId(); ret == nvml.SUCCESS {+ giID = id+ }+ migDev := &Device{+ handle: migHandle,+ info: gpu.DeviceInfo{+ Vendor: gpu.VendorNVIDIA,+ Index: idx,+ Name: migName,+ UUID: migUUID,+ PCIAddress: parent.info.PCIAddress,+ DriverVersion: driverVersion,+ IsMIG: true,+ ParentUUID: uuid,+ MIGDeviceID: migUUID,+ MIGInstanceID: giID,+ MIGProfileName: migName,+ },+ logger: logger.With("gpu", idx, "vendor", "nvidia", "mig", true),+ }+ idx+++ devices = append(devices, migDev)+ }+ }}return devices, nil@@ -113,10 +191,7 @@ func (d *Device) Collect() (*gpu.Snapshot, error) {s.TemperatureGPU = &v}- if fanSpeed, ret := d.handle.GetFanSpeed(); ret == nvml.SUCCESS {- v := float64(fanSpeed)- s.FanSpeedRPM = &v- }+ // NVML GetFanSpeed is percent (0–100), not RPM — omit FanSpeedRPM (AMD/Intel use hwmon RPM).if mem, ret := d.handle.GetMemoryInfo(); ret == nvml.SUCCESS {total := int64(mem.Total)@@ -169,10 +244,79 @@ func (d *Device) Collect() (*gpu.Snapshot, error) {s.ECCDoubleBit = &v}+ if !d.info.IsMIG {+ collectExtended(d, s)+ }+return s, nil}-func (d *Device) Close() {}+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ procs, ret := d.handle.GetComputeRunningProcesses()+ if ret != nvml.SUCCESS {+ // MIG / unsupported — try empty rather than fail the scrape+ d.logger.Debug("GetComputeRunningProcesses unavailable", "error", nvml.ErrorString(ret))+ return nil, nil+ }++ byPID := make(map[uint32]*gpu.ProcessUsage, len(procs))+ for _, p := range procs {+ mem := int64(p.UsedGpuMemory)+ pu := &gpu.ProcessUsage{+ PID: int32(p.Pid),+ ExecutableName: procname.ExecutableName(int32(p.Pid)),+ MemoryBytes: &mem,+ }+ byPID[p.Pid] = pu+ }++ samples, ret := d.handle.GetProcessUtilization(d.lastUtilTimestamp)+ if ret == nvml.SUCCESS {+ var maxTS uint64+ for _, s := range samples {+ if s.TimeStamp > maxTS {+ maxTS = s.TimeStamp+ }+ pu := byPID[s.Pid]+ if pu == nil {+ pu = &gpu.ProcessUsage{+ PID: int32(s.Pid),+ ExecutableName: procname.ExecutableName(int32(s.Pid)),+ }+ byPID[s.Pid] = pu+ }+ // NVML reports percent 0–100+ sm := float64(s.SmUtil) / 100.0+ pu.Utilization = &sm+ if s.EncUtil > 0 || pu.EncoderUtil == nil {+ enc := float64(s.EncUtil) / 100.0+ pu.EncoderUtil = &enc+ }+ if s.DecUtil > 0 || pu.DecoderUtil == nil {+ dec := float64(s.DecUtil) / 100.0+ pu.DecoderUtil = &dec+ }+ }+ if maxTS > 0 {+ d.lastUtilTimestamp = maxTS+ }+ } else if len(byPID) > 0 && !d.migMemoryOnlyLogged {+ // Common on MIG: memory list works, util samples do not.+ d.logger.Debug("GetProcessUtilization unavailable; emitting memory-only process metrics",+ "error", nvml.ErrorString(ret))+ d.migMemoryOnlyLogged = true+ }++ out := make([]gpu.ProcessUsage, 0, len(byPID))+ for _, pu := range byPID {+ out = append(out, *pu)+ }+ return out, nil+}++func (d *Device) Close() {+ d.stopXIDWatcher()+}func pciAddressString(pci nvml.PciInfo) string {// PciInfo.BusId is a fixed-size byte array; convert to string.diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_stub.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_stub.goindex 73f1e938..18abb0da 100644--- a/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_stub.go+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_stub.go@@ -1,4 +1,4 @@-//go:build !(linux && (amd64 || arm64) && cgo)+//go:build !(linux && (amd64 || arm64) && cgo) && !(windows && (amd64 || arm64))package nvidia@@ -10,26 +10,26 @@ import ("github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu")-// Device is a stub for platforms/builds where NVML is unavailable-// (non-Linux, unsupported arch, or CGO disabled).+// Device is a stub for platforms/builds where NVML is unavailable.type Device struct {info gpu.DeviceInfo}func (d *Device) Info() gpu.DeviceInfo { return d.info }func (d *Device) Collect() (*gpu.Snapshot, error) { return nil, errUnsupported() }-func (d *Device) Close() {}+func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ return nil, errUnsupported()+}+func (d *Device) Close() {}func DiscoverDevices(_ *slog.Logger) ([]*Device, error) {return nil, errUnsupported()}-// InitNVML is a no-op on unsupported builds; included so callers don't need-// build tags to invoke it.func InitNVML() error { return errUnsupported() }func ShutdownNVML() {}func errUnsupported() error {- return fmt.Errorf("NVIDIA NVML support requires linux/amd64 or linux/arm64 with cgo enabled (current: %s/%s)", runtime.GOOS, runtime.GOARCH)+ return fmt.Errorf("NVIDIA NVML support requires linux/(amd64|arm64)+cgo or windows/(amd64|arm64) (current: %s/%s)", runtime.GOOS, runtime.GOARCH)}diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_windows.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_windows.gonew file mode 100644index 00000000..25d18d4d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/nvidia_windows.go@@ -0,0 +1,442 @@+//go:build windows && (amd64 || arm64)++package nvidia++import (+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "sync"+ "syscall"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/windxg"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/winpdh"+)++const (+ nvmlSuccess = 0+ nvmlTempGPU = 0+ nvmlClockGraphics = 0+ nvmlClockMem = 1+ nvmlMemoryErrorCorrected = 0+ nvmlMemoryErrorUncorrected = 1+ nvmlVolatileECC = 0+ nvmlFeatureEnabled = 1+)++var (+ initMu sync.Mutex+ initDone bool+ initErr error+ nvmlDLL *windows.LazyDLL++ nvmlInit_v2 *windows.LazyProc+ nvmlShutdown *windows.LazyProc+ nvmlDeviceGetCount_v2 *windows.LazyProc+ nvmlDeviceGetHandleByIndex_v2 *windows.LazyProc+ nvmlDeviceGetName *windows.LazyProc+ nvmlDeviceGetUUID *windows.LazyProc+ nvmlDeviceGetPciInfo_v3 *windows.LazyProc+ nvmlDeviceGetUtilizationRates *windows.LazyProc+ nvmlDeviceGetMemoryInfo *windows.LazyProc+ nvmlDeviceGetTemperature *windows.LazyProc+ nvmlDeviceGetPowerUsage *windows.LazyProc+ nvmlDeviceGetPowerManagementLimit *windows.LazyProc+ nvmlDeviceGetTotalEnergyConsumption *windows.LazyProc+ nvmlDeviceGetClockInfo *windows.LazyProc+ nvmlDeviceGetPcieReplayCounter *windows.LazyProc+ nvmlDeviceGetTotalEccErrors *windows.LazyProc+ nvmlDeviceGetEncoderUtilization *windows.LazyProc+ nvmlDeviceGetDecoderUtilization *windows.LazyProc+ nvmlDeviceGetNumGpuCores *windows.LazyProc+ nvmlSystemGetDriverVersion *windows.LazyProc+ nvmlDeviceGetPcieThroughput *windows.LazyProc+ nvmlDeviceGetCurrentClocksThrottleReasons *windows.LazyProc+ nvmlDeviceGetNvLinkState *windows.LazyProc+ nvmlDeviceGetNvLinkUtilizationCounter *windows.LazyProc+)++type nvmlUtilization struct {+ Gpu uint32+ Memory uint32+}++type nvmlMemory struct {+ Total uint64+ Free uint64+ Used uint64+}++type nvmlPciInfo struct {+ BusIdLegacy [16]byte+ Domain uint32+ Bus uint32+ Device uint32+ PciDeviceId uint32+ PciSubSystemId uint32+ BusId [32]byte+}++// Device implements gpu.Device for NVIDIA GPUs via nvml.dll on Windows.+type Device struct {+ handle uintptr+ info gpu.DeviceInfo+ luidKey string+ logger *slog.Logger+ nvlinkRxPrev uint64+ nvlinkTxPrev uint64+ nvlinkLast time.Time+}++func loadNVML() error {+ candidates := []string{+ "nvml.dll",+ filepath.Join(os.Getenv("SystemRoot"), "System32", "nvml.dll"),+ }+ if prog := os.Getenv("ProgramW6432"); prog != "" {+ candidates = append(candidates, filepath.Join(prog, "NVIDIA Corporation", "NVSMI", "nvml.dll"))+ }+ if prog := os.Getenv("ProgramFiles"); prog != "" {+ candidates = append(candidates, filepath.Join(prog, "NVIDIA Corporation", "NVSMI", "nvml.dll"))+ }++ var lastErr error+ for _, path := range candidates {+ dll := windows.NewLazyDLL(path)+ if err := dll.Load(); err != nil {+ lastErr = err+ continue+ }+ nvmlDLL = dll+ bindProcs()+ return nil+ }+ if lastErr == nil {+ lastErr = fmt.Errorf("nvml.dll not found")+ }+ return lastErr+}++func bindProcs() {+ nvmlInit_v2 = nvmlDLL.NewProc("nvmlInit_v2")+ nvmlShutdown = nvmlDLL.NewProc("nvmlShutdown")+ nvmlDeviceGetCount_v2 = nvmlDLL.NewProc("nvmlDeviceGetCount_v2")+ nvmlDeviceGetHandleByIndex_v2 = nvmlDLL.NewProc("nvmlDeviceGetHandleByIndex_v2")+ nvmlDeviceGetName = nvmlDLL.NewProc("nvmlDeviceGetName")+ nvmlDeviceGetUUID = nvmlDLL.NewProc("nvmlDeviceGetUUID")+ nvmlDeviceGetPciInfo_v3 = nvmlDLL.NewProc("nvmlDeviceGetPciInfo_v3")+ nvmlDeviceGetUtilizationRates = nvmlDLL.NewProc("nvmlDeviceGetUtilizationRates")+ nvmlDeviceGetMemoryInfo = nvmlDLL.NewProc("nvmlDeviceGetMemoryInfo")+ nvmlDeviceGetTemperature = nvmlDLL.NewProc("nvmlDeviceGetTemperature")+ nvmlDeviceGetPowerUsage = nvmlDLL.NewProc("nvmlDeviceGetPowerUsage")+ nvmlDeviceGetPowerManagementLimit = nvmlDLL.NewProc("nvmlDeviceGetPowerManagementLimit")+ nvmlDeviceGetTotalEnergyConsumption = nvmlDLL.NewProc("nvmlDeviceGetTotalEnergyConsumption")+ nvmlDeviceGetClockInfo = nvmlDLL.NewProc("nvmlDeviceGetClockInfo")+ nvmlDeviceGetPcieReplayCounter = nvmlDLL.NewProc("nvmlDeviceGetPcieReplayCounter")+ nvmlDeviceGetTotalEccErrors = nvmlDLL.NewProc("nvmlDeviceGetTotalEccErrors")+ nvmlDeviceGetEncoderUtilization = nvmlDLL.NewProc("nvmlDeviceGetEncoderUtilization")+ nvmlDeviceGetDecoderUtilization = nvmlDLL.NewProc("nvmlDeviceGetDecoderUtilization")+ nvmlDeviceGetNumGpuCores = nvmlDLL.NewProc("nvmlDeviceGetNumGpuCores")+ nvmlSystemGetDriverVersion = nvmlDLL.NewProc("nvmlSystemGetDriverVersion")+ nvmlDeviceGetPcieThroughput = nvmlDLL.NewProc("nvmlDeviceGetPcieThroughput")+ nvmlDeviceGetCurrentClocksThrottleReasons = nvmlDLL.NewProc("nvmlDeviceGetCurrentClocksThrottleReasons")+ nvmlDeviceGetNvLinkState = nvmlDLL.NewProc("nvmlDeviceGetNvLinkState")+ nvmlDeviceGetNvLinkUtilizationCounter = nvmlDLL.NewProc("nvmlDeviceGetNvLinkUtilizationCounter")+}++// InitNVML initializes NVML via nvml.dll.+func InitNVML() error {+ initMu.Lock()+ defer initMu.Unlock()+ if initDone && initErr == nil {+ return nil+ }+ if err := loadNVML(); err != nil {+ initDone = false+ initErr = err+ return initErr+ }+ ret, _, _ := nvmlInit_v2.Call()+ if ret != nvmlSuccess {+ initDone = false+ initErr = fmt.Errorf("nvmlInit_v2: %d", ret)+ return initErr+ }+ initDone = true+ initErr = nil+ return nil+}++// ShutdownNVML shuts down NVML.+func ShutdownNVML() {+ initMu.Lock()+ defer initMu.Unlock()+ if initDone && nvmlShutdown != nil {+ nvmlShutdown.Call()+ }+ initDone = false+ initErr = nil+}++// DiscoverDevices returns NVIDIA GPUs via NVML on Windows.+func DiscoverDevices(logger *slog.Logger) ([]*Device, error) {+ if err := InitNVML(); err != nil {+ return nil, err+ }++ var count uint32+ ret, _, _ := nvmlDeviceGetCount_v2.Call(uintptr(unsafe.Pointer(&count)))+ if ret != nvmlSuccess {+ return nil, fmt.Errorf("DeviceGetCount: %d", ret)+ }++ driverVersion := "unknown"+ var drvBuf [80]byte+ if ret, _, _ := nvmlSystemGetDriverVersion.Call(uintptr(unsafe.Pointer(&drvBuf[0])), 80); ret == nvmlSuccess {+ driverVersion = cString(drvBuf[:])+ }++ var nvidiaLUIDs []string+ if adapters, err := windxg.EnumAdapters(); err == nil {+ for _, a := range adapters {+ if a.VendorID == windxg.VendorNVIDIA {+ nvidiaLUIDs = append(nvidiaLUIDs, a.LUIDKey)+ }+ }+ }++ devices := make([]*Device, 0, count)+ for i := uint32(0); i < count; i++ {+ var handle uintptr+ ret, _, _ := nvmlDeviceGetHandleByIndex_v2.Call(uintptr(i), uintptr(unsafe.Pointer(&handle)))+ if ret != nvmlSuccess {+ logger.Warn("skipping NVIDIA GPU", "index", i, "error", ret)+ continue+ }++ var nameBuf [96]byte+ nvmlDeviceGetName.Call(handle, uintptr(unsafe.Pointer(&nameBuf[0])), 96)+ name := cString(nameBuf[:])++ var uuidBuf [96]byte+ nvmlDeviceGetUUID.Call(handle, uintptr(unsafe.Pointer(&uuidBuf[0])), 96)+ uuid := cString(uuidBuf[:])++ var pci nvmlPciInfo+ nvmlDeviceGetPciInfo_v3.Call(handle, uintptr(unsafe.Pointer(&pci)))+ pciAddr := cString(pci.BusId[:])+ if pciAddr == "" {+ pciAddr = fmt.Sprintf("%04x:%02x:%02x.0", pci.Domain, pci.Bus, pci.Device)+ }++ coreCount := 0+ var cores uint32+ if ret, _, _ := nvmlDeviceGetNumGpuCores.Call(handle, uintptr(unsafe.Pointer(&cores))); ret == nvmlSuccess {+ coreCount = int(cores)+ }++ // Match LUID by successful NVIDIA ordinal (not display name — duplicates collide).+ ord := len(devices)+ luidKey := ""+ if ord < len(nvidiaLUIDs) {+ luidKey = nvidiaLUIDs[ord]+ }++ devices = append(devices, &Device{+ handle: handle,+ info: gpu.DeviceInfo{+ Vendor: gpu.VendorNVIDIA,+ Index: ord,+ Name: name,+ UUID: uuid,+ PCIAddress: pciAddr,+ DriverVersion: driverVersion,+ CoreCount: coreCount,+ },+ luidKey: luidKey,+ logger: logger.With("gpu", ord, "vendor", "nvidia"),+ })+ }+ return devices, nil+}++func (d *Device) Info() gpu.DeviceInfo { return d.info }++func (d *Device) Collect() (*gpu.Snapshot, error) {+ s := &gpu.Snapshot{}+ h := d.handle++ var util nvmlUtilization+ if ret, _, _ := nvmlDeviceGetUtilizationRates.Call(h, uintptr(unsafe.Pointer(&util))); ret == nvmlSuccess {+ gpuUtil := float64(util.Gpu)+ memUtil := float64(util.Memory)+ s.Utilization = &gpuUtil+ s.MemoryUtilization = &memUtil+ }++ var encUtil, encSample uint32+ if ret, _, _ := nvmlDeviceGetEncoderUtilization.Call(h, uintptr(unsafe.Pointer(&encUtil)), uintptr(unsafe.Pointer(&encSample))); ret == nvmlSuccess {+ v := float64(encUtil)+ s.EncoderUtilization = &v+ }+ var decUtil, decSample uint32+ if ret, _, _ := nvmlDeviceGetDecoderUtilization.Call(h, uintptr(unsafe.Pointer(&decUtil)), uintptr(unsafe.Pointer(&decSample))); ret == nvmlSuccess {+ v := float64(decUtil)+ s.DecoderUtilization = &v+ }++ var temp uint32+ if ret, _, _ := nvmlDeviceGetTemperature.Call(h, nvmlTempGPU, uintptr(unsafe.Pointer(&temp))); ret == nvmlSuccess {+ v := float64(temp)+ s.TemperatureGPU = &v+ }++ var mem nvmlMemory+ if ret, _, _ := nvmlDeviceGetMemoryInfo.Call(h, uintptr(unsafe.Pointer(&mem))); ret == nvmlSuccess {+ total := int64(mem.Total)+ used := int64(mem.Used)+ free := int64(mem.Free)+ s.MemoryTotalBytes = &total+ s.MemoryUsedBytes = &used+ s.MemoryFreeBytes = &free+ }++ var power uint32+ if ret, _, _ := nvmlDeviceGetPowerUsage.Call(h, uintptr(unsafe.Pointer(&power))); ret == nvmlSuccess {+ v := float64(power) / 1000.0+ s.PowerDrawWatts = &v+ }+ var limit uint32+ if ret, _, _ := nvmlDeviceGetPowerManagementLimit.Call(h, uintptr(unsafe.Pointer(&limit))); ret == nvmlSuccess {+ v := float64(limit) / 1000.0+ s.PowerLimitWatts = &v+ }+ var energy uint64+ if ret, _, _ := nvmlDeviceGetTotalEnergyConsumption.Call(h, uintptr(unsafe.Pointer(&energy))); ret == nvmlSuccess {+ v := float64(energy) / 1000.0+ s.EnergyJoules = &v+ }++ var clock uint32+ if ret, _, _ := nvmlDeviceGetClockInfo.Call(h, nvmlClockGraphics, uintptr(unsafe.Pointer(&clock))); ret == nvmlSuccess {+ v := float64(clock)+ s.ClockGraphicsMHz = &v+ }+ if ret, _, _ := nvmlDeviceGetClockInfo.Call(h, nvmlClockMem, uintptr(unsafe.Pointer(&clock))); ret == nvmlSuccess {+ v := float64(clock)+ s.ClockMemoryMHz = &v+ }++ var replay uint32+ if ret, _, _ := nvmlDeviceGetPcieReplayCounter.Call(h, uintptr(unsafe.Pointer(&replay))); ret == nvmlSuccess {+ v := int64(replay)+ s.PCIeReplayErrors = &v+ }+ var ecc uint64+ if ret, _, _ := nvmlDeviceGetTotalEccErrors.Call(h, nvmlMemoryErrorCorrected, nvmlVolatileECC, uintptr(unsafe.Pointer(&ecc))); ret == nvmlSuccess {+ v := int64(ecc)+ s.ECCSingleBit = &v+ }+ if ret, _, _ := nvmlDeviceGetTotalEccErrors.Call(h, nvmlMemoryErrorUncorrected, nvmlVolatileECC, uintptr(unsafe.Pointer(&ecc))); ret == nvmlSuccess {+ v := int64(ecc)+ s.ECCDoubleBit = &v+ }++ // PCIe throughput (KB/s)+ const pcieUtilRX = 1+ const pcieUtilTX = 0+ var thr uint32+ if ret, _, _ := nvmlDeviceGetPcieThroughput.Call(h, pcieUtilRX, uintptr(unsafe.Pointer(&thr))); ret == nvmlSuccess {+ v := float64(thr) * 1024.0+ s.PCIeRxBytesPerSec = &v+ }+ if ret, _, _ := nvmlDeviceGetPcieThroughput.Call(h, pcieUtilTX, uintptr(unsafe.Pointer(&thr))); ret == nvmlSuccess {+ v := float64(thr) * 1024.0+ s.PCIeTxBytesPerSec = &v+ }++ var reasons uint64+ if ret, _, _ := nvmlDeviceGetCurrentClocksThrottleReasons.Call(h, uintptr(unsafe.Pointer(&reasons))); ret == nvmlSuccess {+ label := fmt.Sprintf("0x%x", reasons)+ s.ThrottleReasons = &label+ th := 0.0+ if reasons&(32|64|8|4|128) != 0 { // thermal/power bits+ th = 1.0+ }+ s.Throttled = &th+ }++ collectNvLinkWindows(d, s)++ return s, nil+}++func collectNvLinkWindows(d *Device, s *gpu.Snapshot) {+ if nvmlDeviceGetNvLinkState == nil || nvmlDeviceGetNvLinkUtilizationCounter == nil {+ return+ }+ var rxTotal, txTotal uint64+ var links int+ now := time.Now()+ for link := uint32(0); link < 18; link++ {+ var state uint32+ ret, _, _ := nvmlDeviceGetNvLinkState.Call(d.handle, uintptr(link), uintptr(unsafe.Pointer(&state)))+ if ret != nvmlSuccess || state != nvmlFeatureEnabled {+ continue+ }+ var rx, tx uint64+ ret, _, _ = nvmlDeviceGetNvLinkUtilizationCounter.Call(+ d.handle, uintptr(link), 0,+ uintptr(unsafe.Pointer(&rx)), uintptr(unsafe.Pointer(&tx)),+ )+ if ret != nvmlSuccess {+ continue+ }+ rxTotal += rx+ txTotal += tx+ links+++ }+ if links == 0 {+ return+ }+ s.InterconnectType = "nvlink"+ if !d.nvlinkLast.IsZero() {+ dt := now.Sub(d.nvlinkLast).Seconds()+ if dt > 0 && rxTotal >= d.nvlinkRxPrev && txTotal >= d.nvlinkTxPrev {+ rxRate := float64(rxTotal-d.nvlinkRxPrev) / dt+ txRate := float64(txTotal-d.nvlinkTxPrev) / dt+ s.InterconnectRxBytesPerSec = &rxRate+ s.InterconnectTxBytesPerSec = &txRate+ }+ }+ d.nvlinkRxPrev = rxTotal+ d.nvlinkTxPrev = txTotal+ d.nvlinkLast = now+}++func (d *Device) CollectProcesses() ([]gpu.ProcessUsage, error) {+ if d.luidKey == "" {+ return nil, nil+ }+ return winpdh.CollectForLUID(d.luidKey)+}++func (d *Device) Close() {}++func cString(b []byte) string {+ for i, c := range b {+ if c == 0 {+ return string(b[:i])+ }+ }+ return string(b)+}++// Ensure syscall import used on some toolchains.+var _ = syscall.Errno(0)diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/paths_test.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/paths_test.gonew file mode 100644index 00000000..faae3164--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/paths_test.go@@ -0,0 +1,23 @@+package nvidia++import (+ "path/filepath"+ "runtime"+ "testing"+)++func TestNVMLCandidatePaths(t *testing.T) {+ if runtime.GOOS != "windows" {+ // Exercise path helper logic that mirrors load order (portable check).+ cands := []string{+ "nvml.dll",+ filepath.Join("C:\\Windows", "System32", "nvml.dll"),+ filepath.Join("C:\\Program Files", "NVIDIA Corporation", "NVSMI", "nvml.dll"),+ }+ for _, c := range cands {+ if c == "" {+ t.Fatal("empty candidate")+ }+ }+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/nvidia/xid_linux.go b/opentelemetry-gpu-collector/internal/gpu/nvidia/xid_linux.gonew file mode 100644index 00000000..b1bdbf4d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/nvidia/xid_linux.go@@ -0,0 +1,67 @@+//go:build linux && (amd64 || arm64) && cgo++package nvidia++import (+ "log/slog"+ "sync/atomic"+ "time"++ "github.com/NVIDIA/go-nvml/pkg/nvml"+)++// startXIDWatcher registers for critical XID events and increments xidCount.+func (d *Device) startXIDWatcher(logger *slog.Logger) {+ set, ret := nvml.EventSetCreate()+ if ret != nvml.SUCCESS {+ return+ }+ ret = d.handle.RegisterEvents(uint64(nvml.EventTypeXidCriticalError), set)+ if ret != nvml.SUCCESS {+ _ = set.Free()+ return+ }+ d.eventSet = set+ d.xidDone = make(chan struct{})+ go func() {+ defer close(d.xidDone)+ for {+ if atomic.LoadInt32(&d.closed) == 1 {+ return+ }+ data, ret := set.Wait(500)+ if atomic.LoadInt32(&d.closed) == 1 {+ return+ }+ if ret == nvml.ERROR_TIMEOUT {+ continue+ }+ if ret != nvml.SUCCESS {+ return+ }+ if data.EventType&nvml.EventTypeXidCriticalError != 0 {+ atomic.AddInt64(&d.xidCount, 1)+ logger.Warn("NVIDIA XID critical error",+ "gpu", d.info.Index,+ "xid", data.EventData,+ )+ }+ }+ }()+}++// stopXIDWatcher signals the watcher, waits for it to exit, then frees the event set.+// Freeing before Wait returns is unsafe; the 500ms Wait timeout is the wake path.+func (d *Device) stopXIDWatcher() {+ atomic.StoreInt32(&d.closed, 1)+ if d.xidDone != nil {+ select {+ case <-d.xidDone:+ case <-time.After(2 * time.Second):+ }+ }+ if d.eventSet != nil {+ _ = d.eventSet.Free()+ d.eventSet = nil+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo.go b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo.gonew file mode 100644index 00000000..9a5dccb4--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo.go@@ -0,0 +1,22 @@+// Package procinfo reads OS-level process metadata for GPU-attributed PIDs.+package procinfo++import "time"++// Info is OS process metadata used for GPU process attribution.+type Info struct {+ CommandLine string+ UserID string+ Username string+ StartTime time.Time+ State string // running, sleeping, zombie, stopped, dead, unknown+}++// Lookup returns process metadata for pid. Missing fields are left empty;+// State is "unknown" when the process cannot be inspected.+func Lookup(pid int32) Info {+ if pid <= 0 {+ return Info{State: "unknown"}+ }+ return lookup(pid)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux.go b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux.gonew file mode 100644index 00000000..0328b672--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux.go@@ -0,0 +1,171 @@+//go:build linux++package procinfo++import (+ "os"+ "os/user"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/tklauser/go-sysconf"+)++var (+ bootOnce sync.Once+ bootTime time.Time+ clkOnce sync.Once+ clkTicks int64 = 100+ userCache sync.Map // string UID → string username+)++func lookup(pid int32) Info {+ info := Info{State: "unknown"}+ base := "/proc/" + strconv.FormatInt(int64(pid), 10)++ if data, err := os.ReadFile(base + "/cmdline"); err == nil && len(data) > 0 {+ info.CommandLine = formatCmdline(data)+ }++ if data, err := os.ReadFile(base + "/status"); err == nil {+ parseStatus(string(data), &info)+ }++ if data, err := os.ReadFile(base + "/stat"); err == nil {+ if st, ok := parseStartTime(string(data)); ok {+ info.StartTime = st+ }+ }++ if info.UserID != "" && info.Username == "" {+ info.Username = lookupUsername(info.UserID)+ }+ return info+}++func lookupUsername(uid string) string {+ if v, ok := userCache.Load(uid); ok {+ return v.(string)+ }+ u, err := user.LookupId(uid)+ if err != nil {+ userCache.Store(uid, "")+ return ""+ }+ userCache.Store(uid, u.Username)+ return u.Username+}++func formatCmdline(data []byte) string {+ // Avoid strings.Split allocation explosion for huge cmdline buffers.+ n := 0+ for i := 0; i < len(data); i++ {+ if data[i] == 0 {+ n+++ }+ }+ parts := make([]string, 0, n+1)+ start := 0+ for i := 0; i <= len(data); i++ {+ if i == len(data) || data[i] == 0 {+ if i > start {+ parts = append(parts, string(data[start:i]))+ }+ start = i + 1+ }+ }+ return strings.Join(parts, " ")+}++func parseStatus(content string, info *Info) {+ for _, line := range strings.Split(content, "\n") {+ if strings.HasPrefix(line, "State:") {+ fields := strings.Fields(line)+ if len(fields) >= 2 {+ info.State = mapLinuxState(fields[1])+ }+ continue+ }+ if strings.HasPrefix(line, "Uid:") {+ fields := strings.Fields(line)+ if len(fields) >= 2 {+ info.UserID = fields[1]+ }+ }+ }+}++func mapLinuxState(code string) string {+ if code == "" {+ return "unknown"+ }+ switch code[0] {+ case 'R':+ return "running"+ case 'S', 'D', 'I':+ return "sleeping"+ case 'Z':+ return "zombie"+ case 'T', 't':+ return "stopped"+ case 'X', 'x':+ return "dead"+ default:+ return "unknown"+ }+}++func parseStartTime(stat string) (time.Time, bool) {+ i := strings.LastIndex(stat, ")")+ if i < 0 || i+2 >= len(stat) {+ return time.Time{}, false+ }+ fields := strings.Fields(stat[i+2:])+ if len(fields) < 20 {+ return time.Time{}, false+ }+ ticks, err := strconv.ParseUint(fields[19], 10, 64)+ if err != nil {+ return time.Time{}, false+ }+ bt := systemBootTime()+ if bt.IsZero() {+ return time.Time{}, false+ }+ hz := clockTicks()+ sec := float64(ticks) / float64(hz)+ return bt.Add(time.Duration(sec * float64(time.Second))), true+}++func systemBootTime() time.Time {+ bootOnce.Do(func() {+ data, err := os.ReadFile("/proc/stat")+ if err != nil {+ return+ }+ for _, line := range strings.Split(string(data), "\n") {+ if strings.HasPrefix(line, "btime ") {+ fields := strings.Fields(line)+ if len(fields) >= 2 {+ sec, err := strconv.ParseInt(fields[1], 10, 64)+ if err == nil {+ bootTime = time.Unix(sec, 0)+ }+ }+ return+ }+ }+ })+ return bootTime+}++func clockTicks() int64 {+ clkOnce.Do(func() {+ if hz, err := sysconf.Sysconf(sysconf.SC_CLK_TCK); err == nil && hz > 0 {+ clkTicks = hz+ }+ })+ return clkTicks+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux_test.go b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux_test.gonew file mode 100644index 00000000..d02e2b77--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_linux_test.go@@ -0,0 +1,51 @@+//go:build linux++package procinfo++import (+ "os"+ "testing"+)++func TestFormatCmdline(t *testing.T) {+ in := []byte("python\x00-m\x00vllm.entrypoints.openai.api_server\x00")+ got := formatCmdline(in)+ want := "python -m vllm.entrypoints.openai.api_server"+ if got != want {+ t.Fatalf("formatCmdline = %q, want %q", got, want)+ }+}++func TestMapLinuxState(t *testing.T) {+ cases := map[string]string{+ "R (running)": "running",+ "S (sleeping)": "sleeping",+ "Z (zombie)": "zombie",+ "T (stopped)": "stopped",+ "X (dead)": "dead",+ "": "unknown",+ }+ for in, want := range cases {+ if got := mapLinuxState(in); got != want {+ t.Errorf("mapLinuxState(%q)=%q want %q", in, got, want)+ }+ }+}++func TestLookupSelf(t *testing.T) {+ pid := int32(os.Getpid())+ info := Lookup(pid)+ if info.State == "unknown" && info.CommandLine == "" {+ t.Fatalf("Lookup(self) returned empty: %+v", info)+ }+ if info.State == "zombie" {+ t.Fatalf("self should not be zombie: %+v", info)+ }+}++func TestLookupInvalid(t *testing.T) {+ info := Lookup(0)+ if info.State != "unknown" {+ t.Fatalf("state=%q", info.State)+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_other.go b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_other.gonew file mode 100644index 00000000..fff65db4--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_other.go@@ -0,0 +1,9 @@+//go:build !linux && !windows++package procinfo++// lookup on platforms without /proc or Windows process APIs (e.g. macOS).+func lookup(pid int32) Info {+ _ = pid+ return Info{State: "unknown"}+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_windows.go b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_windows.gonew file mode 100644index 00000000..9465f31d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procinfo/procinfo_windows.go@@ -0,0 +1,128 @@+//go:build windows++package procinfo++import (+ "os/user"+ "strings"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"+)++const (+ stillActive = 259+ processQueryLimitedInfo = windows.PROCESS_QUERY_LIMITED_INFORMATION+ tokenQuery = windows.TOKEN_QUERY+)++func lookup(pid int32) Info {+ info := Info{State: "unknown"}+ h, err := windows.OpenProcess(processQueryLimitedInfo|windows.SYNCHRONIZE, false, uint32(pid))+ if err != nil {+ return info+ }+ defer windows.CloseHandle(h)++ var buf [windows.MAX_PATH * 4]uint16+ size := uint32(len(buf))+ if err := windows.QueryFullProcessImageName(h, 0, &buf[0], &size); err == nil {+ info.CommandLine = windows.UTF16ToString(buf[:size])+ }++ // Create time via GetProcessTimes.+ var creation, exit, kernel, userFile windows.Filetime+ if err := windows.GetProcessTimes(h, &creation, &exit, &kernel, &userFile); err == nil {+ info.StartTime = time.Unix(0, creation.Nanoseconds())+ }++ // Exit code: STILL_ACTIVE means running; otherwise treat as dead/zombie-equivalent+ // for GPU attribution (process handle still visible to driver briefly).+ var code uint32+ if err := windows.GetExitCodeProcess(h, &code); err == nil {+ if code == stillActive {+ info.State = "running"+ } else {+ info.State = "zombie"+ }+ }++ // Owner SID → username.+ var token windows.Token+ if err := windows.OpenProcessToken(h, tokenQuery, &token); err == nil {+ defer token.Close()+ tokUser, err := token.GetTokenUser()+ if err == nil && tokUser != nil {+ sid := tokUser.User.Sid+ info.UserID = sid.String()+ account, domain, _, err := sid.LookupAccount("")+ if err == nil {+ if domain != "" {+ info.Username = domain + `\` + account+ } else {+ info.Username = account+ }+ } else if u, err := user.LookupId(info.UserID); err == nil {+ info.Username = u.Username+ }+ }+ }++ // Enrich cmdline via NtQueryInformationProcess ProcessCommandLineInformation when available.+ if cl := queryCommandLine(h); cl != "" {+ info.CommandLine = cl+ }++ return info+}++// PROCESSINFOCLASS 60 = ProcessCommandLineInformation (Win10+)+const processCommandLineInformation = 60++type unicodeString struct {+ Length uint16+ MaximumLength uint16+ Buffer *uint16+}++func queryCommandLine(h windows.Handle) string {+ ntdll := windows.NewLazySystemDLL("ntdll.dll")+ proc := ntdll.NewProc("NtQueryInformationProcess")+ if err := proc.Find(); err != nil {+ return ""+ }++ var retLen uint32+ // Size probe+ r, _, _ := proc.Call(+ uintptr(h),+ uintptr(processCommandLineInformation),+ 0,+ 0,+ uintptr(unsafe.Pointer(&retLen)),+ )+ if retLen == 0 {+ _ = r+ return ""+ }+ buf := make([]byte, retLen)+ r, _, _ = proc.Call(+ uintptr(h),+ uintptr(processCommandLineInformation),+ uintptr(unsafe.Pointer(&buf[0])),+ uintptr(retLen),+ uintptr(unsafe.Pointer(&retLen)),+ )+ // STATUS_SUCCESS = 0+ if r != 0 {+ return ""+ }+ us := (*unicodeString)(unsafe.Pointer(&buf[0]))+ if us.Buffer == nil || us.Length == 0 {+ return ""+ }+ n := int(us.Length / 2)+ slice := unsafe.Slice(us.Buffer, n)+ return strings.TrimSpace(windows.UTF16ToString(slice))+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procname/procname_test.go b/opentelemetry-gpu-collector/internal/gpu/procname/procname_test.gonew file mode 100644index 00000000..45e31670--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procname/procname_test.go@@ -0,0 +1,28 @@+package procname++import (+ "os"+ "runtime"+ "testing"+)++func TestExecutableNameSelf(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("/proc only available on Linux")+ }+ pid := int32(os.Getpid())+ name := ExecutableName(pid)+ if name == "" {+ t.Fatal("expected non-empty executable name for self")+ }+}++func TestExecutableNameMissing(t *testing.T) {+ if got := ExecutableName(0); got != "" {+ t.Fatalf("pid 0: got %q", got)+ }+ if got := ExecutableName(-1); got != "" {+ t.Fatalf("negative pid: got %q", got)+ }+ _ = ExecutableName(1<<30 - 1)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procname/procname_unix.go b/opentelemetry-gpu-collector/internal/gpu/procname/procname_unix.gonew file mode 100644index 00000000..abdd5e6d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procname/procname_unix.go@@ -0,0 +1,46 @@+//go:build !windows++package procname++import (+ "os"+ "strconv"+ "strings"+)++// ExecutableName returns a short process name for pid from /proc.+// Prefer /proc/<pid>/comm; fall back to a truncated cmdline basename.+// Returns "" if the process is gone or unreadable (no panic, no error).+func ExecutableName(pid int32) string {+ if pid <= 0 {+ return ""+ }+ base := "/proc/" + strconv.FormatInt(int64(pid), 10)++ if data, err := os.ReadFile(base + "/comm"); err == nil {+ name := strings.TrimSpace(string(data))+ if name != "" {+ return name+ }+ }++ data, err := os.ReadFile(base + "/cmdline")+ if err != nil || len(data) == 0 {+ return ""+ }+ arg0 := string(data)+ if i := strings.IndexByte(arg0, 0); i >= 0 {+ arg0 = arg0[:i]+ }+ arg0 = strings.TrimSpace(arg0)+ if arg0 == "" {+ return ""+ }+ if i := strings.LastIndex(arg0, "/"); i >= 0 && i+1 < len(arg0) {+ arg0 = arg0[i+1:]+ }+ if len(arg0) > 64 {+ arg0 = arg0[:64]+ }+ return arg0+}diff --git a/opentelemetry-gpu-collector/internal/gpu/procname/procname_windows.go b/opentelemetry-gpu-collector/internal/gpu/procname/procname_windows.gonew file mode 100644index 00000000..ca6b743c--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/procname/procname_windows.go@@ -0,0 +1,35 @@+//go:build windows++package procname++import (+ "path/filepath"+ "strings"++ "golang.org/x/sys/windows"+)++// ExecutableName returns the process image basename for pid on Windows.+func ExecutableName(pid int32) string {+ if pid <= 0 {+ return ""+ }+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))+ if err != nil {+ return ""+ }+ defer windows.CloseHandle(h)++ var buf [windows.MAX_PATH]uint16+ size := uint32(len(buf))+ err = windows.QueryFullProcessImageName(h, 0, &buf[0], &size)+ if err != nil {+ return ""+ }+ full := windows.UTF16ToString(buf[:size])+ base := filepath.Base(full)+ if len(base) > 64 {+ base = base[:64]+ }+ return strings.TrimSpace(base)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/windxg/dxgi_windows.go b/opentelemetry-gpu-collector/internal/gpu/windxg/dxgi_windows.gonew file mode 100644index 00000000..56b1cc46--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/windxg/dxgi_windows.go@@ -0,0 +1,159 @@+//go:build windows++package windxg++import (+ "fmt"+ "syscall"+ "unsafe"++ "golang.org/x/sys/windows"+)++// Vendor PCI IDs.+const (+ VendorNVIDIA = 0x10DE+ VendorAMD = 0x1002+ VendorIntel = 0x8086+)++// Adapter is one DXGI adapter (GPU).+type Adapter struct {+ Name string+ VendorID uint32+ DeviceID uint32+ SubSysID uint32+ Revision uint32+ DedicatedVideoMemory uint64+ DedicatedSystemMem uint64+ SharedSystemMemory uint64+ LUID LUID+ LUIDKey string // "0xHHHHHHHH_0xLLLLLLLL" for PDH matching+}++type dxgiAdapterDesc1 struct {+ Description [128]uint16+ VendorId uint32+ DeviceId uint32+ SubSysId uint32+ Revision uint32+ DedicatedVideoMemory uint64+ DedicatedSystemMemory uint64+ SharedSystemMemory uint64+ AdapterLuid LUID+ Flags uint32+}++var (+ modDXGI = windows.NewLazySystemDLL("dxgi.dll")+ procCreateDXGIFactory1 = modDXGI.NewProc("CreateDXGIFactory1")+ iidIDXGIFactory1 = windows.GUID{Data1: 0x770aae78, Data2: 0xf26f, Data3: 0x4dba, Data4: [8]byte{0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87}}+)++// EnumAdapters returns discrete/integrated DXGI adapters (skips software adapters).+func EnumAdapters() ([]Adapter, error) {+ if err := modDXGI.Load(); err != nil {+ return nil, fmt.Errorf("dxgi.dll: %w", err)+ }+ var factory uintptr+ hr, _, _ := procCreateDXGIFactory1.Call(+ uintptr(unsafe.Pointer(&iidIDXGIFactory1)),+ uintptr(unsafe.Pointer(&factory)),+ )+ if hr != 0 || factory == 0 {+ return nil, fmt.Errorf("CreateDXGIFactory1: HRESULT 0x%08X", uint32(hr))+ }+ defer releaseCOM(factory)++ var out []Adapter+ for i := uint32(0); ; i++ {+ var adapter uintptr+ hr, _, _ := syscall.SyscallN(+ vtable(factory, 12), // EnumAdapters1+ factory,+ uintptr(i),+ uintptr(unsafe.Pointer(&adapter)),+ )+ if hr != 0 || adapter == 0 {+ break+ }+ var desc dxgiAdapterDesc1+ hr, _, _ = syscall.SyscallN(+ vtable(adapter, 10), // GetDesc1+ adapter,+ uintptr(unsafe.Pointer(&desc)),+ )+ releaseCOM(adapter)+ if hr != 0 {+ continue+ }+ // DXGI_ADAPTER_FLAG_SOFTWARE = 2+ if desc.Flags&2 != 0 {+ continue+ }+ name := windows.UTF16ToString(desc.Description[:])+ if isBasicDisplay(name, desc.VendorId) {+ continue+ }+ luid := desc.AdapterLuid+ out = append(out, Adapter{+ Name: name,+ VendorID: desc.VendorId,+ DeviceID: desc.DeviceId,+ SubSysID: desc.SubSysId,+ Revision: desc.Revision,+ DedicatedVideoMemory: desc.DedicatedVideoMemory,+ DedicatedSystemMem: desc.DedicatedSystemMemory,+ SharedSystemMemory: desc.SharedSystemMemory,+ LUID: luid,+ LUIDKey: FormatLUIDKey(luid),+ })+ }+ return out, nil+}++func isBasicDisplay(name string, vendorID uint32) bool {+ if vendorID == 0x1414 { // Microsoft+ return true+ }+ lower := name+ if len(lower) > 0 {+ // cheap ASCII lower+ b := make([]byte, len(lower))+ for i := 0; i < len(lower); i++ {+ c := lower[i]+ if c >= 'A' && c <= 'Z' {+ c += 'a' - 'A'+ }+ b[i] = c+ }+ lower = string(b)+ }+ return contains(lower, "microsoft basic") || contains(lower, "basic render")+}++func contains(s, sub string) bool {+ return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||+ (len(s) > 0 && indexOf(s, sub) >= 0))+}++func indexOf(s, sub string) int {+ for i := 0; i+len(sub) <= len(s); i++ {+ if s[i:i+len(sub)] == sub {+ return i+ }+ }+ return -1+}++func vtable(obj uintptr, index int) uintptr {+ vtbl := *(*uintptr)(unsafe.Pointer(obj))+ return *(*uintptr)(unsafe.Pointer(vtbl + uintptr(index)*unsafe.Sizeof(uintptr(0))))+}++func releaseCOM(obj uintptr) {+ if obj == 0 {+ return+ }+ syscall.SyscallN(vtable(obj, 2), obj) // IUnknown::Release+}diff --git a/opentelemetry-gpu-collector/internal/gpu/windxg/luid.go b/opentelemetry-gpu-collector/internal/gpu/windxg/luid.gonew file mode 100644index 00000000..7063f2cd--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/windxg/luid.go@@ -0,0 +1,15 @@+package windxg++import "fmt"++// LUID is a Windows locally unique identifier for an adapter.+// Defined without OS tags so unit tests run on all platforms.+type LUID struct {+ LowPart uint32+ HighPart int32+}++// FormatLUIDKey formats a LUID the way GPU PDH instance names encode it.+func FormatLUIDKey(l LUID) string {+ return fmt.Sprintf("0x%08X_0x%08X", uint32(l.HighPart), l.LowPart)+}diff --git a/opentelemetry-gpu-collector/internal/gpu/windxg/luid_test.go b/opentelemetry-gpu-collector/internal/gpu/windxg/luid_test.gonew file mode 100644index 00000000..62418dd1--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/windxg/luid_test.go@@ -0,0 +1,10 @@+package windxg++import "testing"++func TestFormatLUIDKey(t *testing.T) {+ got := FormatLUIDKey(LUID{LowPart: 0x5678, HighPart: 0})+ if got != "0x00000000_0x00005678" {+ t.Fatalf("got %q", got)+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/winpdh/parse.go b/opentelemetry-gpu-collector/internal/gpu/winpdh/parse.gonew file mode 100644index 00000000..8b954187--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/winpdh/parse.go@@ -0,0 +1,75 @@+package winpdh++import (+ "fmt"+ "strconv"+ "strings"+)++// Instance fields parsed from a GPU PDH counter instance name.+// Example: "pid_1234_luid_0x00000000_0x00005678_phys_0_eng_0_engtype_3D"+type Instance struct {+ PID int32+ LUIDKey string // "0xHHHHHHHH_0xLLLLLLLL"+ Phys string+ Eng string+ EngType string+}++// ParseInstance parses a Windows GPU Engine / GPU Process Memory instance name.+func ParseInstance(s string) Instance {+ parts := strings.Split(s, "_")+ var inst Instance+ for i, part := range parts {+ switch strings.ToLower(part) {+ case "pid":+ if i+1 < len(parts) {+ if v, err := strconv.ParseInt(parts[i+1], 10, 32); err == nil {+ inst.PID = int32(v)+ }+ }+ case "luid":+ if i+2 < len(parts) {+ inst.LUIDKey = fmt.Sprintf("%s_%s", parts[i+1], parts[i+2])+ }+ case "phys":+ if i+1 < len(parts) {+ inst.Phys = parts[i+1]+ }+ case "eng":+ if i+1 < len(parts) {+ inst.Eng = parts[i+1]+ }+ case "engtype":+ if i+1 < len(parts) {+ inst.EngType = parts[i+1]+ }+ }+ }+ return inst+}++// NormalizeEngType maps PDH engtype strings to coarse categories.+func NormalizeEngType(engtype string) string {+ e := strings.ToLower(engtype)+ switch {+ case strings.Contains(e, "copy"):+ return "copy"+ case strings.Contains(e, "decode") || strings.Contains(e, "videodecode"):+ return "decode"+ case strings.Contains(e, "encode") || strings.Contains(e, "videoencode") || strings.Contains(e, "encode"):+ return "encode"+ case strings.Contains(e, "compute"):+ return "compute"+ case e == "3d" || strings.Contains(e, "3d") || strings.Contains(e, "render") || strings.Contains(e, "graphics"):+ return "3d"+ default:+ return e+ }+}++// IsPrimaryCompute returns true for engines that should feed process.gpu.utilization.+func IsPrimaryCompute(engtype string) bool {+ n := NormalizeEngType(engtype)+ return n == "3d" || n == "compute"+}diff --git a/opentelemetry-gpu-collector/internal/gpu/winpdh/parse_test.go b/opentelemetry-gpu-collector/internal/gpu/winpdh/parse_test.gonew file mode 100644index 00000000..5633f6c0--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/winpdh/parse_test.go@@ -0,0 +1,47 @@+package winpdh++import "testing"++func TestParseInstance(t *testing.T) {+ inst := ParseInstance("pid_1234_luid_0x00000000_0x00005678_phys_0_eng_0_engtype_3D")+ if inst.PID != 1234 {+ t.Fatalf("pid=%d", inst.PID)+ }+ if inst.LUIDKey != "0x00000000_0x00005678" {+ t.Fatalf("luid=%q", inst.LUIDKey)+ }+ if inst.Phys != "0" || inst.Eng != "0" || inst.EngType != "3D" {+ t.Fatalf("got %+v", inst)+ }+}++func TestParseInstanceMemory(t *testing.T) {+ inst := ParseInstance("pid_42_luid_0x00000001_0xABCDEF00_phys_1")+ if inst.PID != 42 || inst.LUIDKey != "0x00000001_0xABCDEF00" || inst.Phys != "1" {+ t.Fatalf("got %+v", inst)+ }+}++func TestNormalizeEngType(t *testing.T) {+ cases := map[string]string{+ "3D": "3d",+ "Compute_0": "compute",+ "VideoDecode": "decode",+ "VideoEncode": "encode",+ "Copy": "copy",+ }+ for in, want := range cases {+ if got := NormalizeEngType(in); got != want {+ t.Errorf("NormalizeEngType(%q)=%q want %q", in, got, want)+ }+ }+}++func TestIsPrimaryCompute(t *testing.T) {+ if !IsPrimaryCompute("3D") || !IsPrimaryCompute("Compute") {+ t.Fatal("expected primary")+ }+ if IsPrimaryCompute("Copy") || IsPrimaryCompute("VideoDecode") {+ t.Fatal("expected non-primary")+ }+}diff --git a/opentelemetry-gpu-collector/internal/gpu/winpdh/pdh_windows.go b/opentelemetry-gpu-collector/internal/gpu/winpdh/pdh_windows.gonew file mode 100644index 00000000..de07fb2f--- /dev/null+++ b/opentelemetry-gpu-collector/internal/gpu/winpdh/pdh_windows.go@@ -0,0 +1,385 @@+//go:build windows++package winpdh++import (+ "fmt"+ "sync"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu"+ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/gpu/procname"+)++const (+ cacheTTL = 200 * time.Millisecond++ pdhMoreData = 0x800007D2+ pdhNoData = 0x800007D5+ pdhCStatusValidData = 0+ pdhCStatusNewData = 1+ pdhFmtDouble = 0x00000200+ pdhFmtNoCap100 = 0x00008000+)++var (+ modPdh = windows.NewLazySystemDLL("pdh.dll")+ procPdhOpenQueryW = modPdh.NewProc("PdhOpenQueryW")+ procPdhAddEnglishCounterW = modPdh.NewProc("PdhAddEnglishCounterW")+ procPdhCollectQueryData = modPdh.NewProc("PdhCollectQueryData")+ procPdhGetFormattedCounterArrayW = modPdh.NewProc("PdhGetFormattedCounterArrayW")+ procPdhCloseQuery = modPdh.NewProc("PdhCloseQuery")+)++// ProcessSample is one process's GPU usage on one adapter LUID.+type ProcessSample struct {+ PID int32+ LUIDKey string+ MemoryBytes int64+ Util float64 // 0..1 primary compute/3D+ EncoderUtil float64+ DecoderUtil float64+ HasMemory bool+ HasUtil bool+ HasEnc bool+ HasDec bool+}++// AdapterUsage aggregates device-level util/memory from PDH for one LUID.+type AdapterUsage struct {+ LUIDKey string+ Util float64 // 0..1+ EncoderUtil float64 // 0..1+ DecoderUtil float64 // 0..1+ MemoryUsed int64+ HasUtil bool+ HasEnc bool+ HasDec bool+ HasMemory bool+}++type cache struct {+ mu sync.Mutex+ at time.Time+ processes []ProcessSample+ adapters map[string]AdapterUsage+}++var shared cache++// Persistent PDH query: sample across scrapes instead of sleeping 50ms in-callback.+type pdhSession struct {+ mu sync.Mutex+ query uintptr+ engCounter uintptr+ memCounter uintptr+ ready bool // true after first CollectQueryData (rates need two samples)+}++var session pdhSession++func (s *pdhSession) ensure() error {+ if s.query != 0 {+ return nil+ }+ if err := modPdh.Load(); err != nil {+ return fmt.Errorf("pdh.dll: %w", err)+ }+ var query uintptr+ if ret := pdhCall(procPdhOpenQueryW, 0, 0, uintptr(unsafe.Pointer(&query))); ret != 0 {+ return fmt.Errorf("PdhOpenQuery: 0x%X", ret)+ }+ var engCounter, memCounter uintptr+ engPath, _ := windows.UTF16PtrFromString(`\GPU Engine(*)\Utilization Percentage`)+ memPath, _ := windows.UTF16PtrFromString(`\GPU Process Memory(*)\Dedicated Usage`)+ if ret := pdhCall(procPdhAddEnglishCounterW, query, uintptr(unsafe.Pointer(engPath)), 0, uintptr(unsafe.Pointer(&engCounter))); ret != 0 {+ pdhCall(procPdhCloseQuery, query)+ return fmt.Errorf("add GPU Engine counter: 0x%X", ret)+ }+ _ = pdhCall(procPdhAddEnglishCounterW, query, uintptr(unsafe.Pointer(memPath)), 0, uintptr(unsafe.Pointer(&memCounter)))+ s.query = query+ s.engCounter = engCounter+ s.memCounter = memCounter+ s.ready = false+ return nil+}++// CollectForLUID returns ProcessUsage for processes on the given adapter LUID key.+func CollectForLUID(luidKey string) ([]gpu.ProcessUsage, error) {+ procs, _, err := scrape()+ if err != nil {+ return nil, err+ }+ out := make([]gpu.ProcessUsage, 0)+ for _, p := range procs {+ if !stringsEqualFoldLUID(p.LUIDKey, luidKey) {+ continue+ }+ pu := gpu.ProcessUsage{+ PID: p.PID,+ ExecutableName: procname.ExecutableName(p.PID),+ }+ if p.HasMemory {+ m := p.MemoryBytes+ pu.MemoryBytes = &m+ }+ if p.HasUtil {+ u := p.Util+ if u > 1 {+ u = 1+ }+ pu.Utilization = &u+ }+ if p.HasEnc {+ e := p.EncoderUtil+ if e > 1 {+ e = 1+ }+ pu.EncoderUtil = &e+ }+ if p.HasDec {+ d := p.DecoderUtil+ if d > 1 {+ d = 1+ }+ pu.DecoderUtil = &d+ }+ out = append(out, pu)+ }+ return out, nil+}++// AdapterSnapshot returns aggregated util/memory for one LUID (DXGI+PDH fallback).+func AdapterSnapshot(luidKey string) (AdapterUsage, bool) {+ _, adapters, err := scrape()+ if err != nil {+ return AdapterUsage{}, false+ }+ for k, a := range adapters {+ if stringsEqualFoldLUID(k, luidKey) {+ return a, true+ }+ }+ return AdapterUsage{}, false+}++func scrape() ([]ProcessSample, map[string]AdapterUsage, error) {+ shared.mu.Lock()+ if shared.processes != nil && time.Since(shared.at) < cacheTTL {+ p, a := shared.processes, shared.adapters+ shared.mu.Unlock()+ return p, a, nil+ }+ shared.mu.Unlock()++ procs, adapters, err := collectPDH()+ if err != nil {+ return nil, nil, err+ }++ shared.mu.Lock()+ shared.processes = procs+ shared.adapters = adapters+ shared.at = time.Now()+ shared.mu.Unlock()+ return procs, adapters, nil+}++func collectPDH() ([]ProcessSample, map[string]AdapterUsage, error) {+ session.mu.Lock()+ defer session.mu.Unlock()++ if err := session.ensure(); err != nil {+ return nil, nil, err+ }+ q := session.query++ if ret := pdhCall(procPdhCollectQueryData, q); ret != 0 && ret != pdhNoData {+ return nil, nil, fmt.Errorf("PdhCollectQueryData: 0x%X", ret)+ }+ if !session.ready {+ // First sample primes rate counters; return empty util without sleeping.+ session.ready = true+ return nil, map[string]AdapterUsage{}, nil+ }++ byKey := make(map[string]*ProcessSample)+ adapters := make(map[string]AdapterUsage)++ if engItems, err := formattedArray(session.engCounter); err == nil {+ for _, it := range engItems {+ inst := ParseInstance(it.Name)+ if inst.PID <= 0 || inst.LUIDKey == "" {+ continue+ }+ key := fmt.Sprintf("%d|%s", inst.PID, inst.LUIDKey)+ ps := byKey[key]+ if ps == nil {+ ps = &ProcessSample{PID: inst.PID, LUIDKey: inst.LUIDKey}+ byKey[key] = ps+ }+ utilFrac := it.Value / 100.0+ if utilFrac < 0 {+ utilFrac = 0+ }+ switch NormalizeEngType(inst.EngType) {+ case "3d", "compute":+ if utilFrac > ps.Util {+ ps.Util = utilFrac+ }+ ps.HasUtil = true+ case "encode":+ if utilFrac > ps.EncoderUtil {+ ps.EncoderUtil = utilFrac+ }+ ps.HasEnc = true+ case "decode":+ if utilFrac > ps.DecoderUtil {+ ps.DecoderUtil = utilFrac+ }+ ps.HasDec = true+ }++ au := adapters[inst.LUIDKey]+ au.LUIDKey = inst.LUIDKey+ switch NormalizeEngType(inst.EngType) {+ case "3d", "compute":+ if utilFrac > au.Util {+ au.Util = utilFrac+ }+ au.HasUtil = true+ case "encode":+ if utilFrac > au.EncoderUtil {+ au.EncoderUtil = utilFrac+ }+ au.HasEnc = true+ case "decode":+ if utilFrac > au.DecoderUtil {+ au.DecoderUtil = utilFrac+ }+ au.HasDec = true+ }+ adapters[inst.LUIDKey] = au+ }+ }++ if session.memCounter != 0 {+ if memItems, err := formattedArray(session.memCounter); err == nil {+ for _, it := range memItems {+ inst := ParseInstance(it.Name)+ if inst.PID <= 0 || inst.LUIDKey == "" {+ continue+ }+ key := fmt.Sprintf("%d|%s", inst.PID, inst.LUIDKey)+ ps := byKey[key]+ if ps == nil {+ ps = &ProcessSample{PID: inst.PID, LUIDKey: inst.LUIDKey}+ byKey[key] = ps+ }+ mem := int64(it.Value)+ ps.MemoryBytes = mem+ ps.HasMemory = true++ au := adapters[inst.LUIDKey]+ au.LUIDKey = inst.LUIDKey+ au.MemoryUsed += mem+ au.HasMemory = true+ adapters[inst.LUIDKey] = au+ }+ }+ }++ out := make([]ProcessSample, 0, len(byKey))+ for _, ps := range byKey {+ out = append(out, *ps)+ }+ return out, adapters, nil+}++type fmtItem struct {+ Name string+ Value float64+}++type pdhFmtCounterValueItemDouble struct {+ SzName *uint16+ FmtValue struct {+ CStatus uint32+ Padding uint32+ Value float64+ }+}++func formattedArray(counter uintptr) ([]fmtItem, error) {+ var bufSize, itemCount uint32+ ret := pdhCall(procPdhGetFormattedCounterArrayW, counter, pdhFmtDouble|pdhFmtNoCap100,+ uintptr(unsafe.Pointer(&bufSize)), uintptr(unsafe.Pointer(&itemCount)), 0)+ if ret != pdhMoreData && ret != 0 {+ if ret == pdhNoData {+ return nil, nil+ }+ return nil, fmt.Errorf("PdhGetFormattedCounterArray size: 0x%X", ret)+ }+ if bufSize == 0 {+ return nil, nil+ }+ buf := make([]byte, bufSize)+ ret = pdhCall(procPdhGetFormattedCounterArrayW, counter, pdhFmtDouble|pdhFmtNoCap100,+ uintptr(unsafe.Pointer(&bufSize)), uintptr(unsafe.Pointer(&itemCount)),+ uintptr(unsafe.Pointer(&buf[0])))+ if ret != 0 {+ if ret == pdhNoData {+ return nil, nil+ }+ return nil, fmt.Errorf("PdhGetFormattedCounterArray: 0x%X", ret)+ }++ items := make([]fmtItem, 0, itemCount)+ size := unsafe.Sizeof(pdhFmtCounterValueItemDouble{})+ for i := uint32(0); i < itemCount; i++ {+ raw := (*pdhFmtCounterValueItemDouble)(unsafe.Pointer(&buf[uintptr(i)*size]))+ if raw.FmtValue.CStatus != pdhCStatusValidData && raw.FmtValue.CStatus != pdhCStatusNewData {+ continue+ }+ name := windows.UTF16PtrToString(raw.SzName)+ items = append(items, fmtItem{Name: name, Value: raw.FmtValue.Value})+ }+ return items, nil+}++func pdhCall(p *windows.LazyProc, args ...uintptr) uintptr {+ r, _, _ := p.Call(args...)+ return r+}++func stringsEqualFoldLUID(a, b string) bool {+ if len(a) != len(b) {+ // still try case-insensitive compare+ }+ if len(a) != len(b) {+ return stringsEqualFold(a, b)+ }+ return stringsEqualFold(a, b)+}++func stringsEqualFold(a, b string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := 0; i < len(a); i++ {+ ca, cb := a[i], b[i]+ if ca >= 'a' && ca <= 'z' {+ ca -= 'a' - 'A'+ }+ if cb >= 'a' && cb <= 'z' {+ cb -= 'a' - 'A'+ }+ if ca != cb {+ return false+ }+ }+ return true+}diff --git a/opentelemetry-gpu-collector/internal/identity/cloud.go b/opentelemetry-gpu-collector/internal/identity/cloud.gonew file mode 100644index 00000000..83e928ce--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/cloud.go@@ -0,0 +1,207 @@+package identity++import (+ "context"+ "fmt"+ "io"+ "net"+ "net/http"+ "strings"+ "sync"+ "time"+)++const (+ // Keep probes short: on non-cloud hosts 169.254.169.254 typically blackholes+ // until Client.Timeout, which would stall collector startup.+ metadataTimeout = 250 * time.Millisecond+ cloudDetectBudget = 600 * time.Millisecond+ metadataMaxBody = 256 << 10 // Azure compute JSON can exceed 4 KiB++ gceMetadataBase = "http://169.254.169.254/computeMetadata/v1"+ azureIMDSBase = "http://169.254.169.254/metadata"+ ec2IMDSBase = "http://169.254.169.254/latest"+)++// httpDoer is the subset of *http.Client used by cloud probes (injectable in tests).+type httpDoer interface {+ Do(req *http.Request) (*http.Response, error)+}++func defaultHTTPClient() *http.Client {+ return &http.Client{+ Timeout: metadataTimeout,+ Transport: &http.Transport{+ Proxy: nil, // never send link-local IMDS via HTTP_PROXY+ DialContext: (&net.Dialer{+ Timeout: metadataTimeout,+ KeepAlive: 0,+ }).DialContext,+ DisableKeepAlives: true,+ TLSHandshakeTimeout: metadataTimeout,+ ResponseHeaderTimeout: metadataTimeout,+ ExpectContinueTimeout: 0,+ MaxIdleConns: 0,+ },+ }+}++func httpGet(ctx context.Context, client httpDoer, url string, headers map[string]string) (string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return "", err+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ resp, err := client.Do(req)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(io.LimitReader(resp.Body, metadataMaxBody))+ if err != nil {+ return "", err+ }+ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("metadata %s: status %d", url, resp.StatusCode)+ }+ return strings.TrimSpace(string(body)), nil+}++func httpPut(ctx context.Context, client httpDoer, url string, headers map[string]string) (string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, nil)+ if err != nil {+ return "", err+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ resp, err := client.Do(req)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(io.LimitReader(resp.Body, metadataMaxBody))+ if err != nil {+ return "", err+ }+ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("metadata PUT %s: status %d", url, resp.StatusCode)+ }+ return strings.TrimSpace(string(body)), nil+}++// clusterNameFromGKE reads GCE instance attribute cluster-name (GKE nodes).+func clusterNameFromGKE(ctx context.Context, client httpDoer) (string, error) {+ return httpGet(ctx, client, gceMetadataBase+"/instance/attributes/cluster-name", map[string]string{+ "Metadata-Flavor": "Google",+ })+}++// hostnameFromGCE reads the GCE instance hostname.+func hostnameFromGCE(ctx context.Context, client httpDoer) (string, error) {+ return httpGet(ctx, client, gceMetadataBase+"/instance/hostname", map[string]string{+ "Metadata-Flavor": "Google",+ })+}++// clusterNameFromAKS reads Azure IMDS resource group and parses the AKS cluster name.+func clusterNameFromAKS(ctx context.Context, client httpDoer) (string, error) {+ rg, err := httpGet(ctx, client, azureIMDSBase+"/instance/compute/resourceGroupName?api-version=2017-08-01&format=text", map[string]string{+ "Metadata": "true",+ })+ if err != nil {+ return "", err+ }+ name := parseAKSClusterName(rg)+ if name == "" {+ return "", fmt.Errorf("unable to parse AKS cluster name from resource group %q", rg)+ }+ return name, nil+}++// parseAKSClusterName extracts the cluster name from an AKS node resource group.+// Format: MC_<resourceGroup>_<clusterName>_<region>+func parseAKSClusterName(resourceGroup string) string {+ if !strings.HasPrefix(strings.ToUpper(resourceGroup), "MC_") {+ return ""+ }+ parts := strings.Split(resourceGroup, "_")+ if len(parts) < 4 {+ return ""+ }+ // Last segment is region; second-to-last is cluster name.+ return parts[len(parts)-2]+}++// clusterNameFromEKS reads EC2 IMDS instance tags for kubernetes.io/cluster/<name>.+func clusterNameFromEKS(ctx context.Context, client httpDoer) (string, error) {+ headers := map[string]string{}+ if token, err := httpPut(ctx, client, ec2IMDSBase+"/api/token", map[string]string{+ "X-aws-ec2-metadata-token-ttl-seconds": "60",+ }); err == nil && token != "" {+ headers["X-aws-ec2-metadata-token"] = token+ }+ // If IMDSv2 token fails, fall through to IMDSv1 (no token header).+ keysBody, err := httpGet(ctx, client, ec2IMDSBase+"/meta-data/tags/instance", headers)+ if err != nil {+ return "", err+ }+ for _, key := range strings.Split(keysBody, "\n") {+ key = strings.TrimSpace(key)+ if name := clusterNameFromEKSTagKey(key); name != "" {+ return name, nil+ }+ }+ return "", fmt.Errorf("no kubernetes.io/cluster/* tag on instance")+}++// clusterNameFromEKSTagKey extracts the cluster name from a tag key like+// "kubernetes.io/cluster/my-cluster".+func clusterNameFromEKSTagKey(key string) string {+ const prefix = "kubernetes.io/cluster/"+ if !strings.HasPrefix(key, prefix) {+ return ""+ }+ name := strings.TrimPrefix(key, prefix)+ if name == "" || strings.Contains(name, "/") {+ return ""+ }+ return name+}++// detectClusterFromCloud tries GKE, AKS, and EKS in parallel within a short budget.+// First success wins; failures are ignored.+func detectClusterFromCloud(ctx context.Context, client httpDoer) string {+ ctx, cancel := context.WithTimeout(ctx, cloudDetectBudget)+ defer cancel()++ type result struct{ name string }+ ch := make(chan result, 3)+ var wg sync.WaitGroup+ run := func(fn func(context.Context, httpDoer) (string, error)) {+ wg.Add(1)+ go func() {+ defer wg.Done()+ name, err := fn(ctx, client)+ if err == nil && name != "" {+ ch <- result{name: name}+ }+ }()+ }+ run(clusterNameFromGKE)+ run(clusterNameFromAKS)+ run(clusterNameFromEKS)+ go func() {+ wg.Wait()+ close(ch)+ }()+ for r := range ch {+ if r.name != "" {+ cancel()+ return r.name+ }+ }+ return ""+}diff --git a/opentelemetry-gpu-collector/internal/identity/cloud_identity.go b/opentelemetry-gpu-collector/internal/identity/cloud_identity.gonew file mode 100644index 00000000..3eb3753d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/cloud_identity.go@@ -0,0 +1,209 @@+package identity++import (+ "context"+ "encoding/json"+ "os"+ "strings"+ "sync"+ "time"+)++const cloudIdentityBudget = 400 * time.Millisecond++// cloudIMDSEnabled is true unless OPENLIT_CLOUD_DETECT=false.+func cloudIMDSEnabled() bool {+ v := strings.TrimSpace(strings.ToLower(os.Getenv("OPENLIT_CLOUD_DETECT")))+ return v != "false" && v != "0" && v != "no"+}++// detectCloudIdentityFromIMDS probes AWS/GCP/Azure in parallel and returns the+// first successful deep-fetch. Fast-probe failures are silent (not this cloud).+func detectCloudIdentityFromIMDS(ctx context.Context, client httpDoer) cloudIdentity {+ ctx, cancel := context.WithTimeout(ctx, cloudIdentityBudget)+ defer cancel()++ type result struct {+ ci cloudIdentity+ ok bool+ }+ ch := make(chan result, 3)+ var wg sync.WaitGroup++ run := func(fn func(context.Context, httpDoer) (cloudIdentity, bool)) {+ wg.Add(1)+ go func() {+ defer wg.Done()+ ci, ok := fn(ctx, client)+ ch <- result{ci: ci, ok: ok}+ }()+ }++ run(imdsAWS)+ run(imdsGCP)+ run(imdsAzure)++ go func() {+ wg.Wait()+ close(ch)+ }()++ for r := range ch {+ if r.ok {+ cancel() // stop siblings+ return r.ci+ }+ }+ return cloudIdentity{}+}++func imdsAWS(ctx context.Context, client httpDoer) (cloudIdentity, bool) {+ headers := map[string]string{}+ token, err := httpPut(ctx, client, ec2IMDSBase+"/api/token", map[string]string{+ "X-aws-ec2-metadata-token-ttl-seconds": "60",+ })+ if err == nil && token != "" {+ headers["X-aws-ec2-metadata-token"] = token+ }++ doc, err := httpGet(ctx, client, ec2IMDSBase+"/dynamic/instance-identity/document", headers)+ if err != nil || doc == "" {+ return cloudIdentity{}, false+ }++ var meta struct {+ InstanceType string `json:"instanceType"`+ Region string `json:"region"`+ AvailabilityZone string `json:"availabilityZone"`+ AccountID string `json:"accountId"`+ InstanceID string `json:"instanceId"`+ }+ if err := json.Unmarshal([]byte(doc), &meta); err != nil {+ return cloudIdentity{}, false+ }+ if meta.InstanceType == "" && meta.InstanceID == "" {+ return cloudIdentity{}, false+ }++ platform := "aws_ec2"+ if isKubernetes() {+ platform = "aws_eks"+ }+ ci := cloudIdentity{+ Provider: "aws",+ Platform: platform,+ HostType: meta.InstanceType,+ Region: meta.Region,+ AvailabilityZone: meta.AvailabilityZone,+ AccountID: meta.AccountID,+ HostID: meta.InstanceID,+ HostTypeSource: "imds",+ }+ if ci.HostType == "" {+ ci.HostTypeSource = ""+ }+ return ci, true+}++func imdsGCP(ctx context.Context, client httpDoer) (cloudIdentity, bool) {+ headers := map[string]string{"Metadata-Flavor": "Google"}++ // Fast presence: project-id is cheap and always present on GCE.+ if _, err := httpGet(ctx, client, gceMetadataBase+"/project/project-id", headers); err != nil {+ return cloudIdentity{}, false+ }++ machineType, _ := httpGet(ctx, client, gceMetadataBase+"/instance/machine-type", headers)+ zonePath, _ := httpGet(ctx, client, gceMetadataBase+"/instance/zone", headers)+ instanceID, _ := httpGet(ctx, client, gceMetadataBase+"/instance/id", headers)+ projectID, _ := httpGet(ctx, client, gceMetadataBase+"/project/project-id", headers)++ hostType := basenameAfter(machineType, "machineTypes/")+ zone := basenameAfter(zonePath, "zones/")+ region := regionFromGCPZone(zone)++ platform := "gcp_compute_engine"+ if isKubernetes() {+ platform = "gcp_kubernetes_engine"+ }++ ci := cloudIdentity{+ Provider: "gcp",+ Platform: platform,+ HostType: hostType,+ Region: region,+ AvailabilityZone: zone,+ AccountID: projectID,+ HostID: instanceID,+ HostTypeSource: "imds",+ }+ if ci.HostType == "" {+ ci.HostTypeSource = ""+ }+ return ci, true+}++func imdsAzure(ctx context.Context, client httpDoer) (cloudIdentity, bool) {+ headers := map[string]string{"Metadata": "true"}+ body, err := httpGet(ctx, client, azureIMDSBase+"/instance/compute?api-version=2021-05-01&format=json", headers)+ if err != nil || body == "" {+ return cloudIdentity{}, false+ }++ var meta struct {+ VMSize string `json:"vmSize"`+ Location string `json:"location"`+ Zone string `json:"zone"`+ SubscriptionID string `json:"subscriptionId"`+ VMID string `json:"vmId"`+ Name string `json:"name"`+ }+ if err := json.Unmarshal([]byte(body), &meta); err != nil {+ return cloudIdentity{}, false+ }+ if meta.VMSize == "" && meta.VMID == "" && meta.Name == "" {+ return cloudIdentity{}, false+ }++ platform := "azure_vm"+ if isKubernetes() {+ platform = "azure_aks"+ }+ ci := cloudIdentity{+ Provider: "azure",+ Platform: platform,+ HostType: meta.VMSize, // map vmSize → host.type+ Region: meta.Location,+ AvailabilityZone: meta.Zone,+ AccountID: meta.SubscriptionID,+ HostID: firstNonEmpty(meta.VMID, meta.Name),+ HostTypeSource: "imds",+ }+ if ci.HostType == "" {+ ci.HostTypeSource = ""+ }+ return ci, true+}++func basenameAfter(path, marker string) string {+ path = strings.TrimSpace(path)+ if i := strings.LastIndex(path, marker); i >= 0 {+ return path[i+len(marker):]+ }+ if i := strings.LastIndex(path, "/"); i >= 0 {+ return path[i+1:]+ }+ return path+}++func regionFromGCPZone(zone string) string {+ zone = strings.TrimSpace(zone)+ if zone == "" {+ return ""+ }+ // us-central1-a → us-central1+ if i := strings.LastIndex(zone, "-"); i > 0 {+ return zone[:i]+ }+ return zone+}diff --git a/opentelemetry-gpu-collector/internal/identity/cloud_identity_test.go b/opentelemetry-gpu-collector/internal/identity/cloud_identity_test.gonew file mode 100644index 00000000..8fd1d735--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/cloud_identity_test.go@@ -0,0 +1,238 @@+package identity++import (+ "context"+ "encoding/json"+ "net/http"+ "strings"+ "testing"+)++func TestProviderFromProviderID(t *testing.T) {+ tests := []struct {+ id, kv string+ wantProvider string+ wantPlatform string+ }{+ {"aws:///us-east-1a/i-0abc", "", "aws", "aws_eks"},+ {"gce://my-proj/us-central1-a/node-1", "", "gcp", "gcp_kubernetes_engine"},+ {"azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1", "", "azure", "azure_aks"},+ {"ocid1.instance.oc1..aaaa", "", "oracle_cloud", "oracle_cloud_oke"},+ {"", "v1.28.0-eks-abc", "aws", "aws_eks"},+ {"", "v1.28.0", "", ""},+ }+ for _, tt := range tests {+ p, plat := providerFromProviderID(tt.id, tt.kv, nil)+ if p != tt.wantProvider || plat != tt.wantPlatform {+ t.Errorf("id=%q kv=%q → %q/%q want %q/%q", tt.id, tt.kv, p, plat, tt.wantProvider, tt.wantPlatform)+ }+ }+}++func TestHostIDFromProviderID(t *testing.T) {+ tests := []struct {+ id, want string+ }{+ {"aws:///us-east-1a/i-0fea4fd46592d050b", "i-0fea4fd46592d050b"},+ {"gce://guestbook-12345/us-central1-a/gke-node-1", "gke-node-1"},+ {"azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/myvm", "myvm"},+ {"azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/myvmss/virtualMachines/0", "myvmss/0"},+ {"", ""},+ }+ for _, tt := range tests {+ if got := hostIDFromProviderID(tt.id); got != tt.want {+ t.Errorf("hostIDFromProviderID(%q)=%q want %q", tt.id, got, tt.want)+ }+ }+}++func TestInstanceTypeFromLabels(t *testing.T) {+ got := instanceTypeFromLabels(map[string]string{+ labelInstanceTypeStable: "g4dn.xlarge",+ })+ if got != "g4dn.xlarge" {+ t.Fatalf("got %q", got)+ }+ got = instanceTypeFromLabels(map[string]string{+ labelInstanceTypeBeta: "Standard_NC6s_v3",+ })+ if got != "Standard_NC6s_v3" {+ t.Fatalf("beta got %q", got)+ }+ got = instanceTypeFromLabels(map[string]string{+ labelInstanceTypeStable: "k3s",+ })+ if got != "" {+ t.Fatalf("k3s should be rejected, got %q", got)+ }+}++func TestParseNodeCloudJSON(t *testing.T) {+ raw := `{+ "metadata": {+ "labels": {+ "node.kubernetes.io/instance-type": "g5.xlarge",+ "topology.kubernetes.io/region": "us-west-2",+ "topology.kubernetes.io/zone": "us-west-2b"+ }+ },+ "spec": {"providerID": "aws:///us-west-2b/i-0123456789abcdef0"},+ "status": {"nodeInfo": {"kubeletVersion": "v1.29.0-eks-1"}}+ }`+ info, err := parseNodeCloudJSON([]byte(raw))+ if err != nil {+ t.Fatal(err)+ }+ ci := cloudIdentityFromNode(info)+ if ci.Provider != "aws" || ci.HostType != "g5.xlarge" || ci.Region != "us-west-2" {+ t.Fatalf("ci=%+v", ci)+ }+ if ci.HostID != "i-0123456789abcdef0" {+ t.Fatalf("HostID=%q", ci.HostID)+ }+ if ci.HostTypeSource != "k8s_label" {+ t.Fatalf("source=%q", ci.HostTypeSource)+ }+ if ci.AvailabilityZone != "us-west-2b" {+ t.Fatalf("zone=%q", ci.AvailabilityZone)+ }+}++func TestValidInstanceType(t *testing.T) {+ if !validInstanceType("n1-standard-8") {+ t.Fatal("n1-standard-8")+ }+ if !validInstanceType("p5.48xlarge") {+ t.Fatal("p5")+ }+ if validInstanceType("k3s") || validInstanceType("unknown") || validInstanceType("") {+ t.Fatal("should reject")+ }+}++func TestIMDSAWSIdentityDocument(t *testing.T) {+ doc, _ := json.Marshal(map[string]string{+ "instanceType": "g4dn.xlarge",+ "region": "us-east-1",+ "availabilityZone": "us-east-1a",+ "accountId": "123456789012",+ "instanceId": "i-abc",+ })+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if req.Method == http.MethodPut && strings.Contains(req.URL.Path, "/api/token") {+ return textResponse(http.StatusOK, "tok"), nil+ }+ if strings.Contains(req.URL.Path, "instance-identity/document") {+ if req.Header.Get("X-aws-ec2-metadata-token") != "tok" {+ t.Fatal("expected IMDSv2 token")+ }+ return textResponse(http.StatusOK, string(doc)), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })++ ci, ok := imdsAWS(context.Background(), client)+ if !ok {+ t.Fatal("expected ok")+ }+ if ci.Provider != "aws" || ci.HostType != "g4dn.xlarge" || ci.Region != "us-east-1" {+ t.Fatalf("%+v", ci)+ }+ if ci.HostTypeSource != "imds" {+ t.Fatalf("source=%q", ci.HostTypeSource)+ }+}++func TestIMDSGCPMachineType(t *testing.T) {+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if req.Header.Get("Metadata-Flavor") != "Google" {+ return textResponse(http.StatusForbidden, ""), nil+ }+ switch {+ case strings.HasSuffix(req.URL.Path, "/project/project-id"):+ return textResponse(http.StatusOK, "my-proj"), nil+ case strings.HasSuffix(req.URL.Path, "/instance/machine-type"):+ return textResponse(http.StatusOK, "projects/123/machineTypes/a2-highgpu-1g"), nil+ case strings.HasSuffix(req.URL.Path, "/instance/zone"):+ return textResponse(http.StatusOK, "projects/123/zones/us-central1-a"), nil+ case strings.HasSuffix(req.URL.Path, "/instance/id"):+ return textResponse(http.StatusOK, "9876543210"), nil+ default:+ return textResponse(http.StatusNotFound, ""), nil+ }+ })+ ci, ok := imdsGCP(context.Background(), client)+ if !ok {+ t.Fatal("expected ok")+ }+ if ci.HostType != "a2-highgpu-1g" || ci.Region != "us-central1" || ci.AvailabilityZone != "us-central1-a" {+ t.Fatalf("%+v", ci)+ }+ if ci.Provider != "gcp" || ci.AccountID != "my-proj" {+ t.Fatalf("%+v", ci)+ }+}++func TestIMDSAzureVMSize(t *testing.T) {+ body := `{"vmSize":"Standard_NC6s_v3","location":"eastus","zone":"1","subscriptionId":"sub-1","vmId":"vm-guid","name":"node1"}`+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if req.Header.Get("Metadata") != "true" {+ return textResponse(http.StatusBadRequest, ""), nil+ }+ if !strings.Contains(req.URL.RawQuery, "api-version=2021-05-01") {+ t.Fatalf("query=%s", req.URL.RawQuery)+ }+ return textResponse(http.StatusOK, body), nil+ })+ ci, ok := imdsAzure(context.Background(), client)+ if !ok {+ t.Fatal("expected ok")+ }+ if ci.Provider != "azure" || ci.HostType != "Standard_NC6s_v3" || ci.Region != "eastus" {+ t.Fatalf("%+v", ci)+ }+}++func TestDetectCloudIdentityParallelFirstWins(t *testing.T) {+ client := testClient(func(req *http.Request) (*http.Response, error) {+ // Only AWS succeeds+ if req.Method == http.MethodPut {+ return textResponse(http.StatusOK, "t"), nil+ }+ if strings.Contains(req.URL.Path, "instance-identity/document") {+ return textResponse(http.StatusOK, `{"instanceType":"m5.large","region":"eu-west-1","instanceId":"i-1","accountId":"1","availabilityZone":"eu-west-1a"}`), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })+ ci := detectCloudIdentityFromIMDS(context.Background(), client)+ if ci.Provider != "aws" || ci.HostType != "m5.large" {+ t.Fatalf("%+v", ci)+ }+}++func TestMergeCloudDoesNotOverwrite(t *testing.T) {+ dst := cloudIdentity{Provider: "aws", HostType: "g5.xlarge", HostTypeSource: "k8s_label"}+ src := cloudIdentity{Provider: "gcp", HostType: "n1-standard-1", Region: "us-central1", HostTypeSource: "imds"}+ got := mergeCloud(dst, src)+ if got.Provider != "aws" || got.HostType != "g5.xlarge" || got.HostTypeSource != "k8s_label" {+ t.Fatalf("%+v", got)+ }+ if got.Region != "us-central1" {+ t.Fatalf("region should fill: %+v", got)+ }+}++func TestK8sNodeLookupDisabled(t *testing.T) {+ t.Setenv("OPENLIT_K8S_NODE_LOOKUP", "false")+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ info, err := fetchNodeCloudInfo(context.Background(), "node-1")+ if err != nil || info != nil {+ t.Fatalf("expected skip, got %+v %v", info, err)+ }+}++func TestRegionFromGCPZone(t *testing.T) {+ if got := regionFromGCPZone("us-central1-a"); got != "us-central1" {+ t.Fatalf("%q", got)+ }+}diff --git a/opentelemetry-gpu-collector/internal/identity/dmi.go b/opentelemetry-gpu-collector/internal/identity/dmi.gonew file mode 100644index 00000000..2c9b6446--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/dmi.go@@ -0,0 +1,26 @@+package identity++import (+ "os"+ "strings"+)++// cloudProviderFromDMI reads /sys/class/dmi/id/sys_vendor when IMDS failed.+// Sets provider only — never invents host.type for bare metal.+func cloudProviderFromDMI() cloudIdentity {+ vendor, err := os.ReadFile("/sys/class/dmi/id/sys_vendor")+ if err != nil {+ return cloudIdentity{}+ }+ v := strings.ToLower(strings.TrimSpace(string(vendor)))+ switch {+ case strings.Contains(v, "amazon"):+ return cloudIdentity{Provider: "aws", Platform: "aws_ec2"}+ case strings.Contains(v, "google"):+ return cloudIdentity{Provider: "gcp", Platform: "gcp_compute_engine"}+ case strings.Contains(v, "microsoft"):+ return cloudIdentity{Provider: "azure", Platform: "azure_vm"}+ default:+ return cloudIdentity{}+ }+}diff --git a/opentelemetry-gpu-collector/internal/identity/identity.go b/opentelemetry-gpu-collector/internal/identity/identity.gonew file mode 100644index 00000000..c3667e92--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/identity.go@@ -0,0 +1,308 @@+package identity++import (+ "context"+ "log/slog"+ "os"+ "strings"++ "go.opentelemetry.io/otel/attribute"+)++const (+ attrHostName = "host.name"+ attrK8sNodeName = "k8s.node.name"+ attrK8sClusterName = "k8s.cluster.name"+ attrCloudProvider = "cloud.provider"+ attrCloudPlatform = "cloud.platform"+ attrHostType = "host.type"+ attrCloudRegion = "cloud.region"+ attrCloudAvailabilityZone = "cloud.availability_zone"+ attrCloudAccountID = "cloud.account.id"+ attrHostID = "host.id"+ attrHostTypeSource = "openlit.host.type.source"+)++// Result holds resolved host / Kubernetes / cloud identity for logging and tests.+type Result struct {+ HostName string+ NodeName string+ ClusterName string+ InKubernetes bool+ CloudProvider string+ CloudPlatform string+ HostType string+ CloudRegion string+ AvailabilityZone string+ CloudAccountID string+ HostID string+ HostTypeSource string+}++// Detect resolves host, Kubernetes, and cloud instance identity.+//+// Hostname / node precedence:+// 1. Explicit OPENLIT_HOSTNAME / HOST_NAME (optional override)+// 2. K8S_NODE_NAME → OTEL_RESOURCE_ATTRIBUTES_NODE_NAME → NODE_NAME (downward API)+// 3. (K8s only) GCE hostname+// 4. OS hostname+//+// Cluster name (K8s only): K8S_CLUSTER_NAME / OPENLIT_K8S_CLUSTER_NAME → GKE/AKS/EKS metadata.+//+// Cloud / instance type (fill missing fields only):+// 1. Explicit OTEL_RESOURCE_ATTRIBUTES (applied after Detect via WithFromEnv)+// 2. K8s Node GET (providerID + labels) when in-cluster+// 3. Parallel AWS/GCP/Azure IMDS+// 4. DMI sys_vendor hint (provider only)+//+// Prefer the OpenTelemetry pattern: set attributes via OTEL_RESOURCE_ATTRIBUTES+// (applied after Detect via resource.WithFromEnv(), so it wins over auto-detect).+func Detect(ctx context.Context, logger *slog.Logger) (Result, []attribute.KeyValue) {+ return detect(ctx, logger, defaultHTTPClient(), osHostname)+}++func detect(+ ctx context.Context,+ logger *slog.Logger,+ client httpDoer,+ osHostnameFn func() (string, error),+) (Result, []attribute.KeyValue) {+ if logger == nil {+ logger = slog.Default()+ }++ res := Result{+ InKubernetes: isKubernetes(),+ }++ res.HostName, res.NodeName = resolveHostname(ctx, client, osHostnameFn, res.InKubernetes)++ if res.InKubernetes {+ res.ClusterName = resolveClusterName(ctx, client)+ }++ applyCloudIdentity(&res, resolveCloudIdentity(ctx, client, logger, res.InKubernetes, res.NodeName))++ attrs := resultAttrs(res)++ logger.Info("resolved resource identity",+ "host.name", res.HostName,+ "k8s.node.name", res.NodeName,+ "k8s.cluster.name", emptyAs(res.ClusterName, "not detected"),+ "cloud.provider", emptyAs(res.CloudProvider, "not detected"),+ "host.type", emptyAs(res.HostType, "not detected"),+ "cloud.region", emptyAs(res.CloudRegion, "not detected"),+ "host.type.source", emptyAs(res.HostTypeSource, ""),+ "kubernetes", res.InKubernetes,+ )++ return res, attrs+}++func emptyAs(v, fallback string) string {+ if v == "" {+ return fallback+ }+ return v+}++func resultAttrs(res Result) []attribute.KeyValue {+ attrs := make([]attribute.KeyValue, 0, 12)+ if res.HostName != "" {+ attrs = append(attrs, attribute.String(attrHostName, res.HostName))+ }+ if res.NodeName != "" {+ attrs = append(attrs, attribute.String(attrK8sNodeName, res.NodeName))+ }+ if res.ClusterName != "" {+ attrs = append(attrs, attribute.String(attrK8sClusterName, res.ClusterName))+ }+ if res.CloudProvider != "" {+ attrs = append(attrs, attribute.String(attrCloudProvider, res.CloudProvider))+ }+ if res.CloudPlatform != "" {+ attrs = append(attrs, attribute.String(attrCloudPlatform, res.CloudPlatform))+ }+ if res.HostType != "" {+ attrs = append(attrs, attribute.String(attrHostType, res.HostType))+ }+ if res.CloudRegion != "" {+ attrs = append(attrs, attribute.String(attrCloudRegion, res.CloudRegion))+ }+ if res.AvailabilityZone != "" {+ attrs = append(attrs, attribute.String(attrCloudAvailabilityZone, res.AvailabilityZone))+ }+ if res.CloudAccountID != "" {+ attrs = append(attrs, attribute.String(attrCloudAccountID, res.CloudAccountID))+ }+ if res.HostID != "" {+ attrs = append(attrs, attribute.String(attrHostID, res.HostID))+ }+ if res.HostTypeSource != "" {+ attrs = append(attrs, attribute.String(attrHostTypeSource, res.HostTypeSource))+ }+ return attrs+}++func applyCloudIdentity(res *Result, ci cloudIdentity) {+ if res.CloudProvider == "" {+ res.CloudProvider = ci.Provider+ }+ if res.CloudPlatform == "" {+ res.CloudPlatform = ci.Platform+ }+ if res.HostType == "" {+ res.HostType = ci.HostType+ if ci.HostType != "" {+ res.HostTypeSource = ci.HostTypeSource+ }+ } else if res.HostTypeSource == "" && ci.HostTypeSource != "" {+ res.HostTypeSource = ci.HostTypeSource+ }+ if res.CloudRegion == "" {+ res.CloudRegion = ci.Region+ }+ if res.AvailabilityZone == "" {+ res.AvailabilityZone = ci.AvailabilityZone+ }+ if res.CloudAccountID == "" {+ res.CloudAccountID = ci.AccountID+ }+ if res.HostID == "" {+ res.HostID = ci.HostID+ }+}++// resolveCloudIdentity fills cloud attrs: K8s node → IMDS → DMI.+// Only later tiers fill fields still empty (mergeCloud).+func resolveCloudIdentity(ctx context.Context, client httpDoer, logger *slog.Logger, inK8s bool, nodeName string) cloudIdentity {+ var out cloudIdentity++ if inK8s && nodeName != "" {+ info, err := fetchNodeCloudInfo(ctx, nodeName)+ if err != nil {+ logger.Debug("k8s node cloud lookup failed", "error", err)+ } else if info != nil {+ out = mergeCloud(out, cloudIdentityFromNode(info))+ }+ }++ if cloudIncomplete(out) && cloudIMDSEnabled() {+ out = mergeCloud(out, detectCloudIdentityFromIMDS(ctx, client))+ }++ if out.Provider == "" {+ out = mergeCloud(out, cloudProviderFromDMI())+ }++ return out+}++func cloudIncomplete(ci cloudIdentity) bool {+ return ci.Provider == "" || ci.HostType == "" || ci.Region == ""+}++// mergeCloud copies non-empty fields from src into dst without overwriting.+func mergeCloud(dst, src cloudIdentity) cloudIdentity {+ if dst.Provider == "" {+ dst.Provider = src.Provider+ }+ if dst.Platform == "" {+ dst.Platform = src.Platform+ }+ if dst.HostType == "" {+ dst.HostType = src.HostType+ if src.HostTypeSource != "" {+ dst.HostTypeSource = src.HostTypeSource+ }+ }+ if dst.Region == "" {+ dst.Region = src.Region+ }+ if dst.AvailabilityZone == "" {+ dst.AvailabilityZone = src.AvailabilityZone+ }+ if dst.AccountID == "" {+ dst.AccountID = src.AccountID+ }+ if dst.HostID == "" {+ dst.HostID = src.HostID+ }+ return dst+}++func isKubernetes() bool {+ return os.Getenv("KUBERNETES_SERVICE_HOST") != ""+}++func resolveHostname(ctx context.Context, client httpDoer, osHostnameFn func() (string, error), inKubernetes bool) (hostName, nodeName string) {+ nodeName = downwardNodeName()++ if v := firstNonEmpty(os.Getenv("OPENLIT_HOSTNAME"), os.Getenv("HOST_NAME")); v != "" {+ return v, nodeName+ }++ if nodeName != "" {+ return nodeName, nodeName+ }++ // Only probe GCE when in Kubernetes (e.g. GKE without downward API).+ // Outside K8s, OS hostname is fine and avoids a metadata timeout on every start.+ if inKubernetes {+ if gceHost, err := hostnameFromGCE(ctx, client); err == nil && gceHost != "" {+ return gceHost, ""+ }+ }++ if osHostnameFn != nil {+ if hn, err := osHostnameFn(); err == nil && hn != "" {+ return hn, ""+ }+ }+ return "", ""+}++// downwardNodeName reads the Kubernetes node name from common downward-API env vars.+// Prefer OTel-aligned names; NODE_NAME remains a legacy fallback.+func downwardNodeName() string {+ return firstNonEmpty(+ os.Getenv("K8S_NODE_NAME"),+ os.Getenv("OTEL_RESOURCE_ATTRIBUTES_NODE_NAME"),+ os.Getenv("NODE_NAME"),+ )+}++func resolveClusterName(ctx context.Context, client httpDoer) string {+ // Prefer K8S_CLUSTER_NAME (common in OTel manifests); OPENLIT_* is an alias.+ if v := firstNonEmpty(os.Getenv("K8S_CLUSTER_NAME"), os.Getenv("OPENLIT_K8S_CLUSTER_NAME")); v != "" {+ return normalizeClusterName(v)+ }+ if name := detectClusterFromCloud(ctx, client); name != "" {+ return normalizeClusterName(name)+ }+ return ""+}++// normalizeClusterName lowercases and replaces underscores with hyphens (RFC1123-ish).+func normalizeClusterName(name string) string {+ name = strings.TrimSpace(name)+ if name == "" {+ return ""+ }+ name = strings.ToLower(name)+ name = strings.ReplaceAll(name, "_", "-")+ return name+}++func firstNonEmpty(values ...string) string {+ for _, v := range values {+ if s := strings.TrimSpace(v); s != "" {+ return s+ }+ }+ return ""+}++func osHostname() (string, error) {+ return os.Hostname()+}diff --git a/opentelemetry-gpu-collector/internal/identity/identity_test.go b/opentelemetry-gpu-collector/internal/identity/identity_test.gonew file mode 100644index 00000000..f8f2dd6e--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/identity_test.go@@ -0,0 +1,398 @@+package identity++import (+ "bytes"+ "context"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "testing"++ "go.opentelemetry.io/otel/attribute"+)++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}++func testClient(fn roundTripFunc) *http.Client {+ return &http.Client{Transport: fn}+}++func textResponse(status int, body string) *http.Response {+ return &http.Response{+ StatusCode: status,+ Body: io.NopCloser(strings.NewReader(body)),+ Header: make(http.Header),+ }+}++func discardLogger() *slog.Logger {+ return slog.New(slog.NewTextHandler(io.Discard, nil))+}++func attrMap(attrs []attribute.KeyValue) map[string]string {+ m := make(map[string]string, len(attrs))+ for _, a := range attrs {+ m[string(a.Key)] = a.Value.AsString()+ }+ return m+}++func TestIsKubernetes(t *testing.T) {+ t.Setenv("KUBERNETES_SERVICE_HOST", "")+ if isKubernetes() {+ t.Fatal("expected false when KUBERNETES_SERVICE_HOST unset")+ }+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ if !isKubernetes() {+ t.Fatal("expected true when KUBERNETES_SERVICE_HOST set")+ }+}++func clearIdentityEnv(t *testing.T) {+ t.Helper()+ t.Setenv("KUBERNETES_SERVICE_HOST", "")+ t.Setenv("OPENLIT_HOSTNAME", "")+ t.Setenv("HOST_NAME", "")+ t.Setenv("K8S_NODE_NAME", "")+ t.Setenv("OTEL_RESOURCE_ATTRIBUTES_NODE_NAME", "")+ t.Setenv("NODE_NAME", "")+ t.Setenv("K8S_CLUSTER_NAME", "")+ t.Setenv("OPENLIT_K8S_CLUSTER_NAME", "")+ t.Setenv("OPENLIT_K8S_NODE_LOOKUP", "false") // skip real SA token paths in unit tests+}++func TestDetectNonKubernetesSkipsGCEHostname(t *testing.T) {+ clearIdentityEnv(t)++ hostnameProbed := false+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if strings.Contains(req.URL.Path, "/instance/hostname") {+ hostnameProbed = true+ return textResponse(http.StatusOK, "gce-host"), nil+ }+ // IMDS probes for cloud identity are allowed outside K8s; fail soft.+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os-host", nil+ })+ if hostnameProbed {+ t.Fatal("GCE hostname should not be probed outside Kubernetes")+ }+ if res.HostName != "os-host" {+ t.Fatalf("HostName = %q", res.HostName)+ }+}++func TestDetectNonKubernetesNoCluster(t *testing.T) {+ clearIdentityEnv(t)++ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, attrs := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "my-laptop", nil+ })++ if res.InKubernetes {+ t.Fatal("InKubernetes should be false")+ }+ if res.ClusterName != "" {+ t.Fatalf("ClusterName = %q, want empty", res.ClusterName)+ }+ if res.HostName != "my-laptop" {+ t.Fatalf("HostName = %q, want my-laptop", res.HostName)+ }+ m := attrMap(attrs)+ if m[attrK8sClusterName] != "" {+ t.Fatalf("unexpected k8s.cluster.name attr %q", m[attrK8sClusterName])+ }+ if m[attrHostName] != "my-laptop" {+ t.Fatalf("host.name = %q", m[attrHostName])+ }+}++func TestDetectK8SNodeNameSetsHostAndNode(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("K8S_NODE_NAME", "gpu-node-1")+ t.Setenv("NODE_NAME", "legacy-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, attrs := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "should-not-use", nil+ })++ if res.HostName != "gpu-node-1" || res.NodeName != "gpu-node-1" {+ t.Fatalf("got host=%q node=%q (K8S_NODE_NAME should win over NODE_NAME)", res.HostName, res.NodeName)+ }+ m := attrMap(attrs)+ if m[attrHostName] != "gpu-node-1" || m[attrK8sNodeName] != "gpu-node-1" {+ t.Fatalf("attrs=%v", m)+ }+ if m[attrK8sClusterName] != "" {+ t.Fatalf("cluster should be empty without override/cloud, got %q", m[attrK8sClusterName])+ }+}++func TestDetectOTelOperatorNodeNameEnv(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("OTEL_RESOURCE_ATTRIBUTES_NODE_NAME", "operator-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.HostName != "operator-node" || res.NodeName != "operator-node" {+ t.Fatalf("got host=%q node=%q", res.HostName, res.NodeName)+ }+}++func TestDetectLegacyNodeNameFallback(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("NODE_NAME", "legacy-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.HostName != "legacy-node" {+ t.Fatalf("HostName = %q", res.HostName)+ }+}++func TestDetectExplicitHostnameBeatsNodeName(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("OPENLIT_HOSTNAME", "explicit-host")+ t.Setenv("K8S_NODE_NAME", "gpu-node-1")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.HostName != "explicit-host" {+ t.Fatalf("HostName = %q", res.HostName)+ }+ if res.NodeName != "gpu-node-1" {+ t.Fatalf("NodeName = %q, want still set from K8S_NODE_NAME", res.NodeName)+ }+}++func TestDetectClusterEnvOverrideBeatsCloud(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("K8S_NODE_NAME", "n1")+ t.Setenv("K8S_CLUSTER_NAME", "My_Cluster")++ clusterProbed := false+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if strings.Contains(req.URL.Path, "cluster-name") ||+ strings.Contains(req.URL.Path, "resourceGroupName") ||+ strings.Contains(req.URL.Path, "/meta-data/tags/instance") {+ clusterProbed = true+ }+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, attrs := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.ClusterName != "my-cluster" {+ t.Fatalf("ClusterName = %q, want my-cluster (normalized)", res.ClusterName)+ }+ if clusterProbed {+ t.Fatal("cluster cloud metadata should not be called when env override is set")+ }+ m := attrMap(attrs)+ if m[attrK8sClusterName] != "my-cluster" {+ t.Fatalf("attrs=%v", m)+ }+}++func TestDetectClusterFromGKE(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("K8S_NODE_NAME", "gke-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ if strings.Contains(req.URL.Path, "cluster-name") {+ if req.Header.Get("Metadata-Flavor") != "Google" {+ t.Fatalf("missing Metadata-Flavor header")+ }+ return textResponse(http.StatusOK, "prod-gke"), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.ClusterName != "prod-gke" {+ t.Fatalf("ClusterName = %q", res.ClusterName)+ }+}++func TestNormalizeClusterName(t *testing.T) {+ tests := []struct{ in, want string }{+ {"Prod_Cluster", "prod-cluster"},+ {" already-ok ", "already-ok"},+ {"", ""},+ }+ for _, tt := range tests {+ if got := normalizeClusterName(tt.in); got != tt.want {+ t.Errorf("normalizeClusterName(%q)=%q want %q", tt.in, got, tt.want)+ }+ }+}++func TestParseAKSClusterName(t *testing.T) {+ tests := []struct{ in, want string }{+ {"MC_MyResourceGroup_example-cluster-name_eastus", "example-cluster-name"},+ {"mc_rg_mycluster_westeurope", "mycluster"},+ {"MC_a_b_c_d_eastus", "d"},+ {"not-mc-group", ""},+ {"MC_short", ""},+ }+ for _, tt := range tests {+ if got := parseAKSClusterName(tt.in); got != tt.want {+ t.Errorf("parseAKSClusterName(%q)=%q want %q", tt.in, got, tt.want)+ }+ }+}++func TestClusterNameFromEKSTagKey(t *testing.T) {+ tests := []struct{ in, want string }{+ {"kubernetes.io/cluster/my-eks", "my-eks"},+ {"kubernetes.io/cluster/", ""},+ {"Name", ""},+ {"kubernetes.io/cluster/a/b", ""},+ }+ for _, tt := range tests {+ if got := clusterNameFromEKSTagKey(tt.in); got != tt.want {+ t.Errorf("clusterNameFromEKSTagKey(%q)=%q want %q", tt.in, got, tt.want)+ }+ }+}++func TestDetectClusterFromAKS(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("K8S_NODE_NAME", "aks-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ // GKE fails first+ if strings.Contains(req.URL.Path, "attributes/cluster-name") {+ return textResponse(http.StatusNotFound, ""), nil+ }+ if strings.Contains(req.URL.Path, "resourceGroupName") {+ if req.Header.Get("Metadata") != "true" {+ t.Fatal("missing Azure Metadata header")+ }+ return textResponse(http.StatusOK, "MC_MyResourceGroup_aks-prod_eastus"), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.ClusterName != "aks-prod" {+ t.Fatalf("ClusterName = %q, want aks-prod", res.ClusterName)+ }+}++func TestDetectClusterFromEKS(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")+ t.Setenv("K8S_NODE_NAME", "eks-node")++ client := testClient(func(req *http.Request) (*http.Response, error) {+ if strings.Contains(req.URL.Path, "attributes/cluster-name") {+ return textResponse(http.StatusNotFound, ""), nil+ }+ if strings.Contains(req.URL.Path, "resourceGroupName") {+ return textResponse(http.StatusNotFound, ""), nil+ }+ if req.Method == http.MethodPut && strings.Contains(req.URL.Path, "/api/token") {+ return textResponse(http.StatusOK, "imds-token"), nil+ }+ if strings.Contains(req.URL.Path, "/meta-data/tags/instance") {+ if req.Header.Get("X-aws-ec2-metadata-token") != "imds-token" {+ t.Fatal("missing IMDS token header")+ }+ return textResponse(http.StatusOK, "Name\nkubernetes.io/cluster/eks-demo\n"), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })++ res, _ := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "os", nil+ })+ if res.ClusterName != "eks-demo" {+ t.Fatalf("ClusterName = %q, want eks-demo", res.ClusterName)+ }+}++func TestDetectIMDSFillsCloudAttrs(t *testing.T) {+ clearIdentityEnv(t)+ doc := `{"instanceType":"g4dn.xlarge","region":"us-east-1","availabilityZone":"us-east-1a","accountId":"123","instanceId":"i-xyz"}`+ client := testClient(func(req *http.Request) (*http.Response, error) {+ if req.Method == http.MethodPut {+ return textResponse(http.StatusOK, "tok"), nil+ }+ if strings.Contains(req.URL.Path, "instance-identity/document") {+ return textResponse(http.StatusOK, doc), nil+ }+ return textResponse(http.StatusNotFound, ""), nil+ })+ res, attrs := detect(context.Background(), discardLogger(), client, func() (string, error) {+ return "host", nil+ })+ if res.CloudProvider != "aws" || res.HostType != "g4dn.xlarge" || res.CloudRegion != "us-east-1" {+ t.Fatalf("%+v", res)+ }+ if res.HostTypeSource != "imds" {+ t.Fatalf("source=%q", res.HostTypeSource)+ }+ m := attrMap(attrs)+ if m[attrCloudProvider] != "aws" || m[attrHostType] != "g4dn.xlarge" || m[attrHostTypeSource] != "imds" {+ t.Fatalf("%v", m)+ }+}++func TestDetectLogsWithoutPanic(t *testing.T) {+ clearIdentityEnv(t)+ t.Setenv("OPENLIT_HOSTNAME", "h")++ var buf bytes.Buffer+ logger := slog.New(slog.NewTextHandler(&buf, nil))+ client := testClient(func(req *http.Request) (*http.Response, error) {+ return textResponse(http.StatusNotFound, ""), nil+ })+ detect(context.Background(), logger, client, func() (string, error) { return "x", nil })+ if !strings.Contains(buf.String(), "resolved resource identity") {+ t.Fatalf("expected log line, got %q", buf.String())+ }+}diff --git a/opentelemetry-gpu-collector/internal/identity/k8s_node.go b/opentelemetry-gpu-collector/internal/identity/k8s_node.gonew file mode 100644index 00000000..f002e6f2--- /dev/null+++ b/opentelemetry-gpu-collector/internal/identity/k8s_node.go@@ -0,0 +1,303 @@+package identity++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "path"+ "strings"+ "time"+)++const (+ labelInstanceTypeStable = "node.kubernetes.io/instance-type"+ labelInstanceTypeBeta = "beta.kubernetes.io/instance-type"+ labelOCIShape = "oci.oraclecloud.com/instance-shape"+ labelRegionStable = "topology.kubernetes.io/region"+ labelRegionBeta = "failure-domain.beta.kubernetes.io/region"+ labelZoneStable = "topology.kubernetes.io/zone"+ labelZoneBeta = "failure-domain.beta.kubernetes.io/zone"++ k8sNodeLookupTimeout = 800 * time.Millisecond+)++// cloudIdentity holds cloud / instance attrs filled by discovery tiers.+type cloudIdentity struct {+ Provider string+ Platform string+ HostType string+ Region string+ AvailabilityZone string+ AccountID string+ HostID string+ HostTypeSource string // env | k8s_label | imds | dmi+}++// nodeCloudInfo is the subset of a Kubernetes Node we care about.+type nodeCloudInfo struct {+ ProviderID string+ KubeletVersion string+ Labels map[string]string+}++// k8sNodeLookupEnabled is true unless OPENLIT_K8S_NODE_LOOKUP=false.+func k8sNodeLookupEnabled() bool {+ v := strings.TrimSpace(strings.ToLower(os.Getenv("OPENLIT_K8S_NODE_LOOKUP")))+ return v != "false" && v != "0" && v != "no"+}++// fetchNodeCloudInfo GETs /api/v1/nodes/$name using in-cluster credentials.+// Returns nil, nil when lookup is disabled or not in-cluster.+func fetchNodeCloudInfo(ctx context.Context, nodeName string) (*nodeCloudInfo, error) {+ if nodeName == "" || !k8sNodeLookupEnabled() {+ return nil, nil+ }+ host := os.Getenv("KUBERNETES_SERVICE_HOST")+ port := os.Getenv("KUBERNETES_SERVICE_PORT")+ if host == "" {+ return nil, nil+ }+ if port == "" {+ port = "443"+ }++ token, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")+ if err != nil || len(token) == 0 {+ return nil, fmt.Errorf("service account token: %w", err)+ }++ client, err := inClusterHTTPClient()+ if err != nil {+ return nil, err+ }++ ctx, cancel := context.WithTimeout(ctx, k8sNodeLookupTimeout)+ defer cancel()++ u := &url.URL{+ Scheme: "https",+ Host: netJoinHostPort(host, port),+ Path: path.Join("/api/v1/nodes", nodeName),+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token)))+ req.Header.Set("Accept", "application/json")++ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if err != nil {+ return nil, err+ }+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("nodes/%s: status %d", nodeName, resp.StatusCode)+ }+ return parseNodeCloudJSON(body)+}++func netJoinHostPort(host, port string) string {+ if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {+ return "[" + host + "]:" + port+ }+ return host + ":" + port+}++func inClusterHTTPClient() (*http.Client, error) {+ ca, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")+ if err != nil {+ return nil, fmt.Errorf("service account CA: %w", err)+ }+ pool := x509.NewCertPool()+ if !pool.AppendCertsFromPEM(ca) {+ return nil, fmt.Errorf("failed to parse service account CA")+ }+ return &http.Client{+ Timeout: k8sNodeLookupTimeout,+ Transport: &http.Transport{+ TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},+ },+ }, nil+}++func parseNodeCloudJSON(data []byte) (*nodeCloudInfo, error) {+ var raw struct {+ Metadata struct {+ Labels map[string]string `json:"labels"`+ } `json:"metadata"`+ Spec struct {+ ProviderID string `json:"providerID"`+ } `json:"spec"`+ Status struct {+ NodeInfo struct {+ KubeletVersion string `json:"kubeletVersion"`+ } `json:"nodeInfo"`+ } `json:"status"`+ }+ if err := json.Unmarshal(data, &raw); err != nil {+ return nil, err+ }+ return &nodeCloudInfo{+ ProviderID: raw.Spec.ProviderID,+ KubeletVersion: raw.Status.NodeInfo.KubeletVersion,+ Labels: raw.Metadata.Labels,+ }, nil+}++// cloudIdentityFromNode extracts cloud attrs from a Kubernetes Node (OpenCost-style).+func cloudIdentityFromNode(n *nodeCloudInfo) cloudIdentity {+ if n == nil {+ return cloudIdentity{}+ }+ ci := cloudIdentity{}++ ci.Provider, ci.Platform = providerFromProviderID(n.ProviderID, n.KubeletVersion, n.Labels)+ ci.HostType = instanceTypeFromLabels(n.Labels)+ ci.Region = firstLabel(n.Labels, labelRegionStable, labelRegionBeta)+ ci.AvailabilityZone = firstLabel(n.Labels, labelZoneStable, labelZoneBeta)+ ci.HostID = hostIDFromProviderID(n.ProviderID)++ if ci.HostType == "" && ci.Provider == "" && ci.Region == "" {+ return cloudIdentity{}+ }+ if ci.HostType != "" {+ ci.HostTypeSource = "k8s_label"+ }+ return ci+}++func firstLabel(labels map[string]string, keys ...string) string {+ if labels == nil {+ return ""+ }+ for _, k := range keys {+ if v := strings.TrimSpace(labels[k]); v != "" {+ return v+ }+ }+ return ""+}++func instanceTypeFromLabels(labels map[string]string) string {+ if labels == nil {+ return ""+ }+ for _, k := range []string{labelInstanceTypeStable, labelInstanceTypeBeta, labelOCIShape} {+ v := strings.TrimSpace(labels[k])+ if !validInstanceType(v) {+ continue+ }+ return v+ }+ return ""+}++// validInstanceType rejects garbage values like bare "k3s".+func validInstanceType(v string) bool {+ if v == "" {+ return false+ }+ lower := strings.ToLower(v)+ if lower == "k3s" || lower == "unknown" || lower == "none" {+ return false+ }+ hasDigit, hasSep := false, false+ for _, r := range v {+ if r >= '0' && r <= '9' {+ hasDigit = true+ }+ if r == '-' || r == '.' || r == '_' {+ hasSep = true+ }+ }+ return hasDigit || hasSep+}++func providerFromProviderID(providerID, kubeletVersion string, labels map[string]string) (provider, platform string) {+ id := strings.ToLower(strings.TrimSpace(providerID))+ switch {+ case strings.HasPrefix(id, "aws://"):+ return "aws", "aws_eks"+ case strings.HasPrefix(id, "gce://"):+ return "gcp", "gcp_kubernetes_engine"+ case strings.HasPrefix(id, "azure://"):+ return "azure", "azure_aks"+ case strings.HasPrefix(id, "ocid") || strings.Contains(id, "ocid1.instance"):+ return "oracle_cloud", "oracle_cloud_oke"+ case strings.HasPrefix(id, "scaleway://"):+ return "scaleway", "scaleway_kapsule"+ case strings.HasPrefix(id, "digitalocean://"):+ return "digitalocean", "digitalocean_kubernetes"+ }++ kv := strings.ToLower(kubeletVersion)+ if strings.Contains(kv, "eks") {+ return "aws", "aws_eks"+ }+ if strings.Contains(kv, "aliyun") {+ return "alibaba_cloud", "alibaba_cloud_ack"+ }+ if labels != nil {+ if _, ok := labels["cce.cloud.com/cce-nodepool"]; ok {+ return "otc", "otc_cce"+ }+ }+ return "", ""+}++// hostIDFromProviderID parses cloud instance IDs from common providerID forms.+func hostIDFromProviderID(providerID string) string {+ id := strings.TrimSpace(providerID)+ if id == "" {+ return ""+ }+ lower := strings.ToLower(id)++ if strings.HasPrefix(lower, "aws://") {+ rest := id[len("aws://"):]+ parts := strings.Split(rest, "/")+ for i := len(parts) - 1; i >= 0; i-- {+ if parts[i] != "" {+ return parts[i]+ }+ }+ }++ if strings.HasPrefix(lower, "gce://") {+ rest := id[len("gce://"):]+ parts := strings.Split(rest, "/")+ if len(parts) >= 3 {+ return parts[len(parts)-1]+ }+ }++ if strings.HasPrefix(lower, "azure://") {+ // VMSS: .../virtualMachineScaleSets/<name>/virtualMachines/<ordinal>+ // Prefer name/ordinal over bare "0", which is not a useful host.id.+ const vmssMarker = "/virtualmachinescalesets/"+ const vmMarker = "/virtualmachines/"+ if i := strings.LastIndex(lower, vmssMarker); i >= 0 {+ rest := id[i+len(vmssMarker):]+ parts := strings.Split(rest, "/")+ if len(parts) >= 3 && strings.EqualFold(parts[1], "virtualMachines") {+ return parts[0] + "/" + parts[2]+ }+ }+ idx := strings.LastIndex(lower, vmMarker)+ if idx >= 0 {+ return id[idx+len(vmMarker):]+ }+ }+ return ""+}diff --git a/opentelemetry-gpu-collector/internal/workload/cgroup.go b/opentelemetry-gpu-collector/internal/workload/cgroup.gonew file mode 100644index 00000000..5e57ed56--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/cgroup.go@@ -0,0 +1,86 @@+package workload++import (+ "os"+ "regexp"+ "strconv"+ "strings"+)++// PodInfo is optional Kubernetes attribution for a process.+type PodInfo struct {+ PodUID string+ PodName string+ Namespace string+ ContainerName string+ ContainerID string+ // DeviceIDs are GPU UUIDs (or vendor device ids) from PodResources allocations.+ DeviceIDs []string+ // PIDs is populated by PodResources when the kubelet exposes container PIDs.+ PIDs []int32+}++var (+ // cgroup v1: .../kubepods/.../pod<UID>/...+ // cgroup v2: .../kubepods.slice/kubepods-...-pod<uid>.slice/...+ podUIDRe = regexp.MustCompile(`pod([0-9a-fA-F_-]{8,})`)+ // cri-containerd / docker / crio container id (64 hex), or bare 64-hex after pod path+ containerIDRe = regexp.MustCompile(`(?:(?:cri-containerd-|docker-|crio-)|(?:pod[0-9a-fA-F_-]+[./]))([0-9a-f]{64})`)+)++// ResolvePod reads /proc/<pid>/cgroup and extracts pod UID / container id when present.+func ResolvePod(pid int32) (PodInfo, bool) {+ if pid <= 0 {+ return PodInfo{}, false+ }+ data, err := os.ReadFile("/proc/" + strconv.FormatInt(int64(pid), 10) + "/cgroup")+ if err != nil {+ return PodInfo{}, false+ }+ return ParseCgroup(string(data))+}++// ParseCgroup extracts pod identity hints from cgroup file contents.+func ParseCgroup(content string) (PodInfo, bool) {+ info := PodInfo{}+ for _, line := range strings.Split(content, "\n") {+ parts := strings.SplitN(line, ":", 3)+ path := line+ if len(parts) == 3 {+ path = parts[2]+ }+ if m := podUIDRe.FindStringSubmatch(path); len(m) > 1 {+ uid := strings.ReplaceAll(m[1], "_", "-")+ info.PodUID = uid+ }+ if m := containerIDRe.FindStringSubmatch(path); len(m) > 1 {+ info.ContainerID = m[1]+ }+ }+ if info.PodUID == "" && info.PodName == "" && info.ContainerID == "" {+ return PodInfo{}, false+ }+ return info, true+}++// Resolver caches ResolvePod results for a scrape cycle (cgroup-only).+type Resolver struct {+ cache map[int32]PodInfo+}++func NewResolver() *Resolver {+ return &Resolver{cache: make(map[int32]PodInfo)}+}++func (r *Resolver) Resolve(pid int32) (PodInfo, bool) {+ if info, ok := r.cache[pid]; ok {+ return info, info.PodUID != "" || info.PodName != "" || info.ContainerID != ""+ }+ info, ok := ResolvePod(pid)+ if ok {+ r.cache[pid] = info+ } else {+ r.cache[pid] = PodInfo{}+ }+ return info, ok+}diff --git a/opentelemetry-gpu-collector/internal/workload/cgroup_test.go b/opentelemetry-gpu-collector/internal/workload/cgroup_test.gonew file mode 100644index 00000000..297069cc--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/cgroup_test.go@@ -0,0 +1,42 @@+package workload++import "testing"++func TestParseCgroupV1(t *testing.T) {+ content := `11:memory:/kubepods/burstable/poda1b2c3d4-e5f6-7890-abcd-ef1234567890/cri-containerd-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef`+ info, ok := ParseCgroup(content)+ if !ok {+ t.Fatal("expected ok")+ }+ if info.PodUID != "a1b2c3d4-e5f6-7890-abcd-ef1234567890" {+ t.Fatalf("uid=%q", info.PodUID)+ }+ if info.ContainerID != "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" {+ t.Fatalf("containerID=%q", info.ContainerID)+ }+}++func TestParseCgroupV2(t *testing.T) {+ content := `0::/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-poda1b2c3d4_e5f6_7890_abcd_ef1234567890.slice/cri-containerd-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef.scope`+ info, ok := ParseCgroup(content)+ if !ok {+ t.Fatal("expected ok")+ }+ want := "a1b2c3d4-e5f6-7890-abcd-ef1234567890"+ if info.PodUID != want {+ t.Fatalf("uid=%q want %q", info.PodUID, want)+ }+}++func TestParseCgroupBareContainerID(t *testing.T) {+ cid := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"+ content := `0::/kubepods/poda1b2c3d4-e5f6-7890-abcd-ef1234567890/` + cid+ info, ok := ParseCgroup(content)+ if !ok {+ t.Fatal("expected ok")+ }+ if info.ContainerID != cid {+ t.Fatalf("containerID=%q", info.ContainerID)+ }+}+diff --git a/opentelemetry-gpu-collector/internal/workload/doc.go b/opentelemetry-gpu-collector/internal/workload/doc.gonew file mode 100644index 00000000..c480e20a--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/doc.go@@ -0,0 +1,4 @@+// Package workload resolves PIDs to Kubernetes pod identity via cgroup paths.+// Optional kubelet PodResources allocation enrichment can be added later for+// zero-util allocated GPUs; utilization attribution uses cgroup → pod UID.+package workloaddiff --git a/opentelemetry-gpu-collector/internal/workload/enricher.go b/opentelemetry-gpu-collector/internal/workload/enricher.gonew file mode 100644index 00000000..bffd94b5--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/enricher.go@@ -0,0 +1,329 @@+package workload++import (+ "context"+ "log/slog"+ "os"+ "sync"+ "time"++ "github.com/openlit/openlit/opentelemetry-gpu-collector/internal/config"+)++// Enricher resolves PID → pod identity using cgroup + optional PodResources + API.+// Outside Kubernetes (or when both enrichment flags are off) Resolve is a free no-op.+type Enricher struct {+ logger *slog.Logger+ cfg *config.Config+ enabled bool++ mu sync.RWMutex+ cache map[int32]PodInfo+ negCache map[int32]time.Time // PID → when negative miss was cached+ cacheAt time.Time+ ttl time.Duration+ byUID map[string]PodInfo+ byName map[string]PodInfo+ byContID map[string]PodInfo+ byPID map[int32]PodInfo+ byDevice map[string]PodInfo // GPU UUID / device id → pod++ refreshMu sync.Mutex+ stopCh chan struct{}+ stopped sync.Once++ podRes *PodResourcesClient+ api *PodAPIClient++ connectMu sync.Mutex+ connectAttempt time.Time+ connectInterval time.Duration+}++// NewEnricher builds a workload enricher. Safe on non-K8s (no-op enrichment).+func NewEnricher(cfg *config.Config, logger *slog.Logger) *Enricher {+ if cfg == nil {+ cfg = config.Load()+ }+ inK8s := os.Getenv("KUBERNETES_SERVICE_HOST") != ""+ enabled := inK8s && (cfg.K8sPodResources || cfg.K8sPodLookup)+ e := &Enricher{+ logger: logger,+ cfg: cfg,+ enabled: enabled,+ cache: make(map[int32]PodInfo),+ negCache: make(map[int32]time.Time),+ byUID: make(map[string]PodInfo),+ byName: make(map[string]PodInfo),+ byContID: make(map[string]PodInfo),+ byPID: make(map[int32]PodInfo),+ byDevice: make(map[string]PodInfo),+ ttl: 15 * time.Second,+ connectInterval: 30 * time.Second,+ stopCh: make(chan struct{}),+ }+ if !enabled {+ return e+ }+ if cfg.K8sPodLookup {+ if c, err := NewPodAPIClient(logger); err != nil {+ logger.Debug("pod API lookup unavailable", "error", err)+ } else {+ e.api = c+ }+ }+ // Background refresh keeps kubelet/API I/O off the metrics scrape path.+ go e.loop()+ return e+}++func (e *Enricher) loop() {+ // Prime maps promptly without blocking NewEnricher callers.+ e.refreshMaps()+ t := time.NewTicker(e.ttl)+ defer t.Stop()+ for {+ select {+ case <-e.stopCh:+ return+ case <-t.C:+ e.refreshMaps()+ }+ }+}++func (e *Enricher) ensureClients() {+ if e == nil || e.cfg == nil || !e.cfg.K8sPodResources {+ return+ }+ sock := podResourcesSocket()+ if runtimeIsUnix() {+ if _, err := os.Stat(sock); err != nil {+ return+ }+ }++ e.connectMu.Lock()+ defer e.connectMu.Unlock()+ if e.podRes != nil {+ return+ }+ if !e.connectAttempt.IsZero() && time.Since(e.connectAttempt) < e.connectInterval {+ return+ }+ e.connectAttempt = time.Now()+ if c, err := NewPodResourcesClient(e.logger); err != nil {+ e.logger.Debug("podresources unavailable", "error", err)+ } else {+ e.podRes = c+ }+}++// Resolve returns the best-known pod identity for pid.+// deviceID is an optional GPU UUID used to join PodResources device allocations.+func (e *Enricher) Resolve(pid int32, deviceID string) (PodInfo, bool) {+ if e == nil || !e.enabled || pid <= 0 {+ return PodInfo{}, false+ }++ e.mu.RLock()+ if info, ok := e.cache[pid]; ok {+ e.mu.RUnlock()+ return info, info.PodUID != "" || info.PodName != ""+ }+ if at, ok := e.negCache[pid]; ok && time.Since(at) < e.ttl {+ e.mu.RUnlock()+ return PodInfo{}, false+ }+ byPID := e.byPID[pid]+ byUID := e.byUID+ byCont := e.byContID+ byDev := e.byDevice+ e.mu.RUnlock()++ info := byPID+ if cg, ok := ResolvePod(pid); ok {+ if info.PodUID == "" {+ info.PodUID = cg.PodUID+ }+ if info.ContainerID == "" {+ info.ContainerID = cg.ContainerID+ }+ }+ // Device allocation from PodResources (works without Pod UID).+ if deviceID != "" {+ if p, ok := byDev[deviceID]; ok {+ mergePod(&info, p)+ }+ }+ // Prefer container ID for multi-container pods.+ if info.ContainerID != "" {+ if p, ok := byCont[info.ContainerID]; ok {+ mergePod(&info, p)+ }+ }+ if info.PodName == "" && info.PodUID != "" {+ if p, ok := byUID[info.PodUID]; ok {+ mergePod(&info, p)+ }+ }++ hit := info.PodUID != "" || info.PodName != ""+ e.mu.Lock()+ if hit {+ e.cache[pid] = info+ delete(e.negCache, pid)+ } else {+ e.negCache[pid] = time.Now()+ }+ e.mu.Unlock()+ return info, hit+}++func mergePod(dst *PodInfo, src PodInfo) {+ if dst.PodUID == "" {+ dst.PodUID = src.PodUID+ }+ if dst.PodName == "" {+ dst.PodName = src.PodName+ }+ if dst.Namespace == "" {+ dst.Namespace = src.Namespace+ }+ if dst.ContainerName == "" {+ dst.ContainerName = src.ContainerName+ }+ if dst.ContainerID == "" {+ dst.ContainerID = src.ContainerID+ }+}++func (e *Enricher) refreshMaps() {+ if e == nil || !e.enabled {+ return+ }+ e.refreshMu.Lock()+ defer e.refreshMu.Unlock()++ e.ensureClients()++ byUID := make(map[string]PodInfo)+ byName := make(map[string]PodInfo)+ byContID := make(map[string]PodInfo)+ byPID := make(map[int32]PodInfo)+ byDevice := make(map[string]PodInfo)+ indexed := false++ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()++ e.connectMu.Lock()+ podRes := e.podRes+ e.connectMu.Unlock()++ if podRes != nil {+ if list, err := podRes.List(ctx); err == nil {+ for _, p := range list {+ if indexPod(byUID, byName, byContID, byPID, byDevice, p) {+ indexed = true+ }+ }+ } else {+ e.logger.Debug("podresources list failed", "error", err)+ }+ }+ if e.api != nil {+ if list, err := e.api.ListNodePods(ctx); err == nil {+ for _, p := range list {+ if indexPod(byUID, byName, byContID, byPID, byDevice, p) {+ indexed = true+ }+ }+ } else {+ e.logger.Debug("pod API list failed", "error", err)+ }+ }++ e.mu.Lock()+ defer e.mu.Unlock()+ if indexed {+ e.cache = make(map[int32]PodInfo)+ e.negCache = make(map[int32]time.Time)+ e.byUID = byUID+ e.byName = byName+ e.byContID = byContID+ e.byPID = byPID+ e.byDevice = byDevice+ }+ e.cacheAt = time.Now()+}++// indexPod updates maps. Returns true if any join key was written.+func indexPod(byUID, byName, byContID map[string]PodInfo, byPID map[int32]PodInfo, byDevice map[string]PodInfo, p PodInfo) bool {+ wrote := false+ if p.PodUID != "" {+ byUID[p.PodUID] = PodInfo{+ PodUID: p.PodUID,+ PodName: p.PodName,+ Namespace: p.Namespace,+ }+ key := p.Namespace + "/" + p.PodName+ if key != "/" {+ byName[key] = byUID[p.PodUID]+ }+ wrote = true+ } else if p.PodName != "" && p.Namespace != "" {+ key := p.Namespace + "/" + p.PodName+ byName[key] = PodInfo{PodName: p.PodName, Namespace: p.Namespace, ContainerName: p.ContainerName}+ wrote = true+ }+ if p.ContainerID != "" {+ byContID[p.ContainerID] = p+ wrote = true+ }+ for _, pid := range p.PIDs {+ byPID[pid] = p+ wrote = true+ }+ for _, id := range p.DeviceIDs {+ if id == "" {+ continue+ }+ byDevice[id] = PodInfo{+ PodUID: p.PodUID,+ PodName: p.PodName,+ Namespace: p.Namespace,+ ContainerName: p.ContainerName,+ ContainerID: p.ContainerID,+ }+ wrote = true+ }+ return wrote+}++// Close releases clients and stops background refresh.+func (e *Enricher) Close() {+ if e == nil {+ return+ }+ e.stopped.Do(func() {+ if e.stopCh != nil {+ close(e.stopCh)+ }+ })+ e.connectMu.Lock()+ podRes := e.podRes+ e.podRes = nil+ e.connectMu.Unlock()+ if podRes != nil {+ podRes.Close()+ }+ if e.api != nil {+ e.api.Close()+ e.api = nil+ }+}++func runtimeIsUnix() bool {+ return os.PathSeparator == '/'+}diff --git a/opentelemetry-gpu-collector/internal/workload/enricher_test.go b/opentelemetry-gpu-collector/internal/workload/enricher_test.gonew file mode 100644index 00000000..c1e6d29d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/enricher_test.go@@ -0,0 +1,64 @@+package workload++import "testing"++func TestIndexPodSeparatesContainerFromUID(t *testing.T) {+ byUID := map[string]PodInfo{}+ byName := map[string]PodInfo{}+ byCont := map[string]PodInfo{}+ byPID := map[int32]PodInfo{}+ byDev := map[string]PodInfo{}++ indexPod(byUID, byName, byCont, byPID, byDev, PodInfo{+ PodUID: "uid-1", PodName: "p", Namespace: "ns",+ ContainerName: "sidecar", ContainerID: "aaa",+ })+ indexPod(byUID, byName, byCont, byPID, byDev, PodInfo{+ PodUID: "uid-1", PodName: "p", Namespace: "ns",+ ContainerName: "app", ContainerID: "bbb",+ DeviceIDs: []string{"GPU-1"},+ })++ if byUID["uid-1"].ContainerName != "" || byUID["uid-1"].ContainerID != "" {+ t.Fatalf("byUID should be pod-level only: %+v", byUID["uid-1"])+ }+ if byCont["bbb"].ContainerName != "app" {+ t.Fatalf("byContID lost app container: %+v", byCont["bbb"])+ }+ if byDev["GPU-1"].ContainerName != "app" || byDev["GPU-1"].PodName != "p" {+ t.Fatalf("byDevice missing allocation: %+v", byDev["GPU-1"])+ }+}++func TestIndexPodResourcesNameOnly(t *testing.T) {+ byUID := map[string]PodInfo{}+ byName := map[string]PodInfo{}+ byCont := map[string]PodInfo{}+ byPID := map[int32]PodInfo{}+ byDev := map[string]PodInfo{}++ ok := indexPod(byUID, byName, byCont, byPID, byDev, PodInfo{+ PodName: "vllm", Namespace: "llm", ContainerName: "server",+ DeviceIDs: []string{"GPU-abc"},+ })+ if !ok {+ t.Fatal("expected indexed")+ }+ if byDev["GPU-abc"].PodName != "vllm" || byDev["GPU-abc"].Namespace != "llm" {+ t.Fatalf("device join failed: %+v", byDev["GPU-abc"])+ }+}++func TestMergePodPrefersExistingContainer(t *testing.T) {+ info := PodInfo{ContainerID: "bbb", ContainerName: "app"}+ mergePod(&info, PodInfo{+ PodUID: "uid-1", PodName: "p", Namespace: "ns",+ ContainerName: "sidecar", ContainerID: "aaa",+ })+ if info.ContainerName != "app" || info.ContainerID != "bbb" {+ t.Fatalf("merge overwrote container identity: %+v", info)+ }+ if info.PodName != "p" || info.Namespace != "ns" {+ t.Fatalf("merge missed pod fields: %+v", info)+ }+}diff --git a/opentelemetry-gpu-collector/internal/workload/podapi.go b/opentelemetry-gpu-collector/internal/workload/podapi.gonew file mode 100644index 00000000..70762bc1--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/podapi.go@@ -0,0 +1,155 @@+package workload++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "os"+ "strings"+ "time"+)++// PodAPIClient lists pods on the current node via the Kubernetes API.+type PodAPIClient struct {+ logger *slog.Logger+ client *http.Client+ host string+ tokenPath string+ nodeName string+}++// NewPodAPIClient uses in-cluster config (service account).+func NewPodAPIClient(logger *slog.Logger) (*PodAPIClient, error) {+ host := os.Getenv("KUBERNETES_SERVICE_HOST")+ port := os.Getenv("KUBERNETES_SERVICE_PORT")+ if host == "" || port == "" {+ return nil, fmt.Errorf("not in cluster")+ }+ tokenPath := "/var/run/secrets/kubernetes.io/serviceaccount/token"+ if _, err := os.Stat(tokenPath); err != nil {+ return nil, err+ }+ ca, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")+ if err != nil {+ return nil, err+ }+ pool := x509.NewCertPool()+ if !pool.AppendCertsFromPEM(ca) {+ return nil, fmt.Errorf("failed to parse serviceaccount CA")+ }+ nodeName := os.Getenv("K8S_NODE_NAME")+ if nodeName == "" {+ nodeName = os.Getenv("NODE_NAME")+ }+ if nodeName == "" {+ return nil, fmt.Errorf("K8S_NODE_NAME required for pod API lookup")+ }+ return &PodAPIClient{+ logger: logger,+ client: &http.Client{+ Timeout: 3 * time.Second,+ Transport: &http.Transport{+ TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},+ },+ },+ host: "https://" + host + ":" + port,+ tokenPath: tokenPath,+ nodeName: nodeName,+ }, nil+}++type podList struct {+ Items []struct {+ Metadata struct {+ Name string `json:"name"`+ Namespace string `json:"namespace"`+ UID string `json:"uid"`+ } `json:"metadata"`+ Status struct {+ ContainerStatuses []struct {+ Name string `json:"name"`+ ContainerID string `json:"containerID"`+ } `json:"containerStatuses"`+ } `json:"status"`+ } `json:"items"`+}++// ListNodePods returns PodInfo for pods scheduled on this node.+func (c *PodAPIClient) ListNodePods(ctx context.Context) ([]PodInfo, error) {+ token, err := os.ReadFile(c.tokenPath)+ if err != nil {+ return nil, err+ }+ u, err := url.Parse(c.host + "/api/v1/pods")+ if err != nil {+ return nil, err+ }+ q := u.Query()+ q.Set("fieldSelector", "spec.nodeName="+c.nodeName)+ u.RawQuery = q.Encode()++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token)))+ req.Header.Set("Accept", "application/json")++ resp, err := c.client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))+ return nil, fmt.Errorf("pod list: %s: %s", resp.Status, string(body))+ }+ var pl podList+ if err := json.NewDecoder(resp.Body).Decode(&pl); err != nil {+ return nil, err+ }+ out := make([]PodInfo, 0)+ for _, item := range pl.Items {+ for _, cs := range item.Status.ContainerStatuses {+ cid := stripRuntimePrefix(cs.ContainerID)+ out = append(out, PodInfo{+ PodUID: item.Metadata.UID,+ PodName: item.Metadata.Name,+ Namespace: item.Metadata.Namespace,+ ContainerName: cs.Name,+ ContainerID: cid,+ })+ }+ if len(item.Status.ContainerStatuses) == 0 {+ out = append(out, PodInfo{+ PodUID: item.Metadata.UID,+ PodName: item.Metadata.Name,+ Namespace: item.Metadata.Namespace,+ })+ }+ }+ return out, nil+}++// Close releases idle HTTP connections.+func (c *PodAPIClient) Close() {+ if c == nil || c.client == nil {+ return+ }+ if t, ok := c.client.Transport.(*http.Transport); ok {+ t.CloseIdleConnections()+ }+}++func stripRuntimePrefix(cid string) string {+ if i := strings.Index(cid, "://"); i >= 0 {+ return cid[i+3:]+ }+ return cid+}diff --git a/opentelemetry-gpu-collector/internal/workload/podresources.go b/opentelemetry-gpu-collector/internal/workload/podresources.gonew file mode 100644index 00000000..b5b6b06d--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/podresources.go@@ -0,0 +1,101 @@+package workload++import (+ "context"+ "fmt"+ "log/slog"+ "net"+ "os"+ "runtime"++ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ podresourcesapi "k8s.io/kubelet/pkg/apis/podresources/v1"+)++// PodResourcesClient talks to the kubelet PodResources gRPC API.+type PodResourcesClient struct {+ logger *slog.Logger+ conn *grpc.ClientConn+ client podresourcesapi.PodResourcesListerClient+}++func podResourcesSocket() string {+ if p := os.Getenv("POD_RESOURCES_SOCKET"); p != "" {+ return p+ }+ if runtime.GOOS == "windows" {+ return `\\.\pipe\kubelet-podresources`+ }+ return "/var/lib/kubelet/pod-resources/kubelet.sock"+}++// NewPodResourcesClient connects to the kubelet PodResources socket.+// Does not probe List at connect time — first List failure is surfaced to the caller+// so transient kubelet unavailability does not permanently disable enrichment.+func NewPodResourcesClient(logger *slog.Logger) (*PodResourcesClient, error) {+ sock := podResourcesSocket()+ dialer := func(ctx context.Context, _ string) (net.Conn, error) {+ if runtime.GOOS == "windows" {+ return dialWindowsPipe(ctx, sock)+ }+ var d net.Dialer+ return d.DialContext(ctx, "unix", sock)+ }++ conn, err := grpc.NewClient("passthrough:///podresources",+ grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithContextDialer(dialer),+ )+ if err != nil {+ return nil, fmt.Errorf("dial podresources %s: %w", sock, err)+ }+ return &PodResourcesClient{+ logger: logger,+ conn: conn,+ client: podresourcesapi.NewPodResourcesListerClient(conn),+ }, nil+}++// List returns pod/container identity for containers known to kubelet.+func (c *PodResourcesClient) List(ctx context.Context) ([]PodInfo, error) {+ if c == nil || c.client == nil {+ return nil, fmt.Errorf("podresources client not connected")+ }+ resp, err := c.client.List(ctx, &podresourcesapi.ListPodResourcesRequest{})+ if err != nil {+ return nil, err+ }+ out := make([]PodInfo, 0, len(resp.GetPodResources()))+ for _, pod := range resp.GetPodResources() {+ conts := pod.GetContainers()+ if len(conts) == 0 {+ out = append(out, PodInfo{+ PodName: pod.GetName(),+ Namespace: pod.GetNamespace(),+ })+ continue+ }+ for _, cont := range conts {+ var deviceIDs []string+ for _, dev := range cont.GetDevices() {+ deviceIDs = append(deviceIDs, dev.GetDeviceIds()...)+ }+ out = append(out, PodInfo{+ PodName: pod.GetName(),+ Namespace: pod.GetNamespace(),+ ContainerName: cont.GetName(),+ DeviceIDs: deviceIDs,+ })+ }+ }+ return out, nil+}++func (c *PodResourcesClient) Close() {+ if c != nil && c.conn != nil {+ _ = c.conn.Close()+ c.conn = nil+ c.client = nil+ }+}diff --git a/opentelemetry-gpu-collector/internal/workload/podresources_unix.go b/opentelemetry-gpu-collector/internal/workload/podresources_unix.gonew file mode 100644index 00000000..3d7b5e2c--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/podresources_unix.go@@ -0,0 +1,15 @@+//go:build !windows++package workload++import (+ "context"+ "fmt"+ "net"+)++func dialWindowsPipe(ctx context.Context, pipe string) (net.Conn, error) {+ _ = ctx+ _ = pipe+ return nil, fmt.Errorf("windows named pipe dial not available on this OS")+}diff --git a/opentelemetry-gpu-collector/internal/workload/podresources_windows.go b/opentelemetry-gpu-collector/internal/workload/podresources_windows.gonew file mode 100644index 00000000..59b43e24--- /dev/null+++ b/opentelemetry-gpu-collector/internal/workload/podresources_windows.go@@ -0,0 +1,22 @@+//go:build windows++package workload++import (+ "context"+ "net"+ "time"++ "github.com/Microsoft/go-winio"+)++func dialWindowsPipe(ctx context.Context, pipe string) (net.Conn, error) {+ timeout := 2 * time.Second+ if d, ok := ctx.Deadline(); ok {+ timeout = time.Until(d)+ if timeout <= 0 {+ timeout = time.Millisecond+ }+ }+ return winio.DialPipe(pipe, &timeout)+}diff --git a/src/client/src/lib/platform/coding-agents/queries.ts b/src/client/src/lib/platform/coding-agents/queries.tsindex 38063605..2fa9b5d8 100644--- a/src/client/src/lib/platform/coding-agents/queries.ts+++ b/src/client/src/lib/platform/coding-agents/queries.ts@@ -118,10 +118,11 @@ export interface CodingAgentSessionRow {// across the session's spans). Empty when no LLM/tool span carried// a model attribute.model: string;- // Aggregate token totals — sumed across LLM-turn spans. Most CLI- // adapters set both halves; Cursor only emits output tokens for- // some events so input may be 0 when the upstream payload didn't- // include it.+ // Aggregate token totals — prefer session-root gen_ai.usage.* when+ // present, else sum non-session child spans. Cursor stamps real+ // counters on `stop` (and drains them onto the session root at+ // sessionEnd); older Cursor builds that omit usage fields leave+ // these at 0 rather than inventing estimates.input_tokens: number;output_tokens: number;total_tokens: number;@@ -174,9 +175,10 @@ export interface CodingAgentSessionRow {* Cost is rolled up two ways:* - the session-level `coding_agent.session.cost_usd` attribute (set by* Claude Code from transcript JSONL with realized prices)- * - sum of `gen_ai.usage.cost` across all child spans (used by Cursor,- * where we estimate cost from token-length heuristics on the- * LLM-turn spans because Cursor's hooks don't surface tokens).+ * - sum of `gen_ai.usage.cost` across non-session child spans (vendors+ * that stamp per-turn cost). Cursor does not emit USD — only real+ * token counters on `stop` / sessionEnd — so Cursor sessions+ * typically roll up to 0 cost rather than estimates.** We take whichever is greater so a vendor's authoritative number wins* when present. Tool-call counts work the same way: prefer the session