discovery.go 35 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gpu

import (
	"context"
	"fmt"
22
23
24
	"net"
	"net/http"
	"os"
25
26
	"strconv"
	"strings"
27
28
29
	"sync"
	"time"

30
	nvidiacomv1beta1 "github.com/ai-dynamo/dynamo/deploy/operator/api/v1beta1"
31
32
33
	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/model"
34
	corev1 "k8s.io/api/core/v1"
35
	"k8s.io/apimachinery/pkg/types"
36
37
38
39
40
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
)

const (
41
	defaultDCGMEndpointTemplate = "http://{POD_IP}:9400/metrics"
42
43
44
45
	// NVIDIA GPU Feature Discovery (GFD) label keys
	LabelGPUCount   = "nvidia.com/gpu.count"
	LabelGPUProduct = "nvidia.com/gpu.product"
	LabelGPUMemory  = "nvidia.com/gpu.memory"
46
	// DCGM exporter label constants
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
	LabelApp                        = "app"
	LabelAppKubernetesName          = "app.kubernetes.io/name"
	LabelValueNvidiaDCGMExporter    = "nvidia-dcgm-exporter"
	LabelValueNvidiaNetworkOperator = "nvidia-network-operator"
	LabelValueDCGMExporter          = "dcgm-exporter"
	LabelValueGPUOperator           = "gpu-operator"
	GPUOperatorNamespace            = "gpu-operator"
	requestTimeout                  = 5 * time.Second
	dialTimeout                     = 3 * time.Second
	tlsHandshakeTimeout             = 3 * time.Second
	CloudProviderGCP                = "gcp"
	CloudProviderAWS                = "aws"
	CloudProviderAKS                = "aks"
	CloudProviderOther              = "other"
	CloudProviderUnknown            = "unknown"
)

// --- Normalization helpers ---
const (
	strDash  = "-"
	strSpace = " "
	strNone  = "none"
)

// --- Form factor tokens ---
const (
	tokenSXM       = "SXM"
	tokenHGX       = "HGX"
	tokenDGX       = "DGX"
	tokenPCIE      = "PCIE"
	formFactorSXM  = "sxm"
	formFactorPCIe = "pcie"
)

// --- GPU model tokens ---
const (
	tokenGB200  = "GB200"
	tokenB200   = "B200"
	tokenH200   = "H200"
	tokenH100   = "H100"
	tokenA100   = "A100"
	tokenL40S   = "L40S"
	tokenL40    = "L40"
	tokenL4     = "L4"
	tokenV100   = "V100"
	tokenT4     = "T4"
	tokenMI300  = "MI300"
	tokenMI250  = "MI250"
	tokenMI200  = "MI200"
	LabelNVLink = "nvlink"
97
98
)

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// awsInstanceTypePrefixes matches known GPU/accelerator instance families on EKS. See: https://aws.amazon.com/ec2/instance-types/
var awsInstanceTypePrefixes = []string{
	"p3.", "p3dn.", "p4d.", "p4de.", "p5.", // GPU instances
	"g3.", "g4dn.", "g4ad.", "g5.", "g6.", // GPU instances
	"inf1.", "inf2.", // Inferentia
	"trn1.", "trn1n.", // Trainium
}

// gcpMachineSeries matches known GCP accelerator-optimised machine series on GKE. See: https://cloud.google.com/compute/docs/machine-resource
var gcpMachineSeries = []string{
	"a2-", // A100 GPU machines
	"a3-", // H100 GPU machines
	"g2-", // L4 GPU machines
}

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
type gpuRule struct {
	token     string
	sxmSKU    nvidiacomv1beta1.GPUSKUType
	pcieSKU   nvidiacomv1beta1.GPUSKUType
	singleSKU nvidiacomv1beta1.GPUSKUType // for GPUs without form factor variants
}

var gpuRules = []gpuRule{
	// Blackwell
	{token: tokenGB200, sxmSKU: nvidiacomv1beta1.GPUSKUTypeGB200SXM},
	{token: tokenB200, sxmSKU: nvidiacomv1beta1.GPUSKUTypeB200SXM},

	// Hopper
	{token: tokenH200, sxmSKU: nvidiacomv1beta1.GPUSKUTypeH200SXM},
	{token: tokenH100, sxmSKU: nvidiacomv1beta1.GPUSKUTypeH100SXM, pcieSKU: nvidiacomv1beta1.GPUSKUTypeH100PCIe},

	// Ampere
	{token: tokenA100, sxmSKU: nvidiacomv1beta1.GPUSKUTypeA100SXM, pcieSKU: nvidiacomv1beta1.GPUSKUTypeA100PCIe},

	// Ada
	{token: tokenL40S, singleSKU: nvidiacomv1beta1.GPUSKUTypeL40S},
	{token: tokenL40, singleSKU: nvidiacomv1beta1.GPUSKUTypeL40},
	{token: tokenL4, singleSKU: nvidiacomv1beta1.GPUSKUTypeL4},

	// Volta / Turing
	{token: tokenV100, sxmSKU: nvidiacomv1beta1.GPUSKUTypeV100SXM, pcieSKU: nvidiacomv1beta1.GPUSKUTypeV100PCIe},
	{token: tokenT4, singleSKU: nvidiacomv1beta1.GPUSKUTypeT4},

	// AMD
	{token: tokenMI300, singleSKU: nvidiacomv1beta1.GPUSKUTypeMI300},
	{token: tokenMI250, singleSKU: nvidiacomv1beta1.GPUSKUTypeMI200},
	{token: tokenMI200, singleSKU: nvidiacomv1beta1.GPUSKUTypeMI200},
}

