-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnvidia_driver_reload.py
More file actions
3694 lines (3128 loc) · 149 KB
/
Copy pathnvidia_driver_reload.py
File metadata and controls
3694 lines (3128 loc) · 149 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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
NVIDIA Driver Hot-Reload Manager - Production Ready
====================================================
A comprehensive Python tool to reload NVIDIA drivers WITHOUT rebooting on
headless Linux servers running Docker GPU workloads.
## VERIFIED TECHNICAL FACTS (from extensive research across 10+ sources):
1. YES, you CAN reload NVIDIA drivers without reboot on HEADLESS servers
- Confirmed by NVIDIA forums and production deployments
- Requires: All GPU processes stopped, persistence daemon stopped,
kernel modules unloaded in correct order
- Reference: https://forums.developer.nvidia.com/t/reset-driver-without-rebooting-on-linux/40625
2. Module unload order is CRITICAL:
nvidia_drm -> nvidia_modeset -> nvidia_uvm -> nvidia
- Reference: https://zyao.net/linux/2024/09/29/cuda-driver-reload/
- Reference: https://wiki.archlinux.org/title/NVIDIA/Tips_and_tricks
3. Docker daemon MUST be restarted after driver reload
- Container toolkit caches driver library paths
- Reference: https://github.com/NVIDIA/nvidia-container-toolkit/issues/169
4. nvidia-persistenced MUST be stopped first
- It holds device files open, preventing module unload
- Reference: https://docs.nvidia.com/deploy/driver-persistence/persistence-daemon.html
5. Display servers (X11/Wayland) prevent unload - but headless servers don't have these
## nvidia_drm.modeset=1 HANDLING:
When modeset=1 is enabled, nvidia_drm installs a framebuffer console that PINS
the kernel modules. The documented solution (used by optimus-manager, GPU
passthrough scripts, and confirmed on Arch Wiki):
1. Unbind VT consoles:
echo 0 > /sys/class/vtconsole/vtcon0/bind
echo 0 > /sys/class/vtconsole/vtcon1/bind
2. Unbind framebuffer drivers:
echo efi-framebuffer.0 > /sys/bus/platform/drivers/efi-framebuffer/unbind
3. Unload modules with retry (optimus-manager uses 5 tries, 1s wait):
modprobe -r nvidia_drm nvidia_modeset nvidia_uvm nvidia
4. After reload, rebind in reverse order:
- Rebind efi-framebuffer FIRST
- Rebind vtconsoles SECOND
References:
- Arch Wiki: https://wiki.archlinux.org/title/NVIDIA#DRM_kernel_mode_setting
- Arch Forums: https://bbs.archlinux.org/viewtopic.php?id=295484
- optimus-manager: https://github.com/Askannz/optimus-manager
- GPU Passthrough: https://github.com/QaidVoid/Complete-Single-GPU-Passthrough
- Gentoo Wiki: https://wiki.gentoo.org/wiki/NVIDIA/nvidia-drivers
- Kernel Docs: https://docs.kernel.org/fb/fbcon.html
- NVIDIA Forums: https://forums.developer.nvidia.com/t/understanding-nvidia-drm-modeset-1/204068
## REBOOT-REQUIRED DETECTION:
The script automatically detects scenarios where driver reload will NOT work:
- XID 79: GPU has fallen off the bus (PCIe link lost)
- XID 74: GPU is lost
- XID 48/94/95: ECC memory errors (hardware failure)
- XID 119: GSP RPC timeout (firmware failure)
- GSP firmware initialization failures
- NULL pointer dereferences in nvidia module
- Module usage count corruption
## SYSTEMD-LOGIND HANDLING:
Research finding: systemd-logind is the #1 hidden culprit that holds DRM device
file handles even after display manager stops. The script restarts systemd-logind
when nvidia_drm.modeset=1 is enabled to release these handles.
Reference: https://bbs.archlinux.org/viewtopic.php?id=295484
## INTELLIGENT GPU PROCESS DETECTION:
The script uses AUTHORITATIVE DETECTION instead of static process name matching:
1. **NVML API** (nvidia-smi library):
- Detects ALL processes actively using GPU compute/graphics resources
- Returns exact PIDs with GPU memory usage
- No guessing - 100% accurate for CUDA/graphics workloads
2. **fuser /dev/nvidia*:**
- Detects ALL processes holding open handles to NVIDIA device files
- Catches processes NVML might miss (device access without compute)
- Works even when NVML is unavailable
3. **NO static process name lists**:
- Does NOT kill "python", "containerd", "docker" based on name alone
- ONLY kills processes detected by NVML or fuser
- Prevents killing innocent processes with similar names
This intelligent approach works for ANY GPU workload without manual updates.
## ENTERPRISE GPU SUPPORT (A100, H100, H200):
The script automatically handles enterprise GPU components when present:
1. **NVIDIA DCGM** (Data Center GPU Manager):
- Automatically stops nvidia-dcgm service before driver unload
- DCGM holds GPU device handles through NVML that block module unload
- Restarts service after driver reload for continued monitoring
- Reference: https://docs.nvidia.com/datacenter/dcgm/
2. **nvidia-peermem** (GPUDirect RDMA for HPC/InfiniBand):
- Automatically unloads if present (HPC clusters with Mellanox OFED)
- Correct module order: nvidia_uvm → nvidia-peermem → nvidia
- Only present on systems with InfiniBand/RoCE networking
- Reference: https://docs.nvidia.com/cuda/gpudirect-rdma/
3. **Fabric Manager** (NVSwitch/NVLink systems):
- Required for DGX A100/H100/H200 and HGX platforms
- Must be stopped before driver unload, restarted after
- Version must match driver version exactly
All enterprise components are detected automatically - if not present, they are
silently skipped. No configuration needed.
## KERNEL COMPATIBILITY:
The script checks for known kernel issues:
- Kernel 6.10.3-6.10.9: follow_pte regression (NULL pointer on suspend)
- Kernel 6.12+: Requires NVIDIA driver >= 550.135
## LIMITATIONS:
- Does NOT work if display server is using the GPU
- Does NOT support GPU checkpoint/restore (CUDA state is lost)
- Multi-GPU NVLink systems need Fabric Manager version matching
- Some corrupted GPU states require reboot (detected automatically)
- Screen goes BLANK during modeset=1 unbind (this is expected)
- H100 CRITICAL: Driver < 535 has silent data corruption bug on reload
(NVIDIA bug: reloading nvidia.ko causes incorrect computation results)
Recommendation: Upgrade to driver 535+ before using reload on H100/H200
## REQUIREMENTS:
- Root privileges (sudo)
- Python 3.8+
- Optional: pip install nvidia-ml-py docker psutil
Author: Production-ready solution for headless Docker GPU servers
Research: Based on 20+ subagent investigations across NVIDIA forums, Arch Wiki,
kernel documentation, optimus-manager, envycontrol, and GPU passthrough projects
License: MIT
"""
from __future__ import annotations
import subprocess
import sys
import os
import time
import signal
import argparse
import json
import logging
import fcntl
import atexit
import traceback
from pathlib import Path
from typing import List, Dict, Optional, Tuple, Set, Any
from dataclasses import dataclass, field, asdict
from enum import Enum
from datetime import datetime
from contextlib import contextmanager
import stat
# ============================================================================
# CONFIGURATION
# ============================================================================
CONFIG = {
# Paths
'lock_file': '/var/run/nvidia-reload.lock',
'state_file': '/var/lib/nvidia-reload/state.json',
'log_file': '/var/log/nvidia-reload.log',
'backup_dir': '/var/lib/nvidia-reload/backups',
# Timeouts (seconds)
'container_stop_timeout': 60,
'module_unload_timeout': 30,
'docker_restart_timeout': 120,
'process_kill_timeout': 10,
# Retry settings
'max_retries': 3,
'retry_delay': 2,
# Safety settings
'require_confirmation': True,
'dry_run': False,
'force_kill_display_processes': False, # DANGEROUS - don't enable
# Module configuration
# Order matters! Unload from top to bottom
# Research reference: https://docs.nvidia.com/multi-node-nvlink-systems/mnnvl-user-guide/deploying.html
'nvidia_modules': [
'nvidia_drm',
'nvidia_modeset',
'nvidia_uvm',
'nvidia_peermem', # GPUDirect RDMA (optional, only present on HPC/InfiniBand systems)
'nvidia',
],
# Services are detected DYNAMICALLY via get_services_for_gpu_processes()
# No static list - discovers what's actually using the GPU via /proc/*/cgroup
'services_to_stop': [],
# Processes that indicate display server (BLOCK unload)
'display_processes': [
'Xorg', 'X', 'Xwayland',
'gnome-shell', 'kwin_wayland', 'kwin_x11',
'sddm', 'gdm', 'lightdm', 'lxdm',
'mutter', 'weston', 'sway',
],
# Services to restart to release DRM handles (research finding: #1 hidden culprit)
# Reference: https://bbs.archlinux.org/viewtopic.php?id=295484
# "systemd-logind holds DRM device file handles even after display manager stops"
'services_to_restart_for_drm': [
'systemd-logind',
],
# ==========================================================================
# INTELLIGENT DETECTION - NO STATIC PROCESS LISTS
# ==========================================================================
# We DO NOT maintain a list of "blocking processes" - that approach is
# fundamentally flawed (kills innocent python/containerd/docker processes).
#
# Instead, we TRUST AUTHORITATIVE DETECTION:
# - NVML API (nvidia-smi): Tells us EXACTLY which PIDs are using GPU compute/graphics
# - fuser: Tells us EXACTLY which PIDs have open handles to /dev/nvidia* devices
#
# If a process is detected by these tools, it IS using the GPU.
# If not detected, it's NOT using the GPU - leave it alone!
#
# This is the ONLY intelligent approach that works for all scenarios.
# ==========================================================================
# ==========================================================================
# XID ERROR CLASSIFICATION (Based on extensive research - 10 subagent findings)
# ==========================================================================
# Research sources:
# - NVIDIA XID Errors Documentation: https://docs.nvidia.com/deploy/xid-errors/
# - NVIDIA GPU Debug Guidelines: https://docs.nvidia.com/deploy/gpu-debug-guidelines/
# - Modal GPU Health (20,000+ GPU fleet): https://modal.com/blog/gpu-health
# - AWS/GCP GPU Troubleshooting guides
# - Arch Wiki, NVIDIA Forums, GitHub issues
#
# KEY FINDING: Many XIDs we thought were "fatal" are actually recoverable!
# ==========================================================================
# TRULY FATAL: These errors indicate hardware failure - reboot REQUIRED
# Even nvidia-smi --gpu-reset won't help
'fatal_xid_errors': [
79, # GPU has fallen off the bus - PCIe link lost, MUST REBOOT
# This is the ONLY truly fatal error where GPU is inaccessible
],
# RECOVERABLE WITH GPU RESET: nvidia-smi --gpu-reset or driver reload works
# Research: These respond to GPU reset on datacenter GPUs
'gpu_reset_xid_errors': [
48, # Double Bit ECC Error - GPU reset retires bad pages
74, # GPU is lost - Often recoverable with reset (not NVLink failure)
95, # Uncontained ECC error - GPU reset required then restart apps
119, # GSP RPC timeout - GPU reset works (common after OOM kill)
],
# RECOVERABLE WITH APP RESTART: No GPU reset needed, just restart application
# Research: NVIDIA docs say "RESTART_APP" for these
'app_restart_xid_errors': [
31, # GPU memory page fault - application bug, GPU healthy
43, # GPU stopped processing - user app fault, GPU healthy
45, # Preemptive cleanup - cleanup from OTHER errors
68, # NVDEC0 Exception - decoder error, restart app
69, # Graphics Engine Class Error - restart app
94, # Contained ECC error - ONLY affected app needs restart
],
# INFORMATIONAL: These may not indicate problems
'informational_xid_errors': [
61, # Internal micro-controller breakpoint/warning
62, # Internal micro-controller halt
63, # ECC page retirement recording - INFO about retirement
64, # ECC page retirement failure - needs investigation
92, # High single bit ECC rate - monitoring alert, not failure
],
# Maximum age (seconds) for XID errors to be considered "recent"
# Old errors in dmesg are likely from previous container runs
'xid_max_age_seconds': 300, # 5 minutes
}
# ============================================================================
# LOGGING SETUP
# ============================================================================
def setup_logging(verbose: bool = False, log_file: Optional[str] = None) -> logging.Logger:
"""Configure logging with both console and file output"""
log_file = log_file or CONFIG['log_file']
# Ensure log directory exists
log_dir = Path(log_file).parent
log_dir.mkdir(parents=True, exist_ok=True)
logger = logging.getLogger('nvidia-reload')
logger.setLevel(logging.DEBUG if verbose else logging.INFO)
# Clear existing handlers
logger.handlers.clear()
# Console handler
console = logging.StreamHandler()
console.setLevel(logging.DEBUG if verbose else logging.INFO)
console_fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%H:%M:%S')
console.setFormatter(console_fmt)
logger.addHandler(console)
# File handler
try:
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
file_handler.setFormatter(file_fmt)
logger.addHandler(file_handler)
except PermissionError:
logger.warning(f"Cannot write to log file {log_file}, continuing without file logging")
return logger
logger = setup_logging()
# ============================================================================
# DATA CLASSES
# ============================================================================
class ReloadPhase(Enum):
"""Phases of the reload process for tracking and recovery"""
INITIALIZED = "initialized"
STOPPING_CONTAINERS = "stopping_containers"
STOPPING_SERVICES = "stopping_services"
KILLING_PROCESSES = "killing_processes"
UNLOADING_MODULES = "unloading_modules"
LOADING_MODULES = "loading_modules"
STARTING_SERVICES = "starting_services"
RESTARTING_DOCKER = "restarting_docker"
STARTING_CONTAINERS = "starting_containers"
COMPLETED = "completed"
FAILED = "failed"
ROLLED_BACK = "rolled_back"
@dataclass
class GPUProcess:
"""Represents a process using the GPU"""
pid: int
name: str
cmdline: str
gpu_memory_mb: float = 0.0
gpu_index: int = 0
is_display_process: bool = False
def to_dict(self) -> Dict:
return asdict(self)
@dataclass
class ContainerInfo:
"""Represents a Docker container"""
id: str
name: str
image: str
status: str
uses_gpu: bool = False
labels: Dict[str, str] = field(default_factory=dict)
def to_dict(self) -> Dict:
return asdict(self)
@dataclass
class ServiceInfo:
"""Represents a systemd service"""
name: str
active: bool
enabled: bool
@dataclass
class ReloadState:
"""
Tracks state throughout the reload process for recovery.
Persisted to disk so we can recover from crashes.
"""
phase: str = ReloadPhase.INITIALIZED.value
started_at: str = ""
driver_version_before: str = ""
driver_version_after: str = ""
stopped_containers: List[str] = field(default_factory=list)
stopped_services: List[str] = field(default_factory=list)
killed_processes: List[Dict] = field(default_factory=list)
unloaded_modules: List[str] = field(default_factory=list)
docker_was_running: bool = True
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
def save(self, path: Optional[str] = None):
"""Persist state to disk"""
path = path or CONFIG['state_file']
state_dir = Path(path).parent
state_dir.mkdir(parents=True, exist_ok=True)
with open(path, 'w') as f:
json.dump(asdict(self), f, indent=2, default=str)
logger.debug(f"State saved to {path}")
@classmethod
def load(cls, path: Optional[str] = None) -> 'ReloadState':
"""Load state from disk"""
path = path or CONFIG['state_file']
try:
with open(path, 'r') as f:
data = json.load(f)
return cls(**data)
except FileNotFoundError:
return cls()
except Exception as e:
logger.warning(f"Could not load state: {e}")
return cls()
def add_error(self, error: str):
self.errors.append(f"{datetime.now().isoformat()}: {error}")
self.save()
def add_warning(self, warning: str):
self.warnings.append(f"{datetime.now().isoformat()}: {warning}")
self.save()
def set_phase(self, phase: ReloadPhase):
self.phase = phase.value
self.save()
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def run_command(
cmd: List[str],
timeout: int = 60,
check: bool = True,
capture: bool = True,
env: Optional[Dict] = None
) -> subprocess.CompletedProcess:
"""
Run a command with proper error handling.
Args:
cmd: Command and arguments as list
timeout: Timeout in seconds
check: Raise exception on non-zero exit
capture: Capture stdout/stderr
env: Environment variables
Returns:
CompletedProcess result
"""
logger.debug(f"Running: {' '.join(cmd)}")
try:
result = subprocess.run(
cmd,
timeout=timeout,
check=check,
capture_output=capture,
text=True,
env=env or os.environ.copy()
)
return result
except subprocess.CalledProcessError as e:
logger.error(f"Command failed: {e.cmd}")
if e.stdout:
logger.error(f"stdout: {e.stdout}")
if e.stderr:
logger.error(f"stderr: {e.stderr}")
raise
except subprocess.TimeoutExpired as e:
logger.error(f"Command timed out after {timeout}s: {cmd}")
raise
def run_command_safe(cmd: List[str], **kwargs) -> Tuple[bool, str, str]:
"""
Run a command without raising exceptions.
Returns:
Tuple of (success, stdout, stderr)
"""
try:
result = run_command(cmd, check=False, **kwargs)
return result.returncode == 0, result.stdout or "", result.stderr or ""
except Exception as e:
return False, "", str(e)
@contextmanager
def exclusive_lock(lock_file: str = None):
"""
Acquire an exclusive lock to prevent concurrent executions.
Uses flock for proper advisory locking.
Reference: https://www.linuxbash.sh/post/use-flock-to-prevent-concurrent-script-execution
"""
lock_file = lock_file or CONFIG['lock_file']
lock_dir = Path(lock_file).parent
lock_dir.mkdir(parents=True, exist_ok=True)
lock_fd = open(lock_file, 'w')
try:
fcntl.flock(lock_fd.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
lock_fd.write(f"{os.getpid()}\n")
lock_fd.flush()
logger.debug(f"Acquired exclusive lock: {lock_file}")
yield
except BlockingIOError:
# Check if the process holding the lock is still alive
try:
with open(lock_file, 'r') as f:
pid = int(f.read().strip())
os.kill(pid, 0) # Check if process exists
raise RuntimeError(
f"Another instance is running (PID {pid}). "
f"If this is incorrect, remove {lock_file}"
)
except (ValueError, ProcessLookupError, FileNotFoundError):
# Stale lock, try to acquire
fcntl.flock(lock_fd.fileno(), fcntl.LOCK_EX)
lock_fd.write(f"{os.getpid()}\n")
lock_fd.flush()
yield
finally:
fcntl.flock(lock_fd.fileno(), fcntl.LOCK_UN)
lock_fd.close()
try:
os.unlink(lock_file)
except:
pass
def check_root() -> bool:
"""Check if running as root"""
if os.geteuid() != 0:
logger.error("This script must be run as root (sudo)")
return False
return True
def get_process_name(pid: int) -> str:
"""Get process name from /proc"""
try:
with open(f'/proc/{pid}/comm', 'r') as f:
return f.read().strip()
except:
return "unknown"
def get_process_cmdline(pid: int) -> str:
"""Get process command line from /proc"""
try:
with open(f'/proc/{pid}/cmdline', 'r') as f:
return f.read().replace('\x00', ' ').strip()
except:
return ""
def process_exists(pid: int) -> bool:
"""Check if a process exists"""
try:
os.kill(pid, 0)
return True
except (ProcessLookupError, PermissionError):
return False
def is_system_process(pid: int, name: str = None) -> bool:
"""
Check if a process is a critical system process that should never be killed.
Uses two criteria:
1. PID < 100: System PIDs (init, kthreads, core daemons)
2. Process name matches critical system processes
Args:
pid: Process ID
name: Process name (optional, will be looked up if not provided)
Returns:
True if this is a system process that must not be killed
"""
# Criterion 1: Low PIDs are always system processes
# PID 1 = systemd/init
# PID 2 = kthreadd
# PIDs 3-99 = kernel threads and core system daemons
if pid < 100:
return True
# Criterion 2: Check process name against critical process list
if name is None:
name = get_process_name(pid)
critical_processes = [
# Init systems
'systemd', 'init',
# Kernel threads (sometimes have high PIDs on some systems)
'kernel', 'kthreadd', 'ksoftirqd', 'rcu_sched', 'rcu_bh',
'migration', 'watchdog', 'cpuhp', 'kworker', 'kswapd',
'khugepaged', 'kcompactd', 'oom_reaper', 'writeback',
'kblockd', 'kintegrityd', 'kdevtmpfs', 'netns',
# Critical system services (these should be restarted, not killed)
'systemd-logind', 'dbus-daemon', 'dbus-broker',
]
return name in critical_processes
def get_process_cgroup_info(pid: int) -> Dict[str, Any]:
"""
Get cgroup information for a process to identify its controlling service/container.
This is the KEY to dynamically identifying what manages a GPU process.
Returns dict with:
- 'service': systemd service name if managed by systemd (e.g., 'k3s-agent.service')
- 'container_id': container ID if running in a container
- 'container_runtime': 'containerd', 'docker', 'crio', etc.
- 'kubernetes': True if managed by kubernetes
- 'pod_uid': Kubernetes pod UID if applicable
"""
result = {
'service': None,
'container_id': None,
'container_runtime': None,
'kubernetes': False,
'pod_uid': None,
'slice': None,
}
try:
cgroup_path = Path(f'/proc/{pid}/cgroup')
if not cgroup_path.exists():
return result
content = cgroup_path.read_text()
for line in content.split('\n'):
if not line.strip():
continue
# Format: hierarchy-ID:controller-list:cgroup-path
# Example: 0::/system.slice/k3s-agent.service
# Example: 0::/kubepods/pod<uid>/containerd-<container-id>
parts = line.split(':')
if len(parts) >= 3:
cgroup = parts[2]
# Detect systemd service
if '.service' in cgroup:
import re
match = re.search(r'([^/]+\.service)', cgroup)
if match:
result['service'] = match.group(1)
# Detect systemd slice
if '.slice' in cgroup:
import re
match = re.search(r'([^/]+\.slice)', cgroup)
if match:
result['slice'] = match.group(1)
# Detect Kubernetes
if 'kubepods' in cgroup or 'kubelet' in cgroup:
result['kubernetes'] = True
# Extract pod UID
import re
pod_match = re.search(r'pod([a-f0-9-]+)', cgroup)
if pod_match:
result['pod_uid'] = pod_match.group(1)
# Detect container ID and runtime
if 'containerd' in cgroup:
result['container_runtime'] = 'containerd'
import re
match = re.search(r'containerd-([a-f0-9]+)', cgroup)
if match:
result['container_id'] = match.group(1)
elif 'docker' in cgroup:
result['container_runtime'] = 'docker'
import re
match = re.search(r'docker-([a-f0-9]+)', cgroup)
if match:
result['container_id'] = match.group(1)
elif 'crio' in cgroup:
result['container_runtime'] = 'crio'
import re
match = re.search(r'crio-([a-f0-9]+)', cgroup)
if match:
result['container_id'] = match.group(1)
except (OSError, PermissionError, FileNotFoundError):
pass
return result
def get_services_for_gpu_processes(processes: List) -> Set[str]:
"""
Dynamically identify systemd services that need to be stopped for GPU processes.
This is SMART detection - no static service lists needed.
Walks up the process tree and cgroup hierarchy to find controlling services.
"""
services_to_stop = set()
for proc in processes:
pid = proc.pid if hasattr(proc, 'pid') else proc
# Get cgroup info for this process
cgroup_info = get_process_cgroup_info(pid)
if cgroup_info['service']:
services_to_stop.add(cgroup_info['service'])
logger.debug(f"PID {pid} controlled by service: {cgroup_info['service']}")
# If it's a kubernetes pod, we need to stop the kubelet/k3s-agent
if cgroup_info['kubernetes']:
# Check what's managing kubernetes on this system
for k8s_service in ['k3s-agent.service', 'k3s.service', 'kubelet.service']:
success, _, _ = run_command_safe(['systemctl', 'is-active', k8s_service], timeout=5)
if success:
services_to_stop.add(k8s_service)
logger.debug(f"PID {pid} is k8s pod, will stop {k8s_service}")
break
# Walk up the process tree to find parent services
try:
current_pid = pid
for _ in range(10): # Max 10 levels up
stat_path = Path(f'/proc/{current_pid}/stat')
if not stat_path.exists():
break
stat_content = stat_path.read_text()
# Format: pid (comm) state ppid ...
import re
match = re.match(r'\d+ \([^)]+\) \S+ (\d+)', stat_content)
if not match:
break
ppid = int(match.group(1))
if ppid <= 1:
break
parent_cgroup = get_process_cgroup_info(ppid)
if parent_cgroup['service'] and parent_cgroup['service'] not in services_to_stop:
services_to_stop.add(parent_cgroup['service'])
logger.debug(f"Found parent service for PID {pid}: {parent_cgroup['service']}")
current_pid = ppid
except (OSError, PermissionError, ValueError):
pass
# Remove critical system services that shouldn't be stopped
critical = {'systemd-logind.service', 'dbus.service', 'dbus-broker.service',
'sshd.service', 'ssh.service', 'systemd-journald.service'}
services_to_stop -= critical
return services_to_stop
# ============================================================================
# NVML WRAPPER - GPU PROCESS MANAGEMENT
# ============================================================================
class NVMLManager:
"""
Wrapper for NVIDIA Management Library.
Falls back to system commands if pynvml not available.
Reference: https://pypi.org/project/nvidia-ml-py/
"""
def __init__(self):
self.nvml = None
self.nvml_available = False
self._init_nvml()
def _init_nvml(self):
"""Try to initialize NVML"""
try:
import pynvml
pynvml.nvmlInit()
self.nvml = pynvml
self.nvml_available = True
logger.debug("NVML initialized successfully")
except ImportError:
logger.info("pynvml not installed (pip install nvidia-ml-py)")
except Exception as e:
logger.debug(f"NVML init failed (driver may not be loaded): {e}")
def shutdown(self):
"""Shutdown NVML"""
if self.nvml_available:
try:
self.nvml.nvmlShutdown()
self.nvml_available = False
except:
pass
def reinit(self):
"""Reinitialize NVML after driver reload"""
self.shutdown()
self._init_nvml()
def get_driver_version(self) -> Optional[str]:
"""Get currently loaded driver version"""
if self.nvml_available:
try:
version = self.nvml.nvmlSystemGetDriverVersion()
return version.decode() if isinstance(version, bytes) else str(version)
except:
pass
# Fallback to nvidia-smi
success, stdout, _ = run_command_safe(
['nvidia-smi', '--query-gpu=driver_version', '--format=csv,noheader,nounits'],
timeout=10
)
if success and stdout.strip():
return stdout.strip().split('\n')[0]
return None
def get_cuda_version(self) -> Optional[str]:
"""Get CUDA version supported by driver"""
success, stdout, _ = run_command_safe(
['nvidia-smi', '--query-gpu=cuda_version', '--format=csv,noheader,nounits'],
timeout=10
)
if success and stdout.strip():
return stdout.strip().split('\n')[0]
return None
def get_gpu_count(self) -> int:
"""Get number of GPUs"""
if self.nvml_available:
try:
return self.nvml.nvmlDeviceGetCount()
except:
pass
success, stdout, _ = run_command_safe(
['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'],
timeout=10
)
if success:
return len([l for l in stdout.strip().split('\n') if l.strip()])
return 0
def get_gpu_info(self) -> List[Dict]:
"""Get information about all GPUs"""
gpus = []
success, stdout, _ = run_command_safe(
['nvidia-smi', '--query-gpu=index,name,memory.total,memory.used,utilization.gpu',
'--format=csv,noheader,nounits'],
timeout=10
)
if success:
for line in stdout.strip().split('\n'):
if not line.strip():
continue
parts = [p.strip() for p in line.split(',')]
if len(parts) >= 5:
gpus.append({
'index': int(parts[0]),
'name': parts[1],
'memory_total_mb': float(parts[2]),
'memory_used_mb': float(parts[3]),
'utilization_percent': float(parts[4]) if parts[4] != '[N/A]' else 0
})
return gpus
def verify_nvidia_smi_works(self) -> Tuple[bool, Dict[str, Any]]:
"""
Comprehensive verification that nvidia-smi works correctly after driver reload.
Based on real-world examples and NVIDIA documentation.
Returns:
Tuple of (success, detailed_results)
References (verified real-world sources):
- nvidia-smi exit codes: https://docs.nvidia.com/deploy/nvidia-smi/index.html
Exit codes: 0=success, 2=invalid arg, 3=unavailable, 4=permission denied,
6=query failed, 8=power cable issue, 9=driver not loaded, 10=interrupt issue,
12=NVML unavailable, 13=function not implemented, 14=infoROM corrupt,
15=GPU inaccessible, 255=internal error
- Version mismatch: https://zyao.net/linux/2024/09/29/cuda-driver-reload/
- Device files: https://github.com/NVIDIA/open-gpu-kernel-modules/discussions/336
- Real working script: https://gist.github.com/gregjhogan/f1c2417a2af5852c2490e8279a7fb141
"""
results = {
'nvidia_smi_runs': False,
'nvidia_smi_exit_code': None,
'nvidia_smi_error': None,
'nvidia_smi_error_meaning': None,
'driver_version': None,
'cuda_version': None,
'gpu_count': 0,
'gpus_detected': [],
'device_files_exist': False,
'device_files': [],
'kernel_module_loaded': False,
'kernel_module_version': None,
'proc_driver_version': None,
'sys_module_version': None,
'version_mismatch': False,
'ecc_errors': [],
'health_ok': True,
'issues': [],
}
# nvidia-smi exit code meanings (from official docs)
EXIT_CODE_MEANINGS = {
0: "Success",
2: "Invalid argument or flag",
3: "Operation unavailable on target device",
4: "Insufficient permissions",
6: "Query unsuccessful",
8: "External power cables not attached",
9: "NVIDIA driver not loaded",
10: "Kernel interrupt issue with GPU",
12: "NVML shared library unavailable",
13: "Function not implemented in local NVML",
14: "infoROM corrupted",
15: "GPU disconnected or inaccessible",
255: "Internal driver error",
}
logger.info("Verifying nvidia-smi functionality...")
# =====================================================================
# Check 1: Basic nvidia-smi execution
# This is the primary test - if nvidia-smi runs, driver is working
# Reference: https://forums.developer.nvidia.com/t/reset-driver-without-rebooting-on-linux/40625
# =====================================================================
try:
result = subprocess.run(
['nvidia-smi'],
capture_output=True, text=True, timeout=30
)
results['nvidia_smi_exit_code'] = result.returncode
results['nvidia_smi_runs'] = (result.returncode == 0)
results['nvidia_smi_error_meaning'] = EXIT_CODE_MEANINGS.get(
result.returncode, f"Unknown error code {result.returncode}"
)
if result.returncode != 0:
results['nvidia_smi_error'] = result.stderr.strip() or result.stdout.strip()
results['issues'].append(
f"nvidia-smi exit code {result.returncode}: {results['nvidia_smi_error_meaning']}"
)
if result.stderr:
results['issues'].append(f"Error output: {result.stderr.strip()[:200]}")
results['health_ok'] = False
except subprocess.TimeoutExpired:
results['nvidia_smi_error'] = "nvidia-smi timed out after 30 seconds"
results['nvidia_smi_exit_code'] = -1
results['issues'].append("nvidia-smi timed out - GPU may be hung")
results['health_ok'] = False
except FileNotFoundError:
results['nvidia_smi_error'] = "nvidia-smi binary not found"
results['nvidia_smi_exit_code'] = -2
results['issues'].append("nvidia-smi not found in PATH - driver may not be installed")
results['health_ok'] = False
# =====================================================================
# Check 2: Kernel module loaded
# Reference: lsmod | grep nvidia
# =====================================================================
success, stdout, _ = run_command_safe(['lsmod'], timeout=10)
if success:
for line in stdout.split('\n'):
if line.startswith('nvidia ') or line.startswith('nvidia\t'):
results['kernel_module_loaded'] = True
# Parse use count from lsmod output: "nvidia 56692736 3 nvidia_uvm,nvidia_modeset"
parts = line.split()
if len(parts) >= 3: