Skip to content
Draft
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
10 changes: 8 additions & 2 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,19 @@ cp config.example.yaml ~/.config/hypeman/config.yaml

### Data directory

Hypeman stores data in a configurable directory. Configure permissions for this directory.
Only the daemon account and trusted administrators should be able to write to `data_dir`.

```bash
sudo mkdir /var/lib/hypeman
sudo chown $USER:$USER /var/lib/hypeman
```

The API takes an exclusive lock on `<data_dir>/.hypeman.lock` before loading guest state.
Leave this file in place across restarts; the OS releases the lock when the process exits.
Stop the old API process before upgrading or downgrading, because older versions do not take this lock.

Guest metadata and socket paths use the configured directory name. Stop the guests and the API before moving or remounting the directory or repointing a symlink in its path.

### Dockerhub login

Requires Docker Hub authentication to avoid rate limits when running the tests:
Expand Down Expand Up @@ -271,7 +277,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`.
Use a workspace-local config and data directory instead:
Use a workspace-local config and [data directory](#data-directory) instead:

```bash
mkdir -p .tmp/hypeman-data
Expand Down
5 changes: 4 additions & 1 deletion cmd/api/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,10 @@ func Load(configPath string) (*Config, error) {
}

func (c *Config) expandPathFields() {
c.DataDir = expandHomePath(c.DataDir)
if c.DataDir != "" {
// Direct lookups of data_dir must agree with filepath.Join's handling of "..".
c.DataDir = filepath.Clean(expandHomePath(c.DataDir))
}
c.Build.SecretsDir = expandHomePath(c.Build.SecretsDir)
c.Build.DockerSocket = expandHomePath(c.Build.DockerSocket)
c.Registry.CACertFile = expandHomePath(c.Registry.CACertFile)
Expand Down
46 changes: 46 additions & 0 deletions cmd/api/data_dir_lock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package main

import (
"errors"
"fmt"
"os"
"path/filepath"

"golang.org/x/sys/unix"
)

const dataDirLockName = ".hypeman.lock"

// lockDataDir holds the lock until process exit. Background writers can outlive
// run(), so leave the raw descriptor open on success. Never unlink the file:
// the next opener must lock the same inode.
func lockDataDir(path string) error {
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
name := filepath.Join(path, dataDirLockName)
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0600)
if err != nil {
return &os.PathError{Op: "open", Path: name, Err: err}
}
if err := lockPrivateFile(fd); err != nil {
unix.Close(fd)
return fmt.Errorf("%s: %w", name, err)
}
return nil
}

func lockPrivateFile(fd int) error {
var st unix.Stat_t
if err := unix.Fstat(fd, &st); err != nil {
return err
}
if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0077 != 0 || st.Uid != uint32(os.Geteuid()) {
return errors.New("lock file must be a private regular file owned by the daemon user")
}
err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB)
if errors.Is(err, unix.EWOULDBLOCK) {
return fmt.Errorf("another Hypeman process is using this directory: %w", err)
}
return err
}
99 changes: 99 additions & 0 deletions cmd/api/data_dir_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package main

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

"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)

const lockTestChild = "HYPEMAN_TEST_LOCKED_STARTUP"

func runLockTestChild(t *testing.T, dataDir string) {
t.Helper()
cfg := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(cfg, []byte("jwt_secret: local-test-secret-for-data-dir-lock\n"), 0600))
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^"+t.Name()+"$", "-test.timeout=30s")
cmd.Env = []string{lockTestChild + "=1", "CONFIG_PATH=" + cfg, "DATA_DIR=" + dataDir}
out, err := cmd.CombinedOutput()
require.NoError(t, err, "%s", out)
}

func lockTestFile(t *testing.T, path string) {
t.Helper()
f, err := os.OpenFile(filepath.Join(path, dataDirLockName), os.O_RDWR, 0)
require.NoError(t, err)
t.Cleanup(func() { f.Close() })
require.NoError(t, unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB))
}

func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) {
if os.Getenv(lockTestChild) == "1" {
require.ErrorIs(t, run(), unix.EWOULDBLOCK)
return
}

path := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(path, dataDirLockName), nil, 0600))
lockTestFile(t, path)
alias := filepath.Join(t.TempDir(), "same-data")
require.NoError(t, os.Symlink(path, alias))
runLockTestChild(t, alias)
entries, err := os.ReadDir(path)
require.NoError(t, err)
require.Len(t, entries, 1, "the second API must not initialize or recover anything")
require.Equal(t, dataDirLockName, entries[0].Name())
}