148
149
// GPUInfo contains discovered GPU configuration from cluster nodes
type GPUInfo struct {
150
151
152
153
154
155
156
157
158
159
160
161
162
163
	NodeName         string                      // Name of the node with this GPU configuration
	GPUsPerNode      int                         // Maximum GPUs per node found in the cluster
	NodesWithGPUs    int                         // Number of nodes that have GPUs
	Model            string                      // GPU product name (e.g., "H100-SXM5-80GB")
	VRAMPerGPU       int                         // VRAM in MiB per GPU
	System           nvidiacomv1beta1.GPUSKUType // AIC hardware system identifier (e.g., "h100_sxm", "h200_sxm"), empty if unknown
	MIGEnabled       bool                        // True if MIG is enabled (inferred from model or additional labels, not implemented in this version)
	MIGProfiles      map[string]int              // Optional: map of MIG profile name to count (requires additional label parsing, not implemented in this version)
	CloudProvider    string                      // aws | gcp | aks | other | unknown
	RDMAEnabled      bool                        // Indicates whether RDMA is enabled for this node (e.g., via InfiniBand, RoCE, or similar high-speed networking)
	RDMAType         string                      // Type of RDMA transport detected (e.g., "infiniband", "roce", "rdma", "sriov", or "none")
	Interconnect     string                      // Primary GPU-to-GPU interconnect technology used within the node (e.g., "nvlink" for high-bandwidth links or "pcie" for standard bus-based communication)
	InterconnectTier string                      // Qualitative or platform-specific classification of the interconnect (e.g., NVLink generation, topology tier, or vendor-defined performance level)
	NVLinkLinks      int                         // Number of NVLink connections per GPU (0 if NVLink is not present or interconnect is PCIe-only)
164
165
166
}

type ScrapeMetricsFunc func(ctx context.Context, endpoint string) (*GPUInfo, error)
167
168

type gpuCacheEntry struct {
169
170
171
	value     *GPUInfo
	expiresAt time.Time
}
172
173
174
175
176
177
178
179

// GPUDiscoveryCache caches discovery results keyed by SKU filter.
// Bounded by the GPUSKUType enum (≤7 values incl. empty for unfiltered).
type GPUDiscoveryCache struct {
	mu      sync.RWMutex
	entries map[nvidiacomv1beta1.GPUSKUType]gpuCacheEntry
}

180
181
182
183
184
185
186
187
188
189
190
191
type GPUDiscovery struct {
	Scraper ScrapeMetricsFunc
}

func NewGPUDiscovery(scraper ScrapeMetricsFunc) *GPUDiscovery {
	return &GPUDiscovery{
		Scraper: scraper,
	}
}

// NewGPUDiscoveryCache creates a new GPUDiscoveryCache instance.
//
192
193
194
// The cache stores discovered GPUInfo values keyed by SKU filter with an
// expiration time. It is safe for concurrent use and is intended to reduce
// repeated DCGM scraping during reconciliation loops.
195
func NewGPUDiscoveryCache() *GPUDiscoveryCache {
196
197
198
	return &GPUDiscoveryCache{
		entries: make(map[nvidiacomv1beta1.GPUSKUType]gpuCacheEntry),
	}
199
200
}

201
202
// Get returns the cached GPUInfo for the given SKU filter if it exists and
// has not expired.
203
204
205
206
207
//
// The boolean return value indicates whether a valid cached value was found.
// If the cache is empty or expired, it returns (nil, false).
//
// This method is safe for concurrent use.
208
func (c *GPUDiscoveryCache) Get(sku nvidiacomv1beta1.GPUSKUType) (*GPUInfo, bool) {
209
	c.mu.RLock()
210
211
212
213
	e, ok := c.entries[sku]
	c.mu.RUnlock()
	if ok && time.Now().Before(e.expiresAt) && e.value != nil {
		return e.value, true
214
215
216
217
218
219
220
221
222
223
	}
	return nil, false
}

// Set stores the provided GPUInfo in the cache with the given TTL (time-to-live).
//
// The cached value will be considered valid until the TTL duration elapses.
// After expiration, Get will return (nil, false) until a new value is set.
//
// This method is safe for concurrent use.
224
func (c *GPUDiscoveryCache) Set(sku nvidiacomv1beta1.GPUSKUType, info *GPUInfo, ttl time.Duration) {
225
226
	c.mu.Lock()
	defer c.mu.Unlock()
227
228
229
230
231
232
233
234
	c.entries[sku] = gpuCacheEntry{value: info, expiresAt: time.Now().Add(ttl)}
}

// DiscoverGPUsFromDCGM is a convenience wrapper that calls
// DiscoverGPUsFromDCGMFiltered with no SKU filter.
// See DiscoverGPUsFromDCGMFiltered for full documentation.
func (g *GPUDiscovery) DiscoverGPUsFromDCGM(ctx context.Context, k8sClient client.Reader, cache *GPUDiscoveryCache) (*GPUInfo, error) {
	return g.DiscoverGPUsFromDCGMFiltered(ctx, k8sClient, cache, "")
235
236
}

