Skip to content

feat(metrics): add native node_name and pod labels to vGPUmonitor metrics - #2153

Closed
swastikCommits wants to merge 2 commits into
Project-HAMi:masterfrom
swastikCommits:feat/instrument-vgpumonitor-node-pod-labels
Closed

feat(metrics): add native node_name and pod labels to vGPUmonitor metrics#2153
swastikCommits wants to merge 2 commits into
Project-HAMi:masterfrom
swastikCommits:feat/instrument-vgpumonitor-node-pod-labels

Conversation

@swastikCommits

@swastikCommits swastikCommits commented Jul 28, 2026

Copy link
Copy Markdown

What type of PR is this?

/kind feature

What this PR does / why we need it:
Currently, vGPUmonitor metrics (like hami_host_gpu_memory_used_bytes and hami_vgpu_memory_used_bytes) don't include the node_name label natively in their metric descriptors. Instead, they rely on external Prometheus relabel_config rules in Helm charts to add the node name.
In custom Prometheus setups or standalone scrapers without ServiceMonitors, this causes metrics from different GPU nodes to lack node identification, making Grafana filtering and cross-node metric joins difficult.

In this PR we update cmd/vGPUmonitor/metrics.go so that node_name is natively attached to all host and container metric descriptors directly at the exporter level.

Which issue(s) this PR fixes:
Fixes #2152

Special notes for your reviewer:
Added unit test coverage in cmd/vGPUmonitor/metrics_test.go to check that all standard and legacy descriptors include the node_name / nodename label.

Does this PR introduce a user-facing change?:

Adds 'node_name' label key to standard vGPUmonitor Prometheus metrics (and 'nodename' to legacy metrics) sourced from Downward API NODE_NAME. Existing Grafana dashboards and Prometheus alerts querying vGPUmonitor series will now include node-level dimension labels.

AI assistance disclosure:
I used AI assistance (Gemini CLI) to help consult codebase patterns, dig deep into the issue and structure unit tests.
All code logic and changes were manually inspected and validated.

Summary by CodeRabbit

  • New Features

    • Added node identity labels as the first metric label for host GPU, container/vGPU, and MIG monitoring metrics (node_name; legacy nodename).
  • Bug Fixes

    • Aligned label ordering between current and legacy metric descriptors and the emitted metric values.
  • Tests

    • Added unit tests covering descriptor contents, node-name resolution from the node-name environment value, and correct metric delivery for both new and legacy emissions.

@hami-robot

hami-robot Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: swastikCommits
Once this PR has been reviewed and has the lgtm label, please assign shouren for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@hami-robot

hami-robot Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Welcome @swastikCommits! It looks like this is your first PR to Project-HAMi/HAMi 🎉

@hami-robot hami-robot Bot added the size/L label Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

vGPUmonitor Prometheus descriptors now include node identifiers across host, container, vGPU, and MIG metrics. Collection paths read the node name from the environment, prepend it to current and legacy metric labels, and tests validate descriptors, lookup, and metric delivery.

Changes

Node-labeled vGPUmonitor metrics

Layer / File(s) Summary
Metric descriptor label contracts
cmd/vGPUmonitor/metrics.go
Current descriptors add leading node_name labels; legacy descriptors add leading nodename labels across host, container, vGPU, and MIG metrics.
Node lookup and metric emission
cmd/vGPUmonitor/metrics.go
getNodeName() reads the configured environment value, collection paths reject an empty value where required, and emitted label values prepend the node name.
Descriptor and emission tests
cmd/vGPUmonitor/metrics_test.go
Tests verify descriptor labels, environment-based node lookup, and current and legacy metric delivery.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Collector as vGPUmonitor collectors
  participant NodeLookup as getNodeName()
  participant Prometheus as Prometheus channel
  Collector->>NodeLookup: read configured node name
  NodeLookup-->>Collector: return node identifier
  Collector->>Prometheus: enqueue labeled host, container, or MIG metric
Loading

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: wawa0210

Poem

I’m a rabbit with labels tucked under my ear,
Each node now tells us, “I’m clearly here!”
Host, pod, and MIG hop into the stream,
Tests keep the carrots aligned in a dream.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes align with #2152 by natively adding node_name to host and container metric labels and keeping pod/container metadata consistent.
Out of Scope Changes check ✅ Passed The PR stays focused on vGPUmonitor metric labeling and related tests, with no clear unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: native node_name and pod-related labels in vGPUmonitor metrics.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
cmd/vGPUmonitor/metrics_test.go (2)

19-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Group imports using the repository’s local-prefix configuration.

Place github.com/prometheus/client_golang/prometheus in the external-import group and github.com/Project-HAMi/HAMi/pkg/util in a following HAMi-local group.

Suggested import layout
 import (
 	"os"
 	"strings"
 	"testing"

-	"github.com/Project-HAMi/HAMi/pkg/util"
 	"github.com/prometheus/client_golang/prometheus"
+
+	"github.com/Project-HAMi/HAMi/pkg/util"
 )

As per coding guidelines, Go import blocks must be grouped as standard library imports first, then external imports, then github.com/Project-HAMi/HAMi/... imports; use goimports with the local prefix github.com/Project-HAMi/HAMi.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/vGPUmonitor/metrics_test.go` around lines 19 - 26, Reorder the import
block in metrics_test.go so standard-library imports remain first, prometheus is
in the external-import group, and the HAMi util import is in a separate
following local group; apply goimports with local prefix
github.com/Project-HAMi/HAMi.

Source: Coding guidelines


28-52: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Strengthen metric-contract assertions.

These tests can pass while descriptor schemas or emitted label values are incorrect.

  • cmd/vGPUmonitor/metrics_test.go#L28-L52: assert exact descriptor label sets and counts, including node_name/nodename, namespace, pod, and container.
  • cmd/vGPUmonitor/metrics_test.go#L70-L90: inspect both emitted metrics and verify their node/device label values, rather than checking only the number enqueued.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/vGPUmonitor/metrics_test.go` around lines 28 - 52, Strengthen
TestAllMetricDescriptorsIncludeNodeName by asserting the exact descriptor count
and required label sets for every descriptor, including node_name or nodename
plus namespace, pod, and container where applicable. In
cmd/vGPUmonitor/metrics_test.go lines 70-90, update the emitted-metric test to
inspect each metric’s descriptor and label values, verifying the expected node
and device values instead of only counting enqueued metrics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/vGPUmonitor/metrics.go`:
- Line 611: Update collectPodAndContainerMigInfo to resolve the node through
getNodeName() for both pod selection and the labels slice, rather than relying
on the direct NODE_NAME lookup. Preserve the existing error handling only when
getNodeName() cannot resolve any node name, and allow hostname fallback
deployments to emit MIG metrics.

---

Nitpick comments:
In `@cmd/vGPUmonitor/metrics_test.go`:
- Around line 19-26: Reorder the import block in metrics_test.go so
standard-library imports remain first, prometheus is in the external-import
group, and the HAMi util import is in a separate following local group; apply
goimports with local prefix github.com/Project-HAMi/HAMi.
- Around line 28-52: Strengthen TestAllMetricDescriptorsIncludeNodeName by
asserting the exact descriptor count and required label sets for every
descriptor, including node_name or nodename plus namespace, pod, and container
where applicable. In cmd/vGPUmonitor/metrics_test.go lines 70-90, update the
emitted-metric test to inspect each metric’s descriptor and label values,
verifying the expected node and device values instead of only counting enqueued
metrics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 79edc3ea-d670-4e09-92e5-2da5019fd016

📥 Commits

Reviewing files that changed from the base of the PR and between c343242 and 01161f9.

📒 Files selected for processing (2)
  • cmd/vGPUmonitor/metrics.go
  • cmd/vGPUmonitor/metrics_test.go

Comment thread cmd/vGPUmonitor/metrics.go
@swastikCommits
swastikCommits force-pushed the feat/instrument-vgpumonitor-node-pod-labels branch from 01161f9 to 42b8be7 Compare July 28, 2026 04:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/vGPUmonitor/metrics_test.go`:
- Around line 40-51: Strengthen the descriptor assertions in the metrics test by
defining the exact expected descriptor names and count for both current and
legacy families. Validate each descriptor’s label set against its family’s
required spelling (`node_name` or `nodename`) rather than accepting either label
universally, and require an exact count instead of a minimum.
- Around line 19-26: Reorder the import block in metrics_test.go so standard
library imports remain first, external Prometheus imports follow, and the
github.com/Project-HAMi/HAMi/pkg/util import is placed in a separate final
group. Apply the project’s goimports grouping with the HAMi repository prefix.
- Around line 70-90: The TestSendMetric test currently verifies only metric
count; inspect both emitted metrics with the Prometheus client read API and
assert their value and expected node-1, 0, gpu-uuid-1, and NVIDIA-A100 labels.
Validate both the sendMetric and sendLegacyMetric outputs, preserving label-name
matching rather than relying on label order, so dropped or mismatched legacy
label values fail the test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 64c7ff43-bf11-43cb-8c9d-4d4407875236

