feat(docker): support explicit GPU device requests (#3789)

Floci's container launcher has no way to ask a daemon for an accelerator, so
every container it starts is CPU-only. Services that need a GPU, such as
SageMaker training and hosting, have nowhere to express the request.

Adds optional device requests to the shared container layer:

- withGpuCount(int) / withAllGpus() build Docker's count form
- withGpuDeviceIds(List) pins specific devices by index or vendor UUID
- withCdiDevices(List) selects Container Device Interface devices by name

Count, device ids and CDI names are alternatives, and passing more than one is
rejected: a Docker request carrying both a count and explicit ids is refused by
the daemon.

CDI is included because Floci already documents rootless Podman as a supported
host, and CDI is how a Podman daemon exposes accelerators over its
Docker-compatible API. It is also not GPU-specific, so the same primitive
reaches any device the host's CDI specs describe. The two forms are not
interchangeable: Podman accepts Docker's count form and then starts the
container with no device attached (containers/podman#22645), so the javadoc
steers a caller that may be talking to Podman toward CDI, whose failure mode is
a refused start rather than a silent CPU-only container.

Default behavior is unchanged. A spec that asks for no device sets no
DeviceRequests on the HostConfig, so a daemon configured with an accelerator
runtime as its default does not start handing devices to every container Floci
launches. Existing ContainerSpec constructors keep working through a delegating
overload that defaults the new component to empty.

Tests cover the exact request built for each form, the absence of any request
by default, the validation rules, and that requests reach the HostConfig.
ContainerGpuDockerIntegrationTest exercises real hardware and is opt-in via
-Dgpu.integration.enabled=true, skipping cleanly where no GPU exists, so CI
still covers request construction without needing one.

Verified on an RTX 5060 Ti against Podman 5.8.2 with NVIDIA Container Toolkit
1.19.1: a container requesting the device by CDI name reported exactly that
UUID from nvidia-smi, and a container requesting nothing failed to start
rather than reaching a GPU.
This commit is contained in:
Austin W authored and GitHub committed 2026-09-17 10:52:59 -04:00
1 parent 0f4865e554
commit dfbb0ee756
6 files changed
+597 -4

No files matched your search

@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.DeviceRequest;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
@@ -102,6 +103,17 @@ public class ContainerBuilder {
* Fluent builder for constructing ContainerSpec instances.
*/
public static class Builder {
/** Docker's capability name for a GPU, as used by {@code docker run --gpus}. */
private static final List<List<String>> GPU_CAPABILITY = List.of(List.of("gpu"));
/** Count understood by the daemon as "every device it has", i.e. {@code --gpus all}. */
private static final int ALL_DEVICES = -1;
/**
* Device-request driver that selects a Container Device Interface device by name.
* Podman resolves this on its Docker-compatible create API (containers/podman#19338);
* Docker's own NVIDIA path uses the count/id form instead.
*/
private static final String CDI_DRIVER = "cdi";
private final String image;
private final EmulatorConfig config;
private final DockerHostResolver dockerHostResolver;
@@ -128,6 +140,7 @@ public class ContainerBuilder {
private String user;
private final List<String> groupAdd = new ArrayList<>();
private final List<String> dnsServers = new ArrayList<>();
private final List<DeviceRequest> deviceRequests = new ArrayList<>();
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
@@ -419,6 +432,118 @@ public class ContainerBuilder {
return this;
}
/**
* Requests {@code count} GPUs, the equivalent of {@code docker run --gpus <count>}.
* The daemon chooses which devices. Prefer {@link #withGpuDeviceIds(List)} or
* {@link #withCdiDevices(List)} when the caller has to pin specific hardware.
*
* <p>Docker only. Podman accepts this form on its Docker-compatible API and then
* starts the container with no device attached (containers/podman#22645), so a
* caller that may be talking to Podman should use {@link #withCdiDevices(List)},
* whose failure mode is a refused start rather than a silent CPU-only container.
*
* @param count how many GPUs to request; must be at least one
* @throws IllegalArgumentException if {@code count} is below one
* @throws IllegalStateException if a device request was already made
*/
public Builder withGpuCount(int count) {
if (count < 1) {
throw new IllegalArgumentException(
"GPU count must be at least 1, or use withAllGpus(); got " + count);
}
requireNoExistingDeviceRequest();
deviceRequests.add(new DeviceRequest()
.withCount(count)
.withCapabilities(GPU_CAPABILITY));
return this;
}
/**
* Requests every GPU the daemon exposes, the equivalent of {@code docker run --gpus all}.
* Docker only, with the same Podman caveat as {@link #withGpuCount(int)}.
*
* @throws IllegalStateException if a device request was already made
*/
public Builder withAllGpus() {
requireNoExistingDeviceRequest();
deviceRequests.add(new DeviceRequest()
.withCount(ALL_DEVICES)
.withCapabilities(GPU_CAPABILITY));
return this;
}
/**
* Requests specific GPUs by daemon-assigned id, the equivalent of
* {@code docker run --gpus '"device=0,GPU-<uuid>"'}. Ids are indices or vendor UUIDs.
*
* <p>Indices are not stable across hosts or reboots, so a caller pinning hardware
* should prefer a UUID.
*
* @param deviceIds device ids to request; must be non-empty and individually non-blank
* @throws IllegalArgumentException if the list is empty or holds a blank id
* @throws IllegalStateException if a device request was already made
*/
public Builder withGpuDeviceIds(List<String> deviceIds) {
requireUsableIds(deviceIds, "GPU device id");
requireNoExistingDeviceRequest();
// Count and ids are alternatives in Docker's API, and sending both is rejected
// by the daemon, so this form deliberately leaves the count unset.
deviceRequests.add(new DeviceRequest()
.withDeviceIds(List.copyOf(deviceIds))
.withCapabilities(GPU_CAPABILITY));
return this;
}
/**
* Requests devices by Container Device Interface name, such as
* {@code nvidia.com/gpu=GPU-<uuid>}. CDI is how a Podman daemon exposes accelerators
* over its Docker-compatible API, and it is not GPU-specific: the name identifies
* whatever device the host's CDI specs describe.
*
* <p>No capability is attached, because the CDI name already selects the device;
* the daemon resolves it against the host's CDI specs and fails the container start
* if it cannot.
*
* @param cdiDeviceNames fully-qualified CDI names, each {@code <vendor>/<class>=<name>}
* @throws IllegalArgumentException if the list is empty, or a name is blank or unqualified
* @throws IllegalStateException if a device request was already made
*/
public Builder withCdiDevices(List<String> cdiDeviceNames) {
requireUsableIds(cdiDeviceNames, "CDI device name");
for (String name : cdiDeviceNames) {
// Catches the common mistake of passing a device path such as /dev/nvidia0,
// which the daemon would otherwise reject with an unresolvable-device error
// that does not say what was actually wrong with the value.
if (!name.contains("/") || !name.contains("=")) {
throw new IllegalArgumentException(
"CDI device name must be fully qualified as <vendor>/<class>=<name>; got " + name);
}
}
requireNoExistingDeviceRequest();
deviceRequests.add(new DeviceRequest()
.withDriver(CDI_DRIVER)
.withDeviceIds(List.copyOf(cdiDeviceNames)));
return this;
}
private void requireNoExistingDeviceRequest() {
if (!deviceRequests.isEmpty()) {
throw new IllegalStateException(
"A device request is already set; count, device ids and CDI names are alternatives");
}
}
private static void requireUsableIds(List<String> ids, String description) {
if (ids == null || ids.isEmpty()) {
throw new IllegalArgumentException("At least one " + description + " is required");
}
for (String id : ids) {
if (id == null || id.isBlank()) {
throw new IllegalArgumentException("A " + description + " must not be blank");
}
}
}
/**
* Injects Floci's embedded DNS server into the container so virtual-hosted
* S3 hostnames (my-bucket.localhost.floci.io) resolve to Floci's Docker
@@ -467,7 +592,8 @@ public class ContainerBuilder {
List.copyOf(dnsServers),
workingDir,
user,
List.copyOf(groupAdd)
List.copyOf(groupAdd),
List.copyOf(deviceRequests)
);
}
}
@@ -953,6 +953,13 @@ public class ContainerLifecycleManager {
hostConfig.withDns(spec.dnsServers().toArray(new String[0]));
}
// Device requests (GPUs). Only set when a caller asked: a daemon configured with an
// accelerator runtime as its default must not start handing devices to every
// container Floci launches.
if (spec.hasDeviceRequests()) {
hostConfig.withDeviceRequests(spec.deviceRequests());
}
return hostConfig;
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.DeviceRequest;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.Mount;
@@ -32,6 +33,7 @@ import java.util.Map;
* @param workingDir Working directory inside the container (overrides image WORKDIR)
* @param user User the container process runs as, formatted "uid[:gid]" (null = image USER)
* @param groupAdd Supplementary group IDs added to the container process
* @param deviceRequests Device requests for accelerators such as GPUs (empty = none)
*/
public record ContainerSpec(
String image,
@@ -54,14 +56,15 @@ public record ContainerSpec(
List<String> dnsServers,
String workingDir,
String user,
List<String> groupAdd
List<String> groupAdd,
List<DeviceRequest> deviceRequests
) {
/**
* Creates a minimal spec with just the image name.
* All other fields will be null or empty lists.
*/
public ContainerSpec(String image) {
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of());
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of(), List.of());
}
/**
@@ -89,7 +92,37 @@ public record ContainerSpec(
String user,
List<String> groupAdd
) {
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, List.of(), exposedPorts, networkMode, mounts, binds, extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd);
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, List.of(), exposedPorts, networkMode, mounts, binds, extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of());
}
/**
* Backward-compatible constructor that defaults {@code deviceRequests} to empty, so a
* caller that predates accelerator support keeps building CPU-only containers.
*/
public ContainerSpec(
String image,
String name,
List<String> env,
List<String> cmd,
List<String> entrypoint,
Long memoryBytes,
Map<Integer, Integer> portBindings,
List<Integer> loopbackPortBindings,
List<Integer> exposedPorts,
String networkMode,
List<Mount> mounts,
List<Bind> binds,
List<String> extraHosts,
Map<String, String> labels,
LogConfig logConfig,
boolean privileged,
String cgroupnsMode,
List<String> dnsServers,
String workingDir,
String user,
List<String> groupAdd
) {
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings, exposedPorts, networkMode, mounts, binds, extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of());
}
/**
@@ -112,4 +145,11 @@ public record ContainerSpec(
public boolean hasLogConfig() {
return logConfig != null;
}
/**
* Returns true if this spec asks the daemon for any device, such as a GPU.
*/
public boolean hasDeviceRequests() {
return deviceRequests != null && !deviceRequests.isEmpty();
}
}