237
238
239
240
241
242
// DiscoverGPUsFromDCGMFiltered discovers GPU information by scraping metrics
// directly from DCGM exporter pods running in the cluster.
//
// When filterSKU is non-empty, only nodes whose inferred SKU matches are
// considered. When empty, the best node is selected first (highest GPU count,
// then VRAM) and then only nodes with the same SKU are counted.
243
244
245
//
// The function performs the following:
//
246
//  1. Returns cached GPU information if still valid (keyed by filterSKU).
247
248
249
250
//  2. Lists DCGM exporter pods across all namespaces using supported labels.
//  3. If no pods are found, attempts to find if GPU operator is installed and DCGM is enabled via Helm.
//  4. Warns user appropriately.
//  5. Scrapes each running pods metrics endpoint (http://<podIP>:9400/metrics).
251
//  6. Selects the "best" GPU node (filtered by SKU when set) based on:
252
253
//     - Highest GPU count
//     - Highest VRAM per GPU (tie-breaker)
254
255
//  7. Counts only nodes matching the selected SKU for NodesWithGPUs.
//  8. Caches the result per SKU for a short duration to avoid repeated scraping.
256
257
258
259
260
261
262
263
264
265
266
267
//
// Behavior Notes:
//
//   - Scrapes pods directly instead of using a Service ClusterIP to avoid
//     load-balancing ambiguity in multi-node clusters.
//   - If at least one pod is successfully scraped, partial failures are tolerated.
//   - If all pods fail to scrape, an aggregated error is returned.
//   - Assumes DCGM exporter runs as a DaemonSet (one pod per GPU node).
//
// Returns:
//   - *GPUInfo for the selected node
//   - error if no GPU data can be retrieved
268
func (g *GPUDiscovery) DiscoverGPUsFromDCGMFiltered(ctx context.Context, k8sClient client.Reader, cache *GPUDiscoveryCache, filterSKU nvidiacomv1beta1.GPUSKUType) (*GPUInfo, error) {
269
	if cache != nil {
270
		if cached, ok := cache.Get(filterSKU); ok {
271
272
273
			return cached, nil
		}
	}
274

275
276
277
278
279
280
281
282
283
284
285
286
287
	// List DCGM exporter pods
	dcgmPods, err := listDCGMExporterPods(ctx, k8sClient)
	if err != nil && !strings.Contains(err.Error(), "no DCGM exporter pods found") {
		return nil, fmt.Errorf("listing DCGM exporter pods failed: %w", err)
	}
	// If no pods found
	if len(dcgmPods) == 0 {
		gpuPods, err := listGPUOperatorRunningPods(ctx, k8sClient)
		if len(gpuPods) > 0 {
			return nil, fmt.Errorf("DCGM is not enabled in the GPU Operator (check GPU Operator configuration and permissions)")
		}
		return nil, err
	}
288
289
290
291
292
293
294
295

	// Scrape each running pod and collect per-node GPU info.
	type nodeInfo struct {
		info     *GPUInfo
		sku      nvidiacomv1beta1.GPUSKUType
		nodeName string
	}
	allNodes := make([]nodeInfo, 0, len(dcgmPods))
296
	var scrapeErrors []error
297

298
299
300
301
302
303
304
305
306
307
	for _, pod := range dcgmPods {
		if pod.Status.Phase != corev1.PodRunning || pod.Status.PodIP == "" {
			continue
		}
		endpoint := buildDCGMEndpoint(pod.Status.PodIP)
		info, err := g.Scraper(ctx, endpoint)
		if err != nil {
			scrapeErrors = append(scrapeErrors, fmt.Errorf("pod %s (%s): %w", pod.Name, pod.Status.PodIP, err))
			continue
		}
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

		allNodes = append(allNodes, nodeInfo{info: info, sku: InferHardwareSystem(info.Model), nodeName: pod.Spec.NodeName})
	}

	if len(allNodes) == 0 {
		if len(scrapeErrors) > 0 {
			return nil, fmt.Errorf("failed to scrape any DCGM exporter pod: %v", scrapeErrors)
		}
		return nil, fmt.Errorf("no GPU metrics could be parsed from any DCGM pod")
	}

	// Select best node (only from matching SKU when filtered).
	var bestNode *GPUInfo
	var bestSKU nvidiacomv1beta1.GPUSKUType
	for _, n := range allNodes {
		if filterSKU != "" && n.sku != filterSKU {
			continue
325
		}
326
		if bestNode == nil ||
327
328
329
330
331
			n.info.GPUsPerNode > bestNode.GPUsPerNode ||
			(n.info.GPUsPerNode == bestNode.GPUsPerNode &&
				n.info.VRAMPerGPU > bestNode.VRAMPerGPU) {
			bestNode = n.info
			bestSKU = n.sku
332
333
		}
	}
334

335
	if bestNode == nil {
336
337
		if filterSKU != "" {
			return nil, fmt.Errorf("no GPU nodes matching SKU %q found", filterSKU)
338
339
340
		}
		return nil, fmt.Errorf("no GPU metrics could be parsed from any DCGM pod")
	}
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361

	// Count only nodes with the same SKU as the selected best node,
	// and detect RDMA on matching nodes only.
	nodesWithGPUs := 0
	var rdmaDetected bool
	var rdmaType string
	for _, n := range allNodes {
		if n.sku != bestSKU {
			continue
		}
		nodesWithGPUs++
		if !rdmaDetected {
			rdma, rType := detectRDMAFromNode(ctx, k8sClient, n.nodeName)
			if rdma {
				rdmaDetected = true
				rdmaType = rType
			}
		}
	}

	// Detect InfiniBand presence
362
363
364
365
366
	ib := detectIBPods(ctx, k8sClient)
	if ib {
		rdmaType = "infiniband"
		rdmaDetected = true
	}
367

368
369
370
371
	cloudProvider, err := GetCloudProviderInfo(ctx, k8sClient)
	if err != nil {
		cloudProvider = CloudProviderUnknown
	}
372
	bestNode.System = bestSKU
373
374
	bestNode.CloudProvider = cloudProvider
	bestNode.NodesWithGPUs = nodesWithGPUs
375
376
	bestNode.RDMAEnabled = rdmaDetected
	bestNode.RDMAType = rdmaType
377

378
	if cache != nil {
379
		cache.Set(filterSKU, bestNode, 60*time.Second)
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
	}
	return bestNode, nil
}
func buildDCGMEndpoint(podIP string) string {
	template := os.Getenv("DCGM_METRICS_ENDPOINT_TEMPLATE")
	if template == "" {
		template = defaultDCGMEndpointTemplate
	}
	return strings.ReplaceAll(template, "{POD_IP}", podIP)
}
func listDCGMExporterPods(ctx context.Context, k8sClient client.Reader) ([]corev1.Pod, error) {
	var result []corev1.Pod
	seen := make(map[string]struct{})
	selectors := []client.MatchingLabels{
		{LabelApp: LabelValueNvidiaDCGMExporter},
		{LabelApp: LabelValueDCGMExporter},
		{LabelAppKubernetesName: LabelValueDCGMExporter},
	}
	var lastErr error
	for _, selector := range selectors {
		podList := &corev1.PodList{}
		err := k8sClient.List(ctx, podList, selector)
		if err != nil {
			lastErr = fmt.Errorf("list pods: %w", err)
			continue
		}
		for _, pod := range podList.Items {
			key := pod.Namespace + "/" + pod.Name
			if _, exists := seen[key]; !exists {
				seen[key] = struct{}{}
				result = append(result, pod)
			}
		}
	}
	if len(result) > 0 {
		return result, nil
	}
	if lastErr != nil {
		return nil, lastErr
	}
	return nil, fmt.Errorf("no DCGM exporter pods found")
}

