Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
955 lines (832 loc) · 30.8 KB
/
Copy pathmain.go
File metadata and controls
955 lines (832 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
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
769
770
771
772
773
774
775
776
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
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
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
//go:build !darwin && !windows
/*
* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
*
* 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 main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/moby/sys/mount"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"golang.org/x/sys/unix"
"github.com/NVIDIA/k8s-driver-manager/internal/info"
kube "github.com/NVIDIA/k8s-driver-manager/internal/kubernetes"
"github.com/NVIDIA/k8s-driver-manager/internal/linuxutils"
)
const (
driverRoot = "/run/nvidia/driver"
driverPIDFile = "/run/nvidia/nvidia-driver.pid"
driverConfigStateFile = "/run/nvidia/nvidia-driver.state"
operatorNamespace = "gpu-operator"
pausedStr = "paused-for-driver-upgrade"
defaultDrainTimeout = time.Second * 0
defaultGracePeriod = 5 * time.Minute
nvidiaDomainPrefix = "nvidia.com"
nvidiaDriverDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.driver"
nvidiaOperatorValidatorDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.operator-validator"
nvidiaContainerToolkitDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.container-toolkit"
nvidiaDevicePluginDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.device-plugin"
nvidiaGFDDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.gpu-feature-discovery"
nvidiaDCGMExporterDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.dcgm-exporter"
nvidiaDCGMDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.dcgm"
nvidiaMIGManagerDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.mig-manager"
nvidiaNVSMDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.nvsm"
nvidiaSandboxValidatorDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.sandbox-validator"
nvidiaSandboxDevicePluginDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.sandbox-device-plugin"
nvidiaVGPUDeviceManagerDeployLabel = nvidiaDomainPrefix + "/" + "gpu.deploy.vgpu-device-manager"
)
// Configuration holds all the configuration from environment variables
type config struct {
nodeName string
drainUseForce bool
drainPodSelectorLabel string
drainTimeout time.Duration
drainDeleteEmptyDirData bool
enableAutoDrain bool
enableGPUPodEviction bool
operatorNamespace string
nodeLabelForGPUPodEviction string
gpuDirectRDMAEnabled bool
useHostMofed bool
kubeconfig string
forceReinstall bool
}
// ComponentState tracks the deployment state of GPU operator components
type componentState struct {
pluginDeployed string
gfdDeployed string
dcgmDeployed string
dcgmExporterDeployed string
nvsmDeployed string
toolkitDeployed string
validatorDeployed string
migManagerDeployed string
sandboxValidatorDeployed string
sandboxPluginDeployed string
vgpuDeviceManagerDeployed string
customOperandNodeLabelValue string
autoUpgradePolicyEnabled string
}
// DriverManager handles the driver management operations
type DriverManager struct {
ctx context.Context
config *config
components *componentState
kubeClient *kube.Client
log *logrus.Logger
}
func main() {
log := logrus.New()
log.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
DisableQuote: true,
})
cfg := &config{}
components := &componentState{}
app := cli.NewApp()
app.Name = "driver-manager"
app.Usage = "The NVIDIA Driver Manager is a Kubernetes component which assists in the seamless upgrades of NVIDIA " +
"GPU Driver Container on each node of the cluster. This component ensures that all pre-requisites are met before driver " +
"upgrades can be performed on the gpu driver container."
app.Version = info.GetVersionString()
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "node-name",
Usage: "The name of the node to manage",
Destination: &cfg.nodeName,
EnvVars: []string{"NODE_NAME"},
Required: true,
},
&cli.BoolFlag{
Name: "drain-use-force",
Usage: "Use force when draining nodes",
Destination: &cfg.drainUseForce,
EnvVars: []string{"DRAIN_USE_FORCE"},
Value: false,
},
&cli.StringFlag{
Name: "drain-pod-selector-label",
Usage: "Pod selector label for draining",
Destination: &cfg.drainPodSelectorLabel,
EnvVars: []string{"DRAIN_POD_SELECTOR_LABEL"},
Value: "",
},
&cli.DurationFlag{
Name: "drain-timeout-seconds",
Usage: "Timeout for drain operations",
Destination: &cfg.drainTimeout,
EnvVars: []string{"DRAIN_TIMEOUT_SECONDS"},
Value: defaultDrainTimeout,
},
&cli.BoolFlag{
Name: "drain-delete-emptydir-data",
Usage: "Delete emptyDir data during drain",
Destination: &cfg.drainDeleteEmptyDirData,
EnvVars: []string{"DRAIN_DELETE_EMPTYDIR_DATA"},
Value: false,
},
&cli.BoolFlag{
Name: "enable-auto-drain",
Usage: "Enable automatic node draining",
Destination: &cfg.enableAutoDrain,
EnvVars: []string{"ENABLE_AUTO_DRAIN"},
Value: true,
},
&cli.BoolFlag{
Name: "enable-gpu-pod-eviction",
Usage: "Enable GPU pod eviction",
Destination: &cfg.enableGPUPodEviction,
EnvVars: []string{"ENABLE_GPU_POD_EVICTION"},
Value: true,
},
&cli.StringFlag{
Name: "operator-namespace",
Usage: "Namespace where the GPU operator is installed in",
Destination: &cfg.operatorNamespace,
EnvVars: []string{"OPERATOR_NAMESPACE"},
Value: operatorNamespace,
},
&cli.StringFlag{
Name: "node-label-for-gpu-pod-eviction",
Usage: "Node label for GPU pod eviction",
Destination: &cfg.nodeLabelForGPUPodEviction,
EnvVars: []string{"NODE_LABEL_FOR_GPU_POD_EVICTION"},
Value: "",
},
&cli.BoolFlag{
Name: "gpu-direct-rdma-enabled",
Usage: "Enable GPU Direct RDMA",
Destination: &cfg.gpuDirectRDMAEnabled,
EnvVars: []string{"GPU_DIRECT_RDMA_ENABLED"},
Value: false,
},
&cli.BoolFlag{
Name: "use-host-mofed",
Usage: "Use host MOFED driver",
Destination: &cfg.useHostMofed,
EnvVars: []string{"USE_HOST_MOFED"},
Value: false,
},
&cli.StringFlag{
Name: "kubeconfig",
Usage: "Path to kubeconfig file",
Destination: &cfg.kubeconfig,
EnvVars: []string{"KUBECONFIG"},
Value: "",
},
&cli.BoolFlag{
Name: "force-reinstall",
Usage: "Force driver reinstall regardless of current state",
Destination: &cfg.forceReinstall,
EnvVars: []string{"FORCE_REINSTALL"},
Value: false,
},
}
app.Commands = []*cli.Command{
{
Name: "uninstall_driver",
Usage: "Uninstall NVIDIA driver and manage GPU operator components",
Action: func(c *cli.Context) error {
dm, err := newDriverManager(c.Context, cfg, components, log)
if err != nil {
return fmt.Errorf("failed to create driver manager: %w", err)
}
return dm.uninstallDriver()
},
},
{
Name: "preflight_check",
Usage: "Perform preflight checks",
Action: func(c *cli.Context) error {
dm, err := newDriverManager(c.Context, cfg, components, log)
if err != nil {
return fmt.Errorf("failed to create driver manager: %w", err)
}
return dm.preflightCheck()
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func newDriverManager(ctx context.Context, cfg *config, components *componentState, log *logrus.Logger) (*DriverManager, error) {
driverManager := &DriverManager{
ctx: ctx,
config: cfg,
components: components,
log: log,
}
kubeClient, err := kube.NewClient(ctx, cfg.kubeconfig, log)
if err != nil {
return nil, fmt.Errorf("failed to create kube client: %w", err)
}
driverManager.kubeClient = kubeClient
return driverManager, nil
}
func (dm *DriverManager) uninstallDriver() error {
dm.log.Info("Starting driver uninstallation process")
// Check if driver is pre-installed on host
if dm.isHostDriver() {
dm.log.Info("NVIDIA GPU driver is already pre-installed on the node, disabling the containerized driver")
if err := dm.disableContainerizedDriver(); err != nil {
return fmt.Errorf("failed to disable containerized driver: %w", err)
}
// Wait for pod termination
time.Sleep(60 * time.Second)
return fmt.Errorf("driver is pre-installed on host")
}
// Fetch current component states
if err := dm.fetchCurrentLabels(); err != nil {
return fmt.Errorf("failed to fetch current labels: %w", err)
}
// Fetch auto upgrade policy annotation
if err := dm.fetchAutoUpgradeAnnotation(); err != nil {
return fmt.Errorf("failed to fetch auto upgrade annotation: %w", err)
}
// Always evict all GPU operator components across a driver restart
if err := dm.evictAllGPUOperatorComponents(); err != nil {
dm.log.Error("Failed to evict GPU operator components, attempting cleanup")
dm.cleanupOnFailure()
return fmt.Errorf("failed to evict GPU operator components: %w", err)
}
if dm.shouldSkipUninstall() {
dm.log.Info("The NVIDIA driver is already loaded with the desired version and configuration, skipping the uninstallation of the driver in an attempt to not disrupt running workloads")
// Clean up stale artifacts from previous container before rescheduling operands
dm.log.Info("Cleaning up stale mounts and state files...")
// Unmount stale rootfs from previous container
if err := dm.unmountRootfs(); err != nil {
return fmt.Errorf("failed to unmount stale rootfs: %w", err)
}
// Remove stale PID file from previous container
dm.removePIDFile()
if err := dm.rescheduleGPUOperatorComponents(); err != nil {
dm.log.Warnf("Failed to reschedule GPU operator components: %v", err)
}
return nil
}
drainOpts := kube.DrainOptions{
Force: dm.config.drainUseForce,
DeleteEmptyDirData: dm.config.drainDeleteEmptyDirData,
Timeout: dm.config.drainTimeout,
PodSelector: dm.config.drainPodSelectorLabel,
}
// Delete any GPU pods running on the node
if dm.isGPUPodEvictionEnabled() {
if err := dm.kubeClient.CordonNode(dm.config.nodeName); err != nil {
return fmt.Errorf("failed to cordon node: %w", err)
}
if err := dm.nvDrainNode(); err != nil {
dm.log.Info("Failed to drain node of GPU pods")
if !dm.isAutoDrainEnabled() {
dm.cleanupOnFailure()
return fmt.Errorf("cannot proceed until all GPU pods are drained from the node")
}
dm.log.Info("Attempting node drain")
if err := dm.kubeClient.DrainNode(dm.config.nodeName, drainOpts); err != nil {
dm.cleanupOnFailure()
return fmt.Errorf("failed to drain node: %w", err)
}
if err := dm.cleanupDriver(); err != nil {
dm.cleanupOnFailure()
return fmt.Errorf("failed to cleanup NVIDIA driver: %w", err)
}
}
}
// Check if driver is loaded and cleanup if needed
if dm.isDriverLoaded() {
if err := dm.cleanupDriver(); err != nil {
if dm.isAutoDrainEnabled() {
dm.log.Info("Unable to cleanup driver modules, attempting again with node drain...")
if err := dm.kubeClient.DrainNode(dm.config.nodeName, drainOpts); err != nil {
dm.cleanupOnFailure()
return fmt.Errorf("failed to drain node: %w", err)
}
if err := dm.cleanupDriver(); err != nil {
dm.cleanupOnFailure()
return fmt.Errorf("failed to cleanup NVIDIA driver: %w", err)
}
} else {
dm.log.Error("Failed to uninstall nvidia driver components")
dm.cleanupOnFailure()
return fmt.Errorf("failed to uninstall nvidia driver components: %w", err)
}
}
dm.log.Info("Successfully uninstalled nvidia driver components")
}
// Handle vfio-pci driver unbinding
if err := dm.unbindVfioPCI(); err != nil {
dm.log.Error("Unable to unbind vfio-pci driver from all devices")
dm.cleanupOnFailure()
return fmt.Errorf("failed to unbind vfio-pci driver: %w", err)
}
// Handle GPUDirect RDMA if enabled
// When GPUDirectRDMA is enabled, wait until MOFED driver has finished installing
if dm.isGPUDirectRDMAEnabled() {
dm.log.Info("GPUDirectRDMA is enabled, validating MOFED driver installation")
if err := dm.waitForMofedDriver(); err != nil {
return fmt.Errorf("failed to wait for MOFED driver: %w", err)
}
}
// Cleanup and reschedule components
if dm.isGPUPodEvictionEnabled() || dm.isAutoDrainEnabled() {
if err := dm.kubeClient.UncordonNode(dm.config.nodeName); err != nil {
dm.log.Warnf("Failed to uncordon node: %v", err)
}
}
if err := dm.rescheduleGPUOperatorComponents(); err != nil {
dm.log.Warnf("Failed to reschedule GPU operator components: %v", err)
}
// Handle nouveau driver
if dm.isNouveauLoaded() {
if err := dm.unloadNouveau(); err != nil {
return fmt.Errorf("failed to unload nouveau driver: %w", err)
}
dm.log.Info("Successfully unloaded nouveau driver")
}
dm.log.Info("Driver uninstallation completed successfully")
return nil
}
func (dm *DriverManager) preflightCheck() error {
dm.log.Info("Performing preflight checks")
// TODO: Add checks for driver package availability for current kernel
// TODO: Add checks for driver dependencies
// TODO: Add checks for entitlements(OCP)
dm.log.Info("Preflight checks completed")
return nil
}
// Helper methods for driver management
func (dm *DriverManager) isHostDriver() bool {
// Check if driver is pre-installed on the host
cmd := exec.Command("chroot", "/host", "nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader")
out, err := cmd.Output()
if err != nil {
return false
}
if len(out) > 0 {
dm.log.Infof("Host driver detected: %s", out)
return true
}
return false
}
func (dm *DriverManager) disableContainerizedDriver() error {
dm.log.Infof("Labeling node %s with %s=%s", dm.config.nodeName, nvidiaDriverDeployLabel, "pre-installed")
// Add the label
operandLabels := map[string]string{
nvidiaDriverDeployLabel: "pre-installed",
}
return dm.kubeClient.UpdateNodeLabels(dm.config.nodeName, operandLabels)
}
func (dm *DriverManager) fetchCurrentLabels() error {
dm.log.Info("Fetching current component labels")
operandLabels := []string{
nvidiaOperatorValidatorDeployLabel,
nvidiaContainerToolkitDeployLabel,
nvidiaDevicePluginDeployLabel,
nvidiaGFDDeployLabel,
nvidiaDCGMExporterDeployLabel,
nvidiaDCGMDeployLabel,
nvidiaMIGManagerDeployLabel,
nvidiaNVSMDeployLabel,
nvidiaSandboxValidatorDeployLabel,
nvidiaSandboxDevicePluginDeployLabel,
nvidiaVGPUDeviceManagerDeployLabel,
}
for _, label := range operandLabels {
dm.log.Infof("Getting current value of the %q node label", label)
value, err := dm.kubeClient.GetNodeLabelValue(dm.config.nodeName, label)
if err != nil {
return fmt.Errorf("failed to get label %s: %w", label, err)
}
dm.log.Infof("Current value of %q=%s", label, value)
dm.setComponentState(label, value)
}
// Handle custom operand node label
if dm.config.nodeLabelForGPUPodEviction != "" {
dm.log.Infof("Getting current value of the %q node label used by custom operands", dm.config.nodeLabelForGPUPodEviction)
value, err := dm.kubeClient.GetNodeLabelValue(dm.config.nodeName, dm.config.nodeLabelForGPUPodEviction)
if err != nil {
return fmt.Errorf("failed to get custom operand label %s: %w", dm.config.nodeLabelForGPUPodEviction, err)
}
dm.log.Infof("Current value of %q=%s", dm.config.nodeLabelForGPUPodEviction, value)
dm.components.customOperandNodeLabelValue = value
}
return nil
}
func (dm *DriverManager) setComponentState(label, value string) {
switch label {
case nvidiaOperatorValidatorDeployLabel:
dm.components.validatorDeployed = value
case nvidiaContainerToolkitDeployLabel:
dm.components.toolkitDeployed = value
case nvidiaDevicePluginDeployLabel:
dm.components.pluginDeployed = value
case nvidiaGFDDeployLabel:
dm.components.gfdDeployed = value
case nvidiaDCGMExporterDeployLabel:
dm.components.dcgmExporterDeployed = value
case nvidiaDCGMDeployLabel:
dm.components.dcgmDeployed = value
case nvidiaMIGManagerDeployLabel:
dm.components.migManagerDeployed = value
case nvidiaNVSMDeployLabel:
dm.components.nvsmDeployed = value
case nvidiaSandboxValidatorDeployLabel:
dm.components.sandboxValidatorDeployed = value
case nvidiaSandboxDevicePluginDeployLabel:
dm.components.sandboxPluginDeployed = value
case nvidiaVGPUDeviceManagerDeployLabel:
dm.components.vgpuDeviceManagerDeployed = value
}
}
func (dm *DriverManager) fetchAutoUpgradeAnnotation() error {
annotationValue, err := dm.kubeClient.GetNodeAnnotationValue(dm.config.nodeName,
"nvidia.com/gpu-driver-upgrade-enabled")
if err != nil {
return fmt.Errorf("failed to get node %s annotation: %w", dm.config.nodeName, err)
}
dm.components.autoUpgradePolicyEnabled = annotationValue
dm.log.Infof("Current value of AUTO_UPGRADE_POLICY_ENABLED=%s", dm.components.autoUpgradePolicyEnabled)
return nil
}
func (dm *DriverManager) evictAllGPUOperatorComponents() error {
dm.log.Info("Shutting down all GPU clients on the current node by disabling their component-specific nodeSelector labels")
// Prepare labels to update
operandLabels := map[string]string{
nvidiaOperatorValidatorDeployLabel: dm.maybeSetPaused(dm.components.validatorDeployed),
nvidiaContainerToolkitDeployLabel: dm.maybeSetPaused(dm.components.toolkitDeployed),
nvidiaDevicePluginDeployLabel: dm.maybeSetPaused(dm.components.pluginDeployed),
nvidiaGFDDeployLabel: dm.maybeSetPaused(dm.components.gfdDeployed),
nvidiaDCGMExporterDeployLabel: dm.maybeSetPaused(dm.components.dcgmExporterDeployed),
nvidiaDCGMDeployLabel: dm.maybeSetPaused(dm.components.dcgmDeployed),
nvidiaNVSMDeployLabel: dm.maybeSetPaused(dm.components.nvsmDeployed),
nvidiaSandboxValidatorDeployLabel: dm.maybeSetPaused(dm.components.sandboxValidatorDeployed),
nvidiaSandboxDevicePluginDeployLabel: dm.maybeSetPaused(dm.components.sandboxPluginDeployed),
nvidiaVGPUDeviceManagerDeployLabel: dm.maybeSetPaused(dm.components.vgpuDeviceManagerDeployed),
}
if dm.components.migManagerDeployed != "" {
operandLabels[nvidiaMIGManagerDeployLabel] = dm.maybeSetPaused(dm.components.migManagerDeployed)
}
// Handle custom operand node selector label
if dm.components.customOperandNodeLabelValue != "" {
dm.log.Infof("Shutting down GPU clients using node selector label %q=%s", dm.config.nodeLabelForGPUPodEviction, dm.components.customOperandNodeLabelValue)
operandLabels[dm.config.nodeLabelForGPUPodEviction] = dm.maybeSetPaused(dm.components.customOperandNodeLabelValue)
}
// Update the node
err := dm.kubeClient.UpdateNodeLabels(dm.config.nodeName, operandLabels)
if err != nil {
return err
}
// Wait for pods to terminate
return dm.waitForPodsToTerminate()
}
func (dm *DriverManager) maybeSetPaused(currentValue string) string {
if currentValue == "" {
return ""
} else if currentValue == "false" {
return "false"
} else if currentValue == "true" {
return pausedStr
} else if strings.Contains(currentValue, pausedStr) {
return currentValue
} else {
return currentValue + "_" + pausedStr
}
}
func (dm *DriverManager) waitForPodsToTerminate() error {
podSelectors := []struct {
app string
timeout time.Duration
}{
{"nvidia-operator-validator", defaultGracePeriod},
{"nvidia-container-toolkit-daemonset", defaultGracePeriod},
{"nvidia-device-plugin-daemonset", defaultGracePeriod},
{"gpu-feature-discovery", defaultGracePeriod},
{"nvidia-dcgm-exporter", defaultGracePeriod},
{"nvidia-dcgm", defaultGracePeriod},
}
namespace := dm.config.operatorNamespace
nodeName := dm.config.nodeName
for _, selector := range podSelectors {
dm.log.Infof("Waiting for %s to shutdown", selector.app)
selectorMap := map[string]string{
"app": selector.app,
}
if err := dm.kubeClient.WaitForPodTermination(selectorMap, namespace, nodeName, selector.timeout); err != nil {
dm.log.Errorf("Failed to wait for %s to shutdown: %v", selector.app, err)
return err
}
}
// Handle optional components
if dm.components.migManagerDeployed != "" {
dm.log.Info("Waiting for mig-manager to shutdown")
selectorMap := map[string]string{
"app": "nvidia-mig-manager",
}
if err := dm.kubeClient.WaitForPodTermination(selectorMap, namespace, nodeName, defaultGracePeriod); err != nil {
dm.log.Errorf("Failed to wait for mig-manager to shutdown: %v", err)
return err
}
}
if dm.components.sandboxValidatorDeployed != "" {
dm.log.Info("Waiting for sandbox-validator to shutdown")
selectorMap := map[string]string{
"app": "nvidia-sandbox-validator",
}
if err := dm.kubeClient.WaitForPodTermination(selectorMap, namespace, nodeName, defaultGracePeriod); err != nil {
dm.log.Errorf("Failed to wait for sandbox-validator to shutdown: %v", err)
return err
}
}
if dm.components.sandboxPluginDeployed != "" {
dm.log.Info("Waiting for sandbox-device-plugin to shutdown")
selectorMap := map[string]string{
"app": "nvidia-sandbox-device-plugin-daemonset",
}
if err := dm.kubeClient.WaitForPodTermination(selectorMap, namespace, nodeName, defaultGracePeriod); err != nil {
dm.log.Errorf("Failed to wait for sandbox-device-plugin to shutdown: %v", err)
return err
}
}
if dm.components.vgpuDeviceManagerDeployed != "" {
dm.log.Info("Waiting for vgpu-device-manager to shutdown")
selectorMap := map[string]string{
"app": "nvidia-vgpu-device-manager",
}
if err := dm.kubeClient.WaitForPodTermination(selectorMap, namespace, nodeName, defaultGracePeriod); err != nil {
dm.log.Errorf("Failed to wait for vgpu-device-manager to shutdown: %v", err)
return err
}
}
return nil
}
func (dm *DriverManager) isDriverLoaded() bool {
_, err := os.Stat("/sys/module/nvidia/refcnt")
return err == nil
}
// readStoredDigest reads the driver configuration digest from the state file
func readStoredDigest() (string, error) {
data, err := os.ReadFile(driverConfigStateFile)
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
// shouldUpdateDriverConfig checks if the driver configuration needs to be updated
func (dm *DriverManager) shouldUpdateDriverConfig() bool {
if !dm.isDriverLoaded() {
return true
}
dm.log.Info("Checking if the currently loaded NVIDIA driver version and configuration matches the desired state...")
currentDigest := os.Getenv("DRIVER_CONFIG_DIGEST")
if currentDigest == "" {
dm.log.Warn("DRIVER_CONFIG_DIGEST env var not set, assuming config changed")
return true
}
storedDigest, err := readStoredDigest()
if err != nil {
if os.IsNotExist(err) {
dm.log.Info("No previous driver configuration found")
} else {
dm.log.Warnf("Failed to read driver config state file: %v", err)
}
return true
}
return currentDigest != storedDigest
}
func (dm *DriverManager) shouldSkipUninstall() bool {
if dm.config.forceReinstall {
dm.log.Info("Force reinstall is enabled, proceeding with driver uninstall")
return false
}
if !dm.shouldUpdateDriverConfig() {
return true
}
return false
}
func (dm *DriverManager) isNouveauLoaded() bool {
_, err := os.Stat("/sys/module/nouveau/refcnt")
return err == nil
}
func (dm *DriverManager) unloadNouveau() error {
dm.log.Info("Unloading nouveau driver")
return unix.DeleteModule("nouveau", 0)
}
func (dm *DriverManager) removePIDFile() {
if err := os.Remove(driverPIDFile); err != nil && !os.IsNotExist(err) {
dm.log.Warnf("Failed to remove PID file %s: %v", driverPIDFile, err)
}
}
func (dm *DriverManager) cleanupDriver() error {
dm.log.Info("Cleaning up NVIDIA driver")
// Unload driver modules
if err := dm.unloadDriver(); err != nil {
return fmt.Errorf("failed to unload driver: %w", err)
}
// Unmount rootfs
if err := dm.unmountRootfs(); err != nil {
return fmt.Errorf("failed to unmount rootfs: %w", err)
}
dm.removePIDFile()
return nil
}
func (dm *DriverManager) unloadDriver() error {
dm.log.Info("Unloading NVIDIA driver kernel modules")
modules := []string{
"nvidia_modeset",
"nvidia_uvm",
"nvidia_peermem",
"nvidia_fs",
"nvidia_vgpu_vfio",
"gdrdrv",
"nvidia",
}
var moduleErrs error
for _, module := range modules {
if _, err := os.Stat(fmt.Sprintf("/sys/module/%s/refcnt", module)); err == nil {
if err := unix.DeleteModule(module, 0); err != nil {
dm.log.Warnf("Failed to unload kernel module %s: %v", module, err)
moduleErrs = errors.Join(err)
}
}
}
if moduleErrs != nil {
dm.log.Info("Could not unload NVIDIA driver kernel modules, driver is in use")
km := linuxutils.NewKernelModules(dm.log)
err := km.List("nvidia")
if err != nil {
dm.log.Warnf("Failed to list kernel modules: %v", err)
}
return moduleErrs
}
return nil
}
func (dm *DriverManager) unmountRootfs() error {
dm.log.Info("Unmounting NVIDIA driver rootfs")
// Check if the mount point exists
if _, err := os.Stat(driverRoot); os.IsNotExist(err) {
dm.log.Info("Driver root directory does not exist, nothing to unmount")
return nil
}
// Recursively unmount all mounts under the driver root
if err := mount.RecursiveUnmount(driverRoot); err != nil {
return fmt.Errorf("failed to recursively unmount %s: %w", driverRoot, err)
}
dm.log.Infof("Successfully unmounted %s and all its submounts", driverRoot)
return nil
}
// If vfio-pci driver is in use, ensure we unbind it from all devices.
// If vfio-pci driver is not in use, and we have reached this point, all devices will not be bound to any driver,
// so the below unbind operation will be a no-op.
func (dm *DriverManager) unbindVfioPCI() error {
dm.log.Info("Unbinding vfio-pci driver from all devices")
cmd := exec.Command("vfio-manage", "unbind", "--all")
return cmd.Run()
}
func (dm *DriverManager) isGPUDirectRDMAEnabled() bool {
if !dm.config.gpuDirectRDMAEnabled {
return false
}
return dm.mellanoxDevicesPresent()
}
func (dm *DriverManager) mellanoxDevicesPresent() bool {
entries, err := os.ReadDir("/sys/bus/pci/devices")
if err != nil {
return false
}
for _, entry := range entries {
vendorFile := filepath.Join("/sys/bus/pci/devices", entry.Name(), "vendor")
if data, err := os.ReadFile(vendorFile); err == nil {
if strings.TrimSpace(string(data)) == "0x15b3" {
dm.log.Infof("Mellanox device found at %s", entry.Name())
return true
}
}
}
dm.log.Info("No Mellanox devices were found")
return false
}
func (dm *DriverManager) waitForMofedDriver() error {
dm.log.Info("Waiting for MOFED to be installed")
var isMofedLoaded func() bool
if dm.config.useHostMofed {
isMofedLoaded = func() bool {
loadedModules, err := os.ReadFile("/proc/modules")
if err != nil {
dm.log.Warnf("Failed to read /proc/modules: %v", err)
return false
}
return strings.Contains(string(loadedModules), "mlx5_core")
}
} else {
isMofedLoaded = func() bool {
_, err := os.Stat("/run/mellanox/drivers/.driver-ready")
return err == nil
}
}
for !isMofedLoaded() {
dm.log.Info("Waiting for MOFED to be installed...")
time.Sleep(5 * time.Second)
}
return nil
}
func (dm *DriverManager) rescheduleGPUOperatorComponents() error {
dm.log.Info("Rescheduling all GPU clients on the current node by enabling their component-specific nodeSelector labels")
// Prepare labels for update
operandLabels := map[string]string{
nvidiaOperatorValidatorDeployLabel: dm.maybeSetTrue(dm.components.validatorDeployed),
nvidiaContainerToolkitDeployLabel: dm.maybeSetTrue(dm.components.toolkitDeployed),
nvidiaDevicePluginDeployLabel: dm.maybeSetTrue(dm.components.pluginDeployed),
nvidiaGFDDeployLabel: dm.maybeSetTrue(dm.components.gfdDeployed),
nvidiaDCGMExporterDeployLabel: dm.maybeSetTrue(dm.components.dcgmExporterDeployed),
nvidiaDCGMDeployLabel: dm.maybeSetTrue(dm.components.dcgmDeployed),
nvidiaNVSMDeployLabel: dm.maybeSetTrue(dm.components.nvsmDeployed),
nvidiaSandboxValidatorDeployLabel: dm.maybeSetTrue(dm.components.sandboxValidatorDeployed),
nvidiaSandboxDevicePluginDeployLabel: dm.maybeSetTrue(dm.components.sandboxPluginDeployed),
nvidiaVGPUDeviceManagerDeployLabel: dm.maybeSetTrue(dm.components.vgpuDeviceManagerDeployed),
}
if dm.components.migManagerDeployed != "" {
operandLabels[nvidiaMIGManagerDeployLabel] = dm.maybeSetTrue(dm.components.migManagerDeployed)
}
// Handle custom operand node selector label
if dm.components.customOperandNodeLabelValue != "" {
operandLabels[dm.config.nodeLabelForGPUPodEviction] = dm.maybeSetTrue(dm.components.customOperandNodeLabelValue)
}
// Update the node
return dm.kubeClient.UpdateNodeLabels(dm.config.nodeName, operandLabels)
}
func (dm *DriverManager) maybeSetTrue(currentValue string) string {
switch currentValue {
case "false":
return "false"
case pausedStr:
return "true"
default:
re := regexp.MustCompile(pausedStr + "_?")
result := re.ReplaceAllString(currentValue, "")
return strings.Trim(result, "_")
}
}
// Policy and feature check methods
func (dm *DriverManager) isAutoDrainEnabled() bool {
if dm.isDriverAutoUpgradePolicyEnabled() {
dm.log.Info("Auto drain of the node is disabled by the upgrade policy")
return false
}
return dm.config.enableAutoDrain
}
func (dm *DriverManager) isGPUPodEvictionEnabled() bool {
if dm.isDriverAutoUpgradePolicyEnabled() {
dm.log.Infof("Auto eviction of GPU pods on node %s is disabled by the upgrade policy", dm.config.nodeName)
return false
}
return dm.config.enableGPUPodEviction
}
func (dm *DriverManager) nvDrainNode() error {
dm.log.Infof("Draining node %s of any GPU pods...", dm.config.nodeName)
drainOpts := kube.DrainOptions{
Force: dm.config.drainUseForce,
DeleteEmptyDirData: dm.config.drainDeleteEmptyDirData,
Timeout: dm.config.drainTimeout,
PodSelector: dm.config.drainPodSelectorLabel,
}
return dm.kubeClient.DeleteOrEvictPods(dm.config.nodeName, drainOpts)
}
func (dm *DriverManager) isDriverAutoUpgradePolicyEnabled() bool {
if dm.components.autoUpgradePolicyEnabled == "true" {
return true
}
dm.log.Info("Auto upgrade policy of the GPU driver on the node is disabled")
return false
}
func (dm *DriverManager) cleanupOnFailure() {
dm.log.Info("Performing cleanup on failure")
if dm.isGPUPodEvictionEnabled() || dm.isAutoDrainEnabled() {
if err := dm.kubeClient.UncordonNode(dm.config.nodeName); err != nil {
dm.log.Warnf("Failed to uncordon node during cleanup: %v", err)
}
}
if err := dm.rescheduleGPUOperatorComponents(); err != nil {
dm.log.Warnf("Failed to reschedule GPU operator components during cleanup: %v", err)
}
}