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
9 changes: 7 additions & 2 deletions cmd/api/api/instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -797,7 +797,7 @@ func (s *ApiService) ForkInstance(ctx context.Context, request oapi.ForkInstance
return oapi.ForkInstance201JSONResponse(instanceToOAPI(*result)), nil
}

// StopInstance gracefully stops a running instance
// StopInstance stops a running instance, gracefully unless force is set
// The id parameter can be an instance ID, name, or ID prefix
// Note: Resolution is handled by ResolveResource middleware
func (s *ApiService) StopInstance(ctx context.Context, request oapi.StopInstanceRequestObject) (oapi.StopInstanceResponseObject, error) {
Expand All @@ -810,7 +810,12 @@ func (s *ApiService) StopInstance(ctx context.Context, request oapi.StopInstance
}
log := logger.FromContext(ctx)

result, err := s.InstanceManager.StopInstance(ctx, inst.Id)
stopReq := instances.StopInstanceRequest{}
if request.Body != nil && request.Body.Force != nil {
stopReq.Force = *request.Body.Force
}

result, err := s.InstanceManager.StopInstance(ctx, inst.Id, stopReq)
if err != nil {
switch {
case errors.Is(err, instances.ErrInvalidState):
Expand Down
55 changes: 55 additions & 0 deletions cmd/api/api/optional_body.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package api

import (
"io"
"net/http"
"strings"
)

// optionalBodyRoutes are the instance actions whose POST body is optional.
var optionalBodyRoutes = []string{"/standby", "/stop"}

// NormalizeOptionalBody rewrites empty POST bodies of instance actions with an
// optional body to "{}" so the generated strict handler can decode them without
// special casing.
func NormalizeOptionalBody(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
next.ServeHTTP(w, r)
return
}
if isOptionalBodyRoutePath(r.URL.Path) && requestBodyIsEmpty(r) {
r.Body = io.NopCloser(strings.NewReader(`{}`))
r.ContentLength = 2
if r.Header.Get("Content-Type") == "" {
r.Header.Set("Content-Type", "application/json")
}
}

next.ServeHTTP(w, r)
})
}

func isOptionalBodyRoutePath(path string) bool {
if !strings.HasPrefix(path, "/instances/") {
return false
}
for _, action := range optionalBodyRoutes {
if !strings.HasSuffix(path, action) {
continue
}
instanceID := strings.TrimSuffix(strings.TrimPrefix(path, "/instances/"), action)
return instanceID != "" && !strings.Contains(instanceID, "/")
}
return false
}

func requestBodyIsEmpty(r *http.Request) bool {
if r == nil {
return true
}
if r.Body == nil || r.Body == http.NoBody {
return true
}
return r.ContentLength == 0 && len(r.TransferEncoding) == 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require"
)

func TestNormalizeOptionalStandbyBody(t *testing.T) {
func TestNormalizeOptionalBody(t *testing.T) {
t.Parallel()

t.Run("empty standby body becomes empty JSON object", func(t *testing.T) {
Expand All @@ -30,13 +30,33 @@ func TestNormalizeOptionalStandbyBody(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/instances/test/standby", nil)
rec := httptest.NewRecorder()

NormalizeOptionalStandbyBody(next).ServeHTTP(rec, req)
NormalizeOptionalBody(next).ServeHTTP(rec, req)

assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Equal(t, []byte(`{}`), gotBody)
assert.Equal(t, "application/json", gotContentType)
})

t.Run("empty stop body becomes empty JSON object", func(t *testing.T) {
t.Parallel()

var gotBody []byte
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
gotBody, err = io.ReadAll(r.Body)
require.NoError(t, err)
w.WriteHeader(http.StatusNoContent)
})

req := httptest.NewRequest(http.MethodPost, "/instances/test/stop", nil)
rec := httptest.NewRecorder()

NormalizeOptionalBody(next).ServeHTTP(rec, req)

assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Equal(t, []byte(`{}`), gotBody)
})

t.Run("existing standby body is preserved", func(t *testing.T) {
t.Parallel()

Expand All @@ -51,13 +71,13 @@ func TestNormalizeOptionalStandbyBody(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/instances/test/standby", bytes.NewBufferString(`{"compression":{"enabled":true}}`))
rec := httptest.NewRecorder()

NormalizeOptionalStandbyBody(next).ServeHTTP(rec, req)
NormalizeOptionalBody(next).ServeHTTP(rec, req)

assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Equal(t, []byte(`{"compression":{"enabled":true}}`), gotBody)
})

t.Run("non-standby route is untouched", func(t *testing.T) {
t.Run("route without an optional body is untouched", func(t *testing.T) {
t.Parallel()

var gotBody []byte
Expand All @@ -71,13 +91,13 @@ func TestNormalizeOptionalStandbyBody(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/instances/test/start", nil)
rec := httptest.NewRecorder()

NormalizeOptionalStandbyBody(next).ServeHTTP(rec, req)
NormalizeOptionalBody(next).ServeHTTP(rec, req)

assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Empty(t, gotBody)
})

t.Run("non-post request skips standby normalization", func(t *testing.T) {
t.Run("non-post request skips normalization", func(t *testing.T) {
t.Parallel()

var gotBody []byte
Expand All @@ -91,18 +111,20 @@ func TestNormalizeOptionalStandbyBody(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/instances/test/standby", nil)
rec := httptest.NewRecorder()

NormalizeOptionalStandbyBody(next).ServeHTTP(rec, req)
NormalizeOptionalBody(next).ServeHTTP(rec, req)

assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Empty(t, gotBody)
})

t.Run("standby route matcher only accepts single path segment ids", func(t *testing.T) {
t.Run("route matcher only accepts single path segment ids", func(t *testing.T) {
t.Parallel()

assert.True(t, isStandbyRoutePath("/instances/test/standby"))
assert.False(t, isStandbyRoutePath("/instances/test/start"))
assert.False(t, isStandbyRoutePath("/instances/test/standby/extra"))
assert.False(t, isStandbyRoutePath("/instances/test/nested/standby"))
assert.True(t, isOptionalBodyRoutePath("/instances/test/standby"))
assert.True(t, isOptionalBodyRoutePath("/instances/test/stop"))
assert.False(t, isOptionalBodyRoutePath("/instances/test/start"))
assert.False(t, isOptionalBodyRoutePath("/instances/test/standby/extra"))
assert.False(t, isOptionalBodyRoutePath("/instances/test/nested/standby"))
assert.False(t, isOptionalBodyRoutePath("/instances/test/nested/stop"))
})
}
47 changes: 0 additions & 47 deletions cmd/api/api/optional_standby_body.go

This file was deleted.

2 changes: 1 addition & 1 deletion cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ func run() error {
// Mount API routes (authentication now handled by validation middleware)
oapi.HandlerWithOptions(strictHandler, oapi.ChiServerOptions{
BaseRouter: r,
Middlewares: []oapi.MiddlewareFunc{api.NormalizeOptionalStandbyBody},
Middlewares: []oapi.MiddlewareFunc{api.NormalizeOptionalBody},
})
})

Expand Down
4 changes: 3 additions & 1 deletion docs/macos-experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,9 @@ credential rekeying; this spike is not a multi-tenant image format.
images, then falls back to VMM shutdown if necessary. Without an enabled Darwin
guest agent it does **not** guarantee an orderly guest OS/application shutdown. Use a human
or an authorized guest shutdown workflow before destructive operations when
application consistency matters. Start cold-boots the instance's existing disk.
application consistency matters. With `{"force": true}`, stop skips the guest
shutdown and powers the VM off; the stop is not graceful, so a stopped snapshot
or fork needs a later graceful stop. Start cold-boots the instance's existing disk.
Delete removes instance storage, not the imported image. Deleting the imported
image does not affect existing instances: each owns independent copies and
starts without the template.
Expand Down
4 changes: 2 additions & 2 deletions integration/vgpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func TestVGPU(t *testing.T) {
if instanceID == "" {
return
}
if _, err := instanceManager.StopInstance(ctx, instanceID); err != nil {
if _, err := instanceManager.StopInstance(ctx, instanceID, instances.StopInstanceRequest{}); err != nil {
t.Logf("Cleanup: stop instance: %v", err)
}
t.Log("Cleanup: Deleting instance...")
Expand Down Expand Up @@ -250,7 +250,7 @@ func TestVGPU(t *testing.T) {
})

t.Log("Step 10: Stopping instance...")
_, err = instanceManager.StopInstance(ctx, inst.Id)
_, err = instanceManager.StopInstance(ctx, inst.Id, instances.StopInstanceRequest{})
require.NoError(t, err, "stop should succeed")

t.Run("VGPUReleasedOnStop", func(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion lib/builds/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (m *mockInstanceManager) RestoreSnapshot(ctx context.Context, id string, sn
return nil, instances.ErrNotSupported
}

func (m *mockInstanceManager) StopInstance(ctx context.Context, id string) (*instances.Instance, error) {
func (m *mockInstanceManager) StopInstance(ctx context.Context, id string, _ instances.StopInstanceRequest) (*instances.Instance, error) {
if m.stopFunc != nil {
return m.stopFunc(ctx, id)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/instances/firecracker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func TestFirecrackerStopClearsStaleSnapshot(t *testing.T) {
require.NoError(t, err)
require.True(t, beforeStop.HasSnapshot, "test setup should create visible stale snapshot")

inst, err = mgr.StopInstance(ctx, inst.Id)
inst, err = mgr.StopInstance(ctx, inst.Id, StopInstanceRequest{})
require.NoError(t, err)
assert.Equal(t, StateStopped, inst.State)
assert.False(t, inst.HasSnapshot, "stopped instances should not retain stale snapshots")
Expand Down
2 changes: 1 addition & 1 deletion lib/instances/fork.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ func (m *manager) applyForkTargetState(ctx context.Context, forkID string, targe
inst, err := m.standbyInstance(ctx, forkID, StandbyInstanceRequest{}, false)
return returnWithReadiness(inst, err, false)
case StateStopped:
inst, err := m.stopInstance(ctx, forkID)
inst, err := m.stopInstance(ctx, forkID, StopInstanceRequest{})
return returnWithReadiness(inst, err, false)
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/instances/fork_speed_darwin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func TestVZForkSpeed(t *testing.T) {
require.Equalf(t, 0, code, "dd to fill overlay should succeed")

// Stop the source so each fork copies a stable on-disk state without booting.
_, err = mgr.StopInstance(ctx, source.Id)
_, err = mgr.StopInstance(ctx, source.Id, StopInstanceRequest{})
require.NoError(t, err)

// Reset the global reflink flag however the test exits — a require failure
Expand Down
6 changes: 3 additions & 3 deletions lib/instances/lifecycle_noop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func TestLifecycleNoopTransitionsReturnCurrentInstanceWithoutEvent(t *testing.T)
name: "stop already stopped",
state: StateStopped,
action: func(ctx context.Context, m *manager, id string) (*Instance, error) {
return m.StopInstance(ctx, id)
return m.StopInstance(ctx, id, StopInstanceRequest{})
},
},
}
Expand Down Expand Up @@ -317,7 +317,7 @@ func TestStopInstanceRetiresPooledGuestConnection(t *testing.T) {
require.NoError(t, err)
require.Same(t, oldConn, cachedConn, "connection must be pooled before stop")

inst, err := m.StopInstance(ctx, id)
inst, err := m.StopInstance(ctx, id, StopInstanceRequest{})
require.NoError(t, err)
require.Equal(t, StateStopped, inst.State)

Expand All @@ -342,7 +342,7 @@ func TestStopStoppedInstanceLeavesVGPUForReconcile(t *testing.T) {

// Stop on an already-stopped instance is a no-op for the assignment; the
// periodic reconcile retries the release.
inst, err := m.StopInstance(context.Background(), id)
inst, err := m.StopInstance(context.Background(), id, StopInstanceRequest{})
require.NoError(t, err)
require.NotNil(t, inst)
assert.Equal(t, StateStopped, inst.State)
Expand Down
2 changes: 1 addition & 1 deletion lib/instances/macos_agent_startup.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (m *manager) stopOverdueMacOSAgentStartup(ctx context.Context, id string, l
reason += ": " + last.(string)
}
log.WarnContext(ctx, "stopping macOS guest whose agent did not start", "instance_id", id, "reason", reason)
if _, err := m.stopInstance(ctx, id); err != nil {
if _, err := m.stopInstance(ctx, id, StopInstanceRequest{}); err != nil {
return err
}
meta, err = m.loadMetadata(id)
Expand Down
2 changes: 1 addition & 1 deletion lib/instances/macos_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func (m *manager) rekeyMacOSCloneOnStart(ctx context.Context, stored *StoredMeta
// Teardown runs even if saving the pending flag fails. Otherwise the clone would keep
// running, networked, with its source's SSH host keys.
saveErr := m.saveMetadata(&metadata{StoredMetadata: *stored})
_, stopErr := m.stopInstance(context.WithoutCancel(ctx), stored.Id)
_, stopErr := m.stopInstance(context.WithoutCancel(ctx), stored.Id, StopInstanceRequest{})
if saveErr != nil || stopErr != nil {
return fmt.Errorf("macOS clone rekey failed and teardown needs attention: %w", errors.Join(err, saveErr, stopErr))
}
Expand Down
8 changes: 4 additions & 4 deletions lib/instances/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type Manager interface {
StandbyInstance(ctx context.Context, id string, req StandbyInstanceRequest) (*Instance, error)
RestoreInstance(ctx context.Context, id string) (*Instance, error)
RestoreSnapshot(ctx context.Context, id string, snapshotID string, req RestoreSnapshotRequest) (*Instance, error)
StopInstance(ctx context.Context, id string) (*Instance, error)
StopInstance(ctx context.Context, id string, req StopInstanceRequest) (*Instance, error)
StartInstance(ctx context.Context, id string, req StartInstanceRequest) (*Instance, error)
UpdateInstance(ctx context.Context, id string, req UpdateInstanceRequest) (*Instance, error)
StreamInstanceLogs(ctx context.Context, id string, tail int, follow bool, source LogSource) (<-chan string, error)
Expand Down Expand Up @@ -681,8 +681,8 @@ func (m *manager) RestoreSnapshot(ctx context.Context, id string, snapshotID str
return inst, err
}

// StopInstance gracefully stops a running instance
func (m *manager) StopInstance(ctx context.Context, id string) (*Instance, error) {
// StopInstance stops a running instance, gracefully unless req.Force is set
func (m *manager) StopInstance(ctx context.Context, id string, req StopInstanceRequest) (*Instance, error) {
lock := m.getInstanceLock(id)
lock.Lock()
defer lock.Unlock()
Expand All @@ -703,7 +703,7 @@ func (m *manager) StopInstance(ctx context.Context, id string) (*Instance, error
if err := m.markRestartManualStopLocked(ctx, id); err != nil {
return nil, err
}
inst, err := m.stopInstance(ctx, id)
inst, err := m.stopInstance(ctx, id, req)
if err == nil {
m.notifyLifecycleEvent(ctx, LifecycleEventStop, inst)
}
Expand Down
Loading
Loading