Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions charts/hami/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ This document provides detailed descriptions of all configurable values paramete
|-----------|-------------|---------------|
| `devicePlugin.pluginPath` | Plugin path | `/var/lib/kubelet/device-plugins` |
| `devicePlugin.libPath` | Library path | `/usr/local/vgpu` |
| `devicePlugin.hostPID` | Use the host PID namespace for the device plugin | `true` |
| `devicePlugin.hostPIDBroker.enabled` | Let HAMi core ask the device plugin for its host PID. This requires `devicePlugin.hostPID`. See [Host PID broker](../../docs/develop/hostpid-broker.md) | `false` |
| `devicePlugin.nvidiaNodeSelector` | NVIDIA node selector | `{"gpu": "on"}` |
| `devicePlugin.updateStrategy.type` | Update strategy type | `RollingUpdate` |
| `devicePlugin.updateStrategy.rollingUpdate.maxUnavailable` | Maximum unavailable count | `1` |
Expand Down
17 changes: 17 additions & 0 deletions charts/hami/templates/device-plugin/daemonsetnvidia.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{{- if and .Values.devicePlugin.enabled .Values.devicePlugin.hostPIDBroker.enabled (not .Values.devicePlugin.hostPID) }}
{{- fail "devicePlugin.hostPIDBroker requires devicePlugin.hostPID" }}
{{- end }}
{{- if .Values.devicePlugin.enabled }}
apiVersion: apps/v1
kind: DaemonSet
Expand Down Expand Up @@ -94,6 +97,10 @@ spec:
value: {{ .Values.devicePlugin.deviceListStrategy }}
- name: HOOK_PATH
value: {{ .Values.global.gpuHookPath }}
{{- if .Values.devicePlugin.hostPIDBroker.enabled }}
- name: LIBVGPU_HOSTPID_BROKER
value: "1"
{{- end }}
{{- if typeIs "bool" .Values.devicePlugin.passDeviceSpecsEnabled }}
- name: PASS_DEVICE_SPECS
value: {{ .Values.devicePlugin.passDeviceSpecsEnabled | quote }}
Expand Down Expand Up @@ -147,6 +154,10 @@ spec:
subPath: device-config.yaml
- name: cdi-root
mountPath: /var/run/cdi
{{- if .Values.devicePlugin.hostPIDBroker.enabled }}
- name: hostpid-broker
mountPath: /var/run/hami/hostpid
{{- end }}
{{- if typeIs "string" .Values.devicePlugin.nvidiaDriverRoot }}
# We always mount the driver root at /driver-root in the container.
# This is required for CDI detection to work correctly.
Expand Down Expand Up @@ -239,6 +250,12 @@ spec:
hostPath:
path: /var/run/cdi
type: DirectoryOrCreate
{{- if .Values.devicePlugin.hostPIDBroker.enabled }}
- name: hostpid-broker
hostPath:
path: /var/run/hami/hostpid
type: DirectoryOrCreate
{{- end }}
- name: usrbin
hostPath:
path: /usr/bin
Expand Down
4 changes: 4 additions & 0 deletions charts/hami/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,10 @@ devicePlugin:

podAnnotations: {}
hostPID: true
# Let HAMi core ask the device plugin for its host PID.
# This requires hostPID to be true.
hostPIDBroker:
enabled: false
hostNetwork: false
securityContext:
privileged: true
Expand Down
47 changes: 47 additions & 0 deletions cmd/device-plugin/nvidia/hostpid_broker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright (c) 2026 The HAMi Authors.
*/

package main

import (
"os"

"k8s.io/klog/v2"

"github.com/Project-HAMi/HAMi/pkg/device-plugin/nvidiadevice/nvinternal/hostpid"
)

type runningHostPIDBroker struct {
broker *hostpid.Broker
done chan struct{}
serveErr error
}

func startHostPIDBroker() (*runningHostPIDBroker, error) {
if !hostpid.Enabled(os.Getenv(hostpid.EnvironmentVariable)) {
return nil, nil
}
broker, err := hostpid.ListenDefault()
if err != nil {
return nil, err
}
running := &runningHostPIDBroker{
broker: broker,
done: make(chan struct{}),
}
go func() {
running.serveErr = broker.Serve()
close(running.done)
}()
klog.Infof("Host PID broker is listening on %s", hostpid.ServerSocketPath)
return running, nil
}

func (running *runningHostPIDBroker) stop() error {
closeErr := running.broker.Close()
<-running.done
return closeErr
}
25 changes: 25 additions & 0 deletions cmd/device-plugin/nvidia/hostpid_broker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright (c) 2026 The HAMi Authors.
*/

package main

import (
"testing"

"github.com/Project-HAMi/HAMi/pkg/device-plugin/nvidiadevice/nvinternal/hostpid"
)