// listGPUOperatorRunningPods lists GPU Operator pods in the given namespace
// and returns only those that are in Running phase.
//
// It uses common GPU Operator label selectors and deduplicates results
// across selectors. If no running pods are found, an error is returned.
func listGPUOperatorRunningPods(ctx context.Context, k8sClient client.Reader) ([]corev1.Pod, error) {
	var result []corev1.Pod
	seen := make(map[string]struct{})
	selectors := []client.MatchingLabels{
		{LabelApp: LabelValueGPUOperator},
		{LabelAppKubernetesName: LabelValueGPUOperator},
	}
	var lastErr error
	for _, selector := range selectors {
		podList := &corev1.PodList{}
		err := k8sClient.List(
			ctx,
			podList,
			client.InNamespace(GPUOperatorNamespace),
			selector,
		)
		if err != nil {
			lastErr = fmt.Errorf("list gpu operator pods: %w", err)
			continue
		}
		for _, pod := range podList.Items {
			if pod.Status.Phase != corev1.PodRunning {
				continue
			}
			key := pod.Namespace + "/" + pod.Name
			if _, exists := seen[key]; !exists {
				seen[key] = struct{}{}
				result = append(result, pod)
			}
		}
	}
	if len(result) > 0 {
		return result, nil
	}
	if lastErr != nil {
		return nil, lastErr
	}
	return nil, fmt.Errorf(
		"gpu operator is not installed %s",
		GPUOperatorNamespace,
	)
}

// scrapeMetricsEndpoint retrieves and parses Prometheus metrics from a
// DCGM exporter pod endpoint.
//
// The function performs an HTTP GET request against the provided endpoint
// (expected format: http://<podIP>:9400/metrics), validates the response,
// and parses the Prometheus text exposition format into metric families.
//
// Parsed metric families are passed to parseMetrics to extract high-level
// GPU information.
//
// Returns:
//   - *GPUInfo derived from the parsed metrics
//   - error if the HTTP request fails, the response is non-200,
//     or metric parsing fails
//
// This function does not implement retries or fallback logic.
// Error handling and multi-pod aggregation are managed by the caller.
func ScrapeMetricsEndpoint(ctx context.Context, endpoint string) (*GPUInfo, error) {
	// Set a timeout for the request
	ctx, cancel := context.WithTimeout(ctx, requestTimeout)
	defer cancel()
	// Create a custom HTTP client with transport-level timeouts
	client := &http.Client{
		Transport: &http.Transport{
			DialContext: (&net.Dialer{
				Timeout:   dialTimeout,      // Dial timeout
				KeepAlive: 30 * time.Second, // Keep-alive for connections
			}).DialContext,
			TLSHandshakeTimeout: tlsHandshakeTimeout, // TLS handshake timeout
		},
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return nil, fmt.Errorf("create request for %s: %w", endpoint, err)
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("HTTP GET %s failed: %w", endpoint, err)
	}
	defer func() {
		if cerr := resp.Body.Close(); cerr != nil {
			// best-effort: can't return an error from defer; log it
			log.FromContext(ctx).V(1).Info("failed to close response body", "err", cerr)
		}
	}()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf(
			"metrics endpoint %s returned status %d",
			endpoint,
			resp.StatusCode,
		)
	}
	parser := expfmt.NewTextParser(model.UTF8Validation)
	metricFamilies, err := parser.TextToMetricFamilies(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("parse prometheus metrics: %w", err)
	}
	return parseMetrics(ctx, metricFamilies)
}

