Files
llmgw/internal/driver/driver.go
T
Ilker ManapandClaude Opus 5.5 383c4d5333
CI / test (push) Successful in 11m47s
A node with an NVIDIA card and no driver gets the driver its cards need
On Ubuntu, node add (and server init for its own machine) installs the
server driver ubuntu-drivers recommends for the cards on the PCI bus, with
the kernel modules Canonical builds and signs for the kernel: no DKMS, and
nothing to enrol under Secure Boot. nvidia-smi comes with it, and on an
HGX board the fabric manager, with nvlsm on Blackwell. When the driver
loads only after a restart, the console asks before restarting the
machine and goes on once it is back; --reboot restarts without asking,
--no-driver leaves the driver to the operator. `llmgw driver status` and
`llmgw driver install` do the same by hand.

Tried on node04 with a sysfs naming an RTX PRO 6000 Blackwell: real apt
and ubuntu-drivers installed 595-server-open and the 6.8.0-151 kernel its
signed modules are built for, and said a restart was needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:56:56 +01:00

347 lines
11 KiB
Go

// Package driver installs the NVIDIA driver a machine's cards need, so a node
// with a card and no driver is set up by llmgw rather than left to whoever
// adds it.
//
// On Ubuntu it is Canonical's server (ERD) driver that ubuntu-drivers
// recommends for the cards on the PCI bus, with the kernel modules Canonical
// builds and signs for the running kernel: no DKMS, no compiler, and nothing
// to enrol when Secure Boot is on. ubuntu-drivers matches each branch against
// the cards' PCI ids, so a card gets a branch that drives it: the open modules
// for Turing and newer (and Blackwell, which has no other), the proprietary
// 580 for a V100.
//
// Other distributions are reported, not guessed at.
package driver
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
// Status is what a machine has: its cards and whether a driver drives them.
type Status struct {
// Cards are the NVIDIA display and 3D controllers on the PCI bus.
Cards int `json:"cards"`
// NVSwitch is set when NVSwitches are on the bus: an HGX board, whose
// cards do not run CUDA until the fabric manager runs.
NVSwitch bool `json:"nvswitch,omitempty"`
// Working is nvidia-smi answering; Version the driver it reports.
Working bool `json:"working"`
Version string `json:"version,omitempty"`
// Present is a driver installed for this kernel but not loaded — waiting
// for a restart, or kept off the card by nouveau.
Present bool `json:"present,omitempty"`
// OS is the distribution and release, "ubuntu 24.04".
OS string `json:"os,omitempty"`
// Supported is whether Install can install a driver here; Reason says
// why not.
Supported bool `json:"supported"`
Reason string `json:"reason,omitempty"`
// SecureBoot is the firmware's Secure Boot, which only signed modules
// load under.
SecureBoot bool `json:"secure_boot,omitempty"`
}
// Result is what Install did.
type Result struct {
Status
// Branch is the driver branch installed, "595-server-open".
Branch string `json:"branch,omitempty"`
// Packages are the packages installed.
Packages []string `json:"packages,omitempty"`
// Reboot is set when the driver is installed but the machine must
// restart before it is loaded.
Reboot bool `json:"reboot,omitempty"`
// Message says what happened, for a person.
Message string `json:"message"`
}
// SysEnv names a sysfs to read the cards from instead of /sys, for trying
// Install on a machine without them.
const SysEnv = "LLMGW_DRIVER_SYSFS"
// Machine is how this package reads and changes the machine; the defaults are
// the real one.
type Machine struct {
// Sys is the sysfs root; "" is /sys.
Sys string
// OSRelease is os-release; "" is /etc/os-release.
OSRelease string
// Run runs a command and returns its combined output; nil runs it.
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
// Log hears what Install does, a line at a time; nil discards it.
Log io.Writer
}
func (m *Machine) sys() string {
if m.Sys == "" {
return "/sys"
}
return m.Sys
}
func (m *Machine) run(ctx context.Context, name string, args ...string) ([]byte, error) {
if m.Run != nil {
return m.Run(ctx, name, args...)
}
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive", "NEEDRESTART_MODE=a")
if m.Sys != "" {
// ubuntu-drivers reads the same cards.
cmd.Env = append(cmd.Env, "UBUNTU_DRIVERS_SYS_DIR="+m.Sys)
}
return cmd.CombinedOutput()
}
func (m *Machine) logf(format string, a ...any) {
if m.Log != nil {
fmt.Fprintf(m.Log, format+"\n", a...)
}
}
// pciDevice is one NVIDIA function on the bus.
type pciDevice struct {
id uint64 // the PCI device id
class string // 0x030000
}
func (m *Machine) devices() []pciDevice {
var out []pciDevice
vendors, _ := filepath.Glob(filepath.Join(m.sys(), "bus", "pci", "devices", "*", "vendor"))
for _, v := range vendors {
b, err := os.ReadFile(v) //nolint:gosec // sysfs
if err != nil || strings.TrimSpace(string(b)) != "0x10de" {
continue
}
dir := filepath.Dir(v)
class, _ := os.ReadFile(filepath.Join(dir, "class")) //nolint:gosec // sysfs
devID, _ := os.ReadFile(filepath.Join(dir, "device")) //nolint:gosec // sysfs
id, _ := strconv.ParseUint(strings.TrimPrefix(strings.TrimSpace(string(devID)), "0x"), 16, 32)
out = append(out, pciDevice{id: id, class: strings.TrimSpace(string(class))})
}
return out
}
// Check reads the machine.
func (m *Machine) Check(ctx context.Context) Status {
var st Status
for _, d := range m.devices() {
switch {
case strings.HasPrefix(d.class, "0x03"):
st.Cards++
case strings.HasPrefix(d.class, "0x0680"):
st.NVSwitch = true
}
}
id, ver := osRelease(m.OSRelease)
st.OS = strings.TrimSpace(id + " " + ver)
switch id {
case "ubuntu":
st.Supported = true
case "":
st.Reason = "the distribution is unknown (no /etc/os-release)"
default:
st.Reason = "llmgw installs the driver on Ubuntu only; this is " + st.OS
}
if out, err := m.run(ctx, "mokutil", "--sb-state"); err == nil {
st.SecureBoot = strings.Contains(string(out), "SecureBoot enabled")
}
if st.Cards == 0 {
return st
}
if out, err := m.run(ctx, "nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"); err == nil {
if v := firstLine(out); v != "" {
st.Working, st.Version = true, v
}
}
if !st.Working {
_, err := m.run(ctx, "modinfo", "-F", "version", "nvidia")
st.Present = err == nil
}
return st
}
// recommended reads `ubuntu-drivers list --gpgpu --recommended`: the driver
// package and the kernel modules package, on one line.
var recommendedLine = regexp.MustCompile(`^nvidia-driver-(\d+)(\S*)\s+(linux-modules-nvidia-\S+)$`)
func parseRecommended(out []byte) (branch, number string, ok bool) {
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
if m := recommendedLine.FindStringSubmatch(strings.TrimSpace(sc.Text())); m != nil {
return m[1] + m[2], m[1], true
}
}
return "", "", false
}
// Install installs the driver the cards need and loads it when it can,
// without restarting the machine. A driver already working is left alone.
func (m *Machine) Install(ctx context.Context) (Result, error) {
st := m.Check(ctx)
res := Result{Status: st}
switch {
case st.Cards == 0:
res.Message = "no NVIDIA card here: nothing to install"
return res, nil
case st.Working:
res.Message = "driver " + st.Version + " already drives the card(s)"
return res, nil
case st.Present:
// Someone's driver is installed for this kernel and not loaded:
// another on top would fight it.
res.Message = "a driver is installed but not loaded"
return m.load(ctx, res)
case !st.Supported:
return res, fmt.Errorf("%s; install the NVIDIA driver for the card(s) by hand, restart, and check that nvidia-smi lists them", st.Reason)
}
apt := []string{"-o", "DPkg::Lock::Timeout=600", "-o", "DPkg::Options::=--force-confnew"}
m.logf("updating the package lists")
if out, err := m.run(ctx, "apt-get", append(apt, "update")...); err != nil {
return res, fmt.Errorf("apt-get update failed: %v: %s", err, lastLines(out, 3))
}
if _, err := m.run(ctx, "sh", "-c", "command -v ubuntu-drivers"); err != nil {
m.logf("installing ubuntu-drivers-common")
if out, err := m.run(ctx, "apt-get", append(apt, "install", "-y", "--no-install-recommends", "ubuntu-drivers-common")...); err != nil {
return res, fmt.Errorf("installing ubuntu-drivers-common failed: %v: %s", err, lastLines(out, 3))
}
}
out, err := m.run(ctx, "ubuntu-drivers", "list", "--gpgpu", "--recommended")
if err != nil {
return res, fmt.Errorf("ubuntu-drivers could not list drivers: %v: %s", err, lastLines(out, 3))
}
branch, number, ok := parseRecommended(out)
if !ok {
kernel, _ := m.run(ctx, "uname", "-r")
return res, fmt.Errorf("Ubuntu has no signed server driver for these cards on kernel %s; "+
"update the machine (apt-get dist-upgrade), restart, and run this again", firstLine(kernel))
}
res.Branch = branch
m.logf("installing NVIDIA driver %s", branch)
if out, err := m.run(ctx, "ubuntu-drivers", "install", "--gpgpu", "nvidia:"+branch); err != nil {
return res, fmt.Errorf("ubuntu-drivers install --gpgpu nvidia:%s failed: %v: %s", branch, err, lastLines(out, 5))
}
// nvidia-smi is not part of the headless driver.
suffix := ""
if strings.Contains(branch, "-server") {
suffix = "-server"
}
extra := []string{"nvidia-utils-" + number + suffix}
if st.NVSwitch {
// An HGX board's cards run nothing until the fabric manager does,
// and NVLink 5 (Blackwell) needs its subnet manager as well.
extra = append(extra, "nvidia-fabricmanager-"+number)
if m.blackwell() {
extra = append(extra, "nvlsm")
}
}
m.logf("installing %s", strings.Join(extra, ", "))
if out, err := m.run(ctx, "apt-get", append(append(apt, "install", "-y", "--no-install-recommends"), extra...)...); err != nil {
return res, fmt.Errorf("installing %s failed: %v: %s", strings.Join(extra, ", "), err, lastLines(out, 3))
}
res.Packages = append([]string{"nvidia-driver-" + branch + " (headless, signed modules)"}, extra...)
if st.NVSwitch {
_, _ = m.run(ctx, "systemctl", "enable", "nvidia-fabricmanager")
}
res.Message = "installed NVIDIA driver " + branch
return m.load(ctx, res)
}
// blackwell is a card of Blackwell or later: device ids from 0x2900.
func (m *Machine) blackwell() bool {
for _, d := range m.devices() {
if strings.HasPrefix(d.class, "0x03") && d.id >= 0x2900 {
return true
}
}
return false
}
// load loads the installed driver without a restart when nothing holds the
// cards, and says a restart is needed otherwise.
func (m *Machine) load(ctx context.Context, res Result) (Result, error) {
if lsmod, _ := m.run(ctx, "sh", "-c", "grep -q '^nouveau ' /proc/modules && echo nouveau"); strings.TrimSpace(string(lsmod)) == "nouveau" {
if _, err := m.run(ctx, "modprobe", "-r", "nouveau"); err != nil {
res.Reboot = true
res.Message += "; nouveau holds the card(s), so the machine must restart to load it"
return res, nil
}
}
if out, err := m.run(ctx, "modprobe", "nvidia"); err != nil {
res.Reboot = true
res.Message += "; it loads after a restart (" + firstLine(out) + ")"
return res, nil
}
_, _ = m.run(ctx, "modprobe", "nvidia-uvm")
if res.NVSwitch {
_, _ = m.run(ctx, "systemctl", "restart", "nvidia-fabricmanager")
}
// The device files appear a moment after the module.
for i := 0; i < 5; i++ {
if st := m.Check(ctx); st.Working {
res.Status = st
res.Message += "; loaded, nvidia-smi sees driver " + st.Version
return res, nil
}
select {
case <-ctx.Done():
return res, ctx.Err()
case <-time.After(time.Second):
}
}
res.Reboot = true
res.Message += "; it loads after a restart"
return res, nil
}
// Wait is how long Install may take: a large download on a slow mirror.
const Wait = 30 * time.Minute
func osRelease(path string) (id, version string) {
if path == "" {
path = "/etc/os-release"
}
b, err := os.ReadFile(path) //nolint:gosec // a fixed system path
if err != nil {
return "", ""
}
for _, line := range strings.Split(string(b), "\n") {
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
v = strings.Trim(strings.TrimSpace(v), `"'`)
switch k {
case "ID":
id = v
case "VERSION_ID":
version = v
}
}
return id, version
}
func firstLine(b []byte) string {
s, _, _ := strings.Cut(strings.TrimSpace(string(b)), "\n")
return strings.TrimSpace(s)
}
func lastLines(b []byte, n int) string {
lines := strings.Split(strings.TrimSpace(string(b)), "\n")
if len(lines) > n {
lines = lines[len(lines)-n:]
}
return strings.Join(lines, " / ")
}