func TestStartHostPIDBrokerDisabled(t *testing.T) {
for _, value := range []string{"", "0", "true", "false", "01", " 1"} {
t.Run(value, func(t *testing.T) {
t.Setenv(hostpid.EnvironmentVariable, value)
running, err := startHostPIDBroker()
if err != nil || running != nil {
t.Fatalf("running=%v err=%v", running, err)
}
})
}
}
38 changes: 33 additions & 5 deletions cmd/device-plugin/nvidia/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package main

import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -259,7 +260,7 @@ func loadConfig(c *cli.Context, flags []cli.Flag) (*spec.Config, error) {
return config, nil
}

func start(c *cli.Context, o *options) error {
func start(c *cli.Context, o *options) (resultErr error) {
util.NodeName = os.Getenv(util.NodeNameEnvName)
client.InitGlobalClient()

Expand All @@ -271,6 +272,23 @@ func start(c *cli.Context, o *options) error {
}
defer watcher.Close()

hostPIDBroker, err := startHostPIDBroker()
if err != nil {
return fmt.Errorf("failed to start host PID broker: %w", err)
}
var hostPIDBrokerDone <-chan struct{}
hostPIDBrokerFailureReported := false
if hostPIDBroker != nil {
hostPIDBrokerDone = hostPIDBroker.done
defer func() {
stopErr := hostPIDBroker.stop()
if !hostPIDBrokerFailureReported {
stopErr = errors.Join(stopErr, hostPIDBroker.serveErr)
}
resultErr = errors.Join(resultErr, stopErr)
}()
}

Comment thread
iemAnshuman marked this conversation as resolved.
Resolved
/*Loading config files*/
klog.Infof("Start working on node %s", util.NodeName)
klog.Info("Starting OS watcher.")
Expand Down Expand Up @@ -304,6 +322,16 @@ restart:
// some messages, trigger a restart of the plugins, or exit the program.
for {
select {
case <-hostPIDBrokerDone:
hostPIDBrokerFailureReported = true
if hostPIDBroker.serveErr != nil {
resultErr = fmt.Errorf("host PID broker stopped: %w",
hostPIDBroker.serveErr)
} else {
resultErr = errors.New("host PID broker stopped unexpectedly")
}
goto exit

// If the restart timeout has expired, then restart the plugins
case <-restartTimeout:
goto restart
Expand Down Expand Up @@ -336,11 +364,11 @@ restart:
}
}
exit:
err = stopPlugins(plugins)
if err != nil {
return fmt.Errorf("error stopping plugins: %v", err)
if err := stopPlugins(plugins); err != nil {
resultErr = errors.Join(resultErr,
fmt.Errorf("error stopping plugins: %v", err))
}
return nil
return resultErr
}

func startPlugins(c *cli.Context, o *options) ([]plugin.Interface, bool, error) {
Expand Down
141 changes: 141 additions & 0 deletions docs/develop/hostpid-broker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Host PID broker

Status: local draft. The feature is disabled by default.

## Purpose

HAMi-core needs the host PID of each CUDA process because NVML reports processes in the host PID namespace. The current fallback discovers that PID by creating a CUDA primary context while holding the post init lock. That work becomes serial when many processes call `cuInit()` together.

The host PID broker returns the caller's own host PID from Linux `SO_PEERCRED`. It runs inside the NVIDIA device plugin, whose pod already uses the host PID namespace. It does not read host procfs and does not accept a PID supplied by the client.

## Requirements

1. The NVIDIA device plugin must run on Linux as root.

2. `devicePlugin.hostPID` must remain `true`.

3. The workload must use a HAMi-core build that supports protocol version 1 and the `LIBVGPU_HOSTPID_BROKER` gate.

4. The container runtime must support the read only nested bind mount used for `/tmp/vgpulock/hostpid`.

## Enablement

Set the chart value below:

```yaml
devicePlugin:
hostPID: true
hostPIDBroker:
enabled: true
```

The chart rejects a configuration that enables the broker while disabling the device plugin host PID namespace.

When enabled, the chart does four things:

1. It sets `LIBVGPU_HOSTPID_BROKER=1` in the device plugin.

2. It mounts the host directory `/var/run/hami/hostpid` into the device plugin.

3. The device plugin creates `/var/run/hami/hostpid/broker.sock` and serves protocol version 1.

4. Each allocation that receives HAMi-core also receives `LIBVGPU_HOSTPID_BROKER=1` and a read only mount from `/var/run/hami/hostpid` to `/tmp/vgpulock/hostpid`.

No value other than the exact string `1` enables the server or client.

## Protocol

The protocol uses one request and one response on a Unix stream connection. Every integer is unsigned and encoded in network byte order.

| Field | Request bytes | Response bytes |
| --- | ---: | ---: |
| Magic `HPID` | 4 | 4 |
| Version | 2 | 2 |
| Command or status | 2 | 2 |
| Host PID | 0 | 4 |

Protocol version 1 supports command 1, which means get the caller's host PID. Status 0 is success. Status 1 means the request was invalid.

The server reads the peer credentials from the connected socket after validating the request. The client never sends a PID.

## Security boundary

1. The server requires effective UID 0 for its default path.

2. The server directory is owned by root with mode `0711`.

3. A root owned `0600` lock file prevents two brokers from replacing each other.

4. The server rejects symlink directories, symlink lock files, regular file collisions, sockets owned by another UID, and active sockets.

5. The server removes only a stale socket owned by the expected UID. During shutdown it removes the path only if its device and inode still match the socket it created.

6. The workload sees the broker directory through a read only mount. The HAMi-core client checks the directory owner, directory write bits, socket type, socket owner, read only mount flag, and connected peer UID before trusting a response.

7. A caller can request only its own PID. The kernel supplies that identity through `SO_PEERCRED` in the broker's host PID namespace.

The socket is available only to workloads that receive the allocation mount. A workload can still create connection pressure. The server limits active handlers, applies one transaction deadline, and closes excess connections. A client that cannot complete the transaction uses the existing bounded HAMi-core fallback.

## Failure behavior

| Condition | Server behavior | HAMi-core behavior |
| --- | --- | --- |
| Feature disabled | No socket is created | Existing NVML discovery path |
| Server cannot start | Device plugin startup fails | No new allocation is served by that plugin instance |
| Socket missing or stale in a workload | No broker response | Existing NVML discovery path |
| Unsafe owner, mode, mount, or peer UID | Request is not trusted | Existing NVML discovery path |
| Malformed protocol reply | Request fails | Existing NVML discovery path |
| Slow or unresponsive broker | Server and client deadlines close the request | Existing NVML discovery path |
| Broker exits after plugin startup | Device plugin exits with the broker error | Kubernetes restarts the device plugin |

The broker never returns a guessed PID. A successful reply contains the PID supplied by the kernel. Every other outcome is a failure that leaves PID discovery to the existing path.

## Rollout

1. Install the server capable HAMi release with `hostPIDBroker.enabled=false`.

2. Install the compatible HAMi-core library. With no broker mount it uses the existing fallback.

3. Enable `hostPIDBroker.enabled` and wait for every NVIDIA device plugin pod to become ready.

4. Restart or recreate selected workloads so their allocation responses include the broker mount and environment gate.

5. Validate the selected workloads before widening the rollout. Check correct host PID assignment, CUDA context accounting, broker use, and fallback behavior.

Existing workloads do not gain a new mount when the device plugin changes. They continue through their existing path until they are recreated.

## Rollback

1. Set `hostPIDBroker.enabled=false`.

2. Wait for the NVIDIA device plugin rollout.

3. Recreate workloads when the broker mount should be removed. Workloads that still have a compatible broker mount can continue until they exit.

4. A newer HAMi-core with no broker available uses the existing fallback, so the library does not need to be rolled back first.

This rollout contract applies to the broker feature. The separate PR 248 lock migration still requires its own mixed binary policy.

## Validation required before release

1. Go race tests for the broker, lifecycle, and allocation integration.

2. The actual C client to Go server contract test.

3. Missing, stale, unsafe, malformed, slow, saturated, restarting, and dying broker cases.

4. Linux and CUDA builds for HAMi-core plus the client and context accounting tests.

5. Kubernetes validation with the feature disabled, enabled, rolled forward, and rolled back.

6. Concurrent `cuInit()` and first primary context benchmarks with raw output, environment details, source revisions, and checksums.

## Known limits

1. The design depends on Linux `SO_PEERCRED` and a device plugin in the host PID namespace.

2. Sandboxed runtimes must be tested in real execution. A mounted Unix socket may be blocked or may not preserve the peer identity needed by this design.

3. Existing workloads need recreation to receive or remove the allocation mount.

4. Additional NVIDIA architectures, driver versions, CRI-O, rootless runtimes, gVisor, and Kata remain separate compatibility cells until each is tested.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
github.com/stretchr/testify v1.11.1
github.com/urfave/cli/v2 v2.27.7
golang.org/x/net v0.57.0
golang.org/x/sys v0.47.0
golang.org/x/term v0.45.0
golang.org/x/tools v0.48.0
google.golang.org/grpc v1.83.0
Expand Down Expand Up @@ -81,7 +82,6 @@ require (
golang.org/x/mod v0.38.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/telemetry v0.0.0-20260708182218-49f421fb7959 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/time v0.14.0 // indirect
Expand Down
Loading
Loading