531
// parseMetrics extracts GPU information and interconnect type for a node from DCGM Prometheus metrics.
532
533
//
// It parses the provided Prometheus metric families exported by the NVIDIA
534
// DCGM exporter and derives high-level GPU inventory and interconnect information for the node.
535
536
537
538
539
540
541
542
543
544
545
546
//
// The function performs the following:
//
//   - Detects the number of GPUs by counting unique "gpu" label values
//     from DCGM_FI_DEV_GPU_TEMP (used as a reliable per-GPU metric).
//
//   - Extracts the GPU model name from the "modelName" label.
//
//   - Calculates total VRAM per GPU using framebuffer metrics:
//     VRAM = FB_FREE + FB_USED + FB_RESERVED
//     (values are in MiB).
//
547
548
549
550
//   - Determines the interconnect type (PCIe or NVLink) from the
//     DCGM_FI_DEV_NVLINK_LINK_COUNT metric. If NVLink links are present,
//     interconnect is set to "nvlink", otherwise defaults to "pcie".
//
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//   - Assumes MIG is disabled unless explicit MIG metrics are present
//     (not included in the provided DCGM metric set).
//
// Parameters:
//
//	ctx       - Context for logging and cancellation.
//	families  - Map of Prometheus metric families keyed by metric name.
//
// Returns:
//
//	*GPUInfo containing:
//	  - NodeName
//	  - GPUsPerNode
//	  - Model
//	  - VRAMPerGPU (MiB)
//	  - MIGEnabled: false because no MIG metrics were collected in the DCGM families
//	  - MIGProfiles: empty map; would contain MIG profile counts if MIG metrics were available
//	  - System (inferred from model)
569
//	  - Interconnect: "pcie" or "nvlink" depending on detected NVLink links
570
571
572
573
574
575
//
// Returns an error if no GPUs can be detected from the metrics.
//
// Notes:
//   - This function relies on DCGM exporter metrics.
//   - If required metrics are missing, zero values may be returned.
576
//   - Interconnect detection is based on NVLink link count; other interconnects are not currently detected.
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//   - The implementation assumes homogeneous GPUs per node.
//   - For heterogeneous configurations, per-GPU parsing should be implemented.
func parseMetrics(ctx context.Context, families map[string]*dto.MetricFamily) (*GPUInfo, error) {
	logger := log.FromContext(ctx)
	getLabel := func(m *dto.Metric, name string) string {
		for _, l := range m.GetLabel() {
			if l.GetName() == name {
				return l.GetValue()
			}
		}
		return ""
	}
	// Track unique GPUs
	gpuSet := map[string]struct{}{}
	var model string
	var vram int
	var hostName string
594
595
	var nvlinkDetected bool
	var nvlinkLinks int
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
	fbFree := map[string]float64{}
	fbUsed := map[string]float64{}
	fbReserved := map[string]float64{}
	// --- Detect GPUs + Model + Hostname ---
	if mf, ok := families["DCGM_FI_DEV_GPU_TEMP"]; ok {
		for _, m := range mf.Metric {
			gpuID := getLabel(m, "gpu")
			if gpuID == "" {
				continue
			}
			gpuSet[gpuID] = struct{}{}
			// Extract model from label
			if model == "" {
				model = getLabel(m, "modelName")
			}
			// Extract Hostname label
			if hostName == "" {
				hostName = getLabel(m, "Hostname")
			}
		}
	}
	// --- Collect framebuffer metrics ---
	if mf, ok := families["DCGM_FI_DEV_FB_FREE"]; ok {
		for _, m := range mf.Metric {
			gpuID := getLabel(m, "gpu")
			if gpuID == "" {
				continue
			}
			fbFree[gpuID] = m.GetGauge().GetValue()
			if hostName == "" {
				hostName = getLabel(m, "Hostname")
			}
		}
	}
	if mf, ok := families["DCGM_FI_DEV_FB_USED"]; ok {
		for _, m := range mf.Metric {
			gpuID := getLabel(m, "gpu")
			if gpuID == "" {
				continue
			}
			fbUsed[gpuID] = m.GetGauge().GetValue()
			if hostName == "" {
				hostName = getLabel(m, "Hostname")
			}
		}
	}
	if mf, ok := families["DCGM_FI_DEV_FB_RESERVED"]; ok {
		for _, m := range mf.Metric {
			gpuID := getLabel(m, "gpu")
			if gpuID == "" {
				continue
			}
			fbReserved[gpuID] = m.GetGauge().GetValue()
			if hostName == "" {
				hostName = getLabel(m, "Hostname")
			}
		}
	}
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
	if mf, ok := families["DCGM_FI_DEV_NVLINK_LINK_COUNT"]; ok {
		for _, m := range mf.Metric {
			val := int(m.GetGauge().GetValue())
			if val > 0 {
				nvlinkDetected = true
				nvlinkLinks = val
				break
			}
		}
	}
	// --- Determine interconnect type ---
	interconnect := "pcie"
	interconnectDetail := strNone
	if nvlinkDetected {
		switch {
		case nvlinkLinks >= 12:
			interconnect = LabelNVLink
			interconnectDetail = "full-mesh" // HGX / DGX class
		case nvlinkLinks >= 6:
			interconnect = LabelNVLink
			interconnectDetail = "high"
		default:
			interconnect = LabelNVLink
			interconnectDetail = "partial"
		}
	}
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
	// --- Calculate Max VRAM
	for gpuID := range gpuSet {
		total := int(fbFree[gpuID] + fbUsed[gpuID] + fbReserved[gpuID])
		if total > vram {
			vram = total
		}
	}
	gpuCount := len(gpuSet)
	if gpuCount == 0 {
		return nil, fmt.Errorf("no GPUs detected from DCGM metrics")
	}
	// --- Infer system from model ---
	system := InferHardwareSystem(model)
	logger.Info("Parsed GPU info",
		"node", hostName,
		"gpuCount", gpuCount,
		"model", model,
		"vramMiB", vram,
		"system", system,
699
700
701
		"interconnect", interconnect,
		"interconnectDetail", interconnectDetail,
		"nvlinkLinks", nvlinkLinks,
702
703
	)
	return &GPUInfo{
704
705
706
707
708
709
710
711
712
713
		NodeName:         hostName,
		GPUsPerNode:      gpuCount,
		Model:            model,
		VRAMPerGPU:       vram,
		MIGEnabled:       false,
		MIGProfiles:      map[string]int{},
		System:           system, // populated from InferHardwareSystem
		Interconnect:     interconnect,
		InterconnectTier: interconnectDetail,
		NVLinkLinks:      nvlinkLinks,
714
	}, nil
715
716
717
718
719
720
721
722
723
}

// DiscoverGPUs queries Kubernetes nodes to determine GPU configuration.
// It extracts GPU information from NVIDIA GPU Feature Discovery (GFD) labels
// and returns aggregated GPU info, preferring nodes with higher GPU count,
// then higher VRAM if counts are equal.
//
// This function requires cluster-wide node read permissions and expects nodes
// to have GFD labels. If no nodes with GPU labels are found, it returns an error.
724
func DiscoverGPUs(ctx context.Context, k8sClient client.Reader) (*GPUInfo, error) {
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
	logger := log.FromContext(ctx)
	logger.Info("Starting GPU discovery from cluster nodes")
	// List all nodes in the cluster
	nodeList := &corev1.NodeList{}
	if err := k8sClient.List(ctx, nodeList); err != nil {
		return nil, fmt.Errorf("failed to list cluster nodes: %w", err)
	}
	if len(nodeList.Items) == 0 {
		return nil, fmt.Errorf("no nodes found in cluster")
	}
	logger.Info("Found cluster nodes", "count", len(nodeList.Items))
	// Track the best GPU configuration found
	var bestGPUInfo *GPUInfo
	nodesWithGPUs := 0
	for i := range nodeList.Items {
		node := &nodeList.Items[i]
		gpuInfo, err := extractGPUInfoFromNode(node)
		if err != nil {
			// Node doesn't have GPU labels or has invalid labels, skip it
			logger.V(1).Info("Skipping node without valid GPU info",
				"node", node.Name,
				"reason", err.Error())
			continue
		}
		nodesWithGPUs++
		logger.Info("Found GPU node",
			"node", node.Name,
			"gpus", gpuInfo.GPUsPerNode,
			"model", gpuInfo.Model,
			"vram", gpuInfo.VRAMPerGPU)
		// Select best configuration: prefer higher GPU count, then higher VRAM
		if bestGPUInfo == nil ||
			gpuInfo.GPUsPerNode > bestGPUInfo.GPUsPerNode ||
			(gpuInfo.GPUsPerNode == bestGPUInfo.GPUsPerNode && gpuInfo.VRAMPerGPU > bestGPUInfo.VRAMPerGPU) {
			bestGPUInfo = gpuInfo
		}
	}
	if bestGPUInfo == nil {
		return nil, fmt.Errorf("no nodes with NVIDIA GPU Feature Discovery labels found (checked %d nodes). "+
			"Ensure GPU nodes have labels: %s, %s, %s",
			len(nodeList.Items), LabelGPUCount, LabelGPUProduct, LabelGPUMemory)
	}
	// Infer hardware system from GPU model
	bestGPUInfo.System = InferHardwareSystem(bestGPUInfo.Model)
hhzhang16's avatar
hhzhang16 committed
769
	bestGPUInfo.NodesWithGPUs = nodesWithGPUs
770
771
	logger.Info("GPU discovery completed",
		"gpusPerNode", bestGPUInfo.GPUsPerNode,
hhzhang16's avatar
hhzhang16 committed
772
773
		"nodesWithGPUs", bestGPUInfo.NodesWithGPUs,
		"totalGpus", bestGPUInfo.GPUsPerNode*bestGPUInfo.NodesWithGPUs,
774
775
		"model", bestGPUInfo.Model,
		"vram", bestGPUInfo.VRAMPerGPU,
hhzhang16's avatar
hhzhang16 committed
776
		"system", bestGPUInfo.System)
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
	return bestGPUInfo, nil
}

// extractGPUInfoFromNode extracts GPU information from a single node's labels.
// Returns error if required labels are missing or invalid.
func extractGPUInfoFromNode(node *corev1.Node) (*GPUInfo, error) {
	labels := node.Labels
	if labels == nil {
		return nil, fmt.Errorf("node has no labels")
	}
	gpuCountStr, ok := labels[LabelGPUCount]
	if !ok {
		return nil, fmt.Errorf("missing label %s", LabelGPUCount)
	}
	gpuCount, err := strconv.Atoi(gpuCountStr)
	if err != nil || gpuCount <= 0 {
		return nil, fmt.Errorf("invalid GPU count: %s", gpuCountStr)
	}
	gpuModel, ok := labels[LabelGPUProduct]
	if !ok || gpuModel == "" {
		return nil, fmt.Errorf("missing or empty label %s", LabelGPUProduct)
	}
	// Extract VRAM (memory in MiB)
	gpuMemoryStr, ok := labels[LabelGPUMemory]
	if !ok {
		return nil, fmt.Errorf("missing label %s", LabelGPUMemory)
	}
	gpuMemory, err := strconv.Atoi(gpuMemoryStr)
	if err != nil || gpuMemory <= 0 {
		return nil, fmt.Errorf("invalid GPU memory: %s", gpuMemoryStr)
	}
	return &GPUInfo{
		GPUsPerNode: gpuCount,
		Model:       gpuModel,
		VRAMPerGPU:  gpuMemory,
	}, nil
}

815
816
// InferHardwareSystem attempts to infer a normalized GPU SKU type from a
// free-form product string (e.g. "NVIDIA H100 SXM", "A100-PCIE").
817
//
818
819
820
821
822
// The function performs three main steps:
//  1. Normalize the input string to a consistent format.
//  2. Detect the GPU form factor (SXM vs PCIe).
//  3. Match the normalized string against known GPU tokens and return
//     the corresponding SKU type.
823
//
824
825
826
// Matching is based on substring checks and is tolerant of variations
// in formatting (case, spaces, dashes). If no known GPU is detected,
// an empty SKU type is returned.
827
828
829
830
831
832
833
// Limitations:
//   - Cannot distinguish SXM vs. PCIe variants from labels alone (assumes SXM for datacenter GPUs)
//   - New GPU models require code updates (gracefully returns empty string)
//   - Non-standard SKU names may not match
//
// Users can manually override the system in their profiling config (hardware.system)
// if auto-detection is incorrect or unavailable.
834
func InferHardwareSystem(gpuProduct string) nvidiacomv1beta1.GPUSKUType {
835
836
837
838
	if gpuProduct == "" {
		return ""
	}

839
840
	normalized := normalize(gpuProduct)
	formFactor := detectFormFactor(normalized)
841

842
843
844
845
846
847
848
849
850
851
852
	for _, rule := range gpuRules {
		if strings.Contains(normalized, rule.token) {
			if rule.singleSKU != "" {
				return rule.singleSKU
			}
			if formFactor == formFactorSXM && rule.sxmSKU != "" {
				return rule.sxmSKU
			}
			if rule.pcieSKU != "" {
				return rule.pcieSKU
			}
853
854
855
856
857
858
			// Token matched but no form factor indicator was present in the string
			// (e.g. "NVIDIA H200" from DCGM has no SXM/HGX/DGX suffix). If the GPU
			// has no PCIe variant it must be SXM-only (H200, B200, GB200).
			if rule.sxmSKU != "" {
				return rule.sxmSKU
			}
859
860
861
862
863
		}
	}

	return ""
}
864

865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
// normalize standardizes a GPU product string to simplify matching.
//
// It converts the string to uppercase and removes common separators
// such as spaces and dashes. This allows consistent substring matching
// regardless of how the input is formatted (e.g. "H100-SXM",
// "h100 sxm", and "H100SXM" all normalize to the same value).
func normalize(input string) string {
	s := strings.ToUpper(strings.ReplaceAll(input, strDash, strSpace))
	return strings.ReplaceAll(s, " ", "")
}

// detectFormFactor determines the GPU form factor (e.g. SXM or PCIe)
// from a normalized product string.
//
// The detection is based on the presence of known substrings such as
// "SXM", "HGX", or "DGX" for SXM-based systems, and "PCIE" for PCIe.
// If no explicit indicator is found, PCIe is used as the default since
// it is the more common and safer assumption.
func detectFormFactor(normalized string) string {
	switch {
	case strings.Contains(normalized, tokenSXM),
		strings.Contains(normalized, tokenHGX),
		strings.Contains(normalized, tokenDGX):
		return formFactorSXM
	case strings.Contains(normalized, tokenPCIE):
		return formFactorPCIe
	default:
		return formFactorPCIe
	}
}