func TestServerKeepsStorageDirectoryLockedUntilExit(t *testing.T) {
if os.Getenv(lockTestChild) == "1" {
require.ErrorIs(t, run(), unix.ENOTDIR)
runtime.GC()
require.ErrorIs(t, lockDataDir(filepath.Clean(os.Getenv("DATA_DIR"))), unix.EWOULDBLOCK)
return
}

path := t.TempDir()
// Fail storage initialization after locking, before the network starts.
require.NoError(t, os.WriteFile(filepath.Join(path, "system"), nil, 0600))
link := filepath.Join(path, "link")
require.NoError(t, os.Symlink(t.TempDir(), link))
runLockTestChild(t, link+"/..") // Preserve the uncleaned path in the child's configuration.
info, err := os.Stat(filepath.Join(path, dataDirLockName))
require.NoError(t, err)
require.Equal(t, os.FileMode(0600), info.Mode())
lockTestFile(t, path)
}

func TestDataDirLockDoesNotSurviveExec(t *testing.T) {
switch os.Getenv(lockTestChild) {
case "1":
require.NoError(t, lockDataDir(os.Getenv("DATA_DIR")))
t.Setenv(lockTestChild, "after-exec")
require.NoError(t, unix.Exec(os.Args[0], os.Args, os.Environ()))
case "after-exec":
lockTestFile(t, os.Getenv("DATA_DIR"))
default:
runLockTestChild(t, filepath.Join(t.TempDir(), "data"))
}
}

func TestDataDirLockRejectsPublicLockFile(t *testing.T) {
dir := t.TempDir()
name := filepath.Join(dir, dataDirLockName)
require.NoError(t, os.WriteFile(name, nil, 0600))
require.NoError(t, os.Chmod(name, 0644))
require.ErrorContains(t, lockDataDir(dir), "private regular file")
}

func TestDataDirLockRejectsSymlink(t *testing.T) {
dir := t.TempDir()
target := filepath.Join(t.TempDir(), "target")
require.NoError(t, os.WriteFile(target, nil, 0600))
require.NoError(t, os.Symlink(target, filepath.Join(dir, dataDirLockName)))
require.ErrorIs(t, lockDataDir(dir), unix.ELOOP)
}
14 changes: 5 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,12 @@ 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)
if err := lockDataDir(cfg.DataDir); err != nil {
return fmt.Errorf("lock data directory %q: %w", cfg.DataDir, err)
}

// Configure GPU profile cache TTL
Expand Down
1 change: 1 addition & 0 deletions config.example.darwin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jwt_secret: dev-secret-change-me
# - "<previous-or-next-secret>"

# Data directory - use macOS conventions
# Stop guests and the API before moving the directory or repointing a symlink in its path.
# Note: ~ is NOT expanded; use full path or let the install script fill this in
data_dir: ~/Library/Application Support/hypeman

Expand Down
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jwt_secret: ""
# - 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

# Data directory (default: /var/lib/hypeman)
# Stop guests and the API before moving the directory or repointing a symlink in its path.
data_dir: /var/lib/hypeman

# Server configuration
Expand Down
28 changes: 20 additions & 8 deletions lib/providers/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"

"github.com/c2h5oh/datasize"
Expand Down Expand Up @@ -58,17 +59,28 @@ func ProvideContext(log *slog.Logger) context.Context {
return logger.AddToContext(context.Background(), log)
}

// ProvideConfig provides the application configuration.
// Panics if configuration is invalid (prevents startup with bad config).
// Config path can be specified via CONFIG_PATH env var or defaults to platform-specific locations.
func ProvideConfig() *config.Config {
configPath := os.Getenv("CONFIG_PATH")
cfg, err := config.Load(configPath)
// ServerConfig loads the configuration once so dependency initialization uses
// the same data directory the API locked before startup.
func ServerConfig() (*config.Config, error) {
return loadServerConfig()
}

var loadServerConfig = sync.OnceValues(func() (*config.Config, error) {
cfg, err := config.Load(os.Getenv("CONFIG_PATH"))
if err != nil {
panic(fmt.Sprintf("failed to load configuration: %v", err))
return nil, fmt.Errorf("load configuration: %w", err)
}
if err := cfg.Validate(); err != nil {
panic(fmt.Sprintf("invalid configuration: %v", err))
return nil, fmt.Errorf("invalid configuration: %w", err)
}
return cfg, nil
})

// ProvideConfig supplies the validated configuration to the dependency graph.
func ProvideConfig() *config.Config {
cfg, err := ServerConfig()
if err != nil {
panic(err)
}
return cfg
}
Expand Down
Loading