Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The HAMi Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

// Package containerconfig defines the per-container GPU allocation config that
// the NVIDIA device plugin writes to disk during Allocate so that libvgpu.so
// can recover GPU limits even when process environment variables have been
// scrubbed by SSH, su, sudo, or login shells (issue #2125).
package containerconfig

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)

// Version is the schema version written into every config.json.
// Increment when making backward-incompatible changes to the struct layout
// so that libvgpu.so can detect and handle old vs new files correctly.
const Version = 1

// Filename is the name of the per-container config file written into the
// container's cache directory. It is a deliberately short, fixed name so that
// libvgpu.so can locate it without any additional coordination.
const Filename = "config.json"

// DeviceLimitConfig holds the resource constraints for a single GPU device
// allocated to a container.
//
// WHY a struct per device: a container can request multiple physical GPUs.
// Each GPU gets its own memory and core limits, so they must be stored
// individually rather than as a single aggregate.
type DeviceLimitConfig struct {
// Index is the 0-based device slot index within this container's allocation
// (matches the suffix of CUDA_DEVICE_MEMORY_LIMIT_<index>).
Index int `json:"index"`

// UUID is the physical GPU UUID string (e.g. "GPU-xxxxxxxx-...").
// libvgpu.so can cross-check this against the device it detects at runtime
// to ensure it is applying limits to the correct GPU.
UUID string `json:"uuid"`

// MemoryLimitMB is the GPU memory quota for this device in mebibytes
// (matches the numeric part of CUDA_DEVICE_MEMORY_LIMIT_<index>=NNNm).
MemoryLimitMB int32 `json:"memory_limit_mb"`

// SMLimit is the GPU compute utilisation limit, expressed as a percentage
// of streaming-multiprocessor throughput (0 = unlimited).
// Matches CUDA_DEVICE_SM_LIMIT.
SMLimit int32 `json:"sm_limit_percent"`
}

// ContainerConfig is the complete allocation record written to config.json.
// It mirrors every environment variable that the device plugin injects so that
// processes with a clean environment (SSH logins, su/sudo shells, child
// processes started with an explicit empty env) can still recover the full
// isolation policy directly from the filesystem.
//
// Backward compatibility: all env-var injection in Allocate is kept unchanged.
// This file is additive — it provides a second, env-independent path to the
// same information.
type ContainerConfig struct {
// Version is the schema version (currently 1).
// libvgpu.so should reject or warn on versions it does not understand.
Version int `json:"version"`

// PodUID is the Kubernetes pod UID for operator diagnostics.
PodUID string `json:"pod_uid"`

// ContainerName is the Kubernetes container name within the pod.
ContainerName string `json:"container_name"`

// Devices lists the per-GPU constraints in ascending index order.
Devices []DeviceLimitConfig `json:"devices"`

// SharedCachePath is the path of the shared-memory tracker file
// (the value of CUDA_DEVICE_MEMORY_SHARED_CACHE).
// All processes within the container must attach to the same cache file so
// that their aggregate allocations are correctly accounted.
SharedCachePath string `json:"shared_cache_path"`

// Oversubscribe indicates whether memory over-subscription is enabled
// (true when DeviceMemoryScaling > 1; matches CUDA_OVERSUBSCRIBE=true).
Oversubscribe bool `json:"oversubscribe"`

// DisableCoreLimit, when true, means compute-utilisation enforcement is
// intentionally disabled (GPU_CORE_UTILIZATION_POLICY=disable).
DisableCoreLimit bool `json:"disable_core_limit"`

// LogLevel is the optional logging verbosity forwarded from the scheduler
// config (LIBCUDA_LOG_LEVEL). Empty string means default.
LogLevel string `json:"log_level,omitempty"`
}

// WriteConfig serialises cfg as JSON and writes it atomically to
// directory/config.json with permissions 0644.
//
// WHY 0644 and not 0600 or 0777:
// - 0644 allows any UID inside the container (including non-root users and
// SSH-spawned shells) to read the file.
// - The file contains no secrets — only resource limits that the container
// is already entitled to know (they are also in its environment).
// - Write permission is root-only (the device plugin runs as root) to
// prevent container processes from tampering with their own limits.
//
// WHY atomic write (temp file + rename):
// - libvgpu.so may open this file at any point after container start.
// - A direct os.WriteFile leaves the file half-written during the syscall.
// - A rename from a temp file on the same filesystem is atomic on Linux,
// so the reader always sees either the complete old file or the complete
// new file, never a partial write.
func WriteConfig(directory string, cfg ContainerConfig) error {
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("marshal container config: %w", err)
}

// Write to a sibling temp file first so the rename is intra-directory
// (same filesystem mount) and therefore atomic on Linux.
tmpPath := filepath.Join(directory, ".config.json.tmp")
if err := os.WriteFile(tmpPath, data, 0644); err != nil {
return fmt.Errorf("write container config temp file: %w", err)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Explicitly chmod 0644 so the file mode is not restricted by a process umask (e.g. 0077),
// guaranteeing that non-root container users (like SSH sessions) can always read the config.
if err := os.Chmod(tmpPath, 0644); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("chmod container config temp file: %w", err)
}

finalPath := filepath.Join(directory, Filename)
if err := os.Rename(tmpPath, finalPath); err != nil {
_ = os.Remove(tmpPath) // best-effort cleanup of the orphaned temp file
return fmt.Errorf("rename container config into place: %w", err)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//go:build !windows
Comment thread
SanyamRana marked this conversation as resolved.
Resolved

/*
* SPDX-License-Identifier: Apache-2.0
*
* The HAMi Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package containerconfig

import (
"os"
"path/filepath"
"syscall"
"testing"
)

// TestWriteConfig_RestrictiveUmask verifies that WriteConfig explicitly applies
// mode 0644 so config.json remains world-readable even when the process has a
// restrictive umask (e.g. 0077 or 0027).
func TestWriteConfig_RestrictiveUmask(t *testing.T) {
// Set a very restrictive umask (0077 -> removes group and other permissions).
oldMask := syscall.Umask(0077)
defer syscall.Umask(oldMask)

dir := t.TempDir()
cfg := ContainerConfig{
Version: Version,
PodUID: "uid-umask-test",
ContainerName: "ctr",
Devices: []DeviceLimitConfig{{Index: 0, UUID: "GPU-UMASK", MemoryLimitMB: 1000, SMLimit: 100}},
SharedCachePath: "/tmp/u.cache",
}

if err := WriteConfig(dir, cfg); err != nil {
t.Fatalf("WriteConfig: %v", err)
}

info, err := os.Stat(filepath.Join(dir, Filename))
if err != nil {
t.Fatalf("stat config.json: %v", err)
}

// Because of explicit os.Chmod(..., 0644), the file must be 0644 despite umask 0077.
const wantMode = 0644
if got := info.Mode().Perm(); got != wantMode {
t.Errorf("file permissions with restrictive umask (0077): got %o, want %o", got, wantMode)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The HAMi Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package containerconfig

import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"testing"
)

func TestWriteConfig_HappyPath(t *testing.T) {
dir := t.TempDir()

cfg := ContainerConfig{
Version: Version,
PodUID: "pod-uid-abc",
ContainerName: "my-container",
Devices: []DeviceLimitConfig{
{Index: 0, UUID: "GPU-1234", MemoryLimitMB: 3000, SMLimit: 50},
{Index: 1, UUID: "GPU-5678", MemoryLimitMB: 4000, SMLimit: 80},
},
SharedCachePath: "/usr/local/vgpu/abc.cache",
Oversubscribe: false,
DisableCoreLimit: false,
LogLevel: "info",
}

if err := WriteConfig(dir, cfg); err != nil {
t.Fatalf("WriteConfig returned unexpected error: %v", err)
}

data, err := os.ReadFile(filepath.Join(dir, Filename))
if err != nil {
t.Fatalf("config.json not found after write: %v", err)
}

var got ContainerConfig
if err := json.Unmarshal(data, &got); err != nil {
t.Fatalf("config.json is not valid JSON: %v", err)
}

if got.Version != Version {
t.Errorf("version: got %d, want %d", got.Version, Version)
}
if got.PodUID != cfg.PodUID {
t.Errorf("pod_uid: got %q, want %q", got.PodUID, cfg.PodUID)
}
if got.ContainerName != cfg.ContainerName {
t.Errorf("container_name: got %q, want %q", got.ContainerName, cfg.ContainerName)
}
if len(got.Devices) != 2 {
t.Fatalf("devices length: got %d, want 2", len(got.Devices))
}
if got.Devices[0].MemoryLimitMB != 3000 {
t.Errorf("devices[0].memory_limit_mb: got %d, want 3000", got.Devices[0].MemoryLimitMB)
}
if got.Devices[1].MemoryLimitMB != 4000 {
t.Errorf("devices[1].memory_limit_mb: got %d, want 4000", got.Devices[1].MemoryLimitMB)
}
if got.SharedCachePath != cfg.SharedCachePath {
t.Errorf("shared_cache_path: got %q, want %q", got.SharedCachePath, cfg.SharedCachePath)
}
}

// TestWriteConfig_FilePermissions verifies config.json is written 0644 so
// non-root users (SSH logins) can read it.
func TestWriteConfig_FilePermissions(t *testing.T) {
dir := t.TempDir()
cfg := ContainerConfig{
Version: Version,
PodUID: "uid-perm-test",
ContainerName: "ctr",
Devices: []DeviceLimitConfig{{Index: 0, UUID: "GPU-PERM", MemoryLimitMB: 1000, SMLimit: 100}},
SharedCachePath: "/tmp/x.cache",
}

if err := WriteConfig(dir, cfg); err != nil {
t.Fatalf("WriteConfig: %v", err)
}

info, err := os.Stat(filepath.Join(dir, Filename))
if err != nil {
t.Fatalf("stat config.json: %v", err)
}

if runtime.GOOS == "windows" {
t.Skip("skipping POSIX file permission bit check on Windows")
}

// 0644: world-readable so SSH-spawned non-root shells can open the file.
const wantMode = 0644
if got := info.Mode().Perm(); got != wantMode {
t.Errorf("file permissions: got %o, want %o", got, wantMode)
}
}

// TestWriteConfig_Idempotent verifies that calling WriteConfig twice overwrites
// the first file cleanly (no stale partial state).
func TestWriteConfig_Idempotent(t *testing.T) {
dir := t.TempDir()

write := func(mem int32) {
cfg := ContainerConfig{
Version: Version,
PodUID: "uid-idem",
ContainerName: "ctr",
Devices: []DeviceLimitConfig{{Index: 0, UUID: "GPU-X", MemoryLimitMB: mem, SMLimit: 50}},
SharedCachePath: "/tmp/y.cache",
}
if err := WriteConfig(dir, cfg); err != nil {
t.Fatalf("WriteConfig(%d): %v", mem, err)
}
}

write(1000)
write(2000)

data, _ := os.ReadFile(filepath.Join(dir, Filename))
var got ContainerConfig
_ = json.Unmarshal(data, &got)
if got.Devices[0].MemoryLimitMB != 2000 {
t.Errorf("expected second write (2000m) to win; got %dm", got.Devices[0].MemoryLimitMB)
}
}

// TestWriteConfig_NonExistentDir verifies WriteConfig returns an error for a
// missing directory rather than panicking.
func TestWriteConfig_NonExistentDir(t *testing.T) {
if err := WriteConfig("/this/path/does/not/exist", ContainerConfig{}); err == nil {
t.Error("expected error for non-existent directory, got nil")
}
}

// TestWriteConfig_OversubscribeFlag verifies the oversubscribe field is
// faithfully preserved (controls libvgpu.so behaviour when scaling > 1).
func TestWriteConfig_OversubscribeFlag(t *testing.T) {
dir := t.TempDir()
cfg := ContainerConfig{
Version: Version,
PodUID: "uid-over",
ContainerName: "ctr-over",
Devices: []DeviceLimitConfig{{Index: 0, UUID: "GPU-O", MemoryLimitMB: 5000, SMLimit: 100}},
SharedCachePath: "/tmp/o.cache",
Oversubscribe: true,
}
if err := WriteConfig(dir, cfg); err != nil {
t.Fatalf("WriteConfig: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, Filename))
var got ContainerConfig
_ = json.Unmarshal(data, &got)
if !got.Oversubscribe {
t.Error("oversubscribe: expected true, got false")
}
}
Loading
Loading