Files
nvdriver/tools/patch_cdi.py
Ziyang Xu 7f1ebf4aa1 install: preserve CDI mounts when adding /dev/char (#474)
Edit the global CDI mount list as YAML and atomically publish a complete spec. Retain the generated content when parsing fails or an existing mount conflicts.
2026-12-03 15:14:46 -08:00

160 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Add the nvdriver /dev/char mount to a generated NVIDIA CDI spec."""
import argparse
import os
from pathlib import Path
import stat
import sys
import tempfile
try:
import yaml
except ImportError:
sys.exit("nvdriver-cdi-patch: install PyYAML for python3 and restart nvidia-cdi-refresh.service")
from yaml.nodes import MappingNode, ScalarNode, SequenceNode
DEVICE_DIR = "/dev/char"
STR_TAG = "tag:yaml.org,2002:str"
MERGE_TAG = "tag:yaml.org,2002:merge"
MAP_TAG = "tag:yaml.org,2002:map"
SEQ_TAG = "tag:yaml.org,2002:seq"
def field_index(mapping, name):
if not isinstance(mapping, MappingNode) or mapping.tag != MAP_TAG:
raise ValueError(f"expected a YAML mapping for {name}")
if any(key.tag == MERGE_TAG for key, _ in mapping.value):
raise ValueError(f"YAML merge keys are unsupported for {name}")
indexes = [
index for index, (key, _) in enumerate(mapping.value)
if isinstance(key, ScalarNode) and key.tag == STR_TAG and key.value == name
]
if len(indexes) > 1:
raise ValueError(f"duplicate YAML key: {name}")
return indexes[0] if indexes else None
def field(mapping, name):
index = field_index(mapping, name)
return mapping.value[index][1] if index is not None else None
def with_field(mapping, name, value):
# Copy the mapping so any device-specific alias keeps its existing content.
index = field_index(mapping, name)
entries = list(mapping.value)
if index is None:
entries.append((ScalarNode(STR_TAG, name), value))
else:
entries[index] = (entries[index][0], value)
return MappingNode(MAP_TAG, entries, flow_style=mapping.flow_style)
def is_string(node, value=None):
return (isinstance(node, ScalarNode) and node.tag == STR_TAG
and (value is None or node.value == value))
def is_sequence(node):
return isinstance(node, SequenceNode) and node.tag == SEQ_TAG
def add_char_mount(contents):
# Work on YAML nodes to avoid changing unrelated scalar types during a
# YAML 1.1 load/dump round trip (for example an annotation named "on").
spec = yaml.compose(contents, Loader=yaml.SafeLoader)
if not (is_string(field(spec, "cdiVersion")) and is_string(field(spec, "kind"))
and is_sequence(field(spec, "devices"))):
raise ValueError("expected a CDI spec with cdiVersion, kind and devices")
edits = field(spec, "containerEdits")
if edits is None:
edits = MappingNode(MAP_TAG, [])
mounts = field(edits, "mounts")
if mounts is None:
mounts = SequenceNode(SEQ_TAG, [])
if not is_sequence(mounts):
raise ValueError("expected a sequence at containerEdits.mounts")
existing = []
for mount in mounts.value:
destination = field(mount, "containerPath")
if not is_string(destination):
raise ValueError("expected a containerPath in each global CDI mount")
if destination.value == DEVICE_DIR:
existing.append(mount)
if existing:
mount = existing[0]
options_node = field(mount, "options")
options = set()
if is_sequence(options_node):
options = {item.value for item in options_node.value if is_string(item)}
if (len(existing) == 1 and is_string(field(mount, "hostPath"), DEVICE_DIR)
and "ro" in options and "rw" not in options
and options.intersection(("bind", "rbind"))):
return None
raise ValueError("conflicting global CDI mount at /dev/char")
mount = yaml.compose(
"hostPath: /dev/char\ncontainerPath: /dev/char\noptions: [ro, nosuid, rbind]\n",
Loader=yaml.SafeLoader,
)
updated = SequenceNode(SEQ_TAG, [*mounts.value, mount], flow_style=mounts.flow_style)
spec = with_field(spec, "containerEdits", with_field(edits, "mounts", updated))
return yaml.serialize(spec, Dumper=yaml.SafeDumper, allow_unicode=True)
def file_identity(info):
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
def patch_file(path):
try:
original = path.lstat()
except FileNotFoundError:
return
if not stat.S_ISREG(original.st_mode):
raise ValueError("expected a regular CDI spec file")
updated = add_char_mount(path.read_text(encoding="utf-8"))
if updated is None:
return
# A runtime watching the CDI directory must see either complete spec.
temporary = None
try:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=path.parent, prefix=".nvdriver-cdi-",
suffix=".tmp", delete=False) as stream:
temporary = Path(stream.name)
stream.write(updated)
owner = temporary.stat()
if (owner.st_uid, owner.st_gid) != (original.st_uid, original.st_gid):
os.chown(temporary, original.st_uid, original.st_gid)
temporary.chmod(stat.S_IMODE(original.st_mode))
if file_identity(path.lstat()) != file_identity(original):
raise ValueError("the CDI spec changed while it was being read")
os.replace(temporary, path)
temporary = None
finally:
if temporary is not None:
temporary.unlink()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("spec", nargs="?", type=Path, default=Path("/var/run/cdi/nvidia.yaml"))
args = parser.parse_args()
try:
patch_file(args.spec)
except (OSError, ValueError, yaml.YAMLError) as error:
print(f"nvdriver-cdi-patch: {args.spec}: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())