Skip to content
Closed
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
20 changes: 18 additions & 2 deletions lib/devices/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
}

log := logger.FromContext(ctx)
if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil {
if err := m.unbindAndVerify(device.PCIAddress); err != nil {
return err
}

Expand Down Expand Up @@ -414,6 +414,22 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error {
return m.saveDevice(device)
}

// The driver probe can bind the device straight back to vfio-pci. Check
// sysfs before recording the release or dropping the owner that can retry it.
func (m *manager) unbindAndVerify(pciAddress string) error {
if err := m.vfioBinder.UnbindFromVFIO(pciAddress); err != nil {
return err
}
bound, err := m.vfioBinder.deviceBoundToVFIO(pciAddress)
if err != nil {
return fmt.Errorf("verify VFIO release of %s: %w", pciAddress, err)
}
if bound {
return fmt.Errorf("device %s is still bound to vfio-pci", pciAddress)
}
return nil
}

// 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 {
Expand All @@ -427,7 +443,7 @@ func (m *manager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceI
return nil
}
// A retry after the unbind but before the save sees ErrNotBound.
if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) {
if err := m.unbindAndVerify(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) {
return err
}
device.AttachedTo = nil
Expand Down
32 changes: 23 additions & 9 deletions lib/devices/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,28 +185,36 @@ func TestDeviceLookupAndDeleteRejectPathTraversal(t *testing.T) {

type releaseTestBinder struct {
*VFIOBinder
unbind func(string) error
unbind func(string) error
bound bool
inspectErr error
}

func (b releaseTestBinder) UnbindFromVFIO(addr string) error { return b.unbind(addr) }
func (b *releaseTestBinder) UnbindFromVFIO(addr string) error { return b.unbind(addr) }
func (b *releaseTestBinder) deviceBoundToVFIO(string) (bool, error) {
return b.bound, b.inspectErr
}

func TestReleaseInstanceDeviceKeepsOwnerUntilUnbound(t *testing.T) {
for _, tc := range []struct {
name string
unbindErr error
bound bool
inspectErr error
retryResult error
}{
{"unbind", nil},
{"already-unbound", ErrNotBound},
{name: "unbind failed", unbindErr: errors.New("device busy")},
{name: "rebound after probe", bound: true},
{name: "binding unreadable", inspectErr: errors.New("sysfs unavailable"), retryResult: ErrNotBound},
} {
t.Run(tc.name, func(t *testing.T) {
m, p, _ := setupTestManager(t)
owner := "fork"
device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner, BoundToVFIO: true}
createTestDevice(t, p, device)
busy := errors.New("device busy")
result := busy
result := tc.unbindErr
var calls int
m.vfioBinder = releaseTestBinder{unbind: func(addr string) error {
binder := &releaseTestBinder{bound: tc.bound, inspectErr: tc.inspectErr, unbind: func(addr string) error {
calls++
require.Equal(t, device.PCIAddress, addr)
stored, err := m.loadDevice(device.Id)
Expand All @@ -215,8 +223,14 @@ func TestReleaseInstanceDeviceKeepsOwnerUntilUnbound(t *testing.T) {
return result
}}

require.ErrorIs(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner), busy)
result = tc.retryResult
m.vfioBinder = binder
require.Error(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner))
kept, err := m.loadDevice(device.Id)
require.NoError(t, err)
require.Equal(t, &owner, kept.AttachedTo)
require.True(t, kept.BoundToVFIO)

result, binder.bound, binder.inspectErr = tc.retryResult, false, nil
require.NoError(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner))
require.Equal(t, 2, calls)
got, err := m.loadDevice(device.Id)
Expand Down
2 changes: 1 addition & 1 deletion lib/devices/vfio_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (v *VFIOBinder) UnbindFromVFIO(pciAddress string) error {

// Clear driver override first
if err := v.setDriverOverride(pciAddress, ""); err != nil {
// Non-fatal, continue with unbind
return fmt.Errorf("clear VFIO driver override: %w", err)
}

// Unbind from vfio-pci
Expand Down
25 changes: 18 additions & 7 deletions lib/hypervisor/vz_shim_pids.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,29 @@ import (
"strings"
)

// vzShimPIDsFromPS returns the PIDs in `ps -o pid=,command=` output whose
// vz-shim configuration names socketPath as its control socket.
// Match the kernel's process name as well as the control socket in the
// shim's -config argument. Other processes can mention that socket in argv.
func vzShimPIDsFromPS(out []byte, socketPath string) []int {
quoted, _ := json.Marshal(socketPath) // a string always marshals
marker := `"control_socket":` + string(quoted)
var pids []int
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) < 2 || !strings.Contains(line, " -config ") || !strings.Contains(line, marker) {
command, arg, ok := strings.Cut(line, " -config ")
if !ok {
continue
}
if pid, err := strconv.Atoi(fields[0]); err == nil {
fields := strings.Fields(command)
if len(fields) < 3 {
continue
}
if name := fields[1]; name != "vz-shim" && !strings.HasPrefix(name, "vz-shim-") {
continue
}
var config struct {
ControlSocket string `json:"control_socket"`
}
if err := json.Unmarshal([]byte(arg), &config); err != nil || config.ControlSocket != socketPath {
continue
}
if pid, err := strconv.Atoi(fields[0]); err == nil && pid > 0 {
pids = append(pids, pid)
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/hypervisor/vz_shim_pids_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
func VZShimPIDs(socketPath string) ([]int, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,command=").Output()
out, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,ucomm=,command=").Output()
if err != nil {
return nil, fmt.Errorf("list processes: %w", err)
}
Expand Down
9 changes: 5 additions & 4 deletions lib/hypervisor/vz_shim_pids_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ func TestVZShimPIDsFromPS(t *testing.T) {
require.NoError(t, err)
return string(data)
}
out := " 101 /tmp/vz-shim-1 -config " + config("/data/guests/a/vz.sock") + "\n" +
" 202 /tmp/vz-shim-2 -config " + config("/data/guests/b/vz.sock") + "\n" +
" 303 grep control_socket\n" +
" 404 /tmp/vz-shim-3 -config " + config("/data/guests/a/vz.sock") + "\n"
out := " 101 vz-shim-1 /tmp/with spaces/vz-shim-1 -config " + config("/data/guests/a/vz.sock") + "\n" +
" 202 vz-shim-2 /tmp/vz-shim-2 -config " + config("/data/guests/b/vz.sock") + "\n" +
" 303 editor editor -config " + config("/data/guests/a/vz.sock") + "\n" +
" 404 vz-shim /tmp/vz-shim -config " + config("/data/guests/a/vz.sock") + "\n" +
` 505 vz-shim-4 /tmp/vz-shim-4 -config {"nested":{"control_socket":"/data/guests/a/vz.sock"}}`
require.Equal(t, []int{101, 404}, vzShimPIDsFromPS([]byte(out), "/data/guests/a/vz.sock"))
require.Empty(t, vzShimPIDsFromPS([]byte(out), "/data/guests/c/vz.sock"))
require.Empty(t, vzShimPIDsFromPS([]byte(out), "/data/guests/a/vz"), "a socket path prefix does not match")
Expand Down
16 changes: 16 additions & 0 deletions lib/instances/fork.go
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,22 @@ func (m *manager) forkOwnerGone(owner ForkOwner) bool {
return owner.gone()
}

// Public boot requests must not take over a fork that can still be discarded.
// The fork's own start/restore transitions use refuseAbandonedFork instead.
func (m *manager) loadMetadataForBootRequest(id string) (*metadata, error) {
meta, err := m.loadMetadata(id)
if err != nil {
return nil, err
}
if meta.ForkPending == nil {
return meta, nil
}
if err := m.refuseAbandonedFork(&meta.StoredMetadata); err != nil {
return nil, err
}
return nil, fmt.Errorf("%w: fork request has not completed", ErrInvalidState)
}

// refuseAbandonedFork keeps a fork that is waiting to be deleted from being
// brought up. Such a fork is still marked, so the next start deletes it, and
// until then it looks like any other instance under the name its caller asked
Expand Down
35 changes: 35 additions & 0 deletions lib/instances/lifecycle_noop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,39 @@ func TestLifecycleNoopTransitionsReturnCurrentInstanceWithoutEvent(t *testing.T)
}
}

func TestPublicBootRejectsPendingForkBeforeFastPaths(t *testing.T) {
for _, state := range []State{StatePaused, StateRunning, StateInitializing} {
for kind, owner := range map[string]*ForkOwner{"in-flight": currentForkOwner(), "abandoned": {}} {
t.Run(string(state)+"/"+kind, func(t *testing.T) {
m, id := newLifecycleNoopManagerWithInstance(t, state, time.Now().UTC())
meta, err := m.loadMetadata(id)
require.NoError(t, err)
meta.ForkPending = owner
meta.RestartStatus.BlockedReason = restartpolicy.BlockedReasonManualStop
require.NoError(t, m.saveMetadata(meta))
events, cancel := m.SubscribeLifecycleEvents(LifecycleEventConsumerWaitForState)
defer cancel()

_, err = m.RestoreInstance(t.Context(), id)
require.ErrorIs(t, err, ErrInvalidState)
_, err = m.RestartInstance(t.Context(), id)
require.ErrorIs(t, err, ErrInvalidState)
require.ErrorContains(t, err, "fork")
for _, req := range []StartInstanceRequest{{}, {Cmd: []string{"true"}}} {
_, err = m.StartInstance(t.Context(), id, req)
require.ErrorIs(t, err, ErrInvalidState)
require.ErrorContains(t, err, "fork")
}
got, err := m.getInstance(t.Context(), id)
require.NoError(t, err)
require.Equal(t, state, got.State)
require.Equal(t, meta.RestartStatus, got.RestartStatus)
assertNoLifecycleEvent(t, events)
})
}
}
}

func TestLifecycleNoopStartWithOverridesStillRejectsActiveInstance(t *testing.T) {
m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC())
events, cancel := m.SubscribeLifecycleEvents(LifecycleEventConsumerWaitForState)
Expand Down Expand Up @@ -415,6 +448,8 @@ func newLifecycleNoopManagerWithInstance(t *testing.T, state State, now time.Tim
writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StateRunning)
case StateInitializing:
writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StateRunning)
case StatePaused:
writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StatePaused)
case StateStandby:
writeLifecycleNoopSnapshot(t, p, id)
}
Expand Down
3 changes: 1 addition & 2 deletions lib/instances/macos.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,7 @@ func sameMACAddress(a, b string) bool {
return bytes.Equal(x, y)
}

// vzShimOwner finds the vz-shim for socketPath when no live shim PID is recorded,
// as after the API dies mid-boot or mid-restore. More than one is ambiguous.
// vzShimOwner finds the unique vz-shim configured for socketPath, even before it listens.
func vzShimOwner(socketPath string) (int, error) {
if socketPath == "" {
return 0, nil
Expand Down
18 changes: 18 additions & 0 deletions lib/instances/macos_boot_admission_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ func (s *macOSBootAdmissionStarter) StartVM(_ context.Context, _ *paths.Paths, _
return os.Getpid(), lifecycleNoopHypervisor{state: hypervisor.StateRunning}, nil
}

func TestMacOSBootAdmissionSkipsOnlyForeignMetadata(t *testing.T) {
p := paths.New(t.TempDir())
m := &manager{paths: p}
guest := &StoredMetadata{Id: "guest", SocketPath: p.InstanceSocket("guest", "vz.sock"), MacOS: testMacImage().MacOS, NetworkEnabled: true}
require.NoError(t, m.ensureDirectories("partial-copy"))
path := p.InstanceMetadata("partial-copy")
require.NoError(t, os.WriteFile(path, []byte(`{"Id":"old-source","MAC":"02:00:00:00:00:01"}`), 0644))
require.NoError(t, m.checkMacOSBootAvailable(t.Context(), guest))
macs, err := m.storedMACs(guest.Id)
require.NoError(t, err)
require.Empty(t, macs)

for _, invalid := range []string{`{`, `{}`} {
require.NoError(t, os.WriteFile(path, []byte(invalid), 0644))
require.Error(t, m.checkMacOSBootAvailable(t.Context(), guest))
}
}

func TestMacOSConcurrentBootsRecheckMACUnderBootLock(t *testing.T) {
p := paths.New(t.TempDir())
m := &manager{paths: p}
Expand Down
8 changes: 4 additions & 4 deletions lib/instances/macos_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ func prepareMacOSClone(clone *StoredMetadata) error {
}

// forEachOtherInstance calls fn with the metadata of every stored instance except
// exclude, stopping at fn's first error. Directories without metadata are skipped;
// any other load error is wrapped with loadErrorContext when it is set.
// exclude, stopping at fn's first error. Directories without their own metadata
// are skipped; unreadable records fail admission.
func (m *manager) forEachOtherInstance(exclude, loadErrorContext string, fn func(*metadata) error) error {
entries, err := os.ReadDir(m.paths.GuestsDir())
if err != nil {
Expand All @@ -78,8 +78,8 @@ func (m *manager) forEachOtherInstance(exclude, loadErrorContext string, fn func
continue
}
meta, err := m.loadMetadata(entry.Name())
if errors.Is(err, ErrNotFound) {
// A create in progress or a leftover directory has no instance to admit against.
if errors.Is(err, ErrNotFound) || errors.Is(err, errMetadataIDMismatch) {
// An incomplete copy is not another instance claiming this identity.
continue
}
if err != nil {
Expand Down
26 changes: 14 additions & 12 deletions lib/instances/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -618,25 +618,26 @@ func (m *manager) RestoreInstance(ctx context.Context, id string) (*Instance, er
lock := m.getInstanceLock(id)
lock.Lock()
defer lock.Unlock()
current, err := m.currentInstanceWithoutHydration(ctx, id)
meta, err := m.loadMetadataForBootRequest(id)
if err != nil {
return nil, err
}
current := m.toInstanceWithoutHydration(ctx, meta)
if current.State == StateRunning || current.State == StateInitializing {
// A running macOS guest has consumed its checkpoint. One still on disk means an
// earlier resume failed before removing it, so finish that resume now.
if current.MacOS != nil && current.HasSnapshot {
// Initializing without a control socket is a shim still loading the VM. It has
// not resumed, so the checkpoint it will consume must stay.
if current.State == StateInitializing && !m.macOSSocketAnswers(ctx, current) {
if current.State == StateInitializing && !m.macOSSocketAnswers(ctx, &current) {
return nil, fmt.Errorf("%w: macOS restore is still loading the VM; retry shortly", ErrInvalidState)
}
if err := m.finishMacOSResume(id); err != nil {
return nil, fmt.Errorf("finish resumed restore: %w", err)
}
return m.currentInstanceWithoutHydration(ctx, id)
}
return current, nil
return &current, nil
}
if current.State == StatePaused {
hv, err := m.getHypervisor(current.SocketPath, current.HypervisorType)
Expand All @@ -658,12 +659,12 @@ func (m *manager) RestoreInstance(ctx context.Context, id string) (*Instance, er
return nil, fmt.Errorf("finish resumed restore: %w", err)
}
}
current, err = m.currentInstanceWithoutHydration(ctx, id)
resumed, err := m.currentInstanceWithoutHydration(ctx, id)
if err != nil {
return nil, err
}
m.notifyLifecycleEvent(ctx, LifecycleEventRestore, current)
return current, nil
m.notifyLifecycleEvent(ctx, LifecycleEventRestore, resumed)
return resumed, nil
}
inst, err := m.restoreInstance(ctx, id)
if err == nil {
Expand Down Expand Up @@ -717,14 +718,15 @@ func (m *manager) StartInstance(ctx context.Context, id string, req StartInstanc
lock := m.getInstanceLock(id)
lock.Lock()
defer lock.Unlock()
if err := m.clearRestartStatusLocked(ctx, id); err != nil {
meta, err := m.loadMetadataForBootRequest(id)
if err != nil {
return nil, err
}
if err := m.clearRestartStatusLocked(ctx, meta); err != nil {
return nil, err
}
if !startRequestHasOverrides(req) {
current, err := m.currentInstanceWithoutHydration(ctx, id)
if err != nil {
return nil, err
}
current := m.toInstanceWithoutHydration(ctx, meta)
if current.State == StateRunning || current.State == StateInitializing {
// The API can exit after a clone boots and before its rekey finishes. Finish it
// here, or the clone keeps its source's SSH host keys.
Expand All @@ -734,7 +736,7 @@ func (m *manager) StartInstance(ctx context.Context, id string, req StartInstanc
}
return m.currentInstanceWithoutHydration(ctx, id)
}
return current, nil
return &current, nil
}
}
inst, err := m.startInstance(ctx, id, req)
Expand Down
9 changes: 6 additions & 3 deletions lib/instances/process_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,13 @@ func resolveLiveHypervisorPID(id HypervisorProcessIdentity, socketPath string) (
}
}
if runtime.GOOS != "linux" {
if stored == 0 {
return vzShimOwner(socketPath)
// Darwin has no recorded start time. Never signal a PID based only on
// its continued existence, even when the control socket is stale.
owner, err := vzShimOwner(socketPath)
if err == nil && owner == 0 && stored != 0 {
return 0, fmt.Errorf("cannot confirm stored shim PID %d for socket %q", stored, socketPath)
}
return stored, nil
return owner, err
}
bootID := hostBootID()
if stored != 0 && id.HypervisorBootID != "" && bootID != "" && id.HypervisorBootID != bootID {
Expand Down
Loading
Loading