// GetCloudProviderInfo attempts to infer the cloud provider of the Kubernetes cluster.
//
// The function inspects the first node in the cluster (assumes homogeneous node setup)
// and uses a combination of ProviderID and node labels to detect the provider.
//
// Detection logic:
//   - Primary detection uses node.Spec.ProviderID:
//   - "azure" → AKS
//   - "aws"   → AWS
//   - "gce"   → GCP
//   - Secondary detection uses node labels and instance type prefixes:
//   - AKS: "kubernetes.azure.com/cluster" label or instance type starting with "standard_"
//   - AWS: "eks.amazonaws.com/nodegroup" label or known AWS instance type prefix
//   - GCP: "cloud.google.com/gke-nodepool" label or known GCP machine series prefix
//   - If none match, returns "other".
//
// Parameters:
//   - ctx: Context for logging, cancellation, or timeout.
//   - k8sClient: Kubernetes client for reading Node objects.
//
// Returns:
//   - A string identifying the cloud provider ("aks", "aws", "gcp", "other", or "unknown").
//   - An error if no nodes are found or listing fails.
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
func GetCloudProviderInfo(ctx context.Context, k8sClient client.Reader) (string, error) {
	var nodeList corev1.NodeList
	if err := k8sClient.List(ctx, &nodeList); err != nil {
		return CloudProviderUnknown, fmt.Errorf("failed to list nodes: %w", err)
	}
	if len(nodeList.Items) == 0 {
		return CloudProviderUnknown, fmt.Errorf("no nodes found in cluster")
	}
	// Use first node as representative (assumes homogeneous control plane)
	node := nodeList.Items[0]
	providerID := strings.ToLower(node.Spec.ProviderID)
	labels := node.Labels
	instanceType := strings.ToLower(labels["node.kubernetes.io/instance-type"])
	// ---- Primary Detection: providerID ----
	switch {
	case strings.Contains(providerID, "azure"):
		return CloudProviderAKS, nil
	case strings.Contains(providerID, "aws"):
		return CloudProviderAWS, nil
	case strings.Contains(providerID, "gce"):
		return CloudProviderGCP, nil
	}
	// ---- Secondary Detection: Node Labels ----
	// AKS labels
	if _, ok := labels["kubernetes.azure.com/cluster"]; ok {
		return CloudProviderAKS, nil
	}
	if strings.Contains(instanceType, "standard_") {
		return CloudProviderAKS, nil
	}
	// EKS labels
	if _, ok := labels["eks.amazonaws.com/nodegroup"]; ok {
		return CloudProviderAWS, nil
	}
	if isAWSInstanceType(instanceType) {
		return CloudProviderAWS, nil
	}
	// GKE labels
	if _, ok := labels["cloud.google.com/gke-nodepool"]; ok {
		return CloudProviderGCP, nil
	}
	if isGCPInstanceType(instanceType) {
		return CloudProviderGCP, nil
	}
	return "other", nil
}

966
967
968
969
970
971
972
// isGCPInstanceType checks whether a given instance type string matches known GCP machine series.
//
// Parameters:
//   - instanceType: string representing the node's instance type (lowercased).
//
// Returns:
//   - true if the instance type belongs to a GCP machine series prefix.
973
974
975
976
977
978
979
980
981
func isGCPInstanceType(instanceType string) bool {
	for _, prefix := range gcpMachineSeries {
		if strings.HasPrefix(instanceType, prefix) {
			return true
		}
	}
	return false
}

982
983
984
985
986
987
988
// isAWSInstanceType checks whether a given instance type string matches known AWS instance type prefixes.
//
// Parameters:
//   - instanceType: string representing the node's instance type (lowercased).
//
// Returns:
//   - true if the instance type belongs to an AWS instance type prefix.
989
990
991
992
993
994
995
996
func isAWSInstanceType(instanceType string) bool {
	for _, prefix := range awsInstanceTypePrefixes {
		if strings.HasPrefix(instanceType, prefix) {
			return true
		}
	}
	return false
}
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052

// detectRDMAFromNode inspects a single node for RDMA or SR-IOV network capability.
//
// Detection logic:
//   - Checks node labels:
//   - "nvidia.com/rdma.present" = "true" → RDMA detected
//   - "feature.node.kubernetes.io/network-sriov.capable" = "true" → SR-IOV detected
//
// Parameters:
//   - ctx: Context for logging or cancellation.
//   - k8sClient: Kubernetes client for reading Node objects.
//   - nodeName: Name of the node to inspect.
//
// Returns:
//   - bool indicating whether RDMA/SR-IOV is present.
//   - string representing the type ("rdma", "sriov", or "none").
func detectRDMAFromNode(ctx context.Context, k8sClient client.Reader, nodeName string) (bool, string) {
	node := &corev1.Node{}
	if err := k8sClient.Get(ctx, types.NamespacedName{Name: nodeName}, node); err != nil {
		return false, strNone
	}
	labels := node.Labels
	if labels["nvidia.com/rdma.present"] == "true" {
		return true, "rdma"
	}
	if labels["feature.node.kubernetes.io/network-sriov.capable"] == "true" {
		return true, "sriov"
	}
	return false, strNone
}

// detectIBPods checks if there are any RDMA or InfiniBand-related pods deployed
// in the "nvidia-network-operator" namespace.
//
// Detection logic:
//   - Lists pods in "nvidia-network-operator" namespace.
//   - If any pod name contains "rdma", returns true.
//
// Parameters:
//   - ctx: Context for logging or cancellation.
//   - k8sClient: Kubernetes client for listing pods.
//
// Returns:
//   - true if any RDMA/IB pods are found, false otherwise.
func detectIBPods(ctx context.Context, k8sClient client.Reader) bool {
	podList := &corev1.PodList{}
	if err := k8sClient.List(ctx, podList, client.InNamespace(LabelValueNvidiaNetworkOperator)); err != nil {
		return false
	}
	for _, p := range podList.Items {
		if strings.Contains(p.Name, "rdma") {
			return true
		}
	}
	return false
}