Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ The server will start on port 4973 (configurable via `port` in config.yaml).
### Shared-Machine Local Config

When developing on a shared host, avoid global paths like `/etc/hypeman` and `/var/lib/hypeman`.
Only one API process can use a data directory at a time. Stop the old process before upgrading or downgrading; older versions do not take the directory lock.
Use a workspace-local config and data directory instead:

```bash
Expand Down
28 changes: 28 additions & 0 deletions cmd/api/data_dir_lock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"errors"
"fmt"
"os"
"syscall"
)

// Instance metadata locks are process-local. Hold the directory inode locked
// until shutdown, before any startup scan can read and write instance records.
func lockDataDir(path string) (*os.File, error) {
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
dir, err := os.Open(path)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(dir.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
dir.Close()
if errors.Is(err, syscall.EWOULDBLOCK) {
return nil, fmt.Errorf("another Hypeman process is using this directory: %w", err)
}
return nil, err
}
return dir, nil
}
41 changes: 41 additions & 0 deletions cmd/api/data_dir_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

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

"github.com/stretchr/testify/require"
)

func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) {
const subprocess = "HYPEMAN_TEST_LOCKED_STARTUP"
if os.Getenv(subprocess) == "1" {
require.ErrorIs(t, run(), syscall.EWOULDBLOCK)
return
}

path := filepath.Join(t.TempDir(), "data")
owner, err := lockDataDir(path)
require.NoError(t, err)
t.Cleanup(func() { owner.Close() })

alias := filepath.Join(t.TempDir(), "same-data")
require.NoError(t, os.Symlink(path, alias))
cfg := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(cfg, []byte("data_dir: "+alias+"\njwt_secret: local-test-secret-for-data-dir-lock\n"), 0600))
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestServerRefusesSecondWriterBeforeStartup$")
cmd.Env = append(os.Environ(), subprocess+"=1", "CONFIG_PATH="+cfg, "DATA_DIR="+alias)
out, err := cmd.CombinedOutput()
require.NoError(t, err, "%s", out)
entries, err := os.ReadDir(path)
require.NoError(t, err)
require.Empty(t, entries, "the second API must not initialize or recover anything")

require.NoError(t, owner.Close())
next, err := lockDataDir(alias)
require.NoError(t, err)
require.NoError(t, next.Close())
}
19 changes: 10 additions & 9 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/kernel/hypeman/lib/ocicachegc"
"github.com/kernel/hypeman/lib/otel"
"github.com/kernel/hypeman/lib/paths"
"github.com/kernel/hypeman/lib/providers"
"github.com/kernel/hypeman/lib/registry"
"github.com/kernel/hypeman/lib/scopes"
"github.com/kernel/hypeman/lib/tokenrevocation"
Expand Down Expand Up @@ -164,17 +165,17 @@ func run() error {
startupStarted := time.Now()
slog.Info("starting hypeman initialization")

// Load config early for OTel initialization
// Config path can be specified via CONFIG_PATH env var or defaults to platform-specific locations
configPath := os.Getenv("CONFIG_PATH")
cfg, err := config.Load(configPath)
cfg, err := providers.ServerConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
return err
}

// Validate configuration before proceeding
if err := cfg.Validate(); err != nil {
return fmt.Errorf("invalid configuration: %w", err)
dataDir, err := lockDataDir(cfg.DataDir)
if err != nil {
return fmt.Errorf("lock data directory %q: %w", cfg.DataDir, err)
}
defer dataDir.Close()
if err := instances.RecoverParkedForkSources(paths.New(cfg.DataDir)); err != nil {
return fmt.Errorf("recover parked fork sources: %w", err)
}

// Configure GPU profile cache TTL
Expand Down
30 changes: 27 additions & 3 deletions lib/devices/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ type Manager interface {
// MarkDetached marks a device as detached from an instance
MarkDetached(ctx context.Context, deviceID string) error

// ReleaseInstanceDevice detaches and unbinds a passthrough device only if this instance owns it.
ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error

// ReconcileDevices cleans up stale device state on startup.
// It detects devices with AttachedTo referencing non-existent instances
// and clears the orphaned attachment state.
Expand Down Expand Up @@ -322,8 +325,6 @@ func (m *manager) BindToVFIO(ctx context.Context, id string) error {
}

func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
log := logger.FromContext(ctx)

m.mu.Lock()
defer m.mu.Unlock()

Expand All @@ -341,7 +342,11 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
return ErrInUse
}

// Unbind from VFIO
return m.unbindFromVFIOLocked(ctx, device)
}

func (m *manager) unbindFromVFIOLocked(ctx context.Context, device *Device) error {
log := logger.FromContext(ctx)
if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil {
return err
}
Expand Down Expand Up @@ -397,6 +402,25 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error {
return m.saveDevice(device)
}

// ReleaseInstanceDevice checks the recorded owner under the same lock as the unbind.
// A fork's device list can name a passthrough device still owned by its source.
func (m *manager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error {
m.mu.Lock()
defer m.mu.Unlock()
device, err := m.loadDevice(deviceID)
if err != nil {
return err
}
if device.AttachedTo == nil || *device.AttachedTo != instanceID {
return nil
}
device.AttachedTo = nil
if err := m.saveDevice(device); err != nil {
return err
}
return m.unbindFromVFIOLocked(ctx, device)
}

// ReconcileDevices cleans up stale device state on startup.
// It performs safe-by-default reconciliation:
// 1. Detects orphaned device attachments (instance missing or not running)
Expand Down
15 changes: 15 additions & 0 deletions lib/devices/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,21 @@ func TestDeviceLookupAndDeleteRejectPathTraversal(t *testing.T) {
require.FileExists(t, marker)
}

func TestReleaseInstanceDeviceClearsItsOwnAttachment(t *testing.T) {
p := paths.New(t.TempDir())
m := NewManager(p).(*manager)
owner := "fork"
device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner}
require.NoError(t, os.MkdirAll(p.DeviceDir(device.Id), 0755))
require.NoError(t, m.saveDevice(device))

// There is no hardware to unbind. Detachment must still persist.
require.Error(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner))
got, err := m.loadDevice(device.Id)
require.NoError(t, err)
require.Nil(t, got.AttachedTo)
}

func TestSaveLoadDevice_MetadataRoundTrip(t *testing.T) {
p := paths.New(t.TempDir())
mgr := &manager{
Expand Down
14 changes: 13 additions & 1 deletion lib/hypervisor/firecracker/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,18 @@ func cleanupFailedRestore(pid int, socketPath string) {
_ = os.Remove(socketPath)
}

// ForkBackupSeparator separates a parked snapshot source from its UnixNano suffix.
const ForkBackupSeparator = ".fork-bak."

// SnapshotSourceAlias returns the source path recorded for the fallback, if any.
func SnapshotSourceAlias(instanceDir string) (string, error) {
meta, err := loadRestoreMetadata(instanceDir)
if err != nil {
return "", err
}
return meta.SnapshotSourceDataDir, nil
}

func withSnapshotSourceDirAlias(meta *restoreMetadata, targetDataDir string, run func() error) error {
if meta == nil || meta.SnapshotSourceDataDir == "" {
return run()
Expand All @@ -239,7 +251,7 @@ func withSnapshotSourceDirAlias(meta *restoreMetadata, targetDataDir string, run

backupDataDir := ""
if _, err := os.Stat(sourceDataDir); err == nil {
backupDataDir = fmt.Sprintf("%s.fork-bak.%d", sourceDataDir, time.Now().UnixNano())
backupDataDir = fmt.Sprintf("%s%s%d", sourceDataDir, ForkBackupSeparator, time.Now().UnixNano())
if err := os.Rename(sourceDataDir, backupDataDir); err != nil {
return fmt.Errorf("backup snapshot source data dir: %w", err)
}
Expand Down
11 changes: 2 additions & 9 deletions lib/instances/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,15 +173,8 @@ func (m *manager) deleteInstanceWithOptions(
if len(inst.Devices) > 0 && m.deviceManager != nil {
for _, deviceID := range inst.Devices {
log.DebugContext(ctx, "detaching device", "id", id, "device", deviceID)
// Mark device as detached
if err := m.deviceManager.MarkDetached(ctx, deviceID); err != nil {
log.WarnContext(ctx, "failed to mark device as detached", "id", id, "device", deviceID, "error", err)
}
// Auto-unbind from VFIO so native driver can reclaim it
log.InfoContext(ctx, "auto-unbinding device from VFIO", "id", id, "device", deviceID)
if err := m.deviceManager.UnbindFromVFIO(ctx, deviceID); err != nil {
// Log but continue - device might already be unbound or in use by another instance
log.WarnContext(ctx, "failed to unbind device from VFIO", "id", id, "device", deviceID, "error", err)
if err := m.deviceManager.ReleaseInstanceDevice(ctx, deviceID, id); err != nil {
log.WarnContext(ctx, "failed to release passthrough device", "instance_id", id, "device", deviceID, "error", err)
}
}
}
Expand Down
126 changes: 126 additions & 0 deletions lib/instances/fork_alias_recovery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package instances

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"

"github.com/kernel/hypeman/lib/hypervisor"
"github.com/kernel/hypeman/lib/hypervisor/firecracker"
"github.com/kernel/hypeman/lib/paths"
)

// RecoverParkedForkSources puts back directories renamed by Firecracker's
// snapshot alias fallback. Call under the data directory lock, before even
// listing instances: a lookup by source ID would otherwise read the fork.
func RecoverParkedForkSources(p *paths.Paths) error {
entries, err := os.ReadDir(p.GuestsDir())
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
backups := make(map[string]string)
for _, entry := range entries {
id, stamp, found := strings.Cut(entry.Name(), firecracker.ForkBackupSeparator)
if !found || !entry.IsDir() {
continue
}
if _, err := strconv.ParseUint(stamp, 10, 63); err != nil {
continue
}
if err := paths.ValidatePathComponent(id); err != nil {
return fmt.Errorf("invalid source ID in backup %q", entry.Name())
}
if other, ok := backups[id]; ok {
return fmt.Errorf("ambiguous backups for %q: %q and %q", id, other, entry.Name())
}
backups[id] = entry.Name()
}
for id, backup := range backups {
if err := restoreParkedForkSource(p, id, backup); err != nil {
return fmt.Errorf("restore %s from %s: %w", id, backup, err)
}
}
if len(backups) > 0 {
return syncDir(p.GuestsDir())
}
return nil
}

func restoreParkedForkSource(p *paths.Paths, id, backup string) error {
parked, err := readForkRecoveryMetadata(p, backup, id)
if err != nil {
return err
}
if parked.ForkPending != nil && !parked.ForkPending.gone() {
return fmt.Errorf("parked source has a live fork owner")
}
source := p.InstanceDir(id)
link, err := os.Readlink(source)
switch {
case err == nil:
if err := verifyForkAlias(p, source, link); err != nil {
return err
}
if err := os.Remove(source); err != nil {
return err
}
case os.IsNotExist(err):
// A kill before creating the link or after removing it leaves only the backup.
default:
return err // Never replace an ordinary source directory.
}
return os.Rename(p.InstanceDir(backup), source)
}

func verifyForkAlias(p *paths.Paths, source, link string) error {
if !filepath.IsAbs(link) {
link = filepath.Join(p.GuestsDir(), link)
}
id := filepath.Base(link)
if link != p.InstanceDir(id) || link == source {
return fmt.Errorf("unexpected source alias target %q", link)
}
info, err := os.Lstat(link)
if err != nil {
return err
}
if !info.IsDir() {
return fmt.Errorf("alias target %q is not a guest directory", link)
}
target, err := readForkRecoveryMetadata(p, id, id)
if err != nil {
return err
}
if target.HypervisorType != hypervisor.TypeFirecracker || (target.ForkPending != nil && !target.ForkPending.gone()) {
return fmt.Errorf("alias target %q is not an abandoned Firecracker restore", link)
}
recorded, err := firecracker.SnapshotSourceAlias(link)
if err != nil {
return err
}
if filepath.Clean(recorded) != source {
return fmt.Errorf("target records source %q, not %q", recorded, source)
}
return nil
}

func readForkRecoveryMetadata(p *paths.Paths, dirID, expectedID string) (*StoredMetadata, error) {
data, err := os.ReadFile(p.InstanceMetadata(dirID))
if err != nil {
return nil, err
}
var meta StoredMetadata
if err := json.Unmarshal(data, &meta); err != nil {
return nil, err
}
if meta.Id != expectedID {
return nil, fmt.Errorf("metadata in %q names %q, expected %q", dirID, meta.Id, expectedID)
}
return &meta, nil
}
6 changes: 1 addition & 5 deletions lib/instances/fork_pending_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,16 +290,12 @@ type detachGateDeviceManager struct {
release chan struct{}
}

func (m detachGateDeviceManager) MarkDetached(ctx context.Context, deviceID string) error {
func (m detachGateDeviceManager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error {
m.arrived <- deviceID
<-m.release
return nil
}

func (m detachGateDeviceManager) UnbindFromVFIO(ctx context.Context, id string) error {
return nil
}

// A restart that interrupts a burst of forks must not delete them one at a
// time: the API does not listen until recovery returns.
func TestRecoverInterruptedForksDeletesConcurrently(t *testing.T) {
Expand Down
Loading
Loading