📥 Commits

Reviewing files that changed from the base of the PR and between 01161f9 and 42b8be7.

📒 Files selected for processing (2)
  • cmd/vGPUmonitor/metrics.go
  • cmd/vGPUmonitor/metrics_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/vGPUmonitor/metrics.go

Comment thread cmd/vGPUmonitor/metrics_test.go
Comment thread cmd/vGPUmonitor/metrics_test.go Outdated
Comment thread cmd/vGPUmonitor/metrics_test.go
@swastikCommits
swastikCommits force-pushed the feat/instrument-vgpumonitor-node-pod-labels branch 2 times, most recently from ba47a5f to 2fb48cd Compare July 28, 2026 04:49
Comment thread cmd/vGPUmonitor/metrics.go Outdated
func getNodeName() string {
nodeName := os.Getenv(util.NodeNameEnvName)
if nodeName == "" {
nodeName, _ = os.Hostname()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

os.Hostname() gives the pod name not the node name unless the ds runs w/ hostNetwork (its false by default in our chart), so this fallback silently mislabels every metric and makes the pod selector below match nothing, better to keep the hard error?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, os.Hostname() inside a container defaults to the Pod name when hostNetwork is false, which would produce misleading node_name labels. I will remove the os.Hostname() fallback and enforce a hard error when NODE_NAME is missing.

Comment thread cmd/vGPUmonitor/metrics.go Outdated
lastKernelTime := c.Info.LastKernelTime()

labels := []string{pod.Namespace, pod.Name, ctr.Name, fmt.Sprint(i), uuid}
labels := []string{getNodeName(), pod.Namespace, pod.Name, ctr.Name, fmt.Sprint(i), uuid}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getNodeName() runs per device inside this loop while the two host paths hoist it, and collectPodAndContainerInfo already has nodeName in scope, can u just pass it down?

Signed-off-by: swastikCommits <textswastik.alt@gmail.com>
@swastikCommits
swastikCommits force-pushed the feat/instrument-vgpumonitor-node-pod-labels branch from 2fb48cd to da28b56 Compare July 28, 2026 07:38
@mesutoezdil

Copy link
Copy Markdown
Contributor

thanks, pls refrain from force pushing once you have started getting reviews,
it makes it much harder to tell what has changed from review to review

@swastikCommits

Copy link
Copy Markdown
Author

Sure I will keep that in mind. Thanks for the review :)

@swastikCommits

Copy link
Copy Markdown
Author

hi @mesutoezdil @archlitchi @wawa0210 does this require any further changes?

@mesutoezdil mesutoezdil left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the body says user-facing change N.A. but this adds node_name as the first label to 11 exported metrics and nodename to 8 legacy ones, so anything keyed on those series changes. pls fill in the block w/ a release-note.

no ai disclosure either, see https://github.com/Project-HAMi/HAMi/blob/master/CONTRIBUTING.md#ai-assistance-notice

Comment thread cmd/vGPUmonitor/metrics_test.go Outdated
Comment thread cmd/vGPUmonitor/metrics.go Outdated
…ors in Describe

Signed-off-by: swastikCommits <textswastik.alt@gmail.com>
@swastikCommits

Copy link
Copy Markdown
Author

Hi @mesutoezdil! I've updated the PR body with the release-note and AI disclosure, hoisted getNodeName() to avoid redundant os.Getenv calls, and added the missing descriptors to Describe() (asserting all 19 in metrics_test.go).

All unit tests pass, its ready for a re-review :)

@archlitchi

Copy link
Copy Markdown
Member

/assign @mesutoezdil

@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 42.85714% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/vGPUmonitor/metrics.go 42.85% 16 Missing ⚠️
Flag Coverage Δ
unittests 61.35% <42.85%> (-0.66%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/vGPUmonitor/metrics.go 22.62% <42.85%> (ø)

... and 29 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@FouoF

FouoF commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Thanks for the metrics work. This PR overlaps the same public label-contract decision being discussed in #2343 and #2398, but with a larger conflicting diff and incomplete coverage. Keeping all three open would create duplicate review work and competing metric schemas. We are closing this implementation so maintainers can select one contract in #2126 before reviewing code. Please document any requirement that the selected path does not cover in that issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature/Metrics] Instrument vGPUmonitor metrics with native node_name and pod labels

4 participants