From 9ea12668778c4a4d6e55f23639becd1ef4061d27 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Fri, 27 Nov 2026 14:09:50 +0100 Subject: [PATCH 1/8] Support MassedCompute network volumes --- mkdocs/docs/concepts/backends.md | 2 +- mkdocs/docs/concepts/volumes.md | 19 +- mkdocs/docs/reference/dstack.yml/volume.md | 8 + runner/internal/shim/api/handlers.go | 5 +- runner/internal/shim/api/handlers_test.go | 2 +- runner/internal/shim/api/schemas.go | 5 +- runner/internal/shim/docker.go | 33 +- runner/internal/shim/docker_test.go | 9 +- runner/internal/shim/models.go | 1 + runner/internal/shim/volumes.go | 85 ++++- runner/internal/shim/volumes_test.go | 58 ++++ .../_internal/core/backends/base/compute.py | 10 + .../core/backends/massedcompute/api_client.py | 160 ++++++++- .../core/backends/massedcompute/compute.py | 304 +++++++++++++++-- .../_internal/core/compatibility/runs.py | 3 +- src/dstack/_internal/core/errors.py | 24 ++ src/dstack/_internal/core/models/runs.py | 21 +- src/dstack/_internal/core/models/volumes.py | 29 +- .../pipeline_tasks/instances/__init__.py | 11 +- .../pipeline_tasks/instances/check.py | 15 + .../pipeline_tasks/instances/common.py | 1 + .../pipeline_tasks/instances/termination.py | 58 +++- .../background/pipeline_tasks/jobs_running.py | 9 + .../pipeline_tasks/jobs_submitted.py | 25 +- .../pipeline_tasks/jobs_terminating.py | 13 + .../background/pipeline_tasks/volumes.py | 129 +++++-- src/dstack/_internal/server/schemas/runner.py | 4 +- .../_internal/server/services/instances.py | 13 + .../server/services/jobs/__init__.py | 13 +- .../server/services/runner/client.py | 29 +- .../_internal/server/services/runner/pool.py | 20 ++ .../backends/massedcompute/test_api_client.py | 65 +++- .../backends/massedcompute/test_compute.py | 320 ++++++++++++++++-- .../_internal/core/models/test_volumes.py | 37 ++ .../pipeline_tasks/instances/test_check.py | 53 ++- .../instances/test_termination.py | 93 ++++- .../pipeline_tasks/test_jobs_running.py | 2 + .../pipeline_tasks/test_jobs_submitted.py | 58 ++++ .../background/pipeline_tasks/test_volumes.py | 280 ++++++++++++++- .../server/services/runner/test_client.py | 58 ++-- .../server/services/test_instances.py | 31 +- 41 files changed, 1934 insertions(+), 181 deletions(-) create mode 100644 runner/internal/shim/volumes_test.go diff --git a/mkdocs/docs/concepts/backends.md b/mkdocs/docs/concepts/backends.md index 903ed34c27..0e8fd37864 100644 --- a/mkdocs/docs/concepts/backends.md +++ b/mkdocs/docs/concepts/backends.md @@ -1109,7 +1109,7 @@ projects: -The backend supports single-node, on-demand CPU and GPU VMs. +The backend supports single-node, on-demand CPU and GPU VMs and experimental [network volumes](volumes.md#network-volumes). MassedCompute chooses the region for each VM. ### Vultr diff --git a/mkdocs/docs/concepts/volumes.md b/mkdocs/docs/concepts/volumes.md index 0eea02cc32..3304f4cffe 100644 --- a/mkdocs/docs/concepts/volumes.md +++ b/mkdocs/docs/concepts/volumes.md @@ -16,7 +16,7 @@ Useful as a cache for cloud fleets or for persistent storage with SSH fleets. ## Network volumes -> Network volumes are currently supported for the `aws`, `gcp`, `runpod`, `kubernetes`, `daytona`, and `lium` backends. +> Network volumes are currently supported for the `aws`, `gcp`, `runpod`, `kubernetes`, `daytona`, `lium`, and `massedcompute` backends. ### Apply a configuration @@ -64,6 +64,20 @@ If you use this configuration, `dstack` will create a new volume based on the sp > Files on Lium volumes are owned by root and accessible to all users in the container. +??? info "MassedCompute" + Network volumes are experimental. Before first use, upgrade the CLI and all server replicas + and enable Persistent Storage in your MassedCompute account. + Storage grows with usage. Omit `size` and `region`. Set `volume_id` to register existing storage. + + Use each volume on one VM at a time, including VMs outside dstack. A VM can mount up to eight + volumes at launch. See [Persistent Storage limitations](https://vm-docs.massedcompute.com/docs/persistent-storage/limitations). + + ```yaml + type: volume + backend: massedcompute + name: my-volume + ``` + ??? info "Kubernetes" Set `region` to a kubeconfig context name enabled in the [backend configuration](backends.md#kubernetes). Omit it only for legacy configurations without `contexts`. @@ -228,7 +242,8 @@ and its contents will persist across runs. ### Detach a volume { #detach-network-volume } -`dstack` automatically detaches volumes from instances when a run stops. +On AWS and GCP, `dstack` automatically detaches volumes when a run stops. +On MassedCompute, terminate the VM before moving its volume to another VM. !!! info "Force detach" In some clouds such as AWS a volume may stuck in the detaching state. diff --git a/mkdocs/docs/reference/dstack.yml/volume.md b/mkdocs/docs/reference/dstack.yml/volume.md index 7172095710..ae6ec17286 100644 --- a/mkdocs/docs/reference/dstack.yml/volume.md +++ b/mkdocs/docs/reference/dstack.yml/volume.md @@ -42,6 +42,14 @@ The `volume` configuration type allows creating, registering, and updating [volu backend: required: true +=== "MassedCompute" + + #SCHEMA# dstack._internal.core.models.volumes.MassedComputeVolumeConfiguration + overrides: + show_root_heading: false + backend: + required: true + === "Kubernetes" Kubernetes backend volumes are mapped to [`PersistentVolumeClaim`](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims) objects. diff --git a/runner/internal/shim/api/handlers.go b/runner/internal/shim/api/handlers.go index 9421e2e678..1ab0f36ce1 100644 --- a/runner/internal/shim/api/handlers.go +++ b/runner/internal/shim/api/handlers.go @@ -17,8 +17,9 @@ func (s *ShimServer) HealthcheckHandler(w http.ResponseWriter, r *http.Request) defer s.mu.RUnlock() return &HealthcheckResponse{ - Service: "dstack-shim", - Version: s.version, + Service: "dstack-shim", + Version: s.version, + SupportsVolumeMountPath: true, }, nil } diff --git a/runner/internal/shim/api/handlers_test.go b/runner/internal/shim/api/handlers_test.go index 9f1c7e6557..1dcc305a88 100644 --- a/runner/internal/shim/api/handlers_test.go +++ b/runner/internal/shim/api/handlers_test.go @@ -25,7 +25,7 @@ func TestHealthcheck(t *testing.T) { t.Errorf("Want status '%d', got '%d'", 200, responseRecorder.Code) } - expected := "{\"service\":\"dstack-shim\",\"version\":\"0.0.1.dev2\"}" + expected := "{\"service\":\"dstack-shim\",\"version\":\"0.0.1.dev2\",\"supports_volume_mount_path\":true}" if strings.TrimSpace(responseRecorder.Body.String()) != expected { t.Errorf("Want '%s', got '%s'", expected, responseRecorder.Body.String()) diff --git a/runner/internal/shim/api/schemas.go b/runner/internal/shim/api/schemas.go index d035bdb176..2bc0c8406d 100644 --- a/runner/internal/shim/api/schemas.go +++ b/runner/internal/shim/api/schemas.go @@ -7,8 +7,9 @@ import ( ) type HealthcheckResponse struct { - Service string `json:"service"` - Version string `json:"version"` + Service string `json:"service"` + Version string `json:"version"` + SupportsVolumeMountPath bool `json:"supports_volume_mount_path"` } type ShutdownRequest struct { diff --git a/runner/internal/shim/docker.go b/runner/internal/shim/docker.go index dd402e558b..82e13292f4 100644 --- a/runner/internal/shim/docker.go +++ b/runner/internal/shim/docker.go @@ -308,7 +308,8 @@ func (d *DockerRunner) restoreStateFromContainers( // Containers created by shim versions that did not write the state file have // no config to restore. The volumes can still be recovered from the container // mounts, unlike the host SSH keys, which are only known to the state file - config.Volumes = volumesFromMounts(containerShort.Mounts) + config.ID = taskID + config.Volumes = volumesFromMounts(taskID, containerShort.Mounts) // Such a task still has a dir that must be removed along with the task taskDir = d.findLegacyTaskDir(containerName) } @@ -357,12 +358,17 @@ func (d *DockerRunner) restoreStateFromContainers( } // volumesFromMounts recovers the volumes attached to a task from its container mounts. -// Only the volume names are recovered, which is all that is needed to unmount them -func volumesFromMounts(mounts []dockertypes.MountPoint) []VolumeInfo { +// Only cleanup needs these entries. For a private bind the original host path is unknown. +func volumesFromMounts(taskID string, mounts []dockertypes.MountPoint) []VolumeInfo { var volumes []VolumeInfo for _, mount := range mounts { if name, found := strings.CutPrefix(mount.Source, volumeMountPointDir+"/"); found { volumes = append(volumes, VolumeInfo{Name: name}) + continue + } + volume := VolumeInfo{Name: filepath.Base(mount.Source), MountPath: mount.Source} + if target, err := taskVolumeMountPoint(taskID, volume); err == nil && target == mount.Source { + volumes = append(volumes, volume) } } return volumes @@ -979,7 +985,7 @@ func (d *DockerRunner) createContainer( if err != nil { return fmt.Errorf("get docker mounts: %w", err) } - volumeMounts, err := getVolumeMounts(task.config.VolumeMounts) + volumeMounts, err := getVolumeMounts(task.config) if err != nil { return fmt.Errorf("get volume mounts: %w", err) } @@ -1328,10 +1334,23 @@ func configureHpcNetworkingIfAvailable(hostConfig *container.HostConfig) { } } -func getVolumeMounts(mountPoints []VolumeMountPoint) ([]mount.Mount, error) { +func getVolumeMounts(cfg TaskConfig) ([]mount.Mount, error) { + sources := make(map[string]string) + for _, volume := range cfg.Volumes { + if volume.MountPath != "" { + source, err := taskVolumeMountPoint(cfg.ID, volume) + if err != nil { + return nil, err + } + sources[volume.Name] = source + } + } mounts := []mount.Mount{} - for _, mountPoint := range mountPoints { - source := getVolumeMountPoint(mountPoint.Name) + for _, mountPoint := range cfg.VolumeMounts { + source, ok := sources[mountPoint.Name] + if !ok { + source = getVolumeMountPoint(mountPoint.Name) + } mounts = append(mounts, mount.Mount{Type: mount.TypeBind, Source: source, Target: mountPoint.Path}) } return mounts, nil diff --git a/runner/internal/shim/docker_test.go b/runner/internal/shim/docker_test.go index 2570f0803e..232ee48516 100644 --- a/runner/internal/shim/docker_test.go +++ b/runner/internal/shim/docker_test.go @@ -213,10 +213,15 @@ func TestVolumesFromMounts(t *testing.T) { {Source: "/root/.dstack/runners/task-0-0-1234abcd/runner", Destination: consts.RunnerTempDir}, {Source: "/mnt/disks/dstack-volumes/volume-1", Destination: "/volume"}, {Source: "/home/dstack/data", Destination: "/instance-data"}, + {Source: taskVolumeMountPointDir + "/task-1/checkpoints", Destination: "/data"}, + {Source: taskVolumeMountPointDir + "/other-task/wrong", Destination: "/other"}, } - assert.Equal(t, []VolumeInfo{{Name: "volume-1"}}, volumesFromMounts(mounts)) - assert.Nil(t, volumesFromMounts(nil)) + assert.Equal(t, []VolumeInfo{ + {Name: "volume-1"}, + {Name: "checkpoints", MountPath: taskVolumeMountPointDir + "/task-1/checkpoints"}, + }, volumesFromMounts("task-1", mounts)) + assert.Nil(t, volumesFromMounts("task-1", nil)) } func TestConfigureGpus_Nvidia(t *testing.T) { diff --git a/runner/internal/shim/models.go b/runner/internal/shim/models.go index 6166c7c7ff..10f284a0b8 100644 --- a/runner/internal/shim/models.go +++ b/runner/internal/shim/models.go @@ -71,6 +71,7 @@ type VolumeInfo struct { VolumeId string `json:"volume_id"` InitFs bool `json:"init_fs"` DeviceName string `json:"device_name"` + MountPath string `json:"mount_path,omitempty"` } type PortMapping struct { diff --git a/runner/internal/shim/volumes.go b/runner/internal/shim/volumes.go index f6d6096b0b..3d51e33d4d 100644 --- a/runner/internal/shim/volumes.go +++ b/runner/internal/shim/volumes.go @@ -23,6 +23,16 @@ func prepareVolumes(ctx context.Context, taskConfig TaskConfig) error { } log.Debug(ctx, "Preparing volumes...") for _, volume := range taskConfig.Volumes { + if volume.MountPath != "" { + target, err := taskVolumeMountPoint(taskConfig.ID, volume) + if err != nil { + return err + } + if err := bindMountedVolume(volume.MountPath, target); err != nil { + return fmt.Errorf("bind mounted volume %s: %w", volume.Name, err) + } + continue + } err := formatAndMountVolume(ctx, volume) if err != nil { return fmt.Errorf("format and mount volume: %w", err) @@ -38,7 +48,22 @@ func unmountVolumes(ctx context.Context, taskConfig TaskConfig) error { log.Debug(ctx, "Unmounting volumes...") var failed []string for _, volume := range taskConfig.Volumes { - mountPoint := getVolumeMountPoint(volume.Name) + mountPoint, err := taskVolumeMountPoint(taskConfig.ID, volume) + if err != nil { + return err + } + if volume.MountPath != "" { + // MNT_FORCE can abort the underlying FUSE connection, including the provider's mount. + err := unix.Unmount(mountPoint, unix.UMOUNT_NOFOLLOW) + if err != nil && !errors.Is(err, unix.EINVAL) && !errors.Is(err, unix.ENOENT) { + log.Error(ctx, "failed to release volume bind mount", "mountpoint", mountPoint, "err", err) + failed = append(failed, mountPoint) + } else { + _ = os.Remove(mountPoint) + _ = os.Remove(filepath.Dir(mountPoint)) + } + continue + } cmd := exec.CommandContext(ctx, "mountpoint", mountPoint) if output, err := cmd.CombinedOutput(); err != nil { log.Info(ctx, "skipping", "mountpoint", mountPoint, "output", output) @@ -58,6 +83,59 @@ func unmountVolumes(ctx context.Context, taskConfig TaskConfig) error { return nil } +// bindMountedVolume pins the source directory before checking its mount ID. A provider +// unmount between verification and bind cannot substitute a directory on the root disk. +func bindMountedVolume(source, target string) error { + // Reject symlinks in the entire path, including the provider's mount parent. + how := &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS} + fd, err := unix.Openat2(unix.AT_FDCWD, source, how) + if err != nil { + return err + } + defer func() { _ = unix.Close(fd) }() + var dir, parent unix.Statx_t + if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID, &dir); err != nil { + return err + } + if err := unix.Statx(fd, "..", 0, unix.STATX_MNT_ID, &parent); err != nil { + return err + } + if dir.Mask&unix.STATX_MNT_ID == 0 || parent.Mask&unix.STATX_MNT_ID == 0 || dir.Mnt_id == parent.Mnt_id { + return fmt.Errorf("%s is not a verified mount point", source) + } + // Build a private bind mount before publishing it to Docker. Failure drops the + // detached mount when its file descriptor closes. + tree, err := unix.OpenTree(fd, "", unix.AT_EMPTY_PATH|unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC) + if err != nil { + return err + } + defer func() { _ = unix.Close(tree) }() + if err := unix.MountSetattr(tree, "", unix.AT_EMPTY_PATH, &unix.MountAttr{Propagation: unix.MS_PRIVATE}); err != nil { + return err + } + if err := os.MkdirAll(target, 0o700); err != nil { + return err + } + targetFD, err := unix.Openat2(unix.AT_FDCWD, target, how) + if err != nil { + return err + } + defer func() { _ = unix.Close(targetFD) }() + return unix.MoveMount(tree, "", targetFD, "", unix.MOVE_MOUNT_F_EMPTY_PATH|unix.MOVE_MOUNT_T_EMPTY_PATH) +} + +func taskVolumeMountPoint(taskID string, volume VolumeInfo) (string, error) { + if volume.MountPath == "" { + return getVolumeMountPoint(volume.Name), nil + } + for _, name := range []string{taskID, volume.Name} { + if name == "." || !filepath.IsLocal(name) || filepath.Base(name) != name { + return "", fmt.Errorf("invalid volume bind path component %q", name) + } + } + return filepath.Join(taskVolumeMountPointDir, taskID, volume.Name), nil +} + func formatAndMountVolume(ctx context.Context, volume VolumeInfo) error { backend, err := backends.GetBackend(volume.Backend) if err != nil { @@ -94,7 +172,10 @@ func formatAndMountVolume(ctx context.Context, volume VolumeInfo) error { // volumeMountPointDir is a dstack-specific dir for volumes, used to avoid clashes with // host dirs. /mnt/disks is used since on some VM images other places may not be // writable (e.g. GCP COS). -const volumeMountPointDir = "/mnt/disks/dstack-volumes" +const ( + volumeMountPointDir = "/mnt/disks/dstack-volumes" + taskVolumeMountPointDir = "/mnt/disks/dstack-task-volumes" +) func getVolumeMountPoint(volumeName string) string { return filepath.Join(volumeMountPointDir, volumeName) diff --git a/runner/internal/shim/volumes_test.go b/runner/internal/shim/volumes_test.go new file mode 100644 index 0000000000..56e4eec09c --- /dev/null +++ b/runner/internal/shim/volumes_test.go @@ -0,0 +1,58 @@ +package shim + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func TestBindMountedVolume(t *testing.T) { + source := t.TempDir() + target := filepath.Join(t.TempDir(), "bind") + // A provider can leave the directory behind even when its filesystem is missing. + require.ErrorContains(t, bindMountedVolume(source, target), "not a verified mount point") + + if err := unix.Mount("tmpfs", source, "tmpfs", 0, "size=1m"); errors.Is(err, unix.EPERM) { + t.Skip("mounting tmpfs requires CAP_SYS_ADMIN") + } else { + require.NoError(t, err) + } + t.Cleanup(func() { _ = unix.Unmount(source, 0) }) + require.NoError(t, os.WriteFile(filepath.Join(source, "checkpoint"), []byte("saved"), 0o600)) + alias := filepath.Join(t.TempDir(), "mounts") + require.NoError(t, os.Symlink(filepath.Dir(source), alias)) + require.ErrorIs(t, bindMountedVolume(filepath.Join(alias, filepath.Base(source)), target), unix.ELOOP) + cfg := TaskConfig{ + ID: filepath.Base(filepath.Dir(source)), + Volumes: []VolumeInfo{{Name: "data", Backend: "massedcompute", MountPath: source}}, + VolumeMounts: []VolumeMountPoint{{Name: "data", Path: "/data"}}, + } + require.NoError(t, prepareVolumes(t.Context(), cfg)) + t.Cleanup(func() { _ = unmountVolumes(t.Context(), cfg) }) + mounts, err := getVolumeMounts(cfg) + require.NoError(t, err) + require.Len(t, mounts, 1) + require.Equal(t, "/data", mounts[0].Target) + target = mounts[0].Source + + // Removing the provider's original mount must never redirect the job to the local disk. + require.NoError(t, unix.Unmount(source, 0)) + data, err := os.ReadFile(filepath.Join(target, "checkpoint")) + require.NoError(t, err) + require.Equal(t, "saved", string(data)) + require.NoFileExists(t, filepath.Join(source, "checkpoint")) + require.NoError(t, unmountVolumes(t.Context(), cfg)) + require.NoDirExists(t, target) + require.NoError(t, unmountVolumes(t.Context(), cfg)) +} + +func TestPrepareProviderVolumeWithoutMountPath(t *testing.T) { + // Older shims ignore mount_path and enter the block-volume path. A missing + // mount path on a new shim must fail before looking up or formatting devices too. + cfg := TaskConfig{Volumes: []VolumeInfo{{Backend: "massedcompute", Name: "data"}}} + require.ErrorContains(t, prepareVolumes(t.Context(), cfg), "unknown backend") +} diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py index aeef66bcd3..d739ae13f3 100644 --- a/src/dstack/_internal/core/backends/base/compute.py +++ b/src/dstack/_internal/core/backends/base/compute.py @@ -785,6 +785,16 @@ def delete_volume(self, volume: Volume): """ raise NotImplementedError() + def get_volume_mounts_to_sync( + self, provisioning_data: JobProvisioningData + ) -> Optional[list[str]]: + """Return host mounts requiring a guest flush before deleting this VM. + + An empty list skips the flush. Return None if the VM is already gone. + Raise a backend error if its state cannot be confirmed. + """ + return [] + def attach_volume( self, volume: Volume, provisioning_data: JobProvisioningData ) -> VolumeAttachmentData: diff --git a/src/dstack/_internal/core/backends/massedcompute/api_client.py b/src/dstack/_internal/core/backends/massedcompute/api_client.py index dd3ef1aefb..961c517aaa 100644 --- a/src/dstack/_internal/core/backends/massedcompute/api_client.py +++ b/src/dstack/_internal/core/backends/massedcompute/api_client.py @@ -4,9 +4,15 @@ import httpx2 from pydantic import AwareDatetime, Field, ValidationError -from typing_extensions import TypedDict - -from dstack._internal.core.errors import BackendAuthError, ComputeError +from typing_extensions import NotRequired, TypedDict + +from dstack._internal.core.errors import ( + BackendAuthError, + ComputeError, + VolumeDeletionPending, + VolumeProvisioningError, + VolumeProvisioningPending, +) from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore from dstack._internal.utils.http import HTTPClient @@ -23,6 +29,50 @@ class MassedComputeInstance(CoreModel): os_booted: bool = False created: Optional[AwareDatetime] = None + def get_uuid(self) -> UUID: + try: + return UUID(self.uuid) + except ValueError: + raise ComputeError("MassedCompute returned an invalid VM UUID") from None + + +class _AttachedInstance(CoreModel): + uuid: UUID + + +class _VolumeIdentity(CoreModel): + id: UUID + name: str + + +class MassedComputeVolume(_VolumeIdentity): + status: str + mount_path: str = Field(alias="mountPath") + can_manage: bool = Field(alias="canManage") + attached_to: list[_AttachedInstance] = Field(alias="attachedTo") + hidden_attached_count: int = Field(alias="hiddenAttachedCount") + + +class _Volumes(CoreModel): + volumes: list[MassedComputeVolume] = Field(alias="storageVolumes") + + +class _CreatedVolume(CoreModel): + volume: _VolumeIdentity = Field(alias="storageVolume") + + +class _VolumeDeletion(CoreModel): + id: Optional[UUID] = None + deleted: bool + + +class _DeletedVolume(CoreModel): + result: _VolumeDeletion + + +class _CreateVolumeRequest(TypedDict, closed=True): + name: str + class _Instances(CoreModel): instances: list[MassedComputeInstance] = Field(alias="runningInstances") @@ -39,12 +89,21 @@ class _LaunchRequest(TypedDict, closed=True): regionName: str command: str sshKeys: list[str] + volumeIds: NotRequired[list[str]] class _TerminateRequest(TypedDict, closed=True): instanceUuids: list[str] +class MassedComputeLaunchUnconfirmed(ComputeError): + """A volume VM may have been created. Reconcile its unique name before retrying.""" + + +class _RequestRejected(ComputeError): + """The request was never sent, or the API reported a documented rejection.""" + + class MassedComputeAPIClient: def __init__(self, api_key: str): self.api_key = api_key @@ -60,12 +119,10 @@ def validate_api_key(self) -> bool: return False return True - def launch(self, name: str, product: str, command: str) -> str: - """Launch once using a unique name. If the response is lost, look up that name. - - Return the VM ID only when creation is confirmed. If the VM is not yet visible, - propagate the launch error. Its name still lets orphan cleanup find it later. - """ + def launch( + self, name: str, product: str, command: str, volume_ids: Optional[list[str]] = None + ) -> str: + """Recover a lost VM launch response by name. Volume launches reconcile in the worker.""" payload: _LaunchRequest = { "instanceName": name, "productName": product, @@ -74,36 +131,97 @@ def launch(self, name: str, product: str, command: str) -> str: "sshKeys": [], "command": command, } + if volume_ids: + payload["volumeIds"] = volume_ids try: - response = self._request("POST", "/instance/launch", payload) + # With volumeIds, these are the documented storage permission, unknown ID, + # inactive storage, and invalid request errors, respectively. + response = self._request( + "POST", + "/instance/launch", + payload, + rejected_statuses=(403, 404, 409, 422) if volume_ids else (), + ) return str(_parse_response(_LaunchResponse, response).response) - except ComputeError: - matches = [vm.uuid for vm in self.list_instances() if vm.name == name] + except _RequestRejected: + raise + except ComputeError as e: + if volume_ids: + raise MassedComputeLaunchUnconfirmed(str(e)) from e + matches = [vm for vm in self.list_instances() if vm.name == name] if len(matches) != 1: raise - return matches[0] + return str(matches[0].get_uuid()) def list_instances(self) -> list[MassedComputeInstance]: return _parse_response(_Instances, self._request("GET", "/instance")).instances + def get_instance_by_name(self, name: str) -> Optional[MassedComputeInstance]: + matches = [vm for vm in self.list_instances() if vm.name == name] + if len(matches) > 1: + raise ComputeError(f"Multiple MassedCompute instances match launch name {name}") + return matches[0] if matches else None + def get_instance(self, instance_id: str) -> Optional[MassedComputeInstance]: response = self._request("GET", "/instance/" + quote(instance_id, safe="")) # The detail endpoint returns the same array as the list endpoint, empty after deletion. instances = _parse_response(_Instances, response).instances if not instances: return None - if len(instances) != 1 or instances[0].uuid != instance_id: + if len(instances) != 1 or instances[0].uuid.lower() != instance_id.lower(): raise ComputeError("MassedCompute returned an unexpected instance ID") return instances[0] def terminate(self, instance_id: str) -> None: self._request("POST", "/instance/terminate", {"instanceUuids": [instance_id]}) + def list_volumes(self) -> list[MassedComputeVolume]: + return _parse_response(_Volumes, self._request("GET", "/storage-volumes")).volumes + + def create_volume(self, name: str) -> str: + payload: _CreateVolumeRequest = {"name": name} + try: + response = self._request( + "POST", + "/storage-volumes", + payload, + # Only the first worker may POST. A name conflict belongs to other storage. + rejected_statuses=(403, 404, 409, 422), + ) + volume = _parse_response(_CreatedVolume, response).volume + if volume.name != name: + raise ComputeError("MassedCompute returned an unexpected volume name") + return str(volume.id) + except (BackendAuthError, _RequestRejected) as e: + raise VolumeProvisioningError(str(e), volume_id=None) from e + except ComputeError as e: + raise VolumeProvisioningPending(f"Unconfirmed creation of volume {name}: {e}") from e + + def delete_volume(self, volume_id: str) -> None: + try: + response = self._request( + "DELETE", "/storage-volumes/" + quote(volume_id, safe=""), allowed_statuses=(404,) + ) + # A repeated delete of a known UUID may already be absent from this account's view. + if response.status_code == 404: + return + if response.status_code == 200: + result = _parse_response(_DeletedVolume, response).result + if result.id is not None and str(result.id) != volume_id.lower(): + raise ComputeError("MassedCompute returned an unexpected deleted volume ID") + if result.deleted: + return + except (BackendAuthError, ComputeError) as e: + raise VolumeDeletionPending(str(e)) from e + raise VolumeDeletionPending("MassedCompute is still emptying the volume") + def _request( self, method: str, path: str, - payload: Optional[Union[_LaunchRequest, _TerminateRequest]] = None, + payload: Optional[Union[_LaunchRequest, _TerminateRequest, _CreateVolumeRequest]] = None, + allowed_statuses: tuple[int, ...] = (), + rejected_statuses: tuple[int, ...] = (), ) -> httpx2.Response: try: response = self._client.request( @@ -114,11 +232,17 @@ def _request( headers={"Authorization": f"Bearer {self.api_key}"}, ) except httpx2.HTTPError as e: - raise ComputeError(f"MassedCompute {method} {path}: {type(e).__name__}") from None + error = f"MassedCompute {method} {path}: {type(e).__name__}" + if rejected_statuses and isinstance(e, httpx2.ConnectTimeout): + raise _RequestRejected(error) from None + raise ComputeError(error) from None if response.status_code == 401: raise BackendAuthError("Invalid MassedCompute API key") - if not 200 <= response.status_code < 300: - raise ComputeError(f"MassedCompute {method} {path}: HTTP {response.status_code}") + if not 200 <= response.status_code < 300 and response.status_code not in allowed_statuses: + error = f"MassedCompute {method} {path}: HTTP {response.status_code}" + if response.status_code in rejected_statuses: + raise _RequestRejected(error) + raise ComputeError(error) return response diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py index 2f763338e2..e0d6cedee0 100644 --- a/src/dstack/_internal/core/backends/massedcompute/compute.py +++ b/src/dstack/_internal/core/backends/massedcompute/compute.py @@ -1,5 +1,7 @@ +import re import shlex from typing import Optional +from uuid import UUID import gpuhunt from gpuhunt.providers.massedcompute import MassedComputeProvider @@ -12,20 +14,35 @@ ComputeWithInstanceVolumesSupport, ComputeWithPrivilegedSupport, ComputeWithResourceListingSupport, + ComputeWithVolumeSupport, generate_unique_instance_name, get_shim_commands, parse_provider_ref_from_name, ) from dstack._internal.core.backends.base.offers import get_catalog_offers -from dstack._internal.core.backends.massedcompute.api_client import MassedComputeAPIClient +from dstack._internal.core.backends.massedcompute.api_client import ( + MassedComputeAPIClient, + MassedComputeInstance, + MassedComputeLaunchUnconfirmed, + MassedComputeVolume, +) from dstack._internal.core.backends.massedcompute.models import MassedComputeConfig -from dstack._internal.core.errors import NotYetTerminated, ProvisioningError +from dstack._internal.core.errors import ( + BackendError, + ComputeError, + NotYetTerminated, + ProvisioningError, + VolumeDeletionPending, + VolumeProvisioningError, + VolumeProvisioningPending, +) from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import ( ListedResourceGroup, OwnerType, ResourceListing, ) +from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore from dstack._internal.core.models.instances import ( InstanceAvailability, InstanceConfiguration, @@ -33,6 +50,9 @@ ) from dstack._internal.core.models.placement import PlacementGroup from dstack._internal.core.models.runs import JobProvisioningData +from dstack._internal.core.models.volumes import Volume, VolumeProvisioningData, VolumeStatus +from dstack._internal.utils.common import get_or_error +from dstack._internal.utils.hash import slugify class MassedComputeCompute( @@ -41,6 +61,7 @@ class MassedComputeCompute( ComputeWithInstanceVolumesSupport, ComputeWithPrivilegedSupport, ComputeWithResourceListingSupport, + ComputeWithVolumeSupport, Compute, ): def __init__(self, config: MassedComputeConfig): @@ -67,28 +88,65 @@ def create_instance( instance_config: InstanceConfiguration, placement_group: Optional[PlacementGroup], ) -> JobProvisioningData: - name = generate_unique_instance_name(instance_config, with_provider_ref=True) # The image's SSH user is case-sensitive. The startup command runs as root. key_script = get_add_authorized_keys_script(instance_config.get_public_keys()) install_keys = shlex.join(["sudo", "-H", "-u", "Ubuntu", "sh", "-c", key_script]) command = " && ".join( [install_keys, *get_shim_commands(arch=instance_offer.instance.resources.cpu_arch)] ) - instance_id = self.api_client.launch(name, instance_offer.instance.name, command) - return JobProvisioningData( - backend=instance_offer.backend, - instance_type=instance_offer.instance, - instance_id=instance_id, - hostname=None, - internal_ip=None, - region=instance_offer.region, - price=instance_offer.price, - username="Ubuntu", - ssh_port=22, - dockerized=True, - ssh_proxy=None, - backend_data=None, + if not instance_config.volumes: + name = generate_unique_instance_name(instance_config, with_provider_ref=True) + instance_id = self.api_client.launch(name, instance_offer.instance.name, command) + return _instance_provisioning_data(instance_offer, instance_id) + + volumes = self._get_launch_volumes(instance_config.volumes) + # The suffix identifies VMs that orphan cleanup cannot flush. Keep the total name + # within the same 60-character limit as an ordinary generated instance name. + name = ( + generate_unique_instance_name( + instance_config, max_length=60 - len(_VOLUME_VM_SUFFIX), with_provider_ref=True + ) + + _VOLUME_VM_SUFFIX ) + launch = _VolumeLaunch(name=name, volume_ids={k: v.id for k, v in volumes.items()}) + try: + instance_id = self.api_client.launch( + name, instance_offer.instance.name, command, [str(v.id) for v in volumes.values()] + ) + except MassedComputeLaunchUnconfirmed: + # Returning incomplete provisioning data keeps the scheduler on this launch. + instance_id = name + data = _instance_provisioning_data(instance_offer, instance_id) + data.backend_data = launch.model_dump_json() + data.volume_mounts = {k: v.mount_path for k, v in volumes.items()} + return data + + def _get_launch_volumes(self, volumes: list[Volume]) -> dict[UUID, MassedComputeVolume]: + if len(volumes) > 8: + raise ComputeError("MassedCompute accepts up to eight volumes per VM") + available = {str(v.id): v for v in self.api_client.list_volumes()} + selected = {} + for volume in volumes: + data = volume.provisioning_data + if ( + data is None + or not data.mount_on_instance + or data.backend != BackendType.MASSEDCOMPUTE + ): + raise ComputeError(f"Invalid MassedCompute volume {volume.name}") + # Consuming each provider UUID once also detects two registrations of the same disk. + storage = available.pop(data.volume_id.lower(), None) + if ( + storage is None + or storage.status != "active" + or not storage.can_manage + or storage.attached_to + or storage.hidden_attached_count + ): + raise ComputeError(f"MassedCompute volume {volume.name} is unavailable or in use") + _check_volume_mount_path(storage) + selected[volume.id] = storage + return selected def update_provisioning_data( self, @@ -96,29 +154,154 @@ def update_provisioning_data( project_ssh_public_key: str, project_ssh_private_key: str, ) -> None: - instance = self.api_client.get_instance(provisioning_data.instance_id) + launch = ( + validate_json_extra_ignore(_VolumeLaunch, provisioning_data.backend_data) + if provisioning_data.backend_data is not None + else None + ) + instance = self._get_instance(provisioning_data.instance_id, launch) if instance is None: return + if launch is not None and provisioning_data.instance_id == launch.name: + # Save the recovered UUID even if the subsequent attachment check fails or times out. + provisioning_data.instance_id = str(instance.get_uuid()) + return if instance.status.lower() == "stopped": raise ProvisioningError("MassedCompute instance stopped during provisioning") if instance.os_booted and instance.ip and instance.username: + if launch is not None: + expected = provisioning_data.volume_mounts or {} + if expected.keys() != launch.volume_ids.keys(): + raise ProvisioningError("MassedCompute volume launch metadata is incomplete") + instance_uuid = instance.get_uuid() + attached = { + v.id: v + for v in self.api_client.list_volumes() + if v.status == "active" + and not v.hidden_attached_count + and [i.uuid for i in v.attached_to] == [instance_uuid] + } + for registration_id, provider_id in launch.volume_ids.items(): + volume = attached.get(provider_id) + if volume is None or volume.mount_path != expected[registration_id]: + raise ProvisioningError( + f"MassedCompute failed to attach volume {provider_id} to the VM" + ) + _check_volume_mount_path(volume) + provisioning_data.backend_data = None provisioning_data.hostname = instance.ip provisioning_data.username = instance.username def terminate_instance( self, instance_id: str, region: str, backend_data: Optional[str] = None ) -> None: - instance = self.api_client.get_instance(instance_id) + launch = validate_json_extra_ignore(_VolumeLaunch, backend_data) if backend_data else None + instance = self._get_instance(instance_id, launch) if instance is None: + # A cancelled name-only launch may appear later. Its -fs suffix makes orphan + # cleanup report the VM for manual removal without deleting its mounted volumes. return if instance.status.lower() not in {"terminating", "deleting"}: - self.api_client.terminate(instance_id) + # An unconfirmed launch is looked up by name, but termination always takes a UUID. + self.api_client.terminate(instance.uuid) raise NotYetTerminated(f"Waiting for MassedCompute instance {instance_id} to terminate") + def _get_instance( + self, instance_id: str, launch: Optional["_VolumeLaunch"] + ) -> Optional[MassedComputeInstance]: + if launch is not None and instance_id == launch.name: + instance = self.api_client.get_instance_by_name(launch.name) + if instance is None: + return None + instance_id = str(instance.get_uuid()) + instance = self.api_client.get_instance(instance_id) + if launch is not None and instance is not None and instance.name != launch.name: + raise ComputeError("MassedCompute returned an unexpected volume VM name") + return instance + + def get_volume_mounts_to_sync( + self, provisioning_data: JobProvisioningData + ) -> Optional[list[str]]: + instance = self.api_client.get_instance(provisioning_data.instance_id) + if instance is None: + return None + if instance.status.lower() in {"terminating", "deleting"}: + raise NotYetTerminated( + f"Waiting for MassedCompute instance {instance.uuid} to terminate" + ) + if instance.status.lower() == "stopped": + raise ComputeError( + "Cannot flush volumes on a stopped MassedCompute VM. " + "Restart the VM to flush its volumes, or terminate it manually in MassedCompute." + ) + return list((provisioning_data.volume_mounts or {}).values()) + + def register_volume(self, volume: Volume) -> VolumeProvisioningData: + volume_id = get_or_error(volume.configuration.external_volume_id) + provisioned = next( + (v for v in self.api_client.list_volumes() if str(v.id) == volume_id.lower()), None + ) + if provisioned is None: + raise ComputeError(f"MassedCompute volume {volume_id} not found") + return _volume_provisioning_data(provisioned) + + def create_volume(self, volume: Volume) -> VolumeProvisioningData: + name = _managed_volume_name(volume) + if volume.status == VolumeStatus.SUBMITTED: + volume_id = self.api_client.create_volume(name) + raise VolumeProvisioningPending(f"Waiting for MassedCompute volume {name}", volume_id) + + # A restarted worker cannot know whether the first request reached the provider. + # A deleted name is reusable, so only the worker that claimed SUBMITTED may POST. + try: + volumes = self.api_client.list_volumes() + except BackendError as e: + raise VolumeProvisioningPending(str(e), volume.volume_id) from e + if volume.volume_id is None: + existing = next((v for v in volumes if v.name == name), None) + else: + existing = next((v for v in volumes if str(v.id) == volume.volume_id), None) + if existing is None: + raise VolumeProvisioningPending( + f"Waiting for MassedCompute volume {name}", volume.volume_id + ) + if existing.name != name: + raise VolumeProvisioningError( + f"Unexpected name for MassedCompute volume {existing.id}", str(existing.id) + ) + try: + return _volume_provisioning_data(existing) + except VolumeProvisioningPending: + raise + except ComputeError as e: + raise VolumeProvisioningError(str(e), str(existing.id)) from e + + def delete_volume(self, volume: Volume) -> None: + if volume.external: + return + volume_id = volume.volume_id + if volume_id is None: + name = _managed_volume_name(volume) + try: + existing = next( + (v for v in self.api_client.list_volumes() if v.name == name), None + ) + except BackendError as e: + raise VolumeDeletionPending(str(e)) from e + if existing is None: + raise VolumeDeletionPending( + f"Could not confirm creation of MassedCompute volume {name}" + ) + # Persist the recovered UUID before a DELETE can remove the only name lookup. + raise VolumeDeletionPending(f"Found MassedCompute volume {name}", str(existing.id)) + self.api_client.delete_volume(volume_id) + def list_resource_groups(self) -> ResourceListing: groups = [] for instance in self.api_client.list_instances(): - provider_ref = parse_provider_ref_from_name(instance.name) + provider_ref = parse_provider_ref_from_name( + instance.name.removesuffix(_VOLUME_VM_SUFFIX) + ) if provider_ref is None or instance.status.lower() in {"terminating", "deleting"}: continue groups.append( @@ -126,15 +309,86 @@ def list_resource_groups(self) -> ResourceListing: backend=BackendType.MASSEDCOMPUTE, owner_type=OwnerType.INSTANCE, provider_ref=provider_ref, - primary_id=instance.uuid, + primary_id=instance.uuid.lower(), region="any", created_at=instance.created, description=instance.name, - backend_data=None, + backend_data=( + _VOLUME_VM_SUFFIX if instance.name.endswith(_VOLUME_VM_SUFFIX) else None + ), ) ) return ResourceListing(resource_groups=groups) def delete_resource_group(self, group: ListedResourceGroup) -> None: - if group.primary_id is not None: - self.terminate_instance(group.primary_id, "any") + if group.primary_id is None: + return + if group.backend_data == _VOLUME_VM_SUFFIX: + raise ComputeError( + "MassedCompute volume VM retained: orphan cleanup cannot flush its mounted volumes" + ) + self.terminate_instance(group.primary_id, "any") + + +class _VolumeLaunch(CoreModel): + """Private provider identities retained until the VM confirms its launch attachments.""" + + name: str + volume_ids: dict[UUID, UUID] + """dstack volume registration ID to MassedCompute storage UUID.""" + + +_VOLUME_VM_SUFFIX = "-fs" + + +def _instance_provisioning_data( + offer: InstanceOfferWithAvailability, instance_id: str +) -> JobProvisioningData: + return JobProvisioningData( + backend=offer.backend, + instance_type=offer.instance, + instance_id=instance_id, + hostname=None, + internal_ip=None, + region=offer.region, + price=offer.price, + username="Ubuntu", + ssh_port=22, + dockerized=True, + ssh_proxy=None, + backend_data=None, + ) + + +def _managed_volume_name(volume: Volume) -> str: + # Provider names are unique per account and limited to 22 characters. + return slugify("dstack", str(volume.id), hash_size=15) + + +_VOLUME_MOUNT_PATH = re.compile(r"/persistent/[a-z0-9](?:[a-z0-9-]{0,20}[a-z0-9])?") + + +def _volume_provisioning_data(volume: MassedComputeVolume) -> VolumeProvisioningData: + if volume.status == "creating": + raise VolumeProvisioningPending( + f"MassedCompute volume {volume.id} is creating", str(volume.id) + ) + if volume.status != "active": + raise ComputeError(f"MassedCompute volume {volume.id} is {volume.status}") + _check_volume_mount_path(volume) + return VolumeProvisioningData( + backend=BackendType.MASSEDCOMPUTE, + volume_id=str(volume.id), + size_gb=None, + attachable=False, + detachable=False, + mount_on_instance=True, + ) + + +def _check_volume_mount_path(volume: MassedComputeVolume) -> None: + if ( + not _VOLUME_MOUNT_PATH.fullmatch(volume.mount_path) + or volume.mount_path != f"/persistent/{volume.name}" + ): + raise ComputeError("Invalid MassedCompute volume mount path") diff --git a/src/dstack/_internal/core/compatibility/runs.py b/src/dstack/_internal/core/compatibility/runs.py index 83e5587e9d..ace77be939 100644 --- a/src/dstack/_internal/core/compatibility/runs.py +++ b/src/dstack/_internal/core/compatibility/runs.py @@ -134,7 +134,8 @@ def get_job_submission_excludes(job_submissions: list[JobSubmission]) -> Include # `Resources.description` is deprecated and never set since 0.21. Not sending it lets 0.22 # drop the field without breaking 0.21 clients. submission_excludes["job_provisioning_data"] = { - "instance_type": {"resources": {"description": True}} + "instance_type": {"resources": {"description": True}}, + "volume_mounts": True, # Server-owned host paths are not part of a run apply request. } submission_excludes["provider_ref"] = True return submission_excludes diff --git a/src/dstack/_internal/core/errors.py b/src/dstack/_internal/core/errors.py index e2685a64e4..4816ce0d19 100644 --- a/src/dstack/_internal/core/errors.py +++ b/src/dstack/_internal/core/errors.py @@ -106,6 +106,30 @@ class ComputeResourceNotFoundError(ComputeError): pass +class VolumeProvisioningPending(ComputeError): + """Provisioning needs another provider check. Preserve the allocated ID when available.""" + + def __init__(self, message: str, volume_id: Optional[str] = None): + super().__init__(message) + self.volume_id = volume_id + + +class VolumeProvisioningError(ComputeError): + """The create was rejected or the allocated volume failed. Preserve any allocated ID.""" + + def __init__(self, message: str, volume_id: Optional[str] = None): + super().__init__(message) + self.volume_id = volume_id + + +class VolumeDeletionPending(ComputeError): + """The provider has not confirmed volume deletion. Retry without forgetting the volume.""" + + def __init__(self, message: str, volume_id: Optional[str] = None): + super().__init__(message) + self.volume_id = volume_id + + class PlacementGroupInUseError(ComputeError): pass diff --git a/src/dstack/_internal/core/models/runs.py b/src/dstack/_internal/core/models/runs.py index 8f11c60e23..27de051fef 100644 --- a/src/dstack/_internal/core/models/runs.py +++ b/src/dstack/_internal/core/models/runs.py @@ -2,6 +2,7 @@ from enum import Enum from typing import Annotated, Any, Dict, List, Literal, Optional, Self from urllib.parse import urlparse +from uuid import UUID from pydantic import UUID4, ConfigDict, Field, model_validator @@ -45,7 +46,7 @@ from dstack._internal.core.models.resources import Memory, ResourcesSpec from dstack._internal.core.models.services import AnyModel from dstack._internal.core.models.unix import UnixUser -from dstack._internal.core.models.volumes import MountPoint +from dstack._internal.core.models.volumes import MountPoint, Volume from dstack._internal.utils import common as common_utils from dstack._internal.utils.common import format_pretty_duration @@ -352,6 +353,8 @@ class JobProvisioningData(CoreModel): ssh_proxy: Optional[SSHConnectionParams] = None backend_data: Optional[str] = None """`backend_data` stores backend-specific data in JSON.""" + volume_mounts: Optional[dict[UUID, str]] = Field(default=None, exclude_if=lambda v: v is None) + """Host mount paths by dstack volume ID. The backend confirms them before publishing hostname.""" gpu_driver: Optional[GpuDriverInfo] = None """`gpu_driver` is the accelerator driver installed on the host, when known. Detected via the shim for VM-based backends and SSH fleets; taken from the @@ -359,6 +362,22 @@ class JobProvisioningData(CoreModel): after provisioning. """ + def can_mount_volume(self, volume: Volume) -> bool: + """Whether the volume can be used by a job on this instance.""" + zone = volume.get_availability_zone() + return ( + volume.matches_location(self.get_base_backend(), self.region) + and ( + zone is None + or self.availability_zone is None + or zone.lower() == self.availability_zone.lower() + ) + and ( + not volume.mount_on_instance + or bool(self.volume_mounts and volume.id in self.volume_mounts) + ) + ) + def get_base_backend(self) -> BackendType: if self.base_backend is not None: return self.base_backend diff --git a/src/dstack/_internal/core/models/volumes.py b/src/dstack/_internal/core/models/volumes.py index 41ed12feed..9da50506d1 100644 --- a/src/dstack/_internal/core/models/volumes.py +++ b/src/dstack/_internal/core/models/volumes.py @@ -18,9 +18,7 @@ class VolumeStatus(str, Enum): SUBMITTED = "submitted" PROVISIONING = "provisioning" - """`PROVISIONING` is currently not used because on all backends supporting volumes, - volumes become `ACTIVE` almost immediately after provisioning. - """ + """A provider create may have started. Reconcile it before deleting the volume.""" ACTIVE = "active" FAILED = "failed" @@ -187,6 +185,24 @@ class DaytonaVolumeConfiguration(VolumeConfigurationWithVolumeID): ) +class MassedComputeVolumeConfiguration(VolumeConfigurationWithVolumeID): + backend: Annotated[ + Literal[BackendType.MASSEDCOMPUTE], Field(description="The volume backend") + ] = BackendType.MASSEDCOMPUTE + auto_cleanup_duration: Annotated[ + OptionalIdleDuration, + Field(description="MassedCompute volumes require manual deletion. Omit or set to `off`"), + ] = None + tags: Annotated[Optional[Dict[str, str]], Field(description="The dstack volume tags")] = None + + @field_validator("auto_cleanup_duration") + @classmethod + def _validate_auto_cleanup_duration(cls, value: Optional[int]) -> Optional[int]: + if value is not None and value > 0: + raise ValueError("MassedCompute volumes do not support automatic cleanup") + return value + + class LiumVolumeConfiguration(VolumeConfigurationWithVolumeID): backend: Annotated[Literal[BackendType.LIUM], Field(description="The volume backend")] = ( BackendType.LIUM @@ -200,6 +216,7 @@ class LiumVolumeConfiguration(VolumeConfigurationWithVolumeID): KubernetesVolumeConfiguration, DaytonaVolumeConfiguration, LiumVolumeConfiguration, + MassedComputeVolumeConfiguration, ] @@ -232,6 +249,8 @@ class VolumeProvisioningData(CoreModel): attachable: bool = True """`attachable` shows whether the volume should be attached and detached manually.""" detachable: bool = True + mount_on_instance: bool = Field(default=False, exclude_if=lambda v: not v) + """The provider mounts this filesystem on the instance before a job starts.""" backend_data: Optional[str] = None """`backend_data` stores backend-specific data in JSON.""" @@ -283,6 +302,10 @@ def get_attachment_data_for_instance(self, instance_id: str) -> Optional[VolumeA # volume was attached before attachments were introduced return self.attachment_data + @property + def mount_on_instance(self) -> bool: + return self.provisioning_data is not None and self.provisioning_data.mount_on_instance + def get_backend(self) -> BackendType: return self.configuration.backend diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py index e6eddfd15c..8d3df6720c 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py @@ -4,7 +4,7 @@ from datetime import timedelta from typing import Optional, Sequence -from sqlalchemy import and_, not_, or_, select, update +from sqlalchemy import and_, delete, not_, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import joinedload, load_only @@ -45,6 +45,7 @@ InstanceModel, JobModel, ProjectModel, + VolumeAttachmentModel, ) from dstack._internal.server.services import events from dstack._internal.server.services.fleets import skip_fleet_min_processing_interval @@ -485,6 +486,14 @@ async def _apply_process_result( ), ) + if result.release_volume_attachments: + await session.execute( + delete(VolumeAttachmentModel).where( + VolumeAttachmentModel.instance_id == instance_model.id, + VolumeAttachmentModel.volume_id.in_(result.release_volume_attachments), + ) + ) + emit_instance_status_change_event( session=session, instance_model=instance_model, diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py index c8cf9c856a..d8c12c1ee1 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py @@ -59,6 +59,7 @@ ) from dstack._internal.server.services.logging import fmt from dstack._internal.server.services.runner import client as runner_client +from dstack._internal.server.services.runner.pool import instance_connection_pool from dstack._internal.server.services.runner.ssh import runner_ssh_tunnel from dstack._internal.utils.common import get_current_datetime, get_or_error, run_async from dstack._internal.utils.logging import get_logger @@ -357,6 +358,20 @@ async def _process_wait_for_instance_provisioning_data( instance_model.project.ssh_public_key, instance_model.project.ssh_private_key, ) + if job_provisioning_data.hostname and job_provisioning_data.volume_mounts: + # Publishing the SSH address admits jobs. Keep it unset while any mount is + # missing so a VM that times out before admission can be deleted without a flush. + conn = await run_async( + instance_connection_pool.get_or_open, + get_instance_ssh_private_keys(instance_model), + job_provisioning_data, + None, + ) + if conn is None: + return result + if not await conn.has_volume_mounts(job_provisioning_data.volume_mounts.values()): + await run_async(instance_connection_pool.drop_by_jpd, job_provisioning_data) + return result result.instance_update_map["job_provisioning_data"] = ( job_provisioning_data.model_dump_json() ) diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py index 8f78b743a2..ee7f810ea8 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py @@ -67,6 +67,7 @@ class HealthCheckCreate(TypedDict): @dataclass class ProcessResult: instance_update_map: InstanceUpdateMap = field(default_factory=InstanceUpdateMap) + release_volume_attachments: list[uuid.UUID] = field(default_factory=list) health_check_create: Optional[HealthCheckCreate] = None new_placement_group_models: list[PlacementGroupModel] = field(default_factory=list) schedule_pg_deletion_fleet_id: Optional[uuid.UUID] = None diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py index a82e449b9b..e43b0ffc74 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py @@ -1,5 +1,10 @@ +from dstack._internal.core.backends.base.compute import ComputeWithVolumeSupport from dstack._internal.core.backends.features import get_backends_with_resource_listing_support -from dstack._internal.core.errors import BackendError, NotYetTerminated +from dstack._internal.core.errors import ( + BackendError, + NotYetTerminated, + SSHError, +) from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import OrphanCleanupMode from dstack._internal.core.models.instances import InstanceStatus @@ -14,7 +19,10 @@ ) from dstack._internal.server.models import InstanceModel from dstack._internal.server.services.backends import cache as backends_cache -from dstack._internal.server.services.instances import get_instance_provisioning_data +from dstack._internal.server.services.instances import ( + get_instance_provisioning_data, + get_instance_ssh_private_keys, +) from dstack._internal.server.services.runner.pool import ( instance_connection_pool, ) @@ -37,6 +45,7 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: if job_provisioning_data is not None and job_provisioning_data.backend != BackendType.REMOTE: try: await _terminate_in_backend(instance_model, job_provisioning_data) + result.release_volume_attachments = list(job_provisioning_data.volume_mounts or ()) except Exception as exc: first_retry_at = instance_model.first_termination_retry_at if first_retry_at is None: @@ -58,6 +67,20 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: exc_info=not isinstance(exc, BackendError), ) return result + if job_provisioning_data.volume_mounts: + # Keep the VM and its attachment records until termination is confirmed. + if not isinstance(exc, NotYetTerminated) and ( + instance_model.last_termination_retry_at is None + or next_termination_retry_at(instance_model.last_termination_retry_at) + < get_termination_deadline(first_retry_at) + ): + result.event_messages.append( + "Volume attachments retained until dstack confirms the VM is gone. " + "dstack will keep retrying. " + f"Last error: {_format_error(exc)}" + ) + logger.warning("Instance %s termination pending: %r", instance_model.name, exc) + return result next_step = "Please terminate the instance manually to avoid unexpected charges." if _is_to_be_deleted_by_orphan_cleanup(instance_model, job_provisioning_data): next_step = "Orphan cleanup will retry deleting the instance." @@ -97,21 +120,50 @@ async def _terminate_in_backend( backend_type=job_provisioning_data.backend, ) as backend: if backend is None: + if job_provisioning_data.volume_mounts: + raise BackendError("Backend unavailable while terminating a VM with volumes") logger.error( "Failed to terminate instance %s. Backend %s not available.", instance_model.name, job_provisioning_data.backend, ) return + compute = backend.compute() + if job_provisioning_data.volume_mounts and job_provisioning_data.hostname: + assert isinstance(compute, ComputeWithVolumeSupport) + paths = await run_async(compute.get_volume_mounts_to_sync, job_provisioning_data) + if paths is None: + # Disappearance was confirmed without a guest. A second lookup could + # observe a running VM and delete it without ever flushing its mounts. + return + if paths: + await _sync_volume_mounts(instance_model, job_provisioning_data, paths) logger.debug("Terminating runner instance %s", job_provisioning_data.hostname) await run_async( - backend.compute().terminate_instance, + compute.terminate_instance, job_provisioning_data.instance_id, job_provisioning_data.region, job_provisioning_data.backend_data, ) +async def _sync_volume_mounts( + instance_model: InstanceModel, job_provisioning_data: JobProvisioningData, paths: list[str] +) -> None: + conn = await run_async( + instance_connection_pool.get_or_open, + get_instance_ssh_private_keys(instance_model), + job_provisioning_data, + None, + ) + if conn is None: + raise BackendError("Could not connect to the VM to flush its volumes") + try: + await conn.sync_volume_mounts(paths) + except SSHError as e: + raise BackendError("Could not flush the VM's volume mounts") from e + + def _format_error(exc: Exception) -> str: if isinstance(exc, BackendError): return str(exc) or type(exc).__name__ diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py index 26d3ffade7..5426f27247 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py @@ -674,6 +674,14 @@ async def _process_provisioning_status( # Expected while the instance is still booting logger.debug("%s: shim is unreachable: %s", fmt(context.job_model), e) success = False + except client.ShimVolumeError as e: + _terminate_job( + job_model=context.job_model, + job_update_map=result.job_update_map, + termination_reason=JobTerminationReason.VOLUME_ERROR, + termination_reason_message=str(e), + ) + return except client.ShimResponseError as e: logger.warning( "%s: shim did not accept the task submission: %s", fmt(context.job_model), e @@ -1456,6 +1464,7 @@ def _process_provisioning_with_shim( host_ssh_keys=[ssh_key] if ssh_key else [], container_ssh_keys=public_keys, instance_id=jpd.instance_id, + volume_mount_paths=jpd.volume_mounts, ) else: submitted = shim_client.submit( diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py index d95ff6355b..3d1cc5f5b8 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py @@ -416,7 +416,8 @@ class _TerminateSubmittedJobResult: @dataclass class _VolumeAttachmentPayload: volume_model: VolumeModel - attachment_data: str + attachment_data: Optional[str] + already_attached: bool = False @dataclass @@ -1909,6 +1910,8 @@ async def _process_volume_attachments( compute = backend.compute() assert isinstance(compute, ComputeWithVolumeSupport) + # A retry can select another backend. Reacquire the same volume locks so the + # worker can release every lock held by its previous attempt. volume_models = await _lock_related_volume_models( item=item, volume_model_ids=prepared_job_volumes.volume_model_ids ) @@ -1927,6 +1930,13 @@ async def _process_volume_attachments( } ) attachments: list[_VolumeAttachmentPayload] = [] + for candidates in prepared_job_volumes.volumes: + if any(v.mount_on_instance for v in candidates) and not any( + job_provisioning_data.can_mount_volume(v) for v in candidates + ): + return _VolumeAttachmentResult( + attachments, locked_volume_ids, "A requested volume is unavailable on the VM" + ) related_volume_lock_owner = _get_related_volume_lock_owner(item.id) for mount_point_volume_models in volume_models: for volume_model in mount_point_volume_models: @@ -1941,6 +1951,17 @@ async def _process_volume_attachments( and volume_model.lock_owner != related_volume_lock_owner ): raise ServerClientError("Cannot attach a volume locked for processing") + if volume.mount_on_instance: + if not job_provisioning_data.can_mount_volume(volume): + continue + already_attached = any( + a.instance_id == job_model.instance_id + for a in volume_model.attachments + ) + attachments.append( + _VolumeAttachmentPayload(volume_model, None, already_attached) + ) + break if ( job_provisioning_data.get_base_backend() != volume.get_backend() or job_provisioning_data.region.lower() != volume.get_region().lower() @@ -2136,6 +2157,8 @@ async def _apply_volume_attachment_result( .values(last_job_processed_at=now) ) for attachment in volume_attachment_result.attachments: + if attachment.already_attached: + continue session.add( VolumeAttachmentModel( volume_id=attachment.volume_model.id, diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py index bd9d71a85e..c752f57dbf 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py @@ -59,6 +59,7 @@ ) from dstack._internal.server.services.instances import ( emit_instance_status_change_event, + get_instance_provisioning_data, get_instance_ssh_private_keys, is_placeholder_instance, ) @@ -432,6 +433,11 @@ async def _load_job_volume_models( if instance_model is None: return [] jrd = get_job_runtime_data(job_model) + if jrd is not None and jrd.volume_names == [] and instance_model.volume_attachments: + instance_data = get_instance_provisioning_data(instance_model) + if instance_data is not None and instance_data.volume_mounts: + # This job used no network volumes. Keep the VM's own attachments idle. + return [] volume_names = ( jrd.volume_names if jrd and jrd.volume_names @@ -974,6 +980,13 @@ async def _detach_job_volumes( if job_provisioning_data is None: return volume_update_rows, _VolumeDetachResult(all_detached=True) + if job_provisioning_data.volume_mounts: + # These attachments belong to the VM and survive individual jobs. + volume_models = [ + v for v in volume_models if v.id not in job_provisioning_data.volume_mounts + ] + if not volume_models: + return volume_update_rows, _VolumeDetachResult(all_detached=True) logger.info("Detaching volumes: %s", [v.name for v in volume_models]) detach_result = await _detach_volumes_from_job_instance( job_model=job_model, diff --git a/src/dstack/_internal/server/background/pipeline_tasks/volumes.py b/src/dstack/_internal/server/background/pipeline_tasks/volumes.py index 23189fd79d..0f8916e379 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/volumes.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/volumes.py @@ -8,8 +8,14 @@ from sqlalchemy.orm import joinedload, load_only from dstack._internal.core.backends.base.compute import ComputeWithVolumeSupport -from dstack._internal.core.errors import BackendError -from dstack._internal.core.models.volumes import VolumeStatus +from dstack._internal.core.errors import ( + BackendError, + VolumeDeletionPending, + VolumeProvisioningError, + VolumeProvisioningPending, +) +from dstack._internal.core.models.backends.base import BackendType +from dstack._internal.core.models.volumes import VolumeProvisioningData, VolumeStatus from dstack._internal.server.background.pipeline_tasks.base import ( NOW_PLACEHOLDER, Fetcher, @@ -142,7 +148,9 @@ async def fetch(self, limit: int) -> list[VolumePipelineItem]: select(VolumeModel) .where( or_( - VolumeModel.status == VolumeStatus.SUBMITTED, + VolumeModel.status.in_( + [VolumeStatus.SUBMITTED, VolumeStatus.PROVISIONING] + ), VolumeModel.to_be_deleted == True, ), VolumeModel.deleted == False, @@ -218,7 +226,7 @@ async def process(self, item: VolumePipelineItem): if item.to_be_deleted: result = await _process_to_be_deleted_volume(volume_model) - elif item.status == VolumeStatus.SUBMITTED: + elif item.status in (VolumeStatus.SUBMITTED, VolumeStatus.PROVISIONING): result = await _process_submitted_volume(volume_model) else: return @@ -274,7 +282,7 @@ async def _apply_process_result( # TODO: Clean up volume. pass return - if item.to_be_deleted: + if update_map.get("deleted"): events.emit( session, "Volume deleted", @@ -293,7 +301,7 @@ async def _apply_process_result( class _VolumeUpdateMap(ItemUpdateMap, total=False): status: VolumeStatus - status_message: str + status_message: Optional[str] volume_provisioning_data: str deleted: bool deleted_at: UpdateMapDateTime @@ -306,6 +314,8 @@ class _ProcessResult: async def _process_submitted_volume(volume_model: VolumeModel) -> _ProcessResult: volume = volume_model_to_volume(volume_model) + managed_create = volume.get_backend() == BackendType.MASSEDCOMPUTE and not volume.external + first_create = managed_create and volume.status == VolumeStatus.SUBMITTED async with backends_cache.lease_project_backend_by_type( project=volume_model.project, backend_type=volume.configuration.backend, @@ -317,14 +327,16 @@ async def _process_submitted_volume(volume_model: VolumeModel) -> _ProcessResult volume.name, volume.configuration.backend.value, ) - return _ProcessResult( - update_map={ - "status": VolumeStatus.FAILED, - "status_message": "Backend not available", - } - ) + update_map = _VolumeUpdateMap(status_message="Backend not available") + if not managed_create: + update_map["status"] = VolumeStatus.FAILED + return _ProcessResult(update_map=update_map) compute = backend.compute() assert isinstance(compute, ComputeWithVolumeSupport) + # The winning caller keeps its SUBMITTED snapshot and may send one POST. + # A replacement reads PROVISIONING and can only look up the original create. + if first_create and not await _mark_volume_provisioning(volume_model): + return _ProcessResult() try: if volume.configuration.is_external: logger.info("Registering external volume %s", volume_model.name) @@ -338,19 +350,27 @@ async def _process_submitted_volume(volume_model: VolumeModel) -> _ProcessResult compute.create_volume, volume=volume, ) + except (VolumeProvisioningPending, VolumeProvisioningError) as e: + update_map = _get_volume_retry_update(str(e), e.volume_id, volume.get_backend()) + # Rejection of a retry cannot rule out an earlier create with a lost response. + if isinstance(e, VolumeProvisioningError) and ( + first_create or not managed_create or e.volume_id is not None + ): + update_map["status"] = VolumeStatus.FAILED + return _ProcessResult(update_map=update_map) except BackendError as e: logger.info("Failed to create volume %s: %s", volume_model.name, repr(e)) status_message = f"Backend error: {repr(e)}" if len(e.args) > 0: status_message = str(e.args[0]) - return _ProcessResult( - update_map={ - "status": VolumeStatus.FAILED, - "status_message": status_message, - } - ) + update_map = _VolumeUpdateMap(status_message=status_message) + if not managed_create or volume.volume_id is not None: + update_map["status"] = VolumeStatus.FAILED + return _ProcessResult(update_map=update_map) except Exception as e: logger.exception("Got exception when creating volume %s", volume_model.name) + if managed_create: + return _ProcessResult(update_map={"status_message": f"Unexpected error: {e!r}"}) return _ProcessResult( update_map={ "status": VolumeStatus.FAILED, @@ -359,33 +379,63 @@ async def _process_submitted_volume(volume_model: VolumeModel) -> _ProcessResult ) logger.info("Added new volume %s", volume_model.name) - # Provisioned volumes marked as active since they become available almost immediately in AWS - # TODO: Consider checking volume state - return _ProcessResult( - update_map={ - "status": VolumeStatus.ACTIVE, - "volume_provisioning_data": vpd.model_dump_json(), - } + update_map = _VolumeUpdateMap( + status=VolumeStatus.ACTIVE, + volume_provisioning_data=vpd.model_dump_json(), ) + if volume.get_backend() == BackendType.MASSEDCOMPUTE and volume.status_message is not None: + update_map["status_message"] = None + return _ProcessResult(update_map=update_map) + + +async def _mark_volume_provisioning(volume_model: VolumeModel) -> bool: + # A create may outlive its worker. Record that it needs reconciliation before calling out. + async with get_session_ctx() as session: + result = await session.execute( + update(VolumeModel) + .where( + VolumeModel.id == volume_model.id, + VolumeModel.lock_token == volume_model.lock_token, + VolumeModel.status == VolumeStatus.SUBMITTED, + VolumeModel.to_be_deleted == False, + ) + .values(status=VolumeStatus.PROVISIONING) + .returning(VolumeModel.id) + ) + if result.scalar_one_or_none() is None: + return False + emit_volume_status_change_event( + session, volume_model, VolumeStatus.SUBMITTED, VolumeStatus.PROVISIONING, None + ) + volume_model.status = VolumeStatus.PROVISIONING + return True async def _process_to_be_deleted_volume(volume_model: VolumeModel) -> _ProcessResult: volume = volume_model_to_volume(volume_model) if volume.external: return _get_deleted_result() - if volume.provisioning_data is None: - # The volume wasn't provisioned so there is nothing to delete + managed_massedcompute = volume.get_backend() == BackendType.MASSEDCOMPUTE + if volume.provisioning_data is not None: + backend_type = volume.provisioning_data.backend + elif managed_massedcompute and volume.status == VolumeStatus.PROVISIONING: + # A previous create may have succeeded without returning its ID. A FAILED + # managed volume with no ID was definitively rejected on its first attempt. + backend_type = volume.get_backend() + else: return _get_deleted_result() - if volume.provisioning_data.backend is None: + if backend_type is None: logger.error( f"Failed to delete volume {volume_model.name}. volume.provisioning_data.backend is None." ) return _get_deleted_result() async with backends_cache.lease_project_backend_by_type( project=volume_model.project, - backend_type=volume.provisioning_data.backend, + backend_type=backend_type, ) as backend: if backend is None: + if managed_massedcompute: + return _ProcessResult(update_map={"status_message": "Backend not available"}) # TODO: Retry deletion logger.error( f"Failed to delete volume {volume_model.name}. Backend {volume.configuration.backend} not available." @@ -399,7 +449,15 @@ async def _process_to_be_deleted_volume(volume_model: VolumeModel) -> _ProcessRe compute.delete_volume, volume=volume, ) - except Exception: + except VolumeDeletionPending as e: + logger.info("Volume %s deletion pending: %s", volume.name, e) + return _ProcessResult( + update_map=_get_volume_retry_update(str(e), e.volume_id, volume.get_backend()) + ) + except Exception as e: + if managed_massedcompute: + logger.exception("Could not confirm deletion of volume %s", volume.name) + return _ProcessResult(update_map={"status_message": f"Deletion unconfirmed: {e}"}) # TODO: Retry deletion logger.exception( "Got exception when deleting volume %s. Please terminate it manually to avoid unexpected charges.", @@ -408,6 +466,17 @@ async def _process_to_be_deleted_volume(volume_model: VolumeModel) -> _ProcessRe return _get_deleted_result() +def _get_volume_retry_update( + message: str, volume_id: Optional[str], backend: BackendType +) -> _VolumeUpdateMap: + update_map = _VolumeUpdateMap(status_message=message) + if volume_id is not None: + update_map["volume_provisioning_data"] = VolumeProvisioningData( + backend=backend, volume_id=volume_id, size_gb=None + ).model_dump_json() + return update_map + + def _get_deleted_result() -> _ProcessResult: return _ProcessResult( update_map={ diff --git a/src/dstack/_internal/server/schemas/runner.py b/src/dstack/_internal/server/schemas/runner.py index 3a3aac4a0a..5f7652d3b3 100644 --- a/src/dstack/_internal/server/schemas/runner.py +++ b/src/dstack/_internal/server/schemas/runner.py @@ -2,7 +2,7 @@ from enum import Enum from typing import Any, Dict, List, Optional, Union -from pydantic import field_validator +from pydantic import Field, field_validator from dstack._internal.core.models.common import CoreModel, NetworkMode from dstack._internal.core.models.repos.remote import RemoteRepoCreds @@ -133,6 +133,7 @@ def json_for_runner(self) -> str: class HealthcheckResponse(CoreModel): service: str version: str + supports_volume_mount_path: bool = False class InstanceHealthResponse(CoreModel): @@ -198,6 +199,7 @@ class ShimVolumeInfo(CoreModel): volume_id: str init_fs: bool device_name: Optional[str] = None + mount_path: Optional[str] = Field(default=None, exclude_if=lambda v: v is None) class PortMapping(CoreModel): diff --git a/src/dstack/_internal/server/services/instances.py b/src/dstack/_internal/server/services/instances.py index 734fc63734..80017bb7d9 100644 --- a/src/dstack/_internal/server/services/instances.py +++ b/src/dstack/_internal/server/services/instances.py @@ -611,6 +611,9 @@ def filter_instances( # A None region matches any region; an empty string remains an exact region. volumes_locations: Optional[set[tuple[BackendType, Optional[str], Optional[str]]]] = None + mounted_volume_groups = [ + candidates for candidates in volumes or [] if any(v.mount_on_instance for v in candidates) + ] if volumes: volumes_locations = set() for volume in volumes[0]: @@ -671,6 +674,11 @@ def filter_instances( continue if volumes_locations is not None: jpd = get_instance_provisioning_data(instance) + if jpd is None and any( + all(v.mount_on_instance for v in candidates) + for candidates in mounted_volume_groups + ): + continue # instance_matches_constraints() also skips filtering if JPD is not set if jpd is not None: instance_backend = jpd.get_base_backend() @@ -685,6 +693,11 @@ def filter_instances( and regionless_location not in volumes_locations ): continue + if any( + not any(jpd.can_mount_volume(v) for v in candidates) + for candidates in mounted_volume_groups + ): + continue filtered_instances.append(instance) return filtered_instances diff --git a/src/dstack/_internal/server/services/jobs/__init__.py b/src/dstack/_internal/server/services/jobs/__init__.py index 77a0e7c54a..99a966ff13 100644 --- a/src/dstack/_internal/server/services/jobs/__init__.py +++ b/src/dstack/_internal/server/services/jobs/__init__.py @@ -604,17 +604,8 @@ def _get_job_mount_point_attached_volume( Returns the volume attached to the job among the list of possible mount point volumes. """ for volume in volumes: - if not volume.matches_location( - job_provisioning_data.get_base_backend(), job_provisioning_data.region - ): - continue - if ( - (volume_availability_zone := volume.get_availability_zone()) is not None - and job_provisioning_data.availability_zone is not None - and volume_availability_zone.lower() != job_provisioning_data.availability_zone.lower() - ): - continue - return volume + if job_provisioning_data.can_mount_volume(volume): + return volume raise ServerClientError("Failed to find an eligible volume for the mount point") diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index b1d929ace2..b06543d6df 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -183,6 +183,10 @@ class ShimAPIVersionError(ShimError): """Raised when a caller uses an API the peer does not support. Signals a server-side bug.""" +class ShimVolumeError(ShimError): + """The requested volume cannot be passed safely to this shim.""" + + class ShimResponseError(ShimError): pass @@ -609,9 +613,14 @@ def submit_task( host_ssh_keys: list[str], container_ssh_keys: list[str], instance_id: str, + volume_mount_paths: Optional[dict[uuid.UUID, str]] = None, ) -> None: if not self.is_api_v2_supported(): raise ShimAPIVersionError() + if any(v.mount_on_instance for v in volumes) and not self._supports_volume_mount_path: + raise ShimVolumeError( + "The shim must be upgraded to use volumes mounted on the instance" + ) body = TaskSubmitRequest( id=str(task_id), name=name, @@ -625,7 +634,9 @@ def submit_task( memory=_memory_to_bytes(memory), # None = 0 = "all available" shm_size=_memory_to_bytes(shm_size), # None = 0 = "use default value" network_mode=network_mode, - volumes=[_volume_to_shim_volume_info(v, instance_id) for v in volumes], + volumes=[ + _volume_to_shim_volume_info(v, instance_id, volume_mount_paths) for v in volumes + ], volume_mounts=volume_mounts, instance_mounts=instance_mounts, gpu_devices=gpu_devices, @@ -755,7 +766,9 @@ def _raise_for_status(self, response: httpx2.Response) -> None: def _negotiate(self, healthcheck_response: Optional[httpx2.Response] = None) -> None: if healthcheck_response is None: healthcheck_response = self._request("GET", "/api/healthcheck", raise_for_status=True) - version_string = self._response(HealthcheckResponse, healthcheck_response).version + health = self._response(HealthcheckResponse, healthcheck_response) + self._supports_volume_mount_path = health.supports_volume_mount_path + version_string = health.version version_tuple = _parse_version(version_string) if version_tuple is None or version_tuple >= self._API_V2_MIN_SHIM_VERSION: api_version = 2 @@ -835,17 +848,25 @@ def instance_info_response_to_gpu_driver( ) -def _volume_to_shim_volume_info(volume: Volume, instance_id: str) -> ShimVolumeInfo: +def _volume_to_shim_volume_info( + volume: Volume, instance_id: str, volume_mount_paths: Optional[dict[uuid.UUID, str]] = None +) -> ShimVolumeInfo: device_name = None attachment_data = volume.get_attachment_data_for_instance(instance_id) if attachment_data is not None: device_name = attachment_data.device_name + mount_path = None + if volume.mount_on_instance: + mount_path = (volume_mount_paths or {}).get(volume.id) + if not mount_path: + raise ShimVolumeError(f"No host mount was provided for volume {volume.name}") return ShimVolumeInfo( backend=volume.configuration.backend.value, name=volume.name, volume_id=get_or_error(volume.volume_id), - init_fs=not volume.external, + init_fs=not volume.external and mount_path is None, device_name=device_name, + mount_path=mount_path, ) diff --git a/src/dstack/_internal/server/services/runner/pool.py b/src/dstack/_internal/server/services/runner/pool.py index 93ba015f70..b42bee411d 100644 --- a/src/dstack/_internal/server/services/runner/pool.py +++ b/src/dstack/_internal/server/services/runner/pool.py @@ -1,4 +1,5 @@ import os +import shlex import shutil import threading import time @@ -238,6 +239,25 @@ def open(self) -> None: self._tunnel.open() self._last_verified_at = time.monotonic() + async def has_volume_mounts(self, paths: Collection[str]) -> bool: + """Check whether the host has mounted all requested filesystems.""" + try: + await self._tunnel.aexec( + " && ".join(f"mountpoint -q -- {shlex.quote(p)}" for p in paths) + ) + except SSHError: + return False + return True + + async def sync_volume_mounts(self, paths: Collection[str]) -> None: + """Request a flush on each mounted filesystem before releasing its VM.""" + commands = [ + # Keep a reference to the directory across the check and fsync. + f"(cd -P -- {shlex.quote(path)} && mountpoint -q -- . && sync -- .)" + for path in paths + ] + await self._tunnel.aexec(" && ".join(commands), timeout=60) + def is_alive(self) -> bool: """ Verifies that the connection's SSH master process is alive: diff --git a/src/tests/_internal/core/backends/massedcompute/test_api_client.py b/src/tests/_internal/core/backends/massedcompute/test_api_client.py index 301b516b56..7c3150c195 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_api_client.py +++ b/src/tests/_internal/core/backends/massedcompute/test_api_client.py @@ -3,8 +3,17 @@ import httpx2 import pytest -from dstack._internal.core.backends.massedcompute.api_client import API_URL, MassedComputeAPIClient -from dstack._internal.core.errors import ComputeError +from dstack._internal.core.backends.massedcompute.api_client import ( + API_URL, + MassedComputeAPIClient, + MassedComputeLaunchUnconfirmed, +) +from dstack._internal.core.errors import ( + BackendAuthError, + ComputeError, + VolumeDeletionPending, + VolumeProvisioningError, +) class TestLaunch: @@ -15,7 +24,7 @@ def test_lost_response(self, http_mock, visible): other = {"name": "other", "uuid": "other-id", "status": "Running"} instances = [other] if visible: - instances.append({"name": name, "uuid": vm_id, "status": "Initializing"}) + instances.append({"name": name, "uuid": vm_id.upper(), "status": "Initializing"}) http_mock.post(f"{API_URL}/instance/launch", exc=httpx2.ReadTimeout) http_mock.get(f"{API_URL}/instance", json={"runningInstances": instances}) client = MassedComputeAPIClient("test-key") @@ -27,6 +36,56 @@ def test_lost_response(self, http_mock, visible): client.launch(name, "gpu_1x_pro_6000_blackwell", "true") assert [r.method for r in http_mock.request_history].count("POST") == 1 + @pytest.mark.parametrize( + ("response", "unconfirmed"), + [ + *[({"status_code": code}, False) for code in (401, 403, 404, 409, 422)], + ({"exc": httpx2.ConnectTimeout}, False), + *[({"status_code": code}, True) for code in (400, 408, 502)], + ({"json": {"response": "invalid"}}, True), + ], + ) + def test_distinguishes_rejected_and_unconfirmed_volume_launches( + self, http_mock, response, unconfirmed + ): + http_mock.post(f"{API_URL}/instance/launch", **response) + with pytest.raises((BackendAuthError, ComputeError)) as exc: + MassedComputeAPIClient("test").launch("vm", "gpu", "true", ["volume"]) + assert isinstance(exc.value, MassedComputeLaunchUnconfirmed) == unconfirmed + + +class TestCreateVolume: + @pytest.mark.parametrize( + "response", + [{"status_code": code} for code in (401, 403, 404, 422)] + + [{"exc": httpx2.ConnectTimeout}], + ) + def test_reports_definite_rejection_without_volume_id(self, http_mock, response): + http_mock.post(f"{API_URL}/storage-volumes", **response) + with pytest.raises(VolumeProvisioningError) as rejected: + MassedComputeAPIClient("test").create_volume("checkpoints") + assert rejected.value.volume_id is None + + +class TestDeleteVolume: + def test_retries_until_provider_confirms_deletion(self, http_mock): + volume_id = "78ee0ea9-4c18-4aa4-b0df-aa1212734d45" + http_mock.delete( + f"{API_URL}/storage-volumes/{volume_id}", + [ + {"status_code": 409}, + {"status_code": 202, "json": {"result": {"deleted": False}}}, + {"status_code": 200, "json": {"result": {"id": volume_id, "deleted": True}}}, + {"status_code": 404}, + ], + ) + client = MassedComputeAPIClient("test") + for _ in range(2): + with pytest.raises(VolumeDeletionPending): + client.delete_volume(volume_id) + client.delete_volume(volume_id) + client.delete_volume(volume_id) + class TestGetInstance: def test_invalid_response_keeps_password_out_of_traceback(self, http_mock): diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py index ed6ce43a40..ac4d588640 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_compute.py +++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py @@ -1,5 +1,6 @@ from datetime import datetime, timezone +import httpx2 import pytest from dstack._internal.core.backends.massedcompute.api_client import API_URL @@ -8,54 +9,313 @@ MassedComputeConfig, MassedComputeCreds, ) -from dstack._internal.core.errors import NotYetTerminated +from dstack._internal.core.errors import ( + ComputeError, + NotYetTerminated, + ProvisioningError, + VolumeDeletionPending, + VolumeProvisioningError, + VolumeProvisioningPending, +) +from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import OwnerType +from dstack._internal.core.models.volumes import ( + MassedComputeVolumeConfiguration, + VolumeStatus, +) +from dstack._internal.server.testing.common import ( + get_instance_configuration, + get_instance_offer_with_availability, + get_job_provisioning_data, + get_volume, +) +from dstack._internal.utils.hash import slugify +VM_ID = "465e97cc-77cc-47dd-bb7c-1835ee127f9f" +VOLUME_ID = "78ee0ea9-4c18-4aa4-b0df-aa1212734d45" +OTHER_ID = "1a821471-d1d7-4c27-971d-10d3951ccce7" +PROVIDER_REF = "abcdefgh1234" -class TestTerminateInstance: - def test_waits_for_disappearance_and_accepts_repeated_calls(self, http_mock): - compute = MassedComputeCompute( - MassedComputeConfig(creds=MassedComputeCreds(api_key="test")) - ) - vm = {"uuid": "vm-id", "name": "vm", "status": "Stopped"} + +@pytest.fixture +def compute(): + return MassedComputeCompute(MassedComputeConfig(creds=MassedComputeCreds(api_key="test"))) + + +@pytest.fixture +def offer(): + return get_instance_offer_with_availability(backend=BackendType.MASSEDCOMPUTE) + + +@pytest.fixture +def storage(): + return { + "id": VOLUME_ID, + "name": "checkpoints", + "status": "active", + "canManage": True, + "mountPath": "/persistent/checkpoints", + "hiddenAttachedCount": 0, + "attachedTo": [], + } + + +@pytest.fixture +def managed_volume(storage): + volume = get_volume( + configuration=MassedComputeVolumeConfiguration(), status=VolumeStatus.SUBMITTED + ) + storage["name"] = slugify("dstack", str(volume.id), hash_size=15) + storage["mountPath"] = "/persistent/" + storage["name"] + return volume + + +@pytest.fixture +def volume_config(compute, http_mock, storage): + http_mock.get(f"{API_URL}/storage-volumes", json={"storageVolumes": [storage]}) + volume = get_volume( + configuration=MassedComputeVolumeConfiguration(volume_id=VOLUME_ID.upper()) + ) + volume.provisioning_data = compute.register_volume(volume) + config = get_instance_configuration() + config.provider_ref = PROVIDER_REF + config.volumes = [volume] + return config + + +@pytest.fixture +def launch_volume_vm(compute, http_mock, offer, volume_config, storage): + def launch(lost_reply=False): + response = {"exc": httpx2.ReadTimeout} if lost_reply else {"json": {"response": VM_ID}} + http_mock.post(f"{API_URL}/instance/launch", **response) + data = compute.create_instance(offer, volume_config, None) + vm = { + "uuid": VM_ID, + "name": http_mock.last_request.json()["instanceName"], + "status": "Running", + "os_booted": True, + "username": "Ubuntu", + "ip": "192.0.2.1", + } + assert http_mock.last_request.json()["volumeIds"] == [VOLUME_ID] + assert data.volume_mounts == {volume_config.volumes[0].id: storage["mountPath"]} + http_mock.get(f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm]}) + return data, vm + + return launch + + +class TestCreateInstance: + def test_omits_volume_ids_for_a_plain_vm(self, compute, http_mock, offer): + http_mock.post(f"{API_URL}/instance/launch", json={"response": VM_ID}) + data = compute.create_instance(offer, get_instance_configuration(), None) + assert "volumeIds" not in http_mock.last_request.json() + assert data.instance_id == VM_ID + assert data.backend_data is None and data.volume_mounts is None + + def test_fails_before_launch_if_volume_in_use( + self, compute, http_mock, offer, volume_config, storage + ): + storage["hiddenAttachedCount"] = 1 + http_mock.get(f"{API_URL}/storage-volumes", json={"storageVolumes": [storage]}) + with pytest.raises(ComputeError, match="unavailable or in use"): + compute.create_instance(offer, volume_config, None) + assert all(request.method == "GET" for request in http_mock.request_history) + + +class TestUpdateProvisioningData: + def test_recovers_the_same_launch_after_a_lost_reply( + self, compute, http_mock, launch_volume_vm, storage + ): + data, vm = launch_volume_vm(lost_reply=True) + assert data.instance_id == vm["name"] + # Resume from the provisioning data saved by the previous worker. + data = type(data).model_validate_json(data.model_dump_json()) http_mock.get( - f"{API_URL}/instance/vm-id", + f"{API_URL}/instance", [ + {"json": {"runningInstances": [{**vm, "name": vm["name"] + "-other"}]}}, + {"json": {"runningInstances": [vm, {**vm, "uuid": OTHER_ID}]}}, {"json": {"runningInstances": [vm]}}, - {"json": {"runningInstances": []}}, ], ) - http_mock.post(f"{API_URL}/instance/terminate", status_code=202) + compute.update_provisioning_data(data, "", "") + assert data.instance_id == vm["name"] and data.hostname is None + with pytest.raises(ComputeError, match="Multiple"): + compute.update_provisioning_data(data, "", "") + compute.update_provisioning_data(data, "", "") + assert data.instance_id == VM_ID and data.hostname is None + storage["attachedTo"] = [{"uuid": VM_ID.upper()}] + http_mock.get(f"{API_URL}/storage-volumes", json={"storageVolumes": [storage]}) + compute.update_provisioning_data(data, "", "") + assert data.hostname == vm["ip"] and data.backend_data is None + assert [r.method for r in http_mock.request_history].count("POST") == 1 + + @pytest.mark.parametrize( + "changes", + [ + {"attachedTo": []}, + {"attachedTo": [{"uuid": OTHER_ID}]}, + {"hiddenAttachedCount": 1}, + {"mountPath": "/persistent/unexpected"}, + ], + ) + def test_rejects_changed_mount_or_owner( + self, compute, http_mock, launch_volume_vm, storage, changes + ): + data, _ = launch_volume_vm() + storage["attachedTo"] = [{"uuid": VM_ID}] + storage.update(changes) + http_mock.get(f"{API_URL}/storage-volumes", json={"storageVolumes": [storage]}) + with pytest.raises(ProvisioningError, match="failed to attach"): + compute.update_provisioning_data(data, "", "") + assert data.hostname is None + +class TestTerminateInstance: + @pytest.mark.parametrize("lost_reply", [False, True]) + def test_terminates_by_uuid_and_accepts_disappearance( + self, compute, http_mock, launch_volume_vm, lost_reply + ): + data, vm = launch_volume_vm(lost_reply=lost_reply) + vm["status"] = "Stopped" + snapshots = [{"json": {"runningInstances": [vm]}}, {"json": {"runningInstances": []}}] + if lost_reply: + http_mock.get(f"{API_URL}/instance", snapshots) + http_mock.get(f"{API_URL}/instance/{VM_ID}", snapshots) + http_mock.post(f"{API_URL}/instance/terminate", status_code=202) # A stopped VM on MassedCompute is still billable. with pytest.raises(NotYetTerminated): - compute.terminate_instance("vm-id", "any") - compute.terminate_instance("vm-id", "any") - compute.terminate_instance("vm-id", "any") - - (terminate,) = [r for r in http_mock.request_history if r.method == "POST"] - assert terminate.json() == {"instanceUuids": ["vm-id"]} + compute.terminate_instance(data.instance_id, "any", data.backend_data) + compute.terminate_instance(data.instance_id, "any", data.backend_data) + (terminate,) = [ + r for r in http_mock.request_history if r.url.path.endswith("/instance/terminate") + ] + assert terminate.json() == {"instanceUuids": [VM_ID]} class TestListResourceGroups: - def test_lists_only_instances_with_a_provider_ref(self, http_mock): - compute = MassedComputeCompute( - MassedComputeConfig(creds=MassedComputeCreds(api_key="test")) - ) - vm = { - "uuid": "vm-id", + def test_reports_volume_vms_for_manual_cleanup(self, compute, http_mock, launch_volume_vm): + _, vm = launch_volume_vm() + plain = { + **vm, + "uuid": OTHER_ID, "name": "dstack-main-gpu-abcdefgh12345678", - "status": "Running", "created": "2026-11-25T14:48:48.000Z", } http_mock.get( - f"{API_URL}/instance", - json={"runningInstances": [vm, {**vm, "name": "manual", "uuid": "another-vm"}]}, + f"{API_URL}/instance", json={"runningInstances": [plain, vm, {**vm, "name": "manual"}]} ) + ordinary, mounted = compute.list_resource_groups().resource_groups + assert ordinary.owner_type == OwnerType.INSTANCE + assert ordinary.primary_id == OTHER_ID and ordinary.backend_data is None + assert ordinary.created_at == datetime(2026, 11, 25, 14, 48, 48, tzinfo=timezone.utc) + assert ordinary.provider_ref == mounted.provider_ref == PROVIDER_REF + assert mounted.primary_id == VM_ID + with pytest.raises(ComputeError, match="cannot flush"): + compute.delete_resource_group(mounted) + - (group,) = compute.list_resource_groups().resource_groups +class TestCreateVolume: + def test_conflicting_first_create_never_adopts_existing_storage( + self, compute, http_mock, storage, managed_volume + ): + http_mock.post(f"{API_URL}/storage-volumes", status_code=409) + with pytest.raises(VolumeProvisioningError, match="409") as rejected: + compute.create_volume(managed_volume) + assert rejected.value.volume_id is None + assert [r.method for r in http_mock.request_history] == ["POST"] - assert group.owner_type == OwnerType.INSTANCE - assert group.provider_ref == "abcdefgh1234" - assert group.primary_id == "vm-id" - assert group.created_at == datetime(2026, 11, 25, 14, 48, 48, tzinfo=timezone.utc) + @pytest.mark.parametrize("lost_reply", [False, True]) + def test_sends_one_create_then_recovers_by_name_or_uuid( + self, compute, http_mock, storage, managed_volume, lost_reply + ): + reply = {"exc": httpx2.ReadTimeout} if lost_reply else {"json": {"storageVolume": storage}} + http_mock.post(f"{API_URL}/storage-volumes", **reply) + with pytest.raises(VolumeProvisioningPending) as result: + compute.create_volume(managed_volume) + assert result.value.volume_id == (None if lost_reply else VOLUME_ID) + assert http_mock.last_request.json() == {"name": storage["name"]} + + managed_volume.status = VolumeStatus.PROVISIONING + managed_volume.volume_id = result.value.volume_id + http_mock.get( + f"{API_URL}/storage-volumes", + [ + {"json": {"storageVolumes": []}}, + {"json": {"storageVolumes": [{**storage, "status": "creating"}]}}, + {"json": {"storageVolumes": [storage]}}, + ], + ) + # Empty snapshots are lookup-only even after a worker lost its reply. + with pytest.raises(VolumeProvisioningPending): + compute.create_volume(managed_volume) + with pytest.raises(VolumeProvisioningPending) as found: + compute.create_volume(managed_volume) + assert found.value.volume_id == VOLUME_ID + managed_volume.volume_id = found.value.volume_id + data = compute.create_volume(managed_volume) + assert data.mount_on_instance and data.volume_id == VOLUME_ID + assert [r.method for r in http_mock.request_history].count("POST") == 1 + + def test_preserves_id_of_unusable_managed_volume( + self, compute, http_mock, storage, managed_volume + ): + managed_volume.status = VolumeStatus.PROVISIONING + storage["mountPath"] = "/" + http_mock.get(f"{API_URL}/storage-volumes", json={"storageVolumes": [storage]}) + with pytest.raises(VolumeProvisioningError) as result: + compute.create_volume(managed_volume) + assert result.value.volume_id == VOLUME_ID + + +class TestDeleteVolume: + def test_persists_recovered_uuid_before_deleting( + self, compute, http_mock, storage, managed_volume + ): + http_mock.get( + f"{API_URL}/storage-volumes", + [ + {"json": {"storageVolumes": []}}, + {"json": {"storageVolumes": [storage]}}, + ], + ) + http_mock.delete(f"{API_URL}/storage-volumes/{VOLUME_ID}", status_code=404) + with pytest.raises(VolumeDeletionPending): + compute.delete_volume(managed_volume) + with pytest.raises(VolumeDeletionPending) as found: + compute.delete_volume(managed_volume) + assert found.value.volume_id == VOLUME_ID + assert all(r.method == "GET" for r in http_mock.request_history) + managed_volume.volume_id = found.value.volume_id + compute.delete_volume(managed_volume) + assert [r.method for r in http_mock.request_history].count("DELETE") == 1 + + def test_preserves_external_storage(self, compute, http_mock): + volume = get_volume( + configuration=MassedComputeVolumeConfiguration(volume_id=VOLUME_ID), external=True + ) + compute.delete_volume(volume) + assert not http_mock.called + + +class TestGetVolumeMountsToSync: + @pytest.mark.parametrize("status", [None, "Stopped", "Deleting", "Running"]) + def test_decides_from_confirmed_vm_snapshot(self, compute, http_mock, volume_config, status): + data = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE) + data.instance_id = VM_ID + data.volume_mounts = {volume_config.volumes[0].id: "/persistent/checkpoints"} + vm = {"uuid": VM_ID, "name": "vm", "status": status} + http_mock.get( + f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm] if status else []} + ) + if status == "Stopped": + with pytest.raises(ComputeError, match="Restart"): + compute.get_volume_mounts_to_sync(data) + elif status == "Deleting": + with pytest.raises(NotYetTerminated): + compute.get_volume_mounts_to_sync(data) + else: + assert compute.get_volume_mounts_to_sync(data) == ( + ["/persistent/checkpoints"] if status else None + ) diff --git a/src/tests/_internal/core/models/test_volumes.py b/src/tests/_internal/core/models/test_volumes.py index 46b692e2aa..cc9d766e5c 100644 --- a/src/tests/_internal/core/models/test_volumes.py +++ b/src/tests/_internal/core/models/test_volumes.py @@ -6,6 +6,7 @@ from dstack._internal.core.models.volumes import ( DaytonaVolumeConfiguration, InstanceMountPoint, + MassedComputeVolumeConfiguration, VolumeConfiguration, VolumeConfigurationWithSize, VolumeMountPoint, @@ -49,6 +50,41 @@ def test_rejects_fixed_size_and_region(self, field, value): VolumeConfiguration.model_validate({"backend": "daytona", field: value}) +class TestMassedComputeVolumeConfiguration: + @pytest.mark.parametrize("volume_id", [None, "existing-volume"]) + def test_roundtrip(self, volume_id): + spec = VolumeSpec.model_validate( + { + "configuration": { + "backend": "massedcompute", + "name": "cache", + "volume_id": volume_id, + } + } + ) + + assert isinstance(spec.configuration, MassedComputeVolumeConfiguration) + assert spec.configuration.is_external == (volume_id is not None) + assert VolumeSpec.model_validate_json(spec.model_dump_json()) == spec + + @pytest.mark.parametrize(("field", "value"), [("size", 100), ("region", "us")]) + def test_rejects_fixed_size_and_region(self, field, value): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + VolumeConfiguration.model_validate({"backend": "massedcompute", field: value}) + + @pytest.mark.parametrize("duration", [None, "off", False, -1, 0]) + def test_allows_disabled_auto_cleanup(self, duration): + config = MassedComputeVolumeConfiguration.model_validate( + {"auto_cleanup_duration": duration} + ) + assert config.auto_cleanup_duration is None or config.auto_cleanup_duration <= 0 + + @pytest.mark.parametrize("duration", [1, "1d"]) + def test_rejects_auto_cleanup(self, duration): + with pytest.raises(ValidationError, match="do not support automatic cleanup"): + MassedComputeVolumeConfiguration.model_validate({"auto_cleanup_duration": duration}) + + class TestVolumeProvisioningData: def test_existing_capacity_remains_an_integer(self): data = VolumeProvisioningData.model_validate( @@ -58,6 +94,7 @@ def test_existing_capacity_remains_an_integer(self): payload = json.loads(data.model_dump_json()) assert type(payload["size_gb"]) is int assert payload["size_gb"] == 120 + assert "mount_on_instance" not in payload assert VolumeProvisioningData.model_validate(payload).size_gb == 120 diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py index 2ea8107eca..2c1142fbd0 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py @@ -1,7 +1,8 @@ import datetime as dt import logging +import uuid from typing import ClassVar, Optional -from unittest.mock import Mock +from unittest.mock import AsyncMock, Mock import httpx2 import pytest @@ -180,6 +181,56 @@ async def test_cloudrift_waits_for_backend_within_timeout( else: backend.compute().update_provisioning_data.assert_called_once() + async def test_deletes_vm_if_volume_never_mounts( + self, + test_db, + session: AsyncSession, + worker: InstanceWorker, + monkeypatch: pytest.MonkeyPatch, + ): + project = await create_project(session) + data = get_job_provisioning_data( + backend=BackendType.MASSEDCOMPUTE, hostname=None, dockerized=True + ) + data.volume_mounts = {uuid.uuid4(): "/persistent/checkpoints"} + instance = await create_instance( + session, project, status=InstanceStatus.PROVISIONING, job_provisioning_data=data + ) + instance.started_at = get_current_datetime() + backend = Mock() + + def set_hostname(data: JobProvisioningData, *args) -> None: + data.hostname = "192.0.2.1" + + backend.compute.return_value.update_provisioning_data.side_effect = set_hostname + monkeypatch.setattr( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_type", + mock_lease(backend), + ) + conn = AsyncMock() + conn.has_volume_mounts.return_value = False + monkeypatch.setattr( + instances_check.instance_connection_pool, "get_or_open", lambda *_: conn + ) + await process_instance(session, worker, instance) + await session.refresh(instance) + conn.has_volume_mounts.assert_awaited_once() + assert instance.job_provisioning_data is not None + assert ( + JobProvisioningData.model_validate_json(instance.job_provisioning_data).hostname + is None + ) + + instance.started_at = get_current_datetime() - dt.timedelta(hours=1) + await process_instance(session, worker, instance) + await session.refresh(instance) + assert instance.status == InstanceStatus.TERMINATING + await process_instance(session, worker, instance) + await session.refresh(instance) + backend.compute.return_value.terminate_instance.assert_called_once() + conn.sync_volume_mounts.assert_not_awaited() + assert instance.status == InstanceStatus.TERMINATED + async def test_check_shim_transitions_provisioning_on_busy( self, test_db, diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py index 109c14bd7f..e05a294050 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py @@ -1,13 +1,18 @@ import datetime as dt from contextlib import contextmanager from typing import Optional, cast -from unittest.mock import Mock, patch +from unittest.mock import AsyncMock, Mock, patch import pytest import time_machine +from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from dstack._internal.core.errors import BackendError, NotYetTerminated +from dstack._internal.core.errors import ( + BackendError, + NotYetTerminated, + SSHError, +) from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import OrphanCleanupMode from dstack._internal.core.models.instances import InstanceStatus, InstanceTerminationReason @@ -16,12 +21,20 @@ from dstack._internal.server.background.pipeline_tasks.instances import ( termination as instances_termination, ) -from dstack._internal.server.models import FleetModel, InstanceModel +from dstack._internal.server.models import ( + FleetModel, + InstanceModel, + VolumeAttachmentModel, +) from dstack._internal.server.testing.common import ( + ComputeMockSpec, create_fleet, create_instance, create_project, + create_user, + create_volume, get_job_provisioning_data, + get_volume_configuration, list_events, mock_lease, ) @@ -139,7 +152,12 @@ async def test_terminates_terminating_deleted_instance( assert instance.finished_at is not None @pytest.mark.parametrize( - "error", [BackendError("err"), RuntimeError("err"), NotYetTerminated("")] + "error", + [ + BackendError("err"), + RuntimeError("err"), + NotYetTerminated(""), + ], ) async def test_terminate_retry( self, @@ -253,6 +271,73 @@ async def test_terminate_on_termination_deadline( await session.refresh(instance) assert instance.status == InstanceStatus.TERMINATED + async def test_flushes_and_releases_vm_volume_attachments( + self, test_db, session: AsyncSession, worker: InstanceWorker + ): + project = await create_project(session) + user = await create_user(session) + volume = await create_volume(session, project, user) + other_volume = await create_volume( + session, project, user, configuration=get_volume_configuration(name="other") + ) + jpd = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE) + jpd.volume_mounts = {volume.id: "/persistent/checkpoints"} + instance = await create_instance( + session, + project, + status=InstanceStatus.TERMINATING, + volumes=[volume, other_volume], + job_provisioning_data=jpd, + ) + now = dt.datetime(2025, 1, 1, tzinfo=dt.timezone.utc) + instance.first_termination_retry_at = now - dt.timedelta(minutes=16) + instance.last_termination_retry_at = instance.first_termination_retry_at + instance.termination_reason = InstanceTerminationReason.IDLE_TIMEOUT + await session.commit() + + compute = Mock(spec=ComputeMockSpec) + compute.get_volume_mounts_to_sync.side_effect = [ + ["/persistent/checkpoints"], + ["/persistent/checkpoints"], + None, + ] + compute.terminate_instance.side_effect = NotYetTerminated("Deletion submitted") + backend = Mock() + backend.compute.return_value = compute + conn = AsyncMock() + conn.sync_volume_mounts.side_effect = [SSHError("flush failed"), None] + with ( + patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_type", + mock_lease(backend), + ), + patch.object( + instances_termination.instance_connection_pool, "get_or_open", return_value=conn + ), + ): + with time_machine.travel(now, tick=False): + await process_instance(session, worker, instance) + compute.terminate_instance.assert_not_called() + await session.refresh(instance) + assert instance.status == InstanceStatus.TERMINATING + attachment = select(VolumeAttachmentModel.volume_id).where( + VolumeAttachmentModel.instance_id == instance.id + ) + assert set(await session.scalars(attachment)) == {volume.id, other_volume.id} + assert any( + "Volume attachments retained" in e.message for e in await list_events(session) + ) + with time_machine.travel(now + dt.timedelta(minutes=1), tick=False): + await process_instance(session, worker, instance) + compute.terminate_instance.assert_called_once() + with time_machine.travel(now + dt.timedelta(minutes=2), tick=False): + await process_instance(session, worker, instance) + compute.terminate_instance.assert_called_once() + assert conn.sync_volume_mounts.await_count == 2 + assert list(await session.scalars(attachment)) == [other_volume.id] + await session.refresh(instance) + assert instance.status == InstanceStatus.TERMINATED + async def test_emits_event_if_all_termination_attempts_failed( self, test_db, diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py index e5b115ce44..0b16b63b13 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py @@ -735,6 +735,7 @@ async def test_provisioning_shim( if sshproxy_enforced else [project_ssh_pub_key, "user_ssh_key"], instance_id=job_provisioning_data.instance_id, + volume_mount_paths=None, ) await session.refresh(job) assert job.status == JobStatus.PULLING @@ -827,6 +828,7 @@ async def test_provisioning_shim_with_volumes( host_ssh_keys=["user_ssh_key"], container_ssh_keys=[project_ssh_pub_key, "user_ssh_key"], instance_id=job_provisioning_data.instance_id, + volume_mount_paths=None, ) await session.refresh(job) assert job.status == JobStatus.PULLING diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py index 603536370e..ad09a5fe0d 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py @@ -40,6 +40,7 @@ from dstack._internal.core.models.runs import JobRuntimeData, JobStatus, JobTerminationReason from dstack._internal.core.models.users import GlobalRole from dstack._internal.core.models.volumes import ( + MassedComputeVolumeConfiguration, VolumeAttachmentData, VolumeMountPoint, VolumeStatus, @@ -2820,6 +2821,63 @@ async def test_attaches_volume_on_existing_instance( (EventTargetType.JOB, job.id), } + async def test_releases_volume_lock_when_retry_uses_another_backend( + self, test_db, session: AsyncSession, worker: JobSubmittedWorker + ): + project = await create_project(session) + user = await create_user(session) + repo = await create_repo(session, project_id=project.id) + fleet = await create_fleet(session, project) + aws_volume = await create_volume( + session, + project, + user, + status=VolumeStatus.ACTIVE, + volume_provisioning_data=get_volume_provisioning_data(backend=BackendType.AWS), + ) + backend = BackendType.MASSEDCOMPUTE + data = get_volume_provisioning_data(backend=backend) + data.mount_on_instance = True + data.attachable = data.detachable = False + volume = await create_volume( + session, + project, + user, + configuration=MassedComputeVolumeConfiguration(name="checkpoints"), + volume_provisioning_data=data, + status=VolumeStatus.ACTIVE, + ) + jpd = get_job_provisioning_data(backend=backend, region="any", dockerized=True) + jpd.volume_mounts = {volume.id: "/persistent/checkpoints"} + instance = await create_instance( + session, project, fleet, backend=backend, region="any", job_provisioning_data=jpd + ) + spec = get_run_spec(repo_id=repo.name) + spec.configuration.volumes = [ + VolumeMountPoint(name=[aws_volume.name, volume.name], path="/data") + ] + run = await create_run(session, project, repo, user, run_spec=spec) + job = await create_job(session, run, instance=instance, instance_assigned=True) + aws_volume.lock_owner = f"{JobSubmittedPipeline.__name__}:{job.id}" + aws_volume.lock_token = uuid.uuid4() + aws_volume.lock_expires_at = get_current_datetime() - timedelta(seconds=1) + backend_mock = Mock(TYPE=backend) + backend_mock.compute.return_value = Mock(spec=ComputeMockSpec) + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_type", + mock_lease(backend_mock), + ): + await _process_job(session, worker, job) + + await session.refresh(job) + await session.refresh(aws_volume) + assert job.status == JobStatus.PROVISIONING + assert JobRuntimeData.model_validate_json( + get_or_error(job.job_runtime_data) + ).volume_names == [volume.name] + assert aws_volume.lock_owner is None + backend_mock.compute.return_value.attach_volume.assert_not_called() + async def test_terminates_job_when_volume_is_locked_for_processing( self, test_db, session: AsyncSession, worker: JobSubmittedWorker ): diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py b/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py index 3cac7f3f05..ad414a07bd 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py @@ -4,11 +4,21 @@ from unittest.mock import Mock, patch import pytest +import time_machine from sqlalchemy.ext.asyncio import AsyncSession -from dstack._internal.core.errors import BackendError +from dstack._internal.core.errors import ( + BackendError, + VolumeDeletionPending, + VolumeProvisioningError, + VolumeProvisioningPending, +) from dstack._internal.core.models.backends.base import BackendType -from dstack._internal.core.models.volumes import VolumeProvisioningData, VolumeStatus +from dstack._internal.core.models.volumes import ( + MassedComputeVolumeConfiguration, + VolumeProvisioningData, + VolumeStatus, +) from dstack._internal.server.background.pipeline_tasks import volumes as volumes_pipeline from dstack._internal.server.background.pipeline_tasks.volumes import ( VolumeFetcher, @@ -17,6 +27,7 @@ VolumeWorker, ) from dstack._internal.server.models import VolumeModel +from dstack._internal.server.services.volumes import delete_volumes from dstack._internal.server.testing.common import ( ComputeMockSpec, create_project, @@ -351,6 +362,164 @@ async def test_marks_volume_failed_if_backend_returns_error( assert len(events) == 1 assert events[0].message == "Volume status changed SUBMITTED -> FAILED (Some error)" + @pytest.mark.parametrize("external", [False, True]) + async def test_reconciles_massedcompute_volume_until_ready( + self, + test_db, + session: AsyncSession, + worker: VolumeWorker, + fetcher: VolumeFetcher, + external, + ): + volume_id = str(uuid.uuid4()) + volume = await create_volume( + session, + await create_project(session), + await create_user(session), + configuration=MassedComputeVolumeConfiguration( + name="data", volume_id=volume_id if external else None + ), + ) + ready = VolumeProvisioningData( + backend=BackendType.MASSEDCOMPUTE, + volume_id=volume_id, + size_gb=None, + attachable=False, + detachable=False, + ) + compute = Mock(spec=ComputeMockSpec) + provision = compute.register_volume if external else compute.create_volume + provision.side_effect = [ + VolumeProvisioningPending("Storage creating", volume_id), + VolumeProvisioningPending("Storage status unavailable"), + ready, + ] + backend = Mock() + backend.compute.return_value = compute + with ( + patch.object( + volumes_pipeline.backends_cache, + "lease_project_backend_by_type", + mock_lease(backend), + ), + time_machine.travel(get_current_datetime(), tick=False) as clock, + ): + for message in ("Storage creating", "Storage status unavailable"): + (item,) = await fetcher.fetch(1) + await worker.process(item) + await session.refresh(volume) + assert volume.status == ( + VolumeStatus.SUBMITTED if external else VolumeStatus.PROVISIONING + ) + assert volume.status_message == message + assert volume.lock_token is None + assert volume.volume_provisioning_data is not None + assert ( + VolumeProvisioningData.model_validate_json( + volume.volume_provisioning_data + ).volume_id + == volume_id + ) + await session.commit() + clock.shift(timedelta(seconds=16)) + + (item,) = await fetcher.fetch(1) + await worker.process(item) + + assert provision.call_args.kwargs["volume"].volume_id == volume_id + await session.refresh(volume) + assert volume.status == VolumeStatus.ACTIVE + assert volume.status_message is None + assert volume.volume_provisioning_data == ready.model_dump_json() + assert [event.message for event in await list_events(session)] == ( + ["Volume status changed SUBMITTED -> ACTIVE"] + if external + else [ + "Volume status changed SUBMITTED -> PROVISIONING", + "Volume status changed PROVISIONING -> ACTIVE", + ] + ) + + @pytest.mark.parametrize( + ("lost_first_reply", "allocated_id", "expected_status"), + [ + (False, None, VolumeStatus.FAILED), + (True, None, VolumeStatus.PROVISIONING), + (False, "allocated-id", VolumeStatus.FAILED), + ], + ) + async def test_deletes_after_massedcompute_create_error( + self, + test_db, + session: AsyncSession, + worker: VolumeWorker, + fetcher: VolumeFetcher, + lost_first_reply: bool, + allocated_id: str | None, + expected_status: VolumeStatus, + ): + project = await create_project(session) + user = await create_user(session) + volume = await create_volume( + session, project, user, configuration=MassedComputeVolumeConfiguration(name="data") + ) + backend = Mock() + compute = backend.compute.return_value = Mock(spec=ComputeMockSpec) + errors: list[BackendError] = [VolumeProvisioningError("Create failed", allocated_id)] + if lost_first_reply: + errors.insert(0, VolumeProvisioningPending("Lost reply")) + compute.create_volume.side_effect = errors + with ( + patch.object( + volumes_pipeline.backends_cache, + "lease_project_backend_by_type", + mock_lease(backend), + ), + time_machine.travel(get_current_datetime(), tick=False) as clock, + ): + for _ in errors: + (item,) = await fetcher.fetch(1) + await worker.process(item) + clock.shift(timedelta(seconds=16)) + assert [ + call.kwargs["volume"].status for call in compute.create_volume.call_args_list + ] == ( + [VolumeStatus.SUBMITTED, VolumeStatus.PROVISIONING] + if lost_first_reply + else [VolumeStatus.SUBMITTED] + ) + await session.refresh(volume) + assert volume.status == expected_status + assert volume.status_message == "Create failed" + await delete_volumes(session, project, [volume.name], user) + + if lost_first_reply: + # This rejection applies only to the retry. Reconcile the original + # request by name and commit its recovered ID before deleting it. + compute.delete_volume.side_effect = [ + VolumeDeletionPending("Found volume", "recovered-id"), + None, + ] + (item,) = await fetcher.fetch(1) + await worker.process(item) + await session.refresh(volume) + assert not volume.deleted + assert compute.delete_volume.call_args.kwargs["volume"].volume_id is None + await session.commit() + clock.shift(timedelta(seconds=16)) + + (item,) = await fetcher.fetch(1) + await worker.process(item) + + await session.refresh(volume) + assert volume.deleted + if allocated_id or lost_first_reply: + assert compute.delete_volume.call_args.kwargs["volume"].volume_id == ( + allocated_id or "recovered-id" + ) + else: + compute.delete_volume.assert_not_called() + async def test_skips_processing_if_lock_token_changed_before_refetch( self, test_db, session: AsyncSession, worker: VolumeWorker ): @@ -421,6 +590,113 @@ async def _change_lock_token_and_return_result(_volume_model: VolumeModel): @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestVolumeWorkerDeleted: + @pytest.mark.parametrize( + ("status", "external_id"), + [(VolumeStatus.SUBMITTED, None), (VolumeStatus.ACTIVE, "external-id")], + ) + async def test_deletes_unsubmitted_or_external_massedcompute_volume_locally( + self, + test_db, + session: AsyncSession, + worker: VolumeWorker, + fetcher: VolumeFetcher, + status, + external_id, + ): + volume = await create_volume( + session, + await create_project(session), + await create_user(session), + configuration=MassedComputeVolumeConfiguration(name="data", volume_id=external_id), + status=status, + volume_provisioning_data=( + VolumeProvisioningData( + backend=BackendType.MASSEDCOMPUTE, volume_id=external_id, size_gb=None + ) + if external_id + else None + ), + ) + volume.to_be_deleted = True + await session.commit() + + with patch.object( + volumes_pipeline.backends_cache, "lease_project_backend_by_type" + ) as lease: + (item,) = await fetcher.fetch(1) + await worker.process(item) + lease.assert_not_called() + + await session.refresh(volume) + assert volume.deleted + assert volume.deleted_at is not None + assert [event.message for event in await list_events(session)] == ["Volume deleted"] + + @pytest.mark.parametrize("volume_id", [None, "known-id"]) + async def test_confirms_massedcompute_deletion_before_forgetting_volume( + self, + test_db, + session: AsyncSession, + worker: VolumeWorker, + fetcher: VolumeFetcher, + volume_id, + ): + volume = await create_volume( + session, + await create_project(session), + await create_user(session), + configuration=MassedComputeVolumeConfiguration(name="data"), + status=VolumeStatus.PROVISIONING if volume_id is None else VolumeStatus.ACTIVE, + volume_provisioning_data=( + VolumeProvisioningData( + backend=BackendType.MASSEDCOMPUTE, volume_id=volume_id, size_gb=None + ) + if volume_id + else None + ), + ) + volume.to_be_deleted = True + await session.commit() + backend = Mock() + compute = Mock(spec=ComputeMockSpec) + backend.compute.return_value = compute + compute.delete_volume.side_effect = [ + VolumeDeletionPending("Still deleting", None if volume_id else "recovered-id"), + RuntimeError("Storage unavailable"), + None, + ] + + with time_machine.travel(get_current_datetime(), tick=False) as clock: + for available_backend in (None, backend, backend): + with patch.object( + volumes_pipeline.backends_cache, + "lease_project_backend_by_type", + mock_lease(available_backend), + ): + (item,) = await fetcher.fetch(1) + await worker.process(item) + await session.refresh(volume) + assert volume.to_be_deleted and not volume.deleted + assert volume.deleted_at is None + assert volume.status_message + assert await list_events(session) == [] + await session.commit() + clock.shift(timedelta(seconds=16)) + with patch.object( + volumes_pipeline.backends_cache, + "lease_project_backend_by_type", + mock_lease(backend), + ): + (item,) = await fetcher.fetch(1) + await worker.process(item) + + requested = compute.delete_volume.call_args.kwargs["volume"] + assert requested.id == volume.id + assert requested.volume_id == (volume_id or "recovered-id") + await session.refresh(volume) + assert volume.deleted and volume.deleted_at is not None + assert [event.message for event in await list_events(session)] == ["Volume deleted"] + async def test_marks_volume_deleted( self, test_db, session: AsyncSession, worker: VolumeWorker ): diff --git a/src/tests/_internal/server/services/runner/test_client.py b/src/tests/_internal/server/services/runner/test_client.py index d5b5da02f8..076eab5f67 100644 --- a/src/tests/_internal/server/services/runner/test_client.py +++ b/src/tests/_internal/server/services/runner/test_client.py @@ -39,6 +39,7 @@ ShimClient, ShimResponseBodyError, ShimResponseStatusError, + ShimVolumeError, _parse_version, healthcheck_response_to_instance_check, instance_info_response_to_gpu_driver, @@ -47,6 +48,7 @@ get_run_spec, get_volume, get_volume_configuration, + get_volume_provisioning_data, ) from tests.http_mock import HTTPMock @@ -616,28 +618,32 @@ def test_submit_task(self, client: ShimClient, http_mock: HTTPMock): ], ) - client.submit_task( - task_id=uuid.UUID("c514f4ee-dfe7-472c-99a3-047178aafb5b"), - name="test-0-0", - registry_username="user", - registry_password="pass", - image_name="debian", - container_user="root", - privileged=True, - gpu=1, - cpu=4.0, - memory=Memory.parse("16GB"), - shm_size=Memory.parse("1GB"), - network_mode=NetworkMode.BRIDGE, - volumes=[volume], - volume_mounts=[VolumeMountPoint(name="vol", path="/vol")], - instance_mounts=[InstanceMountPoint(instance_path="/mnt/nfs/home", path="/home")], - gpu_devices=[], - host_ssh_user="dstack", - host_ssh_keys=["host_key"], - container_ssh_keys=["project_key", "user_key"], - instance_id="i-1", - ) + def submit(paths=None): + client.submit_task( + task_id=uuid.UUID("c514f4ee-dfe7-472c-99a3-047178aafb5b"), + name="test-0-0", + registry_username="user", + registry_password="pass", + image_name="debian", + container_user="root", + privileged=True, + gpu=1, + cpu=4.0, + memory=Memory.parse("16GB"), + shm_size=Memory.parse("1GB"), + network_mode=NetworkMode.BRIDGE, + volumes=[volume], + volume_mounts=[VolumeMountPoint(name="vol", path="/vol")], + instance_mounts=[InstanceMountPoint(instance_path="/mnt/nfs/home", path="/home")], + gpu_devices=[], + host_ssh_user="dstack", + host_ssh_keys=["host_key"], + container_ssh_keys=["project_key", "user_key"], + instance_id="i-1", + volume_mount_paths=paths, + ) + + submit() assert http_mock.call_count == 2 self.assert_request(http_mock, 0, "GET", "/api/healthcheck") @@ -674,6 +680,14 @@ def test_submit_task(self, client: ShimClient, http_mock: HTTPMock): } self.assert_request(http_mock, 1, "POST", "/api/tasks", expected_request) + volume.provisioning_data = get_volume_provisioning_data(backend=BackendType.GCP) + volume.provisioning_data.mount_on_instance = True + with pytest.raises(ShimVolumeError, match="upgraded"): + submit({volume.id: "/srv/checkpoints"}) + assert ( + http_mock.call_count == 2 + ) # An older shim must never fall back to its block device path. + def test_terminate_task(self, client: ShimClient, http_mock: HTTPMock): task_id = "c514f4ee-dfe7-472c-99a3-047178aafb5b" url = f"/api/tasks/{task_id}/terminate" diff --git a/src/tests/_internal/server/services/test_instances.py b/src/tests/_internal/server/services/test_instances.py index e54f0ad97d..10d3d1fa00 100644 --- a/src/tests/_internal/server/services/test_instances.py +++ b/src/tests/_internal/server/services/test_instances.py @@ -23,7 +23,10 @@ Profile, ) from dstack._internal.core.models.runs import JobStatus -from dstack._internal.core.models.volumes import DaytonaVolumeConfiguration +from dstack._internal.core.models.volumes import ( + DaytonaVolumeConfiguration, + MassedComputeVolumeConfiguration, +) from dstack._internal.server.models import InstanceModel from dstack._internal.server.schemas.runner import TaskListItem, TaskListResponse, TaskStatus from dstack._internal.server.services.runner.client import ShimClient @@ -127,6 +130,32 @@ def test_preserves_volume_availability_zone_matching( assert result == ([instance] if matches else []) + def test_provider_mounted_volumes_on_reused_instances(self): + backend = BackendType.MASSEDCOMPUTE + jpd = get_job_provisioning_data(backend=backend, region="any") + vpd = get_volume_provisioning_data(backend=backend) + vpd.mount_on_instance = True + volume = get_volume( + configuration=MassedComputeVolumeConfiguration(), provisioning_data=vpd + ) + alias = volume.model_copy(update={"id": uuid.uuid4()}) + jpd.volume_mounts = {volume.id: "/persistent/data"} + instance = InstanceModel( + unreachable=False, + health=HealthStatus.HEALTHY, + total_blocks=1, + job_provisioning_data=jpd.model_dump_json(), + ) + + def matches(groups): + return bool(instances_services.filter_instances([instance], Profile(), volumes=groups)) + + assert matches([[alias, volume]]) + assert not matches([[volume], [alias]]) + jpd.volume_mounts = None + instance.job_provisioning_data = jpd.model_dump_json() + assert not matches([[volume]]) + def test_global_volume_matches_cpu_and_gpu_regions(self): instances = [ InstanceModel( From 3453a94959c72f0f7ca4945b2b72a391c950d2fa Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 14:13:13 +0100 Subject: [PATCH 2/8] Isolate provider-mounted volume checks and flushes Run the terminal flush on the instance, fence dstack writers, and record its result before acknowledging completion. Bound mounted-instance readiness and termination calls separately from shared provisioning while keeping the original database lease. --- runner/docs/shim.openapi.yaml | 77 ++++ runner/internal/shim/api/api_test.go | 13 + runner/internal/shim/api/handlers.go | 19 + runner/internal/shim/api/handlers_test.go | 36 +- runner/internal/shim/api/schemas.go | 7 + runner/internal/shim/api/server.go | 5 + runner/internal/shim/docker.go | 26 ++ runner/internal/shim/volume_flush.go | 379 ++++++++++++++++++ runner/internal/shim/volume_flush_test.go | 339 ++++++++++++++++ runner/internal/shim/volumes.go | 24 +- .../_internal/core/backends/base/compute.py | 25 +- .../core/backends/massedcompute/compute.py | 10 +- src/dstack/_internal/core/models/runs.py | 2 + .../pipeline_tasks/instances/__init__.py | 167 ++++++-- .../pipeline_tasks/instances/check.py | 48 ++- .../pipeline_tasks/instances/common.py | 27 +- .../pipeline_tasks/instances/termination.py | 102 +++-- src/dstack/_internal/server/schemas/runner.py | 14 +- .../server/services/runner/client.py | 12 + .../_internal/server/services/runner/pool.py | 9 - src/dstack/_internal/server/testing/common.py | 2 + .../backends/massedcompute/test_compute.py | 2 + .../pipeline_tasks/instances/conftest.py | 11 +- .../pipeline_tasks/instances/helpers.py | 2 + .../pipeline_tasks/instances/test_check.py | 1 - .../pipeline_tasks/instances/test_pipeline.py | 50 ++- .../instances/test_termination.py | 15 +- .../server/services/runner/test_client.py | 8 + 28 files changed, 1314 insertions(+), 118 deletions(-) create mode 100644 runner/internal/shim/volume_flush.go create mode 100644 runner/internal/shim/volume_flush_test.go diff --git a/runner/docs/shim.openapi.yaml b/runner/docs/shim.openapi.yaml index 99f76e5c36..5b649a4d1b 100644 --- a/runner/docs/shim.openapi.yaml +++ b/runner/docs/shim.openapi.yaml @@ -102,6 +102,43 @@ paths: schema: $ref: "#/components/schemas/InstanceInfoResponse" + /instance/flush-volumes: + post: + summary: Stop instance workloads and flush volume mounts before VM termination + description: > + Available on instances started with `DSTACK_SHIM_VOLUME_FLUSH=1` that expose a boot ID. + The first request seals the instance against new tasks and starts one background + operation to stop managed workloads and fsync the specified mount roots. + Poll with the same boot ID and set of paths. A disconnected caller can rejoin + the operation. Completion is persisted and can be replayed after a shim restart + on the same boot. A failed attempt keeps the instance sealed and the next poll retries it. + tags: [Instance] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/FlushVolumesRequest" + responses: + "200": + description: Current state of the flush attempt + content: + application/json: + schema: + $ref: "#/components/schemas/VolumeFlushResult" + "400": + description: Invalid JSON, missing boot ID, or invalid list of mount paths + $ref: "#/components/responses/PlainTextBadRequest" + "404": + description: The instance does not advertise volume flush support + $ref: "#/components/responses/PlainTextNotFound" + "409": + description: The VM boot ID changed or the instance was sealed for different paths + $ref: "#/components/responses/PlainTextConflict" + "500": + description: Cannot read the boot ID or persist the termination seal + $ref: "#/components/responses/PlainTextInternalError" + /components: get: summary: Get components @@ -495,11 +532,51 @@ components: type: string examples: - 0.18.34 + supports_volume_mount_path: + type: boolean + description: The shim can bind volumes from a provider mount path. + supports_volume_flush: + type: boolean + description: The shim supports terminal volume flushing bound to this boot ID. + boot_id: + type: string + format: uuid + description: Linux boot ID to record when admitting the instance. required: - service - version additionalProperties: false + FlushVolumesRequest: + title: shim.api.FlushVolumesRequest + type: object + properties: + boot_id: + type: string + format: uuid + description: The boot ID recorded when the server admitted this instance. + paths: + type: array + minItems: 1 + items: + type: string + pattern: '^/.+' + description: Absolute, clean paths to volume mount roots in the guest. Order and duplicates are ignored. + required: [boot_id, paths] + + VolumeFlushResult: + title: shim.VolumeFlushResult + type: object + properties: + status: + type: string + enum: [pending, done, failed] + error: + type: string + description: The reason the attempt failed. + required: [status] + additionalProperties: false + ShutdownRequest: title: shim.api.ShutdownRequest type: object diff --git a/runner/internal/shim/api/api_test.go b/runner/internal/shim/api/api_test.go index 038a447025..448818f337 100644 --- a/runner/internal/shim/api/api_test.go +++ b/runner/internal/shim/api/api_test.go @@ -14,6 +14,7 @@ type DummyRunner struct { gpus []host.GpuInfo processed atomic.Int64 mu sync.Mutex + bootID string } func (ds *DummyRunner) Submit(ctx context.Context, cfg shim.TaskConfig) error { @@ -50,6 +51,18 @@ func (ds *DummyRunner) TaskInfo(taskID string) shim.TaskInfo { return shim.TaskInfo{} } +func (ds *DummyRunner) VolumeFlushBootID() string { return ds.bootID } + +func (ds *DummyRunner) FlushVolumes(_ context.Context, bootID string, paths []string) (shim.VolumeFlushResult, error) { + if len(paths) == 0 || bootID == "" { + return shim.VolumeFlushResult{}, shim.ErrRequest + } + if bootID != ds.bootID { + return shim.VolumeFlushResult{}, shim.ErrFlushBootMismatch + } + return shim.VolumeFlushResult{Status: "pending"}, nil +} + func (ds *DummyRunner) Resources(context.Context) shim.Resources { return shim.Resources{} } diff --git a/runner/internal/shim/api/handlers.go b/runner/internal/shim/api/handlers.go index 1ab0f36ce1..fb8593ec38 100644 --- a/runner/internal/shim/api/handlers.go +++ b/runner/internal/shim/api/handlers.go @@ -16,13 +16,32 @@ func (s *ShimServer) HealthcheckHandler(w http.ResponseWriter, r *http.Request) s.mu.RLock() defer s.mu.RUnlock() + bootID := s.runner.VolumeFlushBootID() return &HealthcheckResponse{ Service: "dstack-shim", Version: s.version, SupportsVolumeMountPath: true, + SupportsVolumeFlush: bootID != "", + BootID: bootID, }, nil } +// FlushVolumesHandler starts or polls a VM termination operation. It must outlive the request. +func (s *ShimServer) FlushVolumesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + var req FlushVolumesRequest + if err := api.DecodeJSONBody(w, r, &req, true); err != nil { + return nil, err + } + result, err := s.runner.FlushVolumes(s.ctx, req.BootID, req.Paths) + if errors.Is(err, shim.ErrFlushPathsChanged) || errors.Is(err, shim.ErrFlushBootMismatch) { + return nil, &api.Error{Status: http.StatusConflict, Err: err} + } + if errors.Is(err, shim.ErrRequest) { + return nil, &api.Error{Status: http.StatusBadRequest, Err: err} + } + return result, err +} + func (s *ShimServer) ShutdownHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { var req ShutdownRequest if err := api.DecodeJSONBody(w, r, &req, true); err != nil { diff --git a/runner/internal/shim/api/handlers_test.go b/runner/internal/shim/api/handlers_test.go index 1dcc305a88..ae26b83915 100644 --- a/runner/internal/shim/api/handlers_test.go +++ b/runner/internal/shim/api/handlers_test.go @@ -2,6 +2,7 @@ package api import ( "context" + "fmt" "net/http/httptest" "strings" "testing" @@ -25,7 +26,7 @@ func TestHealthcheck(t *testing.T) { t.Errorf("Want status '%d', got '%d'", 200, responseRecorder.Code) } - expected := "{\"service\":\"dstack-shim\",\"version\":\"0.0.1.dev2\",\"supports_volume_mount_path\":true}" + expected := `{"service":"dstack-shim","version":"0.0.1.dev2","supports_volume_mount_path":true,"supports_volume_flush":false}` if strings.TrimSpace(responseRecorder.Body.String()) != expected { t.Errorf("Want '%s', got '%s'", expected, responseRecorder.Body.String()) @@ -56,6 +57,39 @@ func TestInstanceInfo(t *testing.T) { } } +func TestFlushVolumesRoute(t *testing.T) { + runner := NewDummyRunner() + server := NewShimServer(t.Context(), ":12346", "test", runner, nil, nil, nil, nil) + response := httptest.NewRecorder() + server.httpServer.Handler.ServeHTTP(response, httptest.NewRequest("POST", "/api/instance/flush-volumes", nil)) + if response.Code != 404 { + t.Fatalf("disabled flush returned %d", response.Code) + } + runner.bootID = "5aa2c153-6803-4bcf-a6f7-f1ba65f7c092" + server = NewShimServer(t.Context(), ":12346", "test", runner, nil, nil, nil, nil) + response = httptest.NewRecorder() + server.httpServer.Handler.ServeHTTP(response, httptest.NewRequest("GET", "/api/healthcheck", nil)) + expected := fmt.Sprintf(`{"service":"dstack-shim","version":"test","supports_volume_mount_path":true,"supports_volume_flush":true,"boot_id":"%s"}`, runner.bootID) + if response.Code != 200 || strings.TrimSpace(response.Body.String()) != expected { + t.Fatalf("enabled healthcheck returned %d %s", response.Code, response.Body.String()) + } + for _, tc := range []struct { + body string + code int + }{ + {fmt.Sprintf(`{"boot_id":"%s","paths":["/vol"]}`, runner.bootID), 200}, + {`{"boot_id":"wrong","paths":["/vol"]}`, 409}, + {`{"paths":["/vol"]}`, 400}, + } { + request := httptest.NewRequest("POST", "/api/instance/flush-volumes", strings.NewReader(tc.body)) + response := httptest.NewRecorder() + server.httpServer.Handler.ServeHTTP(response, request) + if response.Code != tc.code || (tc.code == 200 && strings.TrimSpace(response.Body.String()) != `{"status":"pending"}`) { + t.Errorf("flush %s: got %d %s", tc.body, response.Code, response.Body.String()) + } + } +} + func TestInstanceInfoWithoutGpus(t *testing.T) { request := httptest.NewRequest("GET", "/api/instance/info", nil) responseRecorder := httptest.NewRecorder() diff --git a/runner/internal/shim/api/schemas.go b/runner/internal/shim/api/schemas.go index 2bc0c8406d..c2e034aacb 100644 --- a/runner/internal/shim/api/schemas.go +++ b/runner/internal/shim/api/schemas.go @@ -10,6 +10,13 @@ type HealthcheckResponse struct { Service string `json:"service"` Version string `json:"version"` SupportsVolumeMountPath bool `json:"supports_volume_mount_path"` + SupportsVolumeFlush bool `json:"supports_volume_flush"` + BootID string `json:"boot_id,omitempty"` +} + +type FlushVolumesRequest struct { + BootID string `json:"boot_id"` + Paths []string `json:"paths"` } type ShutdownRequest struct { diff --git a/runner/internal/shim/api/server.go b/runner/internal/shim/api/server.go index 8b42e2d4ae..76f5d62e77 100644 --- a/runner/internal/shim/api/server.go +++ b/runner/internal/shim/api/server.go @@ -27,6 +27,8 @@ type TaskRunner interface { Terminate(ctx context.Context, taskID string, timeout uint, reason string, message string) error Remove(ctx context.Context, taskID string) error ProcessTasks(ctx context.Context) + VolumeFlushBootID() string + FlushVolumes(ctx context.Context, bootID string, paths []string) (shim.VolumeFlushResult, error) Resources(context.Context) shim.Resources Gpus(context.Context) []host.GpuInfo @@ -94,6 +96,9 @@ func NewShimServer( r.AddHandler("POST", "/api/shutdown", s.ShutdownHandler) r.AddHandler("GET", "/api/instance/health", s.InstanceHealthHandler) r.AddHandler("GET", "/api/instance/info", s.InstanceInfoHandler) + if runner.VolumeFlushBootID() != "" { + r.AddHandler("POST", "/api/instance/flush-volumes", s.FlushVolumesHandler) + } r.AddHandler("GET", "/api/components", s.ComponentListHandler) r.AddHandler("POST", "/api/components/install", s.ComponentInstallHandler) r.AddHandler("GET", "/api/tasks", s.TaskListHandler) diff --git a/runner/internal/shim/docker.go b/runner/internal/shim/docker.go index 82e13292f4..ebb0751071 100644 --- a/runner/internal/shim/docker.go +++ b/runner/internal/shim/docker.go @@ -157,6 +157,7 @@ type DockerRunner struct { gpuVendor gpu.GpuVendor gpuLock *GpuLock tasks TaskStorage + flush *terminalVolumeFlush // stateMu serializes task state file updates, see saveTaskState() stateMu sync.Mutex // authorizedKeysMu serializes authorized_keys updates, covering the whole @@ -209,6 +210,11 @@ func NewDockerRunner(ctx context.Context, dockerParams DockerParameters) (*Docke userLookup: user.Lookup, } + // A terminally sealed VM must reject new submissions even after a shim restart. + if err := runner.initVolumeFlush(); err != nil { + return nil, fmt.Errorf("restore terminal volume flush: %w", err) + } + // The task dirs are scanned once: the tasks whose dirs are claimed by a container // are restored, the dirs of the rest are orphaned and swept storedTasks := scanTaskDirs(ctx, dockerParams.TasksDir()) @@ -431,6 +437,13 @@ func (d *DockerRunner) TaskInfo(taskID string) TaskInfo { } func (d *DockerRunner) Submit(ctx context.Context, cfg TaskConfig) error { + if f := d.flush; f != nil { + f.mu.Lock() + defer f.mu.Unlock() + if f.seal != nil { + return fmt.Errorf("%w: instance is terminating", ErrRequest) + } + } task := NewTaskFromConfig(cfg) if ok := d.tasks.Add(task); !ok { return fmt.Errorf("%w: task %s is already submitted", ErrRequest, task.ID) @@ -479,6 +492,19 @@ func (d *DockerRunner) commitTerminated(ctx context.Context, task *Task) { // before returning, except for the resources that cannot be released while the // container may be running -- those are left to ProcessTasks() as well. func (d *DockerRunner) Start(ctx context.Context, taskID string) (err error) { + // A task can be removed while its Docker start request is still in flight. + // Fence the entire operation, independent of its entry in TaskStorage. + if f := d.flush; f != nil { + f.mu.Lock() + if f.seal != nil { + f.mu.Unlock() + return fmt.Errorf("%w: instance is terminating", ErrRequest) + } + f.starts.Add(1) + f.mu.Unlock() + defer f.starts.Done() + } + task, ok := d.tasks.Get(taskID) if !ok { log.Error(ctx, "cannot start: not found", "task", taskID) diff --git a/runner/internal/shim/volume_flush.go b/runner/internal/shim/volume_flush.go new file mode 100644 index 0000000000..3e7453b2c9 --- /dev/null +++ b/runner/internal/shim/volume_flush.go @@ -0,0 +1,379 @@ +package shim + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/errdefs" + "golang.org/x/sys/unix" + + "github.com/dstackai/dstack/runner/internal/common/types" +) + +var ( + ErrFlushPathsChanged = errors.New("instance was sealed for a different set of volume mounts") + ErrFlushBootMismatch = errors.New("instance boot ID differs from the admitted VM") +) + +type VolumeFlushResult struct { + Status string `json:"status"` + Error string `json:"error,omitempty"` +} + +type terminalVolumeFlush struct { + mu sync.Mutex + starts sync.WaitGroup + seal *volumeFlushSeal + recorded bool + restored bool + attempt *volumeFlushAttempt + // The worker keeps these descriptors until the shim exits. A regular mount ID + // cannot be recycled while its original mount is pinned. + pins map[string]*pinnedVolume +} + +type volumeFlushSeal struct { + BootID string `json:"boot_id"` + Paths []string `json:"paths"` + // Unique mount IDs survive a shim restart on this boot (Linux 6.8+). + // A zero entry means that only the current shim's live pins can prove identity. + MountIDs []uint64 `json:"mount_ids,omitempty"` + Complete bool `json:"complete,omitempty"` +} + +type volumeFlushAttempt struct { + done chan struct{} + err error +} + +type pinnedVolume struct { + *os.File + mountID uint64 + uniqueID uint64 +} + +// VolumeFlushBootID is empty on instances that did not opt in or lack a Linux boot ID. +func (d *DockerRunner) VolumeFlushBootID() string { + if d.flush == nil { + return "" + } + id, _ := readBootID() + return id +} + +// FlushVolumes seals the VM, then starts or polls one flush. The local seal must +// be durable before acknowledging the first request. Docker and volume I/O is +// done by the worker; disconnecting the caller does not cancel it. +func (d *DockerRunner) FlushVolumes(ctx context.Context, expectedBootID string, paths []string) (VolumeFlushResult, error) { + f := d.flush + if f == nil { + return VolumeFlushResult{}, fmt.Errorf("%w: volume flushing is disabled", ErrRequest) + } + if expectedBootID == "" { + return VolumeFlushResult{}, fmt.Errorf("%w: missing admitted VM boot ID", ErrRequest) + } + bootID, err := readBootID() + if err != nil { + return VolumeFlushResult{}, err + } + if expectedBootID != bootID { + return VolumeFlushResult{}, ErrFlushBootMismatch + } + paths, err = canonicalFlushPaths(paths) + if err != nil { + return VolumeFlushResult{}, err + } + f.mu.Lock() + defer f.mu.Unlock() + if f.seal == nil { + f.seal = &volumeFlushSeal{BootID: bootID, Paths: paths} + } else if !slices.Equal(f.seal.Paths, paths) { + return VolumeFlushResult{}, ErrFlushPathsChanged + } + if !f.recorded { + if err := d.saveVolumeFlushSeal(); err != nil { + return VolumeFlushResult{}, err + } + f.recorded = true + } + if attempt := f.attempt; attempt != nil { + select { + case <-attempt.done: + if attempt.err != nil { + f.attempt = nil // Deliver the failure once before starting a retry. + return VolumeFlushResult{Status: "failed", Error: attempt.err.Error()}, nil + } + return VolumeFlushResult{Status: "done"}, nil + default: + return VolumeFlushResult{Status: "pending"}, nil + } + } + if f.seal.Complete && f.seal.BootID == bootID { + return VolumeFlushResult{Status: "done"}, nil + } + attempt := &volumeFlushAttempt{done: make(chan struct{})} + f.attempt = attempt + go func() { + attempt.err = d.flushStoppedVolumes(ctx) + close(attempt.done) + }() + return VolumeFlushResult{Status: "pending"}, nil +} + +func canonicalFlushPaths(paths []string) ([]string, error) { + if len(paths) == 0 { + return nil, fmt.Errorf("%w: empty volume mount set", ErrRequest) + } + for _, path := range paths { + if !filepath.IsAbs(path) || path == "/" || filepath.Clean(path) != path || strings.ContainsRune(path, 0) { + return nil, fmt.Errorf("%w: expected an absolute mount directory, got %q", ErrRequest, path) + } + } + paths = slices.Clone(paths) + slices.Sort(paths) + return slices.Compact(paths), nil +} + +// readBootID reads the Linux kernel boot identity shared by admission and terminal RPCs. +var readBootID = sync.OnceValues(func() (string, error) { + id, err := os.ReadFile("/proc/sys/kernel/random/boot_id") + if err != nil { + return "", err + } + if value := strings.TrimSpace(string(id)); value != "" { + return value, nil + } + return "", errors.New("Linux boot ID is unavailable") +}) + +const volumeFlushSealName = ".terminal-volume-flush.json" + +func (d *DockerRunner) initVolumeFlush() error { + if os.Getenv("DSTACK_SHIM_VOLUME_FLUSH") != "1" { + return nil + } + d.flush = &terminalVolumeFlush{} + path := filepath.Join(d.dockerParams.TasksDir(), volumeFlushSealName) + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var seal volumeFlushSeal + if err := json.Unmarshal(data, &seal); err != nil { + return err + } + paths, err := canonicalFlushPaths(seal.Paths) + if err != nil || !slices.Equal(paths, seal.Paths) || seal.BootID == "" || + (len(seal.MountIDs) != 0 && len(seal.MountIDs) != len(paths)) { + return errors.New("invalid terminal volume flush seal") + } + d.flush.seal = &seal + d.flush.recorded = true + d.flush.restored = true + return nil +} + +func (d *DockerRunner) saveVolumeFlushSeal() error { + dir := d.dockerParams.TasksDir() + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + data, err := json.Marshal(d.flush.seal) + if err != nil { + return err + } + path := filepath.Join(dir, volumeFlushSealName) + if err := writeFileSync(path+".tmp", data, 0o600); err != nil { + return err + } + if err := os.Rename(path+".tmp", path); err != nil { + return err + } + // Persist both the rename and a newly created tasks directory. + for _, directory := range []string{dir, filepath.Dir(dir)} { + file, err := os.Open(directory) + if err != nil { + return err + } + if err := errors.Join(file.Sync(), file.Close()); err != nil { + return err + } + } + return nil +} + +func (d *DockerRunner) flushStoppedVolumes(ctx context.Context) error { + f := d.flush + bootID, err := readBootID() + if err != nil { + return err + } + if bootID != f.seal.BootID { + return errors.New("VM rebooted after the termination seal; original mounts cannot be confirmed") + } + if f.restored && (len(f.seal.MountIDs) == 0 || slices.Contains(f.seal.MountIDs, 0)) { + return errors.New("shim restarted without persistent mount identities; manual recovery is required") + } + // Pin the original mounts and persist their identities before starting the + // flush, so a retry cannot certify a replacement filesystem at the same path. + if f.pins == nil { + f.pins = make(map[string]*pinnedVolume) + } + for i, path := range f.seal.Paths { + mount, err := openFlushMount(path) + if err != nil { + return err + } + if prior := f.pins[path]; prior != nil { + _ = mount.Close() + if mount.mountID != prior.mountID { + return fmt.Errorf("volume mount %q changed since termination started", path) + } + continue + } + if f.restored && f.seal.MountIDs[i] != mount.uniqueID { + _ = mount.Close() + return fmt.Errorf("volume mount %q changed since the shim restarted", path) + } + f.pins[path] = mount + } + if len(f.seal.MountIDs) == 0 { + ids := make([]uint64, len(f.seal.Paths)) + for i, path := range f.seal.Paths { + ids[i] = f.pins[path].uniqueID + } + f.seal.MountIDs = ids + if err := d.saveVolumeFlushSeal(); err != nil { + f.seal.MountIDs = nil + return err + } + } + if err := d.stopVolumeWriters(ctx); err != nil { + return err + } + // fsync each pinned mount root, mirroring GNU sync -- . + for _, path := range f.seal.Paths { + if err := f.pins[path].Sync(); err != nil { + return fmt.Errorf("flush volume mount %q: %w", path, err) + } + } + // A mount can change while another remote filesystem is flushing. + for _, path := range f.seal.Paths { + current, err := openFlushMount(path) + if err != nil { + return err + } + _ = current.Close() + if current.mountID != f.pins[path].mountID { + return fmt.Errorf("volume mount %q changed during flush", path) + } + } + // The same sealed guest can replay a lost acknowledgment after shim restart, + // including on kernels without persistent unique mount IDs. + f.seal.Complete = true + if err := d.saveVolumeFlushSeal(); err != nil { + f.seal.Complete = false + return err + } + return nil +} + +func openFlushMount(path string) (*pinnedVolume, error) { + fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{ + Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS, + }) + if err != nil { + return nil, fmt.Errorf("open volume mount %q: %w", path, err) + } + id, err := verifiedMountID(fd, path) + if err != nil { + _ = unix.Close(fd) + return nil, err + } + var st unix.Statx_t + err = unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID_UNIQUE, &st) + if err != nil && !errors.Is(err, unix.EINVAL) { + _ = unix.Close(fd) + return nil, err + } + var uniqueID uint64 + if st.Mask&unix.STATX_MNT_ID_UNIQUE != 0 { + uniqueID = st.Mnt_id + } + return &pinnedVolume{File: os.NewFile(uintptr(fd), path), mountID: id, uniqueID: uniqueID}, nil +} + +func (d *DockerRunner) stopVolumeWriters(ctx context.Context) error { + for _, task := range d.tasks.List() { + if task.Status != TaskStatusTerminated { + err := d.Terminate(ctx, task.ID, 10, string(types.TerminationReasonTerminatedByServer), "Instance is terminating") + if err != nil && !errors.Is(err, ErrNotFound) && !errdefs.IsNotFound(err) { + return err + } + } + } + // A task may disappear from TaskStorage while a Docker create/start request + // is in flight. Sealing prevents further starts; wait for accepted ones. + d.flush.starts.Wait() + opts := container.ListOptions{All: true, Filters: taskContainerFilters()} + containers, err := d.client.ContainerList(ctx, opts) + if err != nil { + return fmt.Errorf("list managed containers: %w", err) + } + for _, c := range containers { + var err error + switch c.State { + case "exited", "dead": + continue + case "created": + // A start accepted by Docker just before a shim restart may still run. + // Removal without force conflicts if the container has already started. + err = d.client.ContainerRemove(ctx, c.ID, container.RemoveOptions{}) + default: + err = d.stopContainer(ctx, c.ID, 10) + } + if err != nil && !errdefs.IsNotFound(err) { + return fmt.Errorf("quiesce managed container %q: %w", c.ID, err) + } + } + containers, err = d.client.ContainerList(ctx, opts) + if err != nil { + return fmt.Errorf("verify stopped managed containers: %w", err) + } + for _, c := range containers { + switch c.State { + case "exited", "dead": + default: + return fmt.Errorf("managed container %q is still %s", c.ID, c.State) + } + // Shim creates containers with Docker's default no-restart policy. An + // adopted container may instead restart when the Docker daemon restarts. + info, err := d.client.ContainerInspect(ctx, c.ID) + if errdefs.IsNotFound(err) { + continue + } + if err != nil { + return err + } + if info.ContainerJSONBase == nil || info.HostConfig == nil { + return fmt.Errorf("missing restart policy for managed container %q", c.ID) + } + if !info.HostConfig.RestartPolicy.IsNone() { + if err := d.client.ContainerRemove(ctx, c.ID, container.RemoveOptions{}); err != nil && !errdefs.IsNotFound(err) { + return fmt.Errorf("remove restartable managed container %q: %w", c.ID, err) + } + } + } + return nil +} diff --git a/runner/internal/shim/volume_flush_test.go b/runner/internal/shim/volume_flush_test.go new file mode 100644 index 0000000000..048a6f3464 --- /dev/null +++ b/runner/internal/shim/volume_flush_test.go @@ -0,0 +1,339 @@ +package shim + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "testing" + "testing/synctest" + "time" + + dockertypes "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" + docker "github.com/docker/docker/client" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func TestTerminalFlushDisabled(t *testing.T) { + runner := newTestRunner(t, nil) + marker := filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName) + require.NoError(t, os.WriteFile(marker, []byte("invalid marker"), 0o600)) + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "") + require.NoError(t, runner.initVolumeFlush()) + require.Nil(t, runner.flush) + require.Empty(t, runner.VolumeFlushBootID()) + _, err := runner.FlushVolumes(t.Context(), "another-boot", []string{"/dev/shm"}) + require.ErrorIs(t, err, ErrRequest) + require.NoError(t, runner.Submit(t.Context(), TaskConfig{ID: "normal"})) + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "1") + require.Error(t, runner.initVolumeFlush(), "an opted-in shim must honor the existing seal") +} + +// Exercise fsync and mount identity through a real mounted tmpfs. +func TestTerminalVolumeFlush(t *testing.T) { + ctx := t.Context() + bootID, err := readBootID() + require.NoError(t, err) + client := &flushDockerClient{ + entered: make(chan struct{}), resume: make(chan struct{}), + } + client.containers = []dockertypes.Container{ + taskContainerSummary("", "dangling-writer", containerStatePaused), + taskContainerSummary("", "start-pending", "created"), + taskContainerSummary("task-finished", "ordinary", "exited"), + } + client.inspect = map[string]dockertypes.ContainerJSON{ + "dangling-writer": {ContainerJSONBase: &dockertypes.ContainerJSONBase{ + HostConfig: &container.HostConfig{RestartPolicy: container.RestartPolicy{Name: container.RestartPolicyAlways}}, + }}, + "ordinary": {ContainerJSONBase: &dockertypes.ContainerJSONBase{HostConfig: &container.HostConfig{}}}, + } + runner := newTestFlushRunner(t, client) + paths := []string{"/dev/shm"} + _, err = runner.FlushVolumes(ctx, "wrong-vm", paths) + require.ErrorIs(t, err, ErrFlushBootMismatch) + for _, invalid := range [][]string{nil, {"relative"}, {"/"}, {"/tmp/../dev/shm"}} { + _, err = runner.FlushVolumes(ctx, bootID, invalid) + require.ErrorIs(t, err, ErrRequest) + } + require.NoFileExists(t, filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName)) + require.NoError(t, runner.Submit(ctx, TaskConfig{ID: "already-submitted"})) + result, err := runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + waitForFlushSignal(t, client.entered) + require.FileExists(t, filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName)) + require.ErrorIs(t, runner.Submit(ctx, TaskConfig{ID: "late"}), ErrRequest) + require.ErrorIs(t, runner.Start(ctx, "already-submitted"), ErrRequest) + require.Equal(t, TaskStatusTerminated, runner.TaskInfo("already-submitted").Status) + _, err = runner.FlushVolumes(ctx, bootID, []string{"/other-volume"}) + require.ErrorIs(t, err, ErrFlushPathsChanged) + result, err = runner.FlushVolumes(ctx, bootID, []string{"/dev/shm", "/dev/shm"}) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + + // Docker accepted stop, but still lists a writer. No filesystem flush may complete. + close(client.resume) + waitForFlushSignal(t, runner.flush.attempt.done) + result, err = runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "failed", result.Status) + require.Contains(t, result.Error, "dangling-writer") + require.Equal(t, []string{"dangling-writer"}, client.stopped) + require.Equal(t, []string{"start-pending"}, client.removed) + + client.containers[0].State = "exited" + result, err = runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + waitForFlushSignal(t, runner.flush.attempt.done) + for range 2 { + result, err = runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, VolumeFlushResult{Status: "done"}, result) + } + require.Equal(t, 4, client.lists) + require.Equal(t, []string{"start-pending", "dangling-writer"}, client.removed) + require.Len(t, client.containers, 1) + require.Equal(t, "ordinary", client.containers[0].ID) +} + +func TestTerminalFlushWaitsForRemovedInFlightStart(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := t.Context() + client := &flushDockerClient{entered: make(chan struct{}), resume: make(chan struct{})} + close(client.resume) + runner := newTestFlushRunner(t, client) + blocked := &blockedTaskDir{DockerParameters: runner.dockerParams, resume: make(chan struct{})} + runner.dockerParams = blocked + require.NoError(t, runner.Submit(ctx, TaskConfig{ID: "in-flight"})) + go func() { _ = runner.Start(ctx, "in-flight") }() + synctest.Wait() + require.Equal(t, TaskStatusPreparing, runner.TaskInfo("in-flight").Status) + require.NoError(t, runner.Terminate(ctx, "in-flight", 0, "shutdown", "")) + require.NoError(t, runner.Remove(ctx, "in-flight")) + + bootID, err := readBootID() + require.NoError(t, err) + result, err := runner.FlushVolumes(ctx, bootID, []string{"/dev/shm"}) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + synctest.Wait() + require.Zero(t, client.lists, "must not certify the VM while Start can still create a container") + + close(blocked.resume) + synctest.Wait() + require.NoError(t, runner.flush.attempt.err) + require.Equal(t, 2, client.lists) + }) +} + +// Linux procfs has a real mount root but rejects directory fsync with EINVAL. +func TestTerminalFlushReportsFilesystemError(t *testing.T) { + runner := newTestFlushRunner(t, &dockerClientMock{}) + paths := []string{"/proc"} + id := runner.VolumeFlushBootID() + _, err := runner.FlushVolumes(t.Context(), id, paths) + require.NoError(t, err) + waitForFlushSignal(t, runner.flush.attempt.done) + require.ErrorIs(t, runner.flush.attempt.err, unix.EINVAL) + result, err := runner.FlushVolumes(t.Context(), id, paths) + require.NoError(t, err) + require.Equal(t, "failed", result.Status) + require.Contains(t, result.Error, `flush volume mount "/proc"`) + require.ErrorIs(t, runner.Submit(t.Context(), TaskConfig{ID: "late"}), ErrRequest) +} + +func TestTerminalFlushRequiresDurableCompletion(t *testing.T) { + client := &flushDockerClient{entered: make(chan struct{}), resume: make(chan struct{})} + runner := newTestFlushRunner(t, client) + paths := []string{"/dev/shm"} + id := runner.VolumeFlushBootID() + _, err := runner.FlushVolumes(t.Context(), id, paths) + require.NoError(t, err) + waitForFlushSignal(t, client.entered) + // Mount identities are already saved. Only the completion write will fail. + path := filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName+".tmp") + require.NoError(t, os.Mkdir(path, 0o700)) + close(client.resume) + waitForFlushSignal(t, runner.flush.attempt.done) + result, err := runner.FlushVolumes(t.Context(), id, paths) + require.NoError(t, err) + require.Equal(t, "failed", result.Status) + runner.flush = nil + require.NoError(t, runner.initVolumeFlush()) + require.False(t, runner.flush.seal.Complete) +} + +type blockedTaskDir struct { + DockerParameters + resume chan struct{} +} + +func (b *blockedTaskDir) MakeTaskDir(string) (string, error) { + <-b.resume + return "", errors.New("interrupted start") +} + +func TestTerminalFlushRestoresSealAndChecksIdentity(t *testing.T) { + ctx := t.Context() + bootID, err := readBootID() + require.NoError(t, err) + first := newTestFlushRunner(t, &dockerClientMock{}) + path := "/dev/shm" + paths := []string{path} + _, err = first.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + waitForFlushSignal(t, first.flush.attempt.done) + require.NoError(t, first.flush.attempt.err) + require.True(t, first.flush.seal.Complete) + // Reopen the completed on-disk seal as a new shim. The same boot and path + // set can replay done even if its kernel lacked persistent unique mount IDs. + mountID := first.flush.seal.MountIDs[0] + first.flush.seal.MountIDs[0] = 0 + require.NoError(t, first.saveVolumeFlushSeal()) + first.flush = nil + require.NoError(t, first.initVolumeFlush()) + result, err := first.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, VolumeFlushResult{Status: "done"}, result) + require.Nil(t, first.flush.attempt) + _, err = first.FlushVolumes(ctx, bootID, []string{"/other"}) + require.ErrorIs(t, err, ErrFlushPathsChanged) + _, err = first.FlushVolumes(ctx, "previous-guest", paths) + require.ErrorIs(t, err, ErrFlushBootMismatch) + first.flush.seal.MountIDs[0] = mountID + for _, tc := range []struct { + name string + mutate func(*volumeFlushSeal) + wantError string + }{ + {"same mount", func(*volumeFlushSeal) {}, ""}, + {"changed mount", func(s *volumeFlushSeal) { s.MountIDs[0]++ }, "changed since"}, + {"reboot", func(s *volumeFlushSeal) { s.BootID = "previous-boot" }, "VM rebooted"}, + {"reboot after completion", func(s *volumeFlushSeal) { s.BootID = "previous-boot"; s.Complete = true }, "VM rebooted"}, + {"no unique mount ID", func(s *volumeFlushSeal) { s.MountIDs[0] = 0 }, "manual recovery"}, + {"restart before mount verification", func(s *volumeFlushSeal) { s.MountIDs = nil }, "manual recovery"}, + } { + t.Run(tc.name, func(t *testing.T) { + again := newTestFlushRunner(t, &dockerClientMock{}) + original := *first.flush.seal + original.Complete = false + original.MountIDs = append([]uint64(nil), first.flush.seal.MountIDs...) + tc.mutate(&original) + again.flush.seal = &original + require.NoError(t, again.saveVolumeFlushSeal()) + again.flush = nil + require.NoError(t, again.initVolumeFlush()) + require.ErrorIs(t, again.Submit(ctx, TaskConfig{ID: "stale-submit"}), ErrRequest) + result, err := again.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + waitForFlushSignal(t, again.flush.attempt.done) + result, err = again.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + wantError := tc.wantError + if first.flush.seal.MountIDs[0] == 0 && tc.name == "same mount" { + wantError = "manual recovery" // Pre-6.8 Linux only supplies reusable mount IDs. + } + if wantError != "" { + require.Equal(t, "failed", result.Status) + require.Contains(t, result.Error, wantError) + } else { + require.Equal(t, "done", result.Status) + } + }) + } +} + +func TestTerminalFlushRejectsReplacedMount(t *testing.T) { + path := t.TempDir() + mount := func() error { return unix.Mount("tmpfs", path, "tmpfs", 0, "size=1m") } + if err := mount(); errors.Is(err, unix.EPERM) { + t.Skip("replacing the original filesystem requires CAP_SYS_ADMIN") + } else { + require.NoError(t, err) + } + t.Cleanup(func() { _ = unix.Unmount(path, unix.MNT_DETACH) }) + ctx := t.Context() + client := &flushDockerClient{entered: make(chan struct{}), resume: make(chan struct{})} + runner := newTestFlushRunner(t, client) + bootID, err := readBootID() + require.NoError(t, err) + paths := []string{path} + _, err = runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + waitForFlushSignal(t, client.entered) + // The old FD survives a lazy detach. Success on it cannot certify the replacement. + require.NoError(t, unix.Unmount(path, unix.MNT_DETACH)) + require.NoError(t, mount()) + close(client.resume) + waitForFlushSignal(t, runner.flush.attempt.done) + result, err := runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "failed", result.Status) + require.Contains(t, result.Error, "changed during flush") + + result, err = runner.FlushVolumes(ctx, bootID, paths) + require.NoError(t, err) + require.Equal(t, "pending", result.Status) + waitForFlushSignal(t, runner.flush.attempt.done) + require.ErrorContains(t, runner.flush.attempt.err, "changed since termination started") +} + +func TestOpenFlushMountRejectsPlainDirectoryAndSymlink(t *testing.T) { + _, err := openFlushMount(t.TempDir()) + require.ErrorContains(t, err, "not a verified mount point") + alias := filepath.Join(t.TempDir(), "alias") + require.NoError(t, os.Symlink("/dev/shm", alias)) + _, err = openFlushMount(alias) + require.ErrorIs(t, err, unix.ELOOP) +} + +func newTestFlushRunner(t *testing.T, client docker.APIClient) *DockerRunner { + t.Helper() + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "1") + runner := newTestRunner(t, client) + require.NoError(t, runner.initVolumeFlush()) + return runner +} + +type flushDockerClient struct { + dockerClientMock + entered, resume chan struct{} + lists int + removed []string +} + +func (c *flushDockerClient) ContainerList(_ context.Context, opts container.ListOptions) ([]dockertypes.Container, error) { + if !opts.All || !opts.Filters.ExactMatch("label", LabelKeyIsTask+"="+LabelValueTrue) { + return nil, errors.New("expected all dstack-managed containers") + } + c.lists++ + if c.lists == 1 { + close(c.entered) + <-c.resume + } + return slices.Clone(c.containers), nil +} + +func (c *flushDockerClient) ContainerRemove(_ context.Context, id string, opts container.RemoveOptions) error { + if opts.Force { + return errors.New("must stop a running writer gracefully") + } + c.containers = slices.DeleteFunc(c.containers, func(c dockertypes.Container) bool { return c.ID == id }) + c.removed = append(c.removed, id) + return nil +} + +func waitForFlushSignal(t *testing.T, signal <-chan struct{}) { + t.Helper() + select { + case <-signal: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for flush worker") + } +} diff --git a/runner/internal/shim/volumes.go b/runner/internal/shim/volumes.go index 3d51e33d4d..38079467bd 100644 --- a/runner/internal/shim/volumes.go +++ b/runner/internal/shim/volumes.go @@ -93,16 +93,9 @@ func bindMountedVolume(source, target string) error { return err } defer func() { _ = unix.Close(fd) }() - var dir, parent unix.Statx_t - if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID, &dir); err != nil { - return err - } - if err := unix.Statx(fd, "..", 0, unix.STATX_MNT_ID, &parent); err != nil { + if _, err := verifiedMountID(fd, source); err != nil { return err } - if dir.Mask&unix.STATX_MNT_ID == 0 || parent.Mask&unix.STATX_MNT_ID == 0 || dir.Mnt_id == parent.Mnt_id { - return fmt.Errorf("%s is not a verified mount point", source) - } // Build a private bind mount before publishing it to Docker. Failure drops the // detached mount when its file descriptor closes. tree, err := unix.OpenTree(fd, "", unix.AT_EMPTY_PATH|unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC) @@ -124,6 +117,21 @@ func bindMountedVolume(source, target string) error { return unix.MoveMount(tree, "", targetFD, "", unix.MOVE_MOUNT_F_EMPTY_PATH|unix.MOVE_MOUNT_T_EMPTY_PATH) } +// verifiedMountID compares the pinned directory with its parent across the mount boundary. +func verifiedMountID(fd int, source string) (uint64, error) { + var dir, parent unix.Statx_t + if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID, &dir); err != nil { + return 0, err + } + if err := unix.Statx(fd, "..", 0, unix.STATX_MNT_ID, &parent); err != nil { + return 0, err + } + if dir.Mask&unix.STATX_MNT_ID == 0 || parent.Mask&unix.STATX_MNT_ID == 0 || dir.Mnt_id == parent.Mnt_id { + return 0, fmt.Errorf("%s is not a verified mount point", source) + } + return dir.Mnt_id, nil +} + func taskVolumeMountPoint(taskID string, volume VolumeInfo) (string, error) { if volume.MountPath == "" { return getVolumeMountPoint(volume.Name), nil diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py index d739ae13f3..abb044fbec 100644 --- a/src/dstack/_internal/core/backends/base/compute.py +++ b/src/dstack/_internal/core/backends/base/compute.py @@ -758,6 +758,21 @@ class ComputeWithPrivateGatewaySupport: pass +class ComputeWithVolumeFlushSupport(ABC): + """A backend whose provider-mounted filesystems require a guest flush before VM deletion.""" + + @abstractmethod + def get_volume_mounts_to_sync( + self, provisioning_data: JobProvisioningData + ) -> Optional[list[str]]: + """Return host mounts requiring a guest flush before deleting this VM. + + An empty list skips the flush. Return None if the VM is already gone. + Raise a backend error if its state cannot be confirmed. + """ + pass + + class ComputeWithVolumeSupport(ABC): """ Must be subclassed and implemented to support volumes. @@ -785,16 +800,6 @@ def delete_volume(self, volume: Volume): """ raise NotImplementedError() - def get_volume_mounts_to_sync( - self, provisioning_data: JobProvisioningData - ) -> Optional[list[str]]: - """Return host mounts requiring a guest flush before deleting this VM. - - An empty list skips the flush. Return None if the VM is already gone. - Raise a backend error if its state cannot be confirmed. - """ - return [] - def attach_volume( self, volume: Volume, provisioning_data: JobProvisioningData ) -> VolumeAttachmentData: diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py index e0d6cedee0..748b08e1ff 100644 --- a/src/dstack/_internal/core/backends/massedcompute/compute.py +++ b/src/dstack/_internal/core/backends/massedcompute/compute.py @@ -14,6 +14,7 @@ ComputeWithInstanceVolumesSupport, ComputeWithPrivilegedSupport, ComputeWithResourceListingSupport, + ComputeWithVolumeFlushSupport, ComputeWithVolumeSupport, generate_unique_instance_name, get_shim_commands, @@ -61,6 +62,7 @@ class MassedComputeCompute( ComputeWithInstanceVolumesSupport, ComputeWithPrivilegedSupport, ComputeWithResourceListingSupport, + ComputeWithVolumeFlushSupport, ComputeWithVolumeSupport, Compute, ): @@ -91,9 +93,13 @@ def create_instance( # The image's SSH user is case-sensitive. The startup command runs as root. key_script = get_add_authorized_keys_script(instance_config.get_public_keys()) install_keys = shlex.join(["sudo", "-H", "-u", "Ubuntu", "sh", "-c", key_script]) - command = " && ".join( - [install_keys, *get_shim_commands(arch=instance_offer.instance.resources.cpu_arch)] + shim_commands = get_shim_commands( + arch=instance_offer.instance.resources.cpu_arch, + backend_shim_env={"DSTACK_SHIM_VOLUME_FLUSH": "1"} + if instance_config.volumes + else None, ) + command = " && ".join([install_keys, *shim_commands]) if not instance_config.volumes: name = generate_unique_instance_name(instance_config, with_provider_ref=True) instance_id = self.api_client.launch(name, instance_offer.instance.name, command) diff --git a/src/dstack/_internal/core/models/runs.py b/src/dstack/_internal/core/models/runs.py index 27de051fef..db8d760ad2 100644 --- a/src/dstack/_internal/core/models/runs.py +++ b/src/dstack/_internal/core/models/runs.py @@ -355,6 +355,8 @@ class JobProvisioningData(CoreModel): """`backend_data` stores backend-specific data in JSON.""" volume_mounts: Optional[dict[UUID, str]] = Field(default=None, exclude_if=lambda v: v is None) """Host mount paths by dstack volume ID. The backend confirms them before publishing hostname.""" + volume_mount_boot_id: Optional[UUID] = Field(default=None, exclude_if=lambda v: v is None) + """Guest boot on which the volume mounts were admitted. Required before flushing them.""" gpu_driver: Optional[GpuDriverInfo] = None """`gpu_driver` is the accelerator driver installed on the host, when known. Detected via the shim for VM-based backends and SSH fleets; taken from the diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py index 8d3df6720c..fca0649e1a 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py @@ -1,7 +1,10 @@ import asyncio import uuid +from collections.abc import Awaitable, Callable +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import timedelta +from functools import partial from typing import Optional, Sequence from sqlalchemy import and_, delete, not_, or_, select, update @@ -51,6 +54,7 @@ from dstack._internal.server.services.fleets import skip_fleet_min_processing_interval from dstack._internal.server.services.instances import ( emit_instance_status_change_event, + get_instance_provisioning_data, is_ssh_instance, ) from dstack._internal.server.services.locking import get_locker @@ -109,8 +113,12 @@ def __init__( lock_timeout=self._lock_timeout, heartbeater=self._heartbeater, ) + self.volume_operations = InstanceVolumeOperations( + lock_timeout, heartbeat_trigger, pipeline_hinter + ) self.__workers = [ InstanceWorker( + volume_operations=self.volume_operations, queue=self._queue, heartbeater=self._heartbeater, pipeline_hinter=pipeline_hinter, @@ -118,6 +126,10 @@ def __init__( for _ in range(self._workers_num) ] + async def drain(self): + await super().drain() + await self.volume_operations.drain() + @property def hint_fetch_model_name(self) -> str: return InstanceModel.__name__ @@ -278,6 +290,7 @@ def __init__( queue: asyncio.Queue[InstancePipelineItem], heartbeater: Heartbeater[InstancePipelineItem], pipeline_hinter: PipelineHinterProtocol, + volume_operations: "InstanceVolumeOperations", ) -> None: super().__init__( queue=queue, @@ -285,32 +298,23 @@ def __init__( pipeline_hinter=pipeline_hinter, ) + self.volume_operations = volume_operations + @tracing.instrument_pipeline_task("InstanceWorker.process") async def process(self, item: InstancePipelineItem): process_context: Optional[_ProcessContext] = None if item.status == InstanceStatus.PENDING: process_context = await _process_pending_item(item) - elif item.status == InstanceStatus.PROVISIONING: - process_context = await _process_provisioning_item(item) + elif item.status in (InstanceStatus.PROVISIONING, InstanceStatus.BUSY): + process_context = await _process_check_item(item, self.volume_operations) elif item.status == InstanceStatus.IDLE: - process_context = await _process_idle_item(item) - elif item.status == InstanceStatus.BUSY: - process_context = await _process_busy_item(item) + process_context = await _process_idle_item(item, self.volume_operations) elif item.status == InstanceStatus.TERMINATING: - process_context = await _process_terminating_item(item) + process_context = await _process_terminating_item(item, self.volume_operations) if process_context is None: return - # Keep apply centralized here because every instance path returns the same - # `ProcessResult` shape for one primary model, with only a small set of - # optional side effects such as health checks or placement-group scheduling. - await _apply_process_result( - item=item, - instance_model=process_context.instance_model, - result=process_context.result, - ) - if process_context.result.wake_fleet_id is not None: - self._pipeline_hinter.hint_fetch(FleetModel.__name__) + await _apply_and_hint(item, process_context, self._pipeline_hinter) @dataclass @@ -319,6 +323,16 @@ class _ProcessContext: result: ProcessResult +async def _apply_and_hint( + item: InstancePipelineItem, context: _ProcessContext, hinter: PipelineHinterProtocol +) -> None: + await _apply_process_result( + item=item, instance_model=context.instance_model, result=context.result + ) + if context.result.wake_fleet_id is not None: + hinter.hint_fetch(FleetModel.__name__) + + async def _process_pending_item(item: InstancePipelineItem) -> Optional[_ProcessContext]: async with get_session_ctx() as session: instance_model = await _refetch_locked_instance_for_pending_or_terminating( @@ -335,17 +349,20 @@ async def _process_pending_item(item: InstancePipelineItem) -> Optional[_Process return _ProcessContext(instance_model=instance_model, result=result) -async def _process_provisioning_item(item: InstancePipelineItem) -> Optional[_ProcessContext]: +async def _process_check_item( + item: InstancePipelineItem, volume_operations: "InstanceVolumeOperations" +) -> Optional[_ProcessContext]: async with get_session_ctx() as session: instance_model = await _refetch_locked_instance_for_check(session=session, item=item) if instance_model is None: log_lock_token_mismatch(logger, item) return None - result = await check_instance(instance_model) - return _ProcessContext(instance_model=instance_model, result=result) + return await _check_or_terminate_instance(item, instance_model, volume_operations) -async def _process_idle_item(item: InstancePipelineItem) -> Optional[_ProcessContext]: +async def _process_idle_item( + item: InstancePipelineItem, volume_operations: "InstanceVolumeOperations" +) -> Optional[_ProcessContext]: async with get_session_ctx() as session: instance_model = await _refetch_locked_instance_for_idle(session=session, item=item) if instance_model is None: @@ -357,21 +374,12 @@ async def _process_idle_item(item: InstancePipelineItem) -> Optional[_ProcessCon ) if idle_result is not None: return _ProcessContext(instance_model=instance_model, result=idle_result) - result = await check_instance(instance_model) - return _ProcessContext(instance_model=instance_model, result=result) + return await _check_or_terminate_instance(item, instance_model, volume_operations) -async def _process_busy_item(item: InstancePipelineItem) -> Optional[_ProcessContext]: - async with get_session_ctx() as session: - instance_model = await _refetch_locked_instance_for_check(session=session, item=item) - if instance_model is None: - log_lock_token_mismatch(logger, item) - return None - result = await check_instance(instance_model) - return _ProcessContext(instance_model=instance_model, result=result) - - -async def _process_terminating_item(item: InstancePipelineItem) -> Optional[_ProcessContext]: +async def _process_terminating_item( + item: InstancePipelineItem, volume_operations: "InstanceVolumeOperations" +) -> Optional[_ProcessContext]: async with get_session_ctx() as session: instance_model = await _refetch_locked_instance_for_pending_or_terminating( session=session, @@ -380,8 +388,97 @@ async def _process_terminating_item(item: InstancePipelineItem) -> Optional[_Pro if instance_model is None: log_lock_token_mismatch(logger, item) return None - result = await terminate_instance(instance_model) - return _ProcessContext(instance_model=instance_model, result=result) + return await _check_or_terminate_instance(item, instance_model, volume_operations) + + +async def _check_or_terminate_instance( + item: InstancePipelineItem, + instance: InstanceModel, + volume_operations: "InstanceVolumeOperations", +) -> Optional[_ProcessContext]: + data = get_instance_provisioning_data(instance) + terminating = item.status == InstanceStatus.TERMINATING + operation = partial( + terminate_instance if terminating else check_instance, instance, job_provisioning_data=data + ) + if ( + data is not None + and data.volume_mounts + and ( + (terminating and data.hostname is not None) + or (not terminating and data.hostname is None) + ) + ): + if await volume_operations.try_start(item, instance, operation): + return None + # All dedicated requests are busy. Release the row for the normal next pass. + return _ProcessContext(instance, ProcessResult()) + return _ProcessContext(instance, await operation()) + + +class InstanceVolumeOperations: + """Check mounts before publishing an instance's hostname and flush them before deletion. + + Keep guest and provider calls outside shared provisioning workers and their executor. + Each pass retains its original database lease. When all four are busy, the instance + stays eligible for a later pass. The guest owns the outcome of the flush. + """ + + def __init__( + self, lock_timeout: timedelta, heartbeat_trigger: timedelta, hinter: PipelineHinterProtocol + ) -> None: + self._limit = 4 + self._executor = ThreadPoolExecutor( + max_workers=self._limit, thread_name_prefix="instance-volumes" + ) + self._tasks: set[asyncio.Task[None]] = set() + # The dispatching worker stops heartbeating its copy when process() returns. + self._heartbeater = Heartbeater[InstancePipelineItem]( + model_type=InstanceModel, + lock_timeout=lock_timeout, + heartbeat_trigger=heartbeat_trigger, + ) + self._heartbeat_task: Optional[asyncio.Task] = None + self._hinter = hinter + + async def try_start( + self, + item: InstancePipelineItem, + instance: InstanceModel, + operation: Callable[[ThreadPoolExecutor], Awaitable[ProcessResult]], + ) -> bool: + if len(self._tasks) >= self._limit: + return False + if self._heartbeat_task is None: + self._heartbeat_task = asyncio.create_task(self._heartbeater.start()) + await self._heartbeater.track(item) + task = asyncio.create_task(self._process(item, instance, operation)) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + return True + + async def _process( + self, + item: InstancePipelineItem, + instance: InstanceModel, + operation: Callable[[ThreadPoolExecutor], Awaitable[ProcessResult]], + ) -> None: + try: + result = await operation(self._executor) + await _apply_and_hint(item, _ProcessContext(instance, result), self._hinter) + except Exception: + logger.exception("Failed to process instance %s with mounted volumes", instance.id) + finally: + await self._heartbeater.untrack(item) + + async def drain(self) -> None: + # Keep the lease and backend client alive until each outstanding HTTP/SSH call returns. + await asyncio.gather(*self._tasks) + if self._heartbeat_task is not None: + self._heartbeater.stop() + self._heartbeat_task.cancel() + await asyncio.gather(self._heartbeat_task, return_exceptions=True) + self._executor.shutdown() async def _refetch_locked_instance_for_pending_or_terminating( diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py index d8c12c1ee1..5ad798012d 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py @@ -1,6 +1,7 @@ import logging import uuid from collections.abc import Mapping +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from typing import Optional @@ -13,6 +14,7 @@ from dstack._internal import settings from dstack._internal.core.backends.base.compute import ( + ComputeWithVolumeFlushSupport, get_dstack_runner_download_url, get_dstack_runner_version, get_dstack_shim_download_url, @@ -36,6 +38,7 @@ can_terminate_fleet_instances_on_idle_duration, get_instance_idle_duration, get_provisioning_deadline, + run_instance_call, set_gpu_driver_update, set_health_update, set_status_update, @@ -106,7 +109,12 @@ async def process_idle_timeout( return result -async def check_instance(instance_model: InstanceModel) -> ProcessResult: +async def check_instance( + instance_model: InstanceModel, + volume_executor: Optional[ThreadPoolExecutor] = None, + *, + job_provisioning_data: Optional[JobProvisioningData] = None, +) -> ProcessResult: result = ProcessResult() if ( instance_model.status == InstanceStatus.BUSY @@ -131,11 +139,13 @@ async def check_instance(instance_model: InstanceModel) -> ProcessResult: ) return result - job_provisioning_data = get_or_error(get_instance_provisioning_data(instance_model)) + if job_provisioning_data is None: + job_provisioning_data = get_or_error(get_instance_provisioning_data(instance_model)) if job_provisioning_data.hostname is None: return await _process_wait_for_instance_provisioning_data( instance_model=instance_model, job_provisioning_data=job_provisioning_data, + volume_executor=volume_executor, ) if not job_provisioning_data.dockerized: @@ -316,6 +326,7 @@ def _log_instance_check_result( async def _process_wait_for_instance_provisioning_data( instance_model: InstanceModel, job_provisioning_data: JobProvisioningData, + volume_executor: Optional[ThreadPoolExecutor], ) -> ProcessResult: result = ProcessResult() logger.debug("Waiting for instance %s to become running", instance_model.name) @@ -352,16 +363,21 @@ async def _process_wait_for_instance_provisioning_data( return result try: - await run_async( - backend.compute().update_provisioning_data, + compute = backend.compute() + await run_instance_call( + volume_executor, + compute.update_provisioning_data, job_provisioning_data, instance_model.project.ssh_public_key, instance_model.project.ssh_private_key, ) if job_provisioning_data.hostname and job_provisioning_data.volume_mounts: + if volume_executor is None: + raise ProvisioningError("The backend must declare its volume mounts at launch") # Publishing the SSH address admits jobs. Keep it unset while any mount is # missing so a VM that times out before admission can be deleted without a flush. - conn = await run_async( + conn = await run_instance_call( + volume_executor, instance_connection_pool.get_or_open, get_instance_ssh_private_keys(instance_model), job_provisioning_data, @@ -370,8 +386,28 @@ async def _process_wait_for_instance_provisioning_data( if conn is None: return result if not await conn.has_volume_mounts(job_provisioning_data.volume_mounts.values()): - await run_async(instance_connection_pool.drop_by_jpd, job_provisioning_data) + await run_instance_call( + volume_executor, + instance_connection_pool.drop_by_jpd, + job_provisioning_data, + ) return result + if isinstance(compute, ComputeWithVolumeFlushSupport): + shim = runner_client.ShimClient.from_address( + conn.forwarded_paths()[DSTACK_SHIM_HTTP_PORT] + ) + health = await run_instance_call(volume_executor, shim.healthcheck) + if health is None: + return result + if ( + health.service != "dstack-shim" + or not health.supports_volume_flush + or not health.boot_id + ): + raise ProvisioningError( + "The shim must be upgraded to flush mounted volumes" + ) + job_provisioning_data.volume_mount_boot_id = uuid.UUID(health.boot_id) result.instance_update_map["job_provisioning_data"] = ( job_provisioning_data.model_dump_json() ) diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py index ee7f810ea8..c0c7a327fd 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py @@ -1,8 +1,13 @@ +import asyncio import datetime import uuid +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context from dataclasses import dataclass, field from datetime import timedelta -from typing import Optional, TypedDict, Union +from functools import partial +from typing import Optional, ParamSpec, TypedDict, TypeVar, Union from paramiko.pkey import PKey from sqlalchemy import func, select @@ -24,7 +29,7 @@ from dstack._internal.server.background.pipeline_tasks.common import get_provisioning_timeout from dstack._internal.server.models import FleetModel, InstanceModel, PlacementGroupModel from dstack._internal.server.services.fleets import get_fleet_spec -from dstack._internal.utils.common import UNSET, Unset, get_current_datetime +from dstack._internal.utils.common import UNSET, Unset, get_current_datetime, run_async from dstack._internal.utils.ssh import pkey_from_str TERMINATION_DEADLINE_OFFSET = timedelta(minutes=20) @@ -33,6 +38,24 @@ PROVISIONING_TIMEOUT_SECONDS = 10 * 60 # 10 minutes in seconds +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +async def run_instance_call( + executor: Optional[ThreadPoolExecutor], + func: Callable[_P, _R], + /, + *args: _P.args, + **kwargs: _P.kwargs, +) -> _R: + """Use the dedicated executor for mounted instances and preserve the pipeline tracing context.""" + if executor is None: + return await run_async(func, *args, **kwargs) + call = partial(copy_context().run, func, *args, **kwargs) + return await asyncio.get_running_loop().run_in_executor(executor, call) + + class InstanceUpdateMap(ItemUpdateMap, total=False): status: InstanceStatus unreachable: bool diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py index e43b0ffc74..064df5bba3 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py @@ -1,9 +1,14 @@ -from dstack._internal.core.backends.base.compute import ComputeWithVolumeSupport +from collections.abc import Mapping +from concurrent.futures import ThreadPoolExecutor +from typing import Optional +from uuid import UUID + +from dstack._internal.core.backends.base.compute import Compute, ComputeWithVolumeFlushSupport from dstack._internal.core.backends.features import get_backends_with_resource_listing_support +from dstack._internal.core.consts import DSTACK_SHIM_HTTP_PORT from dstack._internal.core.errors import ( BackendError, NotYetTerminated, - SSHError, ) from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import OrphanCleanupMode @@ -15,6 +20,7 @@ ProcessResult, get_termination_deadline, next_termination_retry_at, + run_instance_call, set_status_update, ) from dstack._internal.server.models import InstanceModel @@ -23,16 +29,23 @@ get_instance_provisioning_data, get_instance_ssh_private_keys, ) +from dstack._internal.server.services.runner import client from dstack._internal.server.services.runner.pool import ( instance_connection_pool, ) +from dstack._internal.server.services.runner.ssh import runner_ssh_tunnel from dstack._internal.utils.common import get_current_datetime, run_async from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) -async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: +async def terminate_instance( + instance_model: InstanceModel, + volume_executor: Optional[ThreadPoolExecutor] = None, + *, + job_provisioning_data: Optional[JobProvisioningData] = None, +) -> ProcessResult: result = ProcessResult() now = get_current_datetime() if ( @@ -41,10 +54,11 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: ): return result - job_provisioning_data = get_instance_provisioning_data(instance_model) + if job_provisioning_data is None: + job_provisioning_data = get_instance_provisioning_data(instance_model) if job_provisioning_data is not None and job_provisioning_data.backend != BackendType.REMOTE: try: - await _terminate_in_backend(instance_model, job_provisioning_data) + await _terminate_in_backend(instance_model, job_provisioning_data, volume_executor) result.release_volume_attachments = list(job_provisioning_data.volume_mounts or ()) except Exception as exc: first_retry_at = instance_model.first_termination_retry_at @@ -97,7 +111,12 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: ) if job_provisioning_data is not None: - instance_connection_pool.drop_by_jpd(job_provisioning_data) + if volume_executor is None: + instance_connection_pool.drop_by_jpd(job_provisioning_data) + else: + await run_instance_call( + volume_executor, instance_connection_pool.drop_by_jpd, job_provisioning_data + ) result.instance_update_map["deleted"] = True result.instance_update_map["deleted_at"] = NOW_PLACEHOLDER @@ -113,8 +132,10 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult: async def _terminate_in_backend( - instance_model: InstanceModel, job_provisioning_data: JobProvisioningData -): + instance_model: InstanceModel, + job_provisioning_data: JobProvisioningData, + volume_executor: Optional[ThreadPoolExecutor], +) -> None: async with backends_cache.lease_project_backend_by_type( project=instance_model.project, backend_type=job_provisioning_data.backend, @@ -130,14 +151,16 @@ async def _terminate_in_backend( return compute = backend.compute() if job_provisioning_data.volume_mounts and job_provisioning_data.hostname: - assert isinstance(compute, ComputeWithVolumeSupport) - paths = await run_async(compute.get_volume_mounts_to_sync, job_provisioning_data) - if paths is None: - # Disappearance was confirmed without a guest. A second lookup could - # observe a running VM and delete it without ever flushing its mounts. - return - if paths: - await _sync_volume_mounts(instance_model, job_provisioning_data, paths) + if volume_executor is None: + raise BackendError("Mounted instance termination requires a volume flush") + await run_instance_call( + volume_executor, + _terminate_with_volumes, + compute, + job_provisioning_data, + get_instance_ssh_private_keys(instance_model), + ) + return logger.debug("Terminating runner instance %s", job_provisioning_data.hostname) await run_async( compute.terminate_instance, @@ -147,21 +170,40 @@ async def _terminate_in_backend( ) -async def _sync_volume_mounts( - instance_model: InstanceModel, job_provisioning_data: JobProvisioningData, paths: list[str] +def _terminate_with_volumes( + compute: Compute, + data: JobProvisioningData, + ssh_private_keys: tuple[str, Optional[str]], ) -> None: - conn = await run_async( - instance_connection_pool.get_or_open, - get_instance_ssh_private_keys(instance_model), - job_provisioning_data, - None, - ) - if conn is None: - raise BackendError("Could not connect to the VM to flush its volumes") - try: - await conn.sync_volume_mounts(paths) - except SSHError as e: - raise BackendError("Could not flush the VM's volume mounts") from e + if isinstance(compute, ComputeWithVolumeFlushSupport): + paths = compute.get_volume_mounts_to_sync(data) + if paths is None: + # The provider confirmed this VM is gone. Never issue a second lookup or DELETE. + return + if paths: + if data.volume_mount_boot_id is None: + raise BackendError( + "Cannot confirm the guest boot on which the volumes were mounted" + ) + try: + _check_volume_flush(ssh_private_keys, data, None, data.volume_mount_boot_id, paths) + except (client.PeerConnectionError, client.ShimError) as e: + raise BackendError(f"Cannot confirm the volume flush: {e}") from e + elif data.volume_mount_boot_id is not None: + raise BackendError("The backend no longer supports the required volume flush") + compute.terminate_instance(data.instance_id, data.region, data.backend_data) + + +@runner_ssh_tunnel +def _check_volume_flush( + addresses: Mapping[int, client.LocalAddress], boot_id: UUID, paths: list[str] +) -> None: + shim = client.ShimClient.from_address(addresses[DSTACK_SHIM_HTTP_PORT]) + result = shim.flush_volumes(boot_id, paths) + if result.status == "pending": + raise NotYetTerminated("Waiting for the instance to flush its mounted volumes") + if result.status != "done" or result.error is not None: + raise BackendError(result.error or "The instance could not flush its mounted volumes") def _format_error(exc: Exception) -> str: diff --git a/src/dstack/_internal/server/schemas/runner.py b/src/dstack/_internal/server/schemas/runner.py index 5f7652d3b3..bd8d369cf9 100644 --- a/src/dstack/_internal/server/schemas/runner.py +++ b/src/dstack/_internal/server/schemas/runner.py @@ -1,6 +1,6 @@ from base64 import b64decode from enum import Enum -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Literal, Optional, Union from pydantic import Field, field_validator @@ -134,6 +134,18 @@ class HealthcheckResponse(CoreModel): service: str version: str supports_volume_mount_path: bool = False + supports_volume_flush: bool = False + boot_id: Optional[str] = None + + +class FlushVolumesRequest(CoreModel): + boot_id: str + paths: list[str] + + +class FlushVolumesResponse(CoreModel): + status: Literal["pending", "done", "failed"] + error: Optional[str] = None class InstanceHealthResponse(CoreModel): diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index b06543d6df..1e869ecd00 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -28,6 +28,8 @@ ComponentInstallRequest, ComponentListResponse, ComponentName, + FlushVolumesRequest, + FlushVolumesResponse, GPUDevice, HealthcheckResponse, InstanceHealthResponse, @@ -533,6 +535,16 @@ def get_instance_info(self) -> Optional[InstanceInfoResponse]: self._raise_for_status(resp) return self._response(InstanceInfoResponse, resp) + def flush_volumes(self, boot_id: uuid.UUID, paths: list[str]) -> FlushVolumesResponse: + """Start or check the terminal flush for these mounts on the admitted guest boot.""" + body = FlushVolumesRequest(boot_id=str(boot_id), paths=paths) + response = self._request( + "POST", "/api/instance/flush-volumes", body, raise_for_status=True + ) + if response.status_code != HTTPStatus.OK: + raise ShimResponseStatusError(response) + return self._response(FlushVolumesResponse, response) + def shutdown(self, *, force: bool) -> bool: if not self.is_shutdown_supported(): logger.debug("shim shutdown is not supported: %s", self._shim_version_string) diff --git a/src/dstack/_internal/server/services/runner/pool.py b/src/dstack/_internal/server/services/runner/pool.py index b42bee411d..7623f69352 100644 --- a/src/dstack/_internal/server/services/runner/pool.py +++ b/src/dstack/_internal/server/services/runner/pool.py @@ -249,15 +249,6 @@ async def has_volume_mounts(self, paths: Collection[str]) -> bool: return False return True - async def sync_volume_mounts(self, paths: Collection[str]) -> None: - """Request a flush on each mounted filesystem before releasing its VM.""" - commands = [ - # Keep a reference to the directory across the check and fsync. - f"(cd -P -- {shlex.quote(path)} && mountpoint -q -- . && sync -- .)" - for path in paths - ] - await self._tunnel.aexec(" && ".join(commands), timeout=60) - def is_alive(self) -> bool: """ Verifies that the connection's SSH master process is alive: diff --git a/src/dstack/_internal/server/testing/common.py b/src/dstack/_internal/server/testing/common.py index a9404db012..73c54b5a39 100644 --- a/src/dstack/_internal/server/testing/common.py +++ b/src/dstack/_internal/server/testing/common.py @@ -26,6 +26,7 @@ ComputeWithPrivateGatewaySupport, ComputeWithPrivilegedSupport, ComputeWithReservationSupport, + ComputeWithVolumeFlushSupport, ComputeWithVolumeSupport, ) from dstack._internal.core.models.backends.base import BackendType @@ -1531,6 +1532,7 @@ class ComputeMockSpec( ComputeWithGatewaySupport, ComputeWithGatewayLoadBalancerSupport, ComputeWithPrivateGatewaySupport, + ComputeWithVolumeFlushSupport, ComputeWithVolumeSupport, ): """ diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py index ac4d588640..99f1243b6e 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_compute.py +++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py @@ -98,6 +98,7 @@ def launch(lost_reply=False): "ip": "192.0.2.1", } assert http_mock.last_request.json()["volumeIds"] == [VOLUME_ID] + assert 'export "DSTACK_SHIM_VOLUME_FLUSH=1"' in http_mock.last_request.json()["command"] assert data.volume_mounts == {volume_config.volumes[0].id: storage["mountPath"]} http_mock.get(f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm]}) return data, vm @@ -110,6 +111,7 @@ def test_omits_volume_ids_for_a_plain_vm(self, compute, http_mock, offer): http_mock.post(f"{API_URL}/instance/launch", json={"response": VM_ID}) data = compute.create_instance(offer, get_instance_configuration(), None) assert "volumeIds" not in http_mock.last_request.json() + assert "DSTACK_SHIM_VOLUME_FLUSH" not in http_mock.last_request.json()["command"] assert data.instance_id == VM_ID assert data.backend_data is None and data.volume_mounts is None diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/conftest.py b/src/tests/_internal/server/background/pipeline_tasks/instances/conftest.py index c80449aca2..cfeae8eee5 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/conftest.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/conftest.py @@ -3,11 +3,12 @@ from unittest.mock import Mock import pytest +import pytest_asyncio from dstack._internal.core.backends.base.compute import GoArchType from dstack._internal.server.background.pipeline_tasks.instances import ( InstanceFetcher, - InstanceWorker, + InstancePipeline, ) from dstack._internal.server.background.pipeline_tasks.instances import ( ssh_deploy as instances_ssh_deploy, @@ -32,9 +33,11 @@ def fetcher() -> InstanceFetcher: ) -@pytest.fixture -def worker() -> InstanceWorker: - return InstanceWorker(queue=asyncio.Queue(), heartbeater=Mock(), pipeline_hinter=Mock()) +@pytest_asyncio.fixture +async def worker(): + pipeline = InstancePipeline(workers_num=1, pipeline_hinter=Mock()) + yield pipeline._workers[0] + await pipeline.volume_operations.drain() @pytest.fixture diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/helpers.py b/src/tests/_internal/server/background/pipeline_tasks/instances/helpers.py index 81eb0fde5c..60a098d8ef 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/helpers.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/helpers.py @@ -1,3 +1,4 @@ +import asyncio import datetime as dt import uuid @@ -38,3 +39,4 @@ async def process_instance( lock_instance(instance_model) await session.commit() await worker.process(instance_to_pipeline_item(instance_model)) + await asyncio.gather(*worker.volume_operations._tasks) diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py index 2c1142fbd0..511fde4641 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py @@ -228,7 +228,6 @@ def set_hostname(data: JobProvisioningData, *args) -> None: await process_instance(session, worker, instance) await session.refresh(instance) backend.compute.return_value.terminate_instance.assert_called_once() - conn.sync_volume_mounts.assert_not_awaited() assert instance.status == InstanceStatus.TERMINATED async def test_check_shim_transitions_provisioning_on_busy( diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_pipeline.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_pipeline.py index b1df098970..58e0e221b1 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_pipeline.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_pipeline.py @@ -1,11 +1,14 @@ +import asyncio import datetime as dt import uuid -from unittest.mock import Mock +from unittest.mock import AsyncMock, Mock import pytest from sqlalchemy.ext.asyncio import AsyncSession +from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.instances import InstanceStatus +from dstack._internal.server.background.pipeline_tasks import instances from dstack._internal.server.background.pipeline_tasks.fleets import FleetPipeline from dstack._internal.server.background.pipeline_tasks.instances import ( InstanceFetcher, @@ -13,12 +16,14 @@ InstanceWorker, ) from dstack._internal.server.background.pipeline_tasks.instances import check as instances_check +from dstack._internal.server.background.pipeline_tasks.instances.common import ProcessResult from dstack._internal.server.schemas.instances import InstanceCheck from dstack._internal.server.testing.common import ( create_compute_group, create_fleet, create_instance, create_project, + get_job_provisioning_data, ) from dstack._internal.utils.common import get_current_datetime from tests._internal.server.background.pipeline_tasks.instances.helpers import ( @@ -282,6 +287,49 @@ async def test_fetch_respects_fleet_processing_and_key_update_leases( @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestInstanceWorker: + @pytest.mark.parametrize("status", [InstanceStatus.PROVISIONING, InstanceStatus.TERMINATING]) + async def test_mount_check_releases_worker_before_it_finishes( + self, test_db, session: AsyncSession, worker: InstanceWorker, monkeypatch, status + ): + project = await create_project(session) + data = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE) + data.volume_mounts = {uuid.uuid4(): "/persistent/checkpoints"} + if status == InstanceStatus.PROVISIONING: + data.hostname = None + mounted = await create_instance( + session, project, status=status, job_provisioning_data=data + ) + other = await create_instance( + session, project, name="other", status=InstanceStatus.PENDING + ) + entered, release = asyncio.Event(), asyncio.Event() + + async def wait_for_mount(instance, volume_executor=None, **kwargs): + assert volume_executor is worker.volume_operations._executor + entered.set() + await release.wait() + return ProcessResult() + + monkeypatch.setattr(instances, "check_instance", wait_for_mount) + monkeypatch.setattr(instances, "terminate_instance", wait_for_mount) + monkeypatch.setattr( + instances, "create_cloud_instance", AsyncMock(return_value=ProcessResult()) + ) + lock_instance(mounted) + lock_instance(other) + await session.commit() + try: + await asyncio.wait_for(worker.process(instance_to_pipeline_item(mounted)), timeout=2) + await asyncio.wait_for(entered.wait(), timeout=2) + await worker.process(instance_to_pipeline_item(other)) + await session.refresh(other) + assert other.lock_token is None + await session.refresh(mounted) + assert mounted.lock_token is not None + finally: + release.set() + await asyncio.gather(*worker.volume_operations._tasks) + async def test_process_skips_when_lock_token_changes( self, test_db, diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py index e05a294050..b0e005dda8 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py @@ -1,7 +1,8 @@ import datetime as dt +import uuid from contextlib import contextmanager from typing import Optional, cast -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import Mock, patch import pytest import time_machine @@ -10,8 +11,8 @@ from dstack._internal.core.errors import ( BackendError, + ComputeError, NotYetTerminated, - SSHError, ) from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import OrphanCleanupMode @@ -282,6 +283,7 @@ async def test_flushes_and_releases_vm_volume_attachments( ) jpd = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE) jpd.volume_mounts = {volume.id: "/persistent/checkpoints"} + jpd.volume_mount_boot_id = uuid.uuid4() instance = await create_instance( session, project, @@ -304,16 +306,13 @@ async def test_flushes_and_releases_vm_volume_attachments( compute.terminate_instance.side_effect = NotYetTerminated("Deletion submitted") backend = Mock() backend.compute.return_value = compute - conn = AsyncMock() - conn.sync_volume_mounts.side_effect = [SSHError("flush failed"), None] + flush = Mock(side_effect=[ComputeError("flush failed"), None]) with ( patch( "dstack._internal.server.services.backends.cache.lease_project_backend_by_type", mock_lease(backend), ), - patch.object( - instances_termination.instance_connection_pool, "get_or_open", return_value=conn - ), + patch.object(instances_termination, "_check_volume_flush", flush), ): with time_machine.travel(now, tick=False): await process_instance(session, worker, instance) @@ -333,7 +332,7 @@ async def test_flushes_and_releases_vm_volume_attachments( with time_machine.travel(now + dt.timedelta(minutes=2), tick=False): await process_instance(session, worker, instance) compute.terminate_instance.assert_called_once() - assert conn.sync_volume_mounts.await_count == 2 + assert flush.call_count == 2 assert list(await session.scalars(attachment)) == [other_volume.id] await session.refresh(instance) assert instance.status == InstanceStatus.TERMINATED diff --git a/src/tests/_internal/server/services/runner/test_client.py b/src/tests/_internal/server/services/runner/test_client.py index 076eab5f67..8e0323f80e 100644 --- a/src/tests/_internal/server/services/runner/test_client.py +++ b/src/tests/_internal/server/services/runner/test_client.py @@ -318,6 +318,14 @@ def test( class TestShimClientResponseErrors(BaseShimClientTest): + def test_flush_requires_completed_http_response(self, client: ShimClient, http_mock: HTTPMock): + # A 202 acknowledges receipt. Its body must never authorize instance deletion. + http_mock.post( + f"{SHIM_URL}/api/instance/flush-volumes", status_code=202, json={"status": "done"} + ) + with pytest.raises(ShimResponseStatusError): + client.flush_volumes(uuid.uuid4(), ["/persistent/checkpoints"]) + def test_status_error(self, client: ShimClient, http_mock: HTTPMock): http_mock.get( f"{SHIM_URL}/test/path", From c1352861a1fe0dad6470018fd971d049ab0b2b55 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 14:34:45 +0100 Subject: [PATCH 3/8] Verify admitted mounts through a private shim socket Record stable mount identities before publishing the hostname, and compare them on the same file descriptor that binds or flushes a volume. Restrict the opted-in shim to the management account's Unix socket over SSH. --- runner/docs/shim.openapi.yaml | 85 ++++- runner/internal/shim/api/api_test.go | 23 +- runner/internal/shim/api/control_socket.go | 95 +++++ .../internal/shim/api/control_socket_test.go | 80 ++++ runner/internal/shim/api/handlers.go | 35 +- runner/internal/shim/api/handlers_test.go | 26 +- runner/internal/shim/api/schemas.go | 8 +- runner/internal/shim/api/server.go | 22 +- runner/internal/shim/docker.go | 10 +- runner/internal/shim/volume_flush.go | 351 +++++++++++------- runner/internal/shim/volume_flush_test.go | 213 ++++++----- runner/internal/shim/volumes.go | 46 ++- runner/internal/shim/volumes_test.go | 8 +- .../core/backends/massedcompute/compute.py | 3 +- src/dstack/_internal/core/consts.py | 1 + src/dstack/_internal/core/models/runs.py | 2 + .../pipeline_tasks/instances/check.py | 55 ++- .../pipeline_tasks/instances/termination.py | 2 + src/dstack/_internal/server/schemas/runner.py | 11 +- .../server/services/runner/client.py | 11 + .../_internal/server/services/runner/pool.py | 24 +- .../backends/massedcompute/test_compute.py | 7 +- .../pipeline_tasks/instances/test_check.py | 30 +- .../instances/test_termination.py | 1 + .../server/services/runner/test_ssh.py | 25 +- 25 files changed, 844 insertions(+), 330 deletions(-) create mode 100644 runner/internal/shim/api/control_socket.go create mode 100644 runner/internal/shim/api/control_socket_test.go diff --git a/runner/docs/shim.openapi.yaml b/runner/docs/shim.openapi.yaml index 5b649a4d1b..cbbd751a0c 100644 --- a/runner/docs/shim.openapi.yaml +++ b/runner/docs/shim.openapi.yaml @@ -23,6 +23,10 @@ info: we call the older one “Legacy API” and the newer one “Future API”. These versions are not exposed via API, clients should figure out them via shim binary version + When `DSTACK_SHIM_VOLUME_FLUSH_USER` names a management SSH account, the shim serves + its entire HTTP API on the Unix socket `/run/dstack-shim/control.sock`. The socket + is accessible to that account and root. Ordinary shims use the TCP address below. + servers: - url: http://localhost:10998/api @@ -102,11 +106,64 @@ paths: schema: $ref: "#/components/schemas/InstanceInfoResponse" + /instance/volume-mounts: + post: + summary: Admit the provider mounts before running tasks on this instance + description: > + Available through the management socket. The shim checks each mount root and + records its unique Linux mount ID and boot ID before accepting tasks. Repeating + admission verifies the same mounts. Task binds and terminal fsync also verify + these identities. This requires kernel support for STATX_MNT_ID_UNIQUE. + tags: [Instance] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + paths: + $ref: "#/components/schemas/VolumeMountPaths" + required: [paths] + responses: + "200": + description: All requested mounts have been admitted + content: + application/json: + schema: + type: object + properties: + boot_id: + type: string + format: uuid + required: [boot_id] + "400": + description: Invalid mount path list + $ref: "#/components/responses/PlainTextBadRequest" + "404": + description: The shim uses ordinary TCP transport + $ref: "#/components/responses/PlainTextNotFound" + "409": + description: An admitted identity changed or the instance is terminating + $ref: "#/components/responses/PlainTextConflict" + "422": + description: The kernel lacks unique mount IDs, a path contains a symlink, or the shim lacks mount access + content: + text/plain: + schema: + type: string + "503": + description: Mount verification is in progress, a mount is missing, or the filesystem is temporarily unavailable + content: + text/plain: + schema: + type: string + /instance/flush-volumes: post: summary: Stop instance workloads and flush volume mounts before VM termination description: > - Available on instances started with `DSTACK_SHIM_VOLUME_FLUSH=1` that expose a boot ID. + Available through the management socket after successful volume-mount admission. The first request seals the instance against new tasks and starts one background operation to stop managed workloads and fsync the specified mount roots. Poll with the same boot ID and set of paths. A disconnected caller can rejoin @@ -130,10 +187,10 @@ paths: description: Invalid JSON, missing boot ID, or invalid list of mount paths $ref: "#/components/responses/PlainTextBadRequest" "404": - description: The instance does not advertise volume flush support + description: The shim uses ordinary TCP transport $ref: "#/components/responses/PlainTextNotFound" "409": - description: The VM boot ID changed or the instance was sealed for different paths + description: The VM boot ID changed or the requested mount set was not admitted $ref: "#/components/responses/PlainTextConflict" "500": description: Cannot read the boot ID or persist the termination seal @@ -535,18 +592,19 @@ components: supports_volume_mount_path: type: boolean description: The shim can bind volumes from a provider mount path. - supports_volume_flush: - type: boolean - description: The shim supports terminal volume flushing bound to this boot ID. - boot_id: - type: string - format: uuid - description: Linux boot ID to record when admitting the instance. required: - service - version additionalProperties: false + VolumeMountPaths: + type: array + minItems: 1 + items: + type: string + pattern: '^/.+' + description: Absolute, clean paths to volume mount roots in the guest. Order and duplicates are ignored. + FlushVolumesRequest: title: shim.api.FlushVolumesRequest type: object @@ -556,12 +614,7 @@ components: format: uuid description: The boot ID recorded when the server admitted this instance. paths: - type: array - minItems: 1 - items: - type: string - pattern: '^/.+' - description: Absolute, clean paths to volume mount roots in the guest. Order and duplicates are ignored. + $ref: "#/components/schemas/VolumeMountPaths" required: [boot_id, paths] VolumeFlushResult: diff --git a/runner/internal/shim/api/api_test.go b/runner/internal/shim/api/api_test.go index 448818f337..831477f196 100644 --- a/runner/internal/shim/api/api_test.go +++ b/runner/internal/shim/api/api_test.go @@ -10,11 +10,12 @@ import ( ) type DummyRunner struct { - tasks map[string]bool - gpus []host.GpuInfo - processed atomic.Int64 - mu sync.Mutex - bootID string + tasks map[string]bool + gpus []host.GpuInfo + processed atomic.Int64 + mu sync.Mutex + bootID string + socketUser string } func (ds *DummyRunner) Submit(ctx context.Context, cfg shim.TaskConfig) error { @@ -51,14 +52,22 @@ func (ds *DummyRunner) TaskInfo(taskID string) shim.TaskInfo { return shim.TaskInfo{} } -func (ds *DummyRunner) VolumeFlushBootID() string { return ds.bootID } +func (ds *DummyRunner) VolumeFlushUser() string { + return ds.socketUser +} +func (ds *DummyRunner) AdmitVolumeMounts(paths []string) (string, error) { + if len(paths) == 0 { + return "", shim.ErrRequest + } + return ds.bootID, nil +} func (ds *DummyRunner) FlushVolumes(_ context.Context, bootID string, paths []string) (shim.VolumeFlushResult, error) { if len(paths) == 0 || bootID == "" { return shim.VolumeFlushResult{}, shim.ErrRequest } if bootID != ds.bootID { - return shim.VolumeFlushResult{}, shim.ErrFlushBootMismatch + return shim.VolumeFlushResult{}, shim.ErrVolumeConflict } return shim.VolumeFlushResult{Status: "pending"}, nil } diff --git a/runner/internal/shim/api/control_socket.go b/runner/internal/shim/api/control_socket.go new file mode 100644 index 0000000000..5e31900088 --- /dev/null +++ b/runner/internal/shim/api/control_socket.go @@ -0,0 +1,95 @@ +package api + +import ( + "errors" + "fmt" + "net" + "os" + "os/user" + "path/filepath" + "strconv" + + "golang.org/x/sys/unix" +) + +const controlSocketPath = "/run/dstack-shim/control.sock" + +// Only management SSH sessions may connect. A private staging directory keeps +// the socket inaccessible until its ownership and permissions have been set. +func listenControlSocket(path, username string) (listener net.Listener, err error) { + account, err := user.Lookup(username) + if err != nil { + return nil, err + } + uid, err := strconv.Atoi(account.Uid) + if err != nil { + return nil, err + } + dir := filepath.Dir(path) + if err := os.Mkdir(dir, 0o711); err != nil && !errors.Is(err, os.ErrExist) { + return nil, err + } + fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return nil, err + } + lock := os.NewFile(uintptr(fd), dir) + defer func() { + if err != nil { + _ = lock.Close() + } + }() + var st unix.Stat_t + if err := unix.Fstat(fd, &st); err != nil { + return nil, err + } + if st.Uid != 0 || st.Mode&0o022 != 0 { + return nil, fmt.Errorf("shim control directory %q must be root-owned and writable only by root", dir) + } + // Keep the directory locked for the lifetime of the listener. Only a stale + // socket from this shim's previous process can then be replaced. + if err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB); err != nil { + return nil, err + } + if err := lock.Chmod(0o711); err != nil { + return nil, err + } + if previous, err := os.Lstat(path); err == nil && previous.Mode()&os.ModeSocket == 0 { + return nil, fmt.Errorf("shim control path %q is not a socket", path) + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + staging, err := os.MkdirTemp(dir, ".socket-") + if err != nil { + return nil, err + } + defer os.RemoveAll(staging) + tmp := filepath.Join(staging, "s") + sock, err := net.ListenUnix("unix", &net.UnixAddr{Name: tmp, Net: "unix"}) + if err != nil { + return nil, err + } + sock.SetUnlinkOnClose(false) + defer func() { + if err != nil { + _ = sock.Close() + } + }() + if err := os.Chmod(tmp, 0o600); err != nil { + return nil, err + } + if err := os.Chown(tmp, uid, -1); err != nil { + return nil, err + } + if err := os.Rename(tmp, path); err != nil { + return nil, err + } + return &controlListener{Listener: sock, lock: lock}, nil +} + +type controlListener struct { + net.Listener + lock *os.File +} + +func (l *controlListener) Close() error { return errors.Join(l.Listener.Close(), l.lock.Close()) } diff --git a/runner/internal/shim/api/control_socket_test.go b/runner/internal/shim/api/control_socket_test.go new file mode 100644 index 0000000000..4745266eee --- /dev/null +++ b/runner/internal/shim/api/control_socket_test.go @@ -0,0 +1,80 @@ +package api + +import ( + "fmt" + "net" + "os" + "os/exec" + "os/user" + "path/filepath" + "strconv" + "syscall" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func TestControlListener(t *testing.T) { + // The child probes effective connect permission under a different Unix account. + if path := os.Getenv("DSTACK_TEST_CONTROL_SOCKET"); path != "" { + c, err := net.Dial("unix", path) + if os.Getenv("DSTACK_TEST_CONTROL_EXPECT_ACCESS") == "true" { + require.NoError(t, err) + require.NoError(t, c.Close()) + } else { + require.ErrorIs(t, err, unix.EACCES) + } + return + } + r := NewDummyRunner() + s := NewShimServer(t.Context(), "127.0.0.1:0", "test", r, nil, nil, nil, nil) + tcp, err := s.listen("") + require.NoError(t, err) + require.Equal(t, "tcp", tcp.Addr().Network()) + require.NoError(t, tcp.Close()) + if os.Geteuid() != 0 { + t.Skip("dropping process credentials requires root") + } + // Each test subprocess must be able to traverse the parent, including after setuid. + parent, err := os.MkdirTemp("", "shim-control-") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(parent) }) + require.NoError(t, os.Chmod(parent, 0711)) + path := filepath.Join(parent, "dstack-shim", "control.sock") + r.socketUser = "nobody" + l, err := s.listen(path) + require.NoError(t, err) + require.Equal(t, "unix", l.Addr().Network()) + info, err := os.Stat(path) + require.NoError(t, err) + require.Equal(t, os.FileMode(0600), info.Mode().Perm()) + var st unix.Stat_t + require.NoError(t, unix.Stat(filepath.Dir(path), &st)) + require.Zero(t, st.Uid) + require.EqualValues(t, 0711, st.Mode&0777) + // A second daemon cannot replace the socket that is currently serving. + _, err = s.listen(path) + require.ErrorIs(t, err, unix.EWOULDBLOCK) + for _, name := range []string{"nobody", "daemon"} { + acct, err := user.Lookup(name) + require.NoError(t, err) + uid, err := strconv.Atoi(acct.Uid) + require.NoError(t, err) + gid, err := strconv.Atoi(acct.Gid) + require.NoError(t, err) + cmd := exec.Command("/proc/self/exe", "-test.run=^TestControlListener$") + cmd.Env = append(os.Environ(), "DSTACK_TEST_CONTROL_SOCKET="+path, fmt.Sprintf("DSTACK_TEST_CONTROL_EXPECT_ACCESS=%t", name == r.socketUser)) + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}} + output, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", output) + } + require.NoError(t, l.Close()) + l, err = s.listen(path) + require.NoError(t, err) + require.NoError(t, l.Close()) + require.NoError(t, os.Remove(path)) + require.NoError(t, os.WriteFile(path, []byte("existing"), 0600)) + _, err = s.listen(path) + require.ErrorContains(t, err, "not a socket") +} diff --git a/runner/internal/shim/api/handlers.go b/runner/internal/shim/api/handlers.go index fb8593ec38..19bd115050 100644 --- a/runner/internal/shim/api/handlers.go +++ b/runner/internal/shim/api/handlers.go @@ -16,16 +16,25 @@ func (s *ShimServer) HealthcheckHandler(w http.ResponseWriter, r *http.Request) s.mu.RLock() defer s.mu.RUnlock() - bootID := s.runner.VolumeFlushBootID() return &HealthcheckResponse{ Service: "dstack-shim", Version: s.version, SupportsVolumeMountPath: true, - SupportsVolumeFlush: bootID != "", - BootID: bootID, }, nil } +func (s *ShimServer) AdmitVolumeMountsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + var req VolumeMountsRequest + if err := api.DecodeJSONBody(w, r, &req, true); err != nil { + return nil, err + } + bootID, err := s.runner.AdmitVolumeMounts(req.Paths) + if err != nil { + return nil, volumeRequestError(err) + } + return &VolumeMountsResponse{BootID: bootID}, nil +} + // FlushVolumesHandler starts or polls a VM termination operation. It must outlive the request. func (s *ShimServer) FlushVolumesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { var req FlushVolumesRequest @@ -33,13 +42,21 @@ func (s *ShimServer) FlushVolumesHandler(w http.ResponseWriter, r *http.Request) return nil, err } result, err := s.runner.FlushVolumes(s.ctx, req.BootID, req.Paths) - if errors.Is(err, shim.ErrFlushPathsChanged) || errors.Is(err, shim.ErrFlushBootMismatch) { - return nil, &api.Error{Status: http.StatusConflict, Err: err} - } - if errors.Is(err, shim.ErrRequest) { - return nil, &api.Error{Status: http.StatusBadRequest, Err: err} + return result, volumeRequestError(err) +} + +func volumeRequestError(err error) error { + switch { + case errors.Is(err, shim.ErrVolumeConflict): + return &api.Error{Status: http.StatusConflict, Err: err} + case errors.Is(err, shim.ErrMountUnsupported): + return &api.Error{Status: http.StatusUnprocessableEntity, Err: err} + case errors.Is(err, shim.ErrMountNotReady): + return &api.Error{Status: http.StatusServiceUnavailable, Err: err} + case errors.Is(err, shim.ErrRequest): + return &api.Error{Status: http.StatusBadRequest, Err: err} } - return result, err + return err } func (s *ShimServer) ShutdownHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { diff --git a/runner/internal/shim/api/handlers_test.go b/runner/internal/shim/api/handlers_test.go index ae26b83915..acd4b1c1d5 100644 --- a/runner/internal/shim/api/handlers_test.go +++ b/runner/internal/shim/api/handlers_test.go @@ -2,6 +2,7 @@ package api import ( "context" + "errors" "fmt" "net/http/httptest" "strings" @@ -10,6 +11,7 @@ import ( commonapi "github.com/dstackai/dstack/runner/internal/common/api" "github.com/dstackai/dstack/runner/internal/common/gpu" + "github.com/dstackai/dstack/runner/internal/shim" "github.com/dstackai/dstack/runner/internal/shim/host" ) @@ -26,7 +28,7 @@ func TestHealthcheck(t *testing.T) { t.Errorf("Want status '%d', got '%d'", 200, responseRecorder.Code) } - expected := `{"service":"dstack-shim","version":"0.0.1.dev2","supports_volume_mount_path":true,"supports_volume_flush":false}` + expected := `{"service":"dstack-shim","version":"0.0.1.dev2","supports_volume_mount_path":true}` if strings.TrimSpace(responseRecorder.Body.String()) != expected { t.Errorf("Want '%s', got '%s'", expected, responseRecorder.Body.String()) @@ -65,13 +67,13 @@ func TestFlushVolumesRoute(t *testing.T) { if response.Code != 404 { t.Fatalf("disabled flush returned %d", response.Code) } + runner.socketUser = "root" runner.bootID = "5aa2c153-6803-4bcf-a6f7-f1ba65f7c092" server = NewShimServer(t.Context(), ":12346", "test", runner, nil, nil, nil, nil) response = httptest.NewRecorder() - server.httpServer.Handler.ServeHTTP(response, httptest.NewRequest("GET", "/api/healthcheck", nil)) - expected := fmt.Sprintf(`{"service":"dstack-shim","version":"test","supports_volume_mount_path":true,"supports_volume_flush":true,"boot_id":"%s"}`, runner.bootID) - if response.Code != 200 || strings.TrimSpace(response.Body.String()) != expected { - t.Fatalf("enabled healthcheck returned %d %s", response.Code, response.Body.String()) + server.httpServer.Handler.ServeHTTP(response, httptest.NewRequest("POST", "/api/instance/volume-mounts", strings.NewReader(`{"paths":["/vol"]}`))) + if response.Code != 200 || strings.TrimSpace(response.Body.String()) != fmt.Sprintf(`{"boot_id":"%s"}`, runner.bootID) { + t.Fatalf("mount admission returned %d %s", response.Code, response.Body.String()) } for _, tc := range []struct { body string @@ -90,6 +92,20 @@ func TestFlushVolumesRoute(t *testing.T) { } } +func TestVolumeAdmissionErrorStatus(t *testing.T) { + for _, tc := range []struct { + err error + status int + }{ + {shim.ErrMountUnsupported, 422}, {shim.ErrMountNotReady, 503}, {shim.ErrVolumeConflict, 409}, {shim.ErrRequest, 400}, + } { + var apiErr *commonapi.Error + if !errors.As(volumeRequestError(tc.err), &apiErr) || apiErr.Status != tc.status { + t.Errorf("incorrect admission status for %v", tc.err) + } + } +} + func TestInstanceInfoWithoutGpus(t *testing.T) { request := httptest.NewRequest("GET", "/api/instance/info", nil) responseRecorder := httptest.NewRecorder() diff --git a/runner/internal/shim/api/schemas.go b/runner/internal/shim/api/schemas.go index c2e034aacb..b3c7421b5c 100644 --- a/runner/internal/shim/api/schemas.go +++ b/runner/internal/shim/api/schemas.go @@ -10,10 +10,14 @@ type HealthcheckResponse struct { Service string `json:"service"` Version string `json:"version"` SupportsVolumeMountPath bool `json:"supports_volume_mount_path"` - SupportsVolumeFlush bool `json:"supports_volume_flush"` - BootID string `json:"boot_id,omitempty"` } +type VolumeMountsRequest struct { + Paths []string `json:"paths"` +} +type VolumeMountsResponse struct { + BootID string `json:"boot_id"` +} type FlushVolumesRequest struct { BootID string `json:"boot_id"` Paths []string `json:"paths"` diff --git a/runner/internal/shim/api/server.go b/runner/internal/shim/api/server.go index 76f5d62e77..7392b03a9c 100644 --- a/runner/internal/shim/api/server.go +++ b/runner/internal/shim/api/server.go @@ -27,7 +27,8 @@ type TaskRunner interface { Terminate(ctx context.Context, taskID string, timeout uint, reason string, message string) error Remove(ctx context.Context, taskID string) error ProcessTasks(ctx context.Context) - VolumeFlushBootID() string + VolumeFlushUser() string + AdmitVolumeMounts(paths []string) (string, error) FlushVolumes(ctx context.Context, bootID string, paths []string) (shim.VolumeFlushResult, error) Resources(context.Context) shim.Resources @@ -96,7 +97,8 @@ func NewShimServer( r.AddHandler("POST", "/api/shutdown", s.ShutdownHandler) r.AddHandler("GET", "/api/instance/health", s.InstanceHealthHandler) r.AddHandler("GET", "/api/instance/info", s.InstanceInfoHandler) - if runner.VolumeFlushBootID() != "" { + if runner.VolumeFlushUser() != "" { + r.AddHandler("POST", "/api/instance/volume-mounts", s.AdmitVolumeMountsHandler) r.AddHandler("POST", "/api/instance/flush-volumes", s.FlushVolumesHandler) } r.AddHandler("GET", "/api/components", s.ComponentListHandler) @@ -112,15 +114,25 @@ func NewShimServer( } func (s *ShimServer) Serve() error { - // Started before serving requests, so that tasks whose containers exited while - // the shim was not running are processed before the server reports their status + listener, err := s.listen(controlSocketPath) + if err != nil { + return err + } + // Start before serving, so completed containers are reconciled before a status request. s.bgJobsGroup.Go(func() { s.processTasks(s.bgJobsCtx) }) - if err := s.httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + if err := s.httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { return err } return nil } +func (s *ShimServer) listen(controlPath string) (net.Listener, error) { + if username := s.runner.VolumeFlushUser(); username != "" { + return listenControlSocket(controlPath, username) + } + return net.Listen("tcp", s.httpServer.Addr) +} + // processTasks processes tasks periodically until ctx is cancelled by Shutdown() func (s *ShimServer) processTasks(ctx context.Context) { ticker := time.NewTicker(taskProcessingInterval) diff --git a/runner/internal/shim/docker.go b/runner/internal/shim/docker.go index ebb0751071..4018a1249c 100644 --- a/runner/internal/shim/docker.go +++ b/runner/internal/shim/docker.go @@ -440,8 +440,8 @@ func (d *DockerRunner) Submit(ctx context.Context, cfg TaskConfig) error { if f := d.flush; f != nil { f.mu.Lock() defer f.mu.Unlock() - if f.seal != nil { - return fmt.Errorf("%w: instance is terminating", ErrRequest) + if !f.canStart() { + return fmt.Errorf("%w: instance has no active volume admission", ErrRequest) } } task := NewTaskFromConfig(cfg) @@ -496,9 +496,9 @@ func (d *DockerRunner) Start(ctx context.Context, taskID string) (err error) { // Fence the entire operation, independent of its entry in TaskStorage. if f := d.flush; f != nil { f.mu.Lock() - if f.seal != nil { + if !f.canStart() { f.mu.Unlock() - return fmt.Errorf("%w: instance is terminating", ErrRequest) + return fmt.Errorf("%w: instance has no active volume admission", ErrRequest) } f.starts.Add(1) f.mu.Unlock() @@ -598,7 +598,7 @@ func (d *DockerRunner) Start(ctx context.Context, taskID string) (err error) { } // Volumes mounted by a failed prepareVolumes() call are unmounted by cleanupLocked() - err = prepareVolumes(ctx, cfg) + err = d.prepareVolumes(ctx, cfg) if err != nil { errMessage := fmt.Sprintf("prepareVolumes error: %s", err.Error()) log.Error(ctx, errMessage) diff --git a/runner/internal/shim/volume_flush.go b/runner/internal/shim/volume_flush.go index 3e7453b2c9..bbb7226c07 100644 --- a/runner/internal/shim/volume_flush.go +++ b/runner/internal/shim/volume_flush.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "os" "path/filepath" "slices" @@ -19,8 +20,9 @@ import ( ) var ( - ErrFlushPathsChanged = errors.New("instance was sealed for a different set of volume mounts") - ErrFlushBootMismatch = errors.New("instance boot ID differs from the admitted VM") + ErrVolumeConflict = errors.New("volume admission conflict") + ErrMountNotReady = errors.New("volume mounts are not ready") + ErrMountUnsupported = errors.New("volume mount cannot be admitted") ) type VolumeFlushResult struct { @@ -29,24 +31,26 @@ type VolumeFlushResult struct { } type terminalVolumeFlush struct { - mu sync.Mutex - starts sync.WaitGroup - seal *volumeFlushSeal - recorded bool - restored bool - attempt *volumeFlushAttempt - // The worker keeps these descriptors until the shim exits. A regular mount ID - // cannot be recycled while its original mount is pinned. - pins map[string]*pinnedVolume + user string + mu sync.Mutex + admission sync.Mutex + starts sync.WaitGroup + seal *volumeFlushSeal + attempt *volumeFlushAttempt } +const ( + volumesAdmitted = "admitted" + volumesFlushing = "flushing" + volumesFlushed = "flushed" +) + +// A record is immutable once published. MountIDs are unique on the recorded boot. type volumeFlushSeal struct { - BootID string `json:"boot_id"` - Paths []string `json:"paths"` - // Unique mount IDs survive a shim restart on this boot (Linux 6.8+). - // A zero entry means that only the current shim's live pins can prove identity. - MountIDs []uint64 `json:"mount_ids,omitempty"` - Complete bool `json:"complete,omitempty"` + BootID string `json:"boot_id"` + Paths []string `json:"paths"` + MountIDs []uint64 `json:"mount_ids"` + Phase string `json:"phase"` } type volumeFlushAttempt struct { @@ -54,24 +58,91 @@ type volumeFlushAttempt struct { err error } -type pinnedVolume struct { - *os.File - mountID uint64 - uniqueID uint64 -} - -// VolumeFlushBootID is empty on instances that did not opt in or lack a Linux boot ID. -func (d *DockerRunner) VolumeFlushBootID() string { +func (d *DockerRunner) VolumeFlushUser() string { if d.flush == nil { return "" } - id, _ := readBootID() - return id + return d.flush.user +} + +// AdmitVolumeMounts fixes the filesystem identities before this VM accepts any tasks. +// A replay after a lost reply verifies the original identities without replacing them. +func (d *DockerRunner) AdmitVolumeMounts(paths []string) (string, error) { + f := d.flush + if f == nil { + return "", fmt.Errorf("%w: volume admission is disabled", ErrRequest) + } + paths, err := canonicalFlushPaths(paths) + if err != nil { + return "", err + } + bootID, err := readBootID() + if err != nil { + return "", err + } + // A stalled provider mount must not tie up subsequent callers or unrelated shim requests. + if !f.admission.TryLock() { + return "", fmt.Errorf("%w: verification in progress", ErrMountNotReady) + } + defer f.admission.Unlock() + f.mu.Lock() + seal := f.seal + f.mu.Unlock() + if seal != nil { + if err := seal.matches(bootID, paths); err != nil { + return "", err + } + if seal.Phase != volumesAdmitted { + return "", fmt.Errorf("%w: instance is terminating", ErrVolumeConflict) + } + } + ids := make([]uint64, len(paths)) + for i, path := range paths { + file, id, err := openVolumeMount(path) + if err != nil { + if errors.Is(err, errUniqueMountIDUnavailable) || errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) || errors.Is(err, unix.ELOOP) { + return "", fmt.Errorf("%w: %w", ErrMountUnsupported, err) + } + return "", fmt.Errorf("%w: %w", ErrMountNotReady, err) + } + defer file.Close() + if seal != nil && seal.MountIDs[i] != id { + return "", fmt.Errorf("%w: volume mount %q changed since admission", ErrVolumeConflict, path) + } + ids[i] = id + } + f.mu.Lock() + defer f.mu.Unlock() + if f.seal != seal { + return "", fmt.Errorf("%w: instance is terminating", ErrVolumeConflict) + } + if seal == nil { + if err := d.saveVolumeFlushSeal(&volumeFlushSeal{BootID: bootID, Paths: paths, MountIDs: ids, Phase: volumesAdmitted}); err != nil { + return "", err + } + } + return bootID, nil +} + +func (s *volumeFlushSeal) matches(bootID string, paths []string) error { + if s == nil { + return fmt.Errorf("%w: no volume mounts were admitted", ErrVolumeConflict) + } + if s.BootID != bootID { + return fmt.Errorf("%w: VM boot changed since admission", ErrVolumeConflict) + } + if !slices.Equal(s.Paths, paths) { + return fmt.Errorf("%w: different set of admitted mount paths", ErrVolumeConflict) + } + return nil +} + +// canStart must be checked under mu together with accepting the submission/start. +func (f *terminalVolumeFlush) canStart() bool { + id, err := readBootID() + return err == nil && f.seal != nil && f.seal.BootID == id && f.seal.Phase == volumesAdmitted } -// FlushVolumes seals the VM, then starts or polls one flush. The local seal must -// be durable before acknowledging the first request. Docker and volume I/O is -// done by the worker; disconnecting the caller does not cancel it. func (d *DockerRunner) FlushVolumes(ctx context.Context, expectedBootID string, paths []string) (VolumeFlushResult, error) { f := d.flush if f == nil { @@ -85,7 +156,7 @@ func (d *DockerRunner) FlushVolumes(ctx context.Context, expectedBootID string, return VolumeFlushResult{}, err } if expectedBootID != bootID { - return VolumeFlushResult{}, ErrFlushBootMismatch + return VolumeFlushResult{}, fmt.Errorf("%w: unexpected VM boot ID", ErrVolumeConflict) } paths, err = canonicalFlushPaths(paths) if err != nil { @@ -93,36 +164,31 @@ func (d *DockerRunner) FlushVolumes(ctx context.Context, expectedBootID string, } f.mu.Lock() defer f.mu.Unlock() - if f.seal == nil { - f.seal = &volumeFlushSeal{BootID: bootID, Paths: paths} - } else if !slices.Equal(f.seal.Paths, paths) { - return VolumeFlushResult{}, ErrFlushPathsChanged + if err := f.seal.matches(bootID, paths); err != nil { + return VolumeFlushResult{}, err } - if !f.recorded { - if err := d.saveVolumeFlushSeal(); err != nil { + if f.seal.Phase == volumesFlushed { + return VolumeFlushResult{Status: "done"}, nil + } + if f.seal.Phase == volumesAdmitted { + if err := d.setVolumePhase(volumesFlushing); err != nil { return VolumeFlushResult{}, err } - f.recorded = true } if attempt := f.attempt; attempt != nil { select { case <-attempt.done: - if attempt.err != nil { - f.attempt = nil // Deliver the failure once before starting a retry. - return VolumeFlushResult{Status: "failed", Error: attempt.err.Error()}, nil - } - return VolumeFlushResult{Status: "done"}, nil + f.attempt = nil + return VolumeFlushResult{Status: "failed", Error: attempt.err.Error()}, nil default: return VolumeFlushResult{Status: "pending"}, nil } } - if f.seal.Complete && f.seal.BootID == bootID { - return VolumeFlushResult{Status: "done"}, nil - } attempt := &volumeFlushAttempt{done: make(chan struct{})} + seal := f.seal f.attempt = attempt go func() { - attempt.err = d.flushStoppedVolumes(ctx) + attempt.err = d.flushStoppedVolumes(ctx, seal) close(attempt.done) }() return VolumeFlushResult{Status: "pending"}, nil @@ -157,161 +223,164 @@ var readBootID = sync.OnceValues(func() (string, error) { const volumeFlushSealName = ".terminal-volume-flush.json" func (d *DockerRunner) initVolumeFlush() error { - if os.Getenv("DSTACK_SHIM_VOLUME_FLUSH") != "1" { + user := os.Getenv("DSTACK_SHIM_VOLUME_FLUSH_USER") + if user == "" { return nil } - d.flush = &terminalVolumeFlush{} - path := filepath.Join(d.dockerParams.TasksDir(), volumeFlushSealName) - data, err := os.ReadFile(path) + d.flush = &terminalVolumeFlush{user: user} + dir, err := openVolumeState(unix.AT_FDCWD, d.dockerParams.TasksDir(), unix.S_IFDIR) if errors.Is(err, os.ErrNotExist) { return nil } if err != nil { return err } + defer dir.Close() + marker, err := openVolumeState(int(dir.Fd()), volumeFlushSealName, unix.S_IFREG) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer marker.Close() + data, err := io.ReadAll(marker) + if err != nil { + return err + } var seal volumeFlushSeal if err := json.Unmarshal(data, &seal); err != nil { return err } paths, err := canonicalFlushPaths(seal.Paths) if err != nil || !slices.Equal(paths, seal.Paths) || seal.BootID == "" || - (len(seal.MountIDs) != 0 && len(seal.MountIDs) != len(paths)) { + len(seal.MountIDs) != len(paths) || slices.Contains(seal.MountIDs, 0) || + (seal.Phase != volumesAdmitted && seal.Phase != volumesFlushing && seal.Phase != volumesFlushed) { return errors.New("invalid terminal volume flush seal") } d.flush.seal = &seal - d.flush.recorded = true - d.flush.restored = true return nil } -func (d *DockerRunner) saveVolumeFlushSeal() error { - dir := d.dockerParams.TasksDir() - if err := os.MkdirAll(dir, 0o700); err != nil { +// setVolumePhase and saveVolumeFlushSeal publish a new immutable record under flush.mu. +func (d *DockerRunner) setVolumePhase(phase string) error { + next := *d.flush.seal + next.Phase = phase + return d.saveVolumeFlushSeal(&next) +} + +func (d *DockerRunner) saveVolumeFlushSeal(seal *volumeFlushSeal) error { + path := d.dockerParams.TasksDir() + if err := os.MkdirAll(path, 0o700); err != nil { return err } - data, err := json.Marshal(d.flush.seal) + dir, err := openVolumeState(unix.AT_FDCWD, path, unix.S_IFDIR) if err != nil { return err } - path := filepath.Join(dir, volumeFlushSealName) - if err := writeFileSync(path+".tmp", data, 0o600); err != nil { + defer dir.Close() + data, err := json.Marshal(seal) + if err != nil { return err } - if err := os.Rename(path+".tmp", path); err != nil { + dirFD := int(dir.Fd()) + const tmp = volumeFlushSealName + ".tmp" + if err := unix.Unlinkat(dirFD, tmp, 0); err != nil && !errors.Is(err, unix.ENOENT) { return err } - // Persist both the rename and a newly created tasks directory. - for _, directory := range []string{dir, filepath.Dir(dir)} { - file, err := os.Open(directory) - if err != nil { - return err - } - if err := errors.Join(file.Sync(), file.Close()); err != nil { - return err - } + fd, err := unix.Openat(dirFD, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC, 0600) + if err != nil { + return err + } + file := os.NewFile(uintptr(fd), tmp) + if _, err = file.Write(data); err == nil { + err = file.Sync() + } + if err := errors.Join(err, file.Close()); err != nil { + return err } + if err := unix.Renameat(dirFD, tmp, dirFD, volumeFlushSealName); err != nil { + return err + } + if err := dir.Sync(); err != nil { + return err + } + parent, err := os.Open(filepath.Dir(path)) + if err != nil { + return err + } + if err := errors.Join(parent.Sync(), parent.Close()); err != nil { + return err + } + d.flush.seal = seal return nil } -func (d *DockerRunner) flushStoppedVolumes(ctx context.Context) error { - f := d.flush - bootID, err := readBootID() +// Only shim-owned state can authorize a bind or replay a completed flush. +func openVolumeState(dirFD int, path string, kind uint32) (*os.File, error) { + fd, err := unix.Openat2(dirFD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NONBLOCK, Resolve: unix.RESOLVE_NO_SYMLINKS}) if err != nil { - return err + return nil, err } - if bootID != f.seal.BootID { - return errors.New("VM rebooted after the termination seal; original mounts cannot be confirmed") + var st unix.Stat_t + if err = unix.Fstat(fd, &st); err == nil && (st.Mode&unix.S_IFMT != kind || st.Uid != uint32(os.Geteuid()) || st.Mode&0022 != 0) { + err = fmt.Errorf("unsafe ownership, permissions, or file type for volume state %q", path) } - if f.restored && (len(f.seal.MountIDs) == 0 || slices.Contains(f.seal.MountIDs, 0)) { - return errors.New("shim restarted without persistent mount identities; manual recovery is required") + if err != nil { + _ = unix.Close(fd) + return nil, err } - // Pin the original mounts and persist their identities before starting the - // flush, so a retry cannot certify a replacement filesystem at the same path. - if f.pins == nil { - f.pins = make(map[string]*pinnedVolume) + return os.NewFile(uintptr(fd), path), nil +} + +func (d *DockerRunner) flushStoppedVolumes(ctx context.Context, seal *volumeFlushSeal) error { + if err := d.stopVolumeWriters(ctx); err != nil { + return err } - for i, path := range f.seal.Paths { - mount, err := openFlushMount(path) + for i, path := range seal.Paths { + f, id, err := openVolumeMount(path) if err != nil { return err } - if prior := f.pins[path]; prior != nil { - _ = mount.Close() - if mount.mountID != prior.mountID { - return fmt.Errorf("volume mount %q changed since termination started", path) - } - continue - } - if f.restored && f.seal.MountIDs[i] != mount.uniqueID { - _ = mount.Close() - return fmt.Errorf("volume mount %q changed since the shim restarted", path) - } - f.pins[path] = mount - } - if len(f.seal.MountIDs) == 0 { - ids := make([]uint64, len(f.seal.Paths)) - for i, path := range f.seal.Paths { - ids[i] = f.pins[path].uniqueID - } - f.seal.MountIDs = ids - if err := d.saveVolumeFlushSeal(); err != nil { - f.seal.MountIDs = nil - return err + if id != seal.MountIDs[i] { + _ = f.Close() + return fmt.Errorf("volume mount %q changed since admission", path) } - } - if err := d.stopVolumeWriters(ctx); err != nil { - return err - } - // fsync each pinned mount root, mirroring GNU sync -- . - for _, path := range f.seal.Paths { - if err := f.pins[path].Sync(); err != nil { + // fsync the same verified directory descriptor, mirroring GNU sync -- . + err = f.Sync() + closeErr := f.Close() + if err := errors.Join(err, closeErr); err != nil { return fmt.Errorf("flush volume mount %q: %w", path, err) } } - // A mount can change while another remote filesystem is flushing. - for _, path := range f.seal.Paths { - current, err := openFlushMount(path) + for i, path := range seal.Paths { + f, id, err := openVolumeMount(path) if err != nil { return err } - _ = current.Close() - if current.mountID != f.pins[path].mountID { + _ = f.Close() + if id != seal.MountIDs[i] { return fmt.Errorf("volume mount %q changed during flush", path) } } - // The same sealed guest can replay a lost acknowledgment after shim restart, - // including on kernels without persistent unique mount IDs. - f.seal.Complete = true - if err := d.saveVolumeFlushSeal(); err != nil { - f.seal.Complete = false - return err - } - return nil + d.flush.mu.Lock() + defer d.flush.mu.Unlock() + return d.setVolumePhase(volumesFlushed) } -func openFlushMount(path string) (*pinnedVolume, error) { +func openVolumeMount(path string) (*os.File, uint64, error) { fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{ Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS, }) if err != nil { - return nil, fmt.Errorf("open volume mount %q: %w", path, err) + return nil, 0, fmt.Errorf("open volume mount %q: %w", path, err) } - id, err := verifiedMountID(fd, path) + id, err := verifiedMountID(fd, path, unix.STATX_MNT_ID_UNIQUE) if err != nil { _ = unix.Close(fd) - return nil, err - } - var st unix.Statx_t - err = unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID_UNIQUE, &st) - if err != nil && !errors.Is(err, unix.EINVAL) { - _ = unix.Close(fd) - return nil, err - } - var uniqueID uint64 - if st.Mask&unix.STATX_MNT_ID_UNIQUE != 0 { - uniqueID = st.Mnt_id + return nil, 0, err } - return &pinnedVolume{File: os.NewFile(uintptr(fd), path), mountID: id, uniqueID: uniqueID}, nil + return os.NewFile(uintptr(fd), path), id, nil } func (d *DockerRunner) stopVolumeWriters(ctx context.Context) error { diff --git a/runner/internal/shim/volume_flush_test.go b/runner/internal/shim/volume_flush_test.go index 048a6f3464..5c86b42c4f 100644 --- a/runner/internal/shim/volume_flush_test.go +++ b/runner/internal/shim/volume_flush_test.go @@ -21,17 +21,40 @@ func TestTerminalFlushDisabled(t *testing.T) { runner := newTestRunner(t, nil) marker := filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName) require.NoError(t, os.WriteFile(marker, []byte("invalid marker"), 0o600)) - t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "") + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH_USER", "") + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "1") require.NoError(t, runner.initVolumeFlush()) require.Nil(t, runner.flush) - require.Empty(t, runner.VolumeFlushBootID()) + require.Empty(t, runner.VolumeFlushUser()) _, err := runner.FlushVolumes(t.Context(), "another-boot", []string{"/dev/shm"}) require.ErrorIs(t, err, ErrRequest) require.NoError(t, runner.Submit(t.Context(), TaskConfig{ID: "normal"})) - t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "1") + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH_USER", "root") require.Error(t, runner.initVolumeFlush(), "an opted-in shim must honor the existing seal") } +func TestVolumeAdmissionRejectsUntrustedState(t *testing.T) { + runner := newTestFlushRunner(t, &dockerClientMock{}) + _, err := runner.AdmitVolumeMounts([]string{"/dev/shm"}) + require.NoError(t, err) + dir := runner.dockerParams.TasksDir() + marker := filepath.Join(dir, volumeFlushSealName) + require.NoError(t, os.Chmod(marker, 0666)) + require.ErrorContains(t, runner.initVolumeFlush(), "unsafe ownership, permissions, or file type") + require.NoError(t, os.Chmod(marker, 0600)) + require.NoError(t, os.Chmod(dir, 0777)) + require.ErrorContains(t, runner.initVolumeFlush(), "unsafe ownership, permissions, or file type") + require.NoError(t, os.Chmod(dir, 0700)) + require.NoError(t, os.Rename(marker, marker+".old")) + require.NoError(t, os.Symlink(marker+".old", marker)) + require.ErrorIs(t, runner.initVolumeFlush(), unix.ELOOP) + require.NoError(t, os.Remove(marker)) + // The previous protocol could mark a path complete without ever admitting it. + previous := []byte(`{"boot_id":"previous","paths":["/dev/shm"],"mount_ids":[1],"complete":true}`) + require.NoError(t, os.WriteFile(marker, previous, 0600)) + require.ErrorContains(t, runner.initVolumeFlush(), "invalid terminal volume flush seal") +} + // Exercise fsync and mount identity through a real mounted tmpfs. func TestTerminalVolumeFlush(t *testing.T) { ctx := t.Context() @@ -54,12 +77,18 @@ func TestTerminalVolumeFlush(t *testing.T) { runner := newTestFlushRunner(t, client) paths := []string{"/dev/shm"} _, err = runner.FlushVolumes(ctx, "wrong-vm", paths) - require.ErrorIs(t, err, ErrFlushBootMismatch) + require.ErrorIs(t, err, ErrVolumeConflict) for _, invalid := range [][]string{nil, {"relative"}, {"/"}, {"/tmp/../dev/shm"}} { _, err = runner.FlushVolumes(ctx, bootID, invalid) require.ErrorIs(t, err, ErrRequest) } + _, err = runner.FlushVolumes(ctx, bootID, paths) + require.ErrorIs(t, err, ErrVolumeConflict) + require.ErrorIs(t, runner.Submit(ctx, TaskConfig{ID: "too-early"}), ErrRequest) require.NoFileExists(t, filepath.Join(runner.dockerParams.TasksDir(), volumeFlushSealName)) + admitted, err := runner.AdmitVolumeMounts(paths) + require.NoError(t, err) + require.Equal(t, bootID, admitted) require.NoError(t, runner.Submit(ctx, TaskConfig{ID: "already-submitted"})) result, err := runner.FlushVolumes(ctx, bootID, paths) require.NoError(t, err) @@ -70,7 +99,7 @@ func TestTerminalVolumeFlush(t *testing.T) { require.ErrorIs(t, runner.Start(ctx, "already-submitted"), ErrRequest) require.Equal(t, TaskStatusTerminated, runner.TaskInfo("already-submitted").Status) _, err = runner.FlushVolumes(ctx, bootID, []string{"/other-volume"}) - require.ErrorIs(t, err, ErrFlushPathsChanged) + require.ErrorIs(t, err, ErrVolumeConflict) result, err = runner.FlushVolumes(ctx, bootID, []string{"/dev/shm", "/dev/shm"}) require.NoError(t, err) require.Equal(t, "pending", result.Status) @@ -109,6 +138,8 @@ func TestTerminalFlushWaitsForRemovedInFlightStart(t *testing.T) { runner := newTestFlushRunner(t, client) blocked := &blockedTaskDir{DockerParameters: runner.dockerParams, resume: make(chan struct{})} runner.dockerParams = blocked + _, err := runner.AdmitVolumeMounts([]string{"/dev/shm"}) + require.NoError(t, err) require.NoError(t, runner.Submit(ctx, TaskConfig{ID: "in-flight"})) go func() { _ = runner.Start(ctx, "in-flight") }() synctest.Wait() @@ -135,8 +166,9 @@ func TestTerminalFlushWaitsForRemovedInFlightStart(t *testing.T) { func TestTerminalFlushReportsFilesystemError(t *testing.T) { runner := newTestFlushRunner(t, &dockerClientMock{}) paths := []string{"/proc"} - id := runner.VolumeFlushBootID() - _, err := runner.FlushVolumes(t.Context(), id, paths) + id, err := runner.AdmitVolumeMounts(paths) + require.NoError(t, err) + _, err = runner.FlushVolumes(t.Context(), id, paths) require.NoError(t, err) waitForFlushSignal(t, runner.flush.attempt.done) require.ErrorIs(t, runner.flush.attempt.err, unix.EINVAL) @@ -151,8 +183,9 @@ func TestTerminalFlushRequiresDurableCompletion(t *testing.T) { client := &flushDockerClient{entered: make(chan struct{}), resume: make(chan struct{})} runner := newTestFlushRunner(t, client) paths := []string{"/dev/shm"} - id := runner.VolumeFlushBootID() - _, err := runner.FlushVolumes(t.Context(), id, paths) + id, err := runner.AdmitVolumeMounts(paths) + require.NoError(t, err) + _, err = runner.FlushVolumes(t.Context(), id, paths) require.NoError(t, err) waitForFlushSignal(t, client.entered) // Mount identities are already saved. Only the completion write will fail. @@ -165,7 +198,7 @@ func TestTerminalFlushRequiresDurableCompletion(t *testing.T) { require.Equal(t, "failed", result.Status) runner.flush = nil require.NoError(t, runner.initVolumeFlush()) - require.False(t, runner.flush.seal.Complete) + require.Equal(t, volumesFlushing, runner.flush.seal.Phase) } type blockedTaskDir struct { @@ -178,124 +211,114 @@ func (b *blockedTaskDir) MakeTaskDir(string) (string, error) { return "", errors.New("interrupted start") } -func TestTerminalFlushRestoresSealAndChecksIdentity(t *testing.T) { +func TestTerminalFlushRestoresAdmissionAndCompletion(t *testing.T) { ctx := t.Context() - bootID, err := readBootID() + runner := newTestFlushRunner(t, &dockerClientMock{}) + paths := []string{"/dev/shm"} + bootID, err := runner.AdmitVolumeMounts(paths) require.NoError(t, err) - first := newTestFlushRunner(t, &dockerClientMock{}) - path := "/dev/shm" - paths := []string{path} - _, err = first.FlushVolumes(ctx, bootID, paths) + runner.flush = nil + require.NoError(t, runner.initVolumeFlush()) + again, err := runner.AdmitVolumeMounts(paths) + require.NoError(t, err) + require.Equal(t, bootID, again) + _, err = runner.AdmitVolumeMounts([]string{"/proc"}) + require.ErrorIs(t, err, ErrVolumeConflict) + _, err = runner.FlushVolumes(ctx, bootID, paths) require.NoError(t, err) - waitForFlushSignal(t, first.flush.attempt.done) - require.NoError(t, first.flush.attempt.err) - require.True(t, first.flush.seal.Complete) - // Reopen the completed on-disk seal as a new shim. The same boot and path - // set can replay done even if its kernel lacked persistent unique mount IDs. - mountID := first.flush.seal.MountIDs[0] - first.flush.seal.MountIDs[0] = 0 - require.NoError(t, first.saveVolumeFlushSeal()) - first.flush = nil - require.NoError(t, first.initVolumeFlush()) - result, err := first.FlushVolumes(ctx, bootID, paths) + waitForFlushSignal(t, runner.flush.attempt.done) + require.Equal(t, volumesFlushed, runner.flush.seal.Phase) + runner.flush = nil + require.NoError(t, runner.initVolumeFlush()) + result, err := runner.FlushVolumes(ctx, bootID, paths) require.NoError(t, err) require.Equal(t, VolumeFlushResult{Status: "done"}, result) - require.Nil(t, first.flush.attempt) - _, err = first.FlushVolumes(ctx, bootID, []string{"/other"}) - require.ErrorIs(t, err, ErrFlushPathsChanged) - _, err = first.FlushVolumes(ctx, "previous-guest", paths) - require.ErrorIs(t, err, ErrFlushBootMismatch) - first.flush.seal.MountIDs[0] = mountID - for _, tc := range []struct { - name string - mutate func(*volumeFlushSeal) - wantError string - }{ - {"same mount", func(*volumeFlushSeal) {}, ""}, - {"changed mount", func(s *volumeFlushSeal) { s.MountIDs[0]++ }, "changed since"}, - {"reboot", func(s *volumeFlushSeal) { s.BootID = "previous-boot" }, "VM rebooted"}, - {"reboot after completion", func(s *volumeFlushSeal) { s.BootID = "previous-boot"; s.Complete = true }, "VM rebooted"}, - {"no unique mount ID", func(s *volumeFlushSeal) { s.MountIDs[0] = 0 }, "manual recovery"}, - {"restart before mount verification", func(s *volumeFlushSeal) { s.MountIDs = nil }, "manual recovery"}, - } { - t.Run(tc.name, func(t *testing.T) { - again := newTestFlushRunner(t, &dockerClientMock{}) - original := *first.flush.seal - original.Complete = false - original.MountIDs = append([]uint64(nil), first.flush.seal.MountIDs...) - tc.mutate(&original) - again.flush.seal = &original - require.NoError(t, again.saveVolumeFlushSeal()) - again.flush = nil - require.NoError(t, again.initVolumeFlush()) - require.ErrorIs(t, again.Submit(ctx, TaskConfig{ID: "stale-submit"}), ErrRequest) - result, err := again.FlushVolumes(ctx, bootID, paths) - require.NoError(t, err) - require.Equal(t, "pending", result.Status) - waitForFlushSignal(t, again.flush.attempt.done) - result, err = again.FlushVolumes(ctx, bootID, paths) - require.NoError(t, err) - wantError := tc.wantError - if first.flush.seal.MountIDs[0] == 0 && tc.name == "same mount" { - wantError = "manual recovery" // Pre-6.8 Linux only supplies reusable mount IDs. - } - if wantError != "" { - require.Equal(t, "failed", result.Status) - require.Contains(t, result.Error, wantError) - } else { - require.Equal(t, "done", result.Status) - } - }) + require.Nil(t, runner.flush.attempt) + require.ErrorIs(t, runner.Submit(ctx, TaskConfig{ID: "late"}), ErrRequest) + _, err = runner.AdmitVolumeMounts(paths) + require.ErrorIs(t, err, ErrVolumeConflict) + _, err = runner.FlushVolumes(ctx, bootID, []string{"/other"}) + require.ErrorIs(t, err, ErrVolumeConflict) + _, err = runner.FlushVolumes(ctx, "previous", paths) + require.ErrorIs(t, err, ErrVolumeConflict) + for _, phase := range []string{volumesAdmitted, volumesFlushing, volumesFlushed} { + previous := *runner.flush.seal + previous.BootID = "previous-boot" + previous.Phase = phase + require.NoError(t, runner.saveVolumeFlushSeal(&previous)) + runner.flush = nil + require.NoError(t, runner.initVolumeFlush()) + require.ErrorIs(t, runner.Submit(ctx, TaskConfig{ID: "other-boot"}), ErrRequest) + _, err = runner.AdmitVolumeMounts(paths) + require.ErrorIs(t, err, ErrVolumeConflict) + _, err = runner.FlushVolumes(ctx, bootID, paths) + require.ErrorIs(t, err, ErrVolumeConflict) } } func TestTerminalFlushRejectsReplacedMount(t *testing.T) { path := t.TempDir() + paths := []string{path} + ctx := t.Context() + runner := newTestFlushRunner(t, &dockerClientMock{}) mount := func() error { return unix.Mount("tmpfs", path, "tmpfs", 0, "size=1m") } + _, err := runner.AdmitVolumeMounts(paths) + require.ErrorIs(t, err, ErrMountNotReady) + require.Nil(t, runner.flush.seal) if err := mount(); errors.Is(err, unix.EPERM) { - t.Skip("replacing the original filesystem requires CAP_SYS_ADMIN") + t.Skip("replacing a mounted filesystem requires CAP_SYS_ADMIN") } else { require.NoError(t, err) } t.Cleanup(func() { _ = unix.Unmount(path, unix.MNT_DETACH) }) - ctx := t.Context() - client := &flushDockerClient{entered: make(chan struct{}), resume: make(chan struct{})} - runner := newTestFlushRunner(t, client) - bootID, err := readBootID() - require.NoError(t, err) - paths := []string{path} - _, err = runner.FlushVolumes(ctx, bootID, paths) + id, err := runner.AdmitVolumeMounts(paths) require.NoError(t, err) - waitForFlushSignal(t, client.entered) - // The old FD survives a lazy detach. Success on it cannot certify the replacement. + bind := filepath.Join(t.TempDir(), "bind") + require.NoError(t, runner.bindMountedVolume(path, bind)) + t.Cleanup(func() { _ = unix.Unmount(bind, unix.MNT_DETACH) }) + require.NoError(t, os.WriteFile(filepath.Join(bind, "original"), []byte("written"), 0600)) require.NoError(t, unix.Unmount(path, unix.MNT_DETACH)) require.NoError(t, mount()) - close(client.resume) + runner.flush = nil + require.NoError(t, runner.initVolumeFlush()) + _, err = runner.AdmitVolumeMounts(paths) + require.ErrorIs(t, err, ErrVolumeConflict) + require.ErrorIs(t, runner.bindMountedVolume(path, filepath.Join(t.TempDir(), "late")), ErrVolumeConflict) + require.ErrorIs(t, runner.bindMountedVolume("/dev/shm", filepath.Join(t.TempDir(), "unknown")), ErrVolumeConflict) + require.NoFileExists(t, filepath.Join(path, "original")) + require.FileExists(t, filepath.Join(bind, "original")) + _, err = runner.FlushVolumes(ctx, id, paths) + require.NoError(t, err) waitForFlushSignal(t, runner.flush.attempt.done) - result, err := runner.FlushVolumes(ctx, bootID, paths) + result, err := runner.FlushVolumes(ctx, id, paths) require.NoError(t, err) require.Equal(t, "failed", result.Status) - require.Contains(t, result.Error, "changed during flush") - - result, err = runner.FlushVolumes(ctx, bootID, paths) - require.NoError(t, err) - require.Equal(t, "pending", result.Status) - waitForFlushSignal(t, runner.flush.attempt.done) - require.ErrorContains(t, runner.flush.attempt.err, "changed since termination started") + require.Contains(t, result.Error, "changed since admission") } func TestOpenFlushMountRejectsPlainDirectoryAndSymlink(t *testing.T) { - _, err := openFlushMount(t.TempDir()) + _, _, err := openVolumeMount(t.TempDir()) require.ErrorContains(t, err, "not a verified mount point") alias := filepath.Join(t.TempDir(), "alias") require.NoError(t, os.Symlink("/dev/shm", alias)) - _, err = openFlushMount(alias) + _, _, err = openVolumeMount(alias) require.ErrorIs(t, err, unix.ELOOP) + r := newTestFlushRunner(t, &dockerClientMock{}) + _, err = r.AdmitVolumeMounts([]string{alias}) + require.ErrorIs(t, err, ErrMountUnsupported) + _, err = r.AdmitVolumeMounts([]string{filepath.Join(t.TempDir(), "missing")}) + require.ErrorIs(t, err, ErrMountNotReady) } func newTestFlushRunner(t *testing.T, client docker.APIClient) *DockerRunner { t.Helper() - t.Setenv("DSTACK_SHIM_VOLUME_FLUSH", "1") + f, _, err := openVolumeMount("/dev/shm") + if errors.Is(err, errUniqueMountIDUnavailable) { + t.Skip("volume admission needs Linux STATX_MNT_ID_UNIQUE") + } + require.NoError(t, err) + require.NoError(t, f.Close()) + t.Setenv("DSTACK_SHIM_VOLUME_FLUSH_USER", "root") runner := newTestRunner(t, client) require.NoError(t, runner.initVolumeFlush()) return runner diff --git a/runner/internal/shim/volumes.go b/runner/internal/shim/volumes.go index 38079467bd..5224f6e9b5 100644 --- a/runner/internal/shim/volumes.go +++ b/runner/internal/shim/volumes.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -17,7 +18,7 @@ import ( "github.com/dstackai/dstack/runner/internal/shim/backends" ) -func prepareVolumes(ctx context.Context, taskConfig TaskConfig) error { +func (d *DockerRunner) prepareVolumes(ctx context.Context, taskConfig TaskConfig) error { if len(taskConfig.Volumes) == 0 { return nil } @@ -28,7 +29,7 @@ func prepareVolumes(ctx context.Context, taskConfig TaskConfig) error { if err != nil { return err } - if err := bindMountedVolume(volume.MountPath, target); err != nil { + if err := d.bindMountedVolume(volume.MountPath, target); err != nil { return fmt.Errorf("bind mounted volume %s: %w", volume.Name, err) } continue @@ -85,7 +86,7 @@ func unmountVolumes(ctx context.Context, taskConfig TaskConfig) error { // bindMountedVolume pins the source directory before checking its mount ID. A provider // unmount between verification and bind cannot substitute a directory on the root disk. -func bindMountedVolume(source, target string) error { +func (d *DockerRunner) bindMountedVolume(source, target string) error { // Reject symlinks in the entire path, including the provider's mount parent. how := &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS} fd, err := unix.Openat2(unix.AT_FDCWD, source, how) @@ -93,9 +94,27 @@ func bindMountedVolume(source, target string) error { return err } defer func() { _ = unix.Close(fd) }() - if _, err := verifiedMountID(fd, source); err != nil { + mask := unix.STATX_MNT_ID + if d.flush != nil { + mask = unix.STATX_MNT_ID_UNIQUE + } + id, err := verifiedMountID(fd, source, mask) + if err != nil { return err } + if f := d.flush; f != nil { + f.mu.Lock() + admitted := f.canStart() + seal := f.seal + f.mu.Unlock() + if !admitted { + return fmt.Errorf("%w: no active volume admission", ErrVolumeConflict) + } + i, ok := slices.BinarySearch(seal.Paths, source) + if !ok || seal.MountIDs[i] != id { + return fmt.Errorf("%w: mount %q differs from admission", ErrVolumeConflict, source) + } + } // Build a private bind mount before publishing it to Docker. Failure drops the // detached mount when its file descriptor closes. tree, err := unix.OpenTree(fd, "", unix.AT_EMPTY_PATH|unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC) @@ -117,16 +136,27 @@ func bindMountedVolume(source, target string) error { return unix.MoveMount(tree, "", targetFD, "", unix.MOVE_MOUNT_F_EMPTY_PATH|unix.MOVE_MOUNT_T_EMPTY_PATH) } +var errUniqueMountIDUnavailable = errors.New("kernel does not provide STATX_MNT_ID_UNIQUE") + // verifiedMountID compares the pinned directory with its parent across the mount boundary. -func verifiedMountID(fd int, source string) (uint64, error) { +func verifiedMountID(fd int, source string, mask int) (uint64, error) { var dir, parent unix.Statx_t - if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID, &dir); err != nil { + if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH|unix.AT_STATX_DONT_SYNC, mask, &dir); err != nil { + if mask == unix.STATX_MNT_ID_UNIQUE && errors.Is(err, unix.EINVAL) { + return 0, errUniqueMountIDUnavailable + } return 0, err } - if err := unix.Statx(fd, "..", 0, unix.STATX_MNT_ID, &parent); err != nil { + if mask == unix.STATX_MNT_ID_UNIQUE && dir.Mask&uint32(mask) == 0 { + return 0, errUniqueMountIDUnavailable + } + if err := unix.Statx(fd, "..", unix.AT_STATX_DONT_SYNC, mask, &parent); err != nil { return 0, err } - if dir.Mask&unix.STATX_MNT_ID == 0 || parent.Mask&unix.STATX_MNT_ID == 0 || dir.Mnt_id == parent.Mnt_id { + if dir.Mask&uint32(mask) == 0 || parent.Mask&uint32(mask) == 0 { + return 0, fmt.Errorf("kernel does not provide the required mount ID for %q", source) + } + if dir.Mnt_id == 0 || dir.Mnt_id == parent.Mnt_id { return 0, fmt.Errorf("%s is not a verified mount point", source) } return dir.Mnt_id, nil diff --git a/runner/internal/shim/volumes_test.go b/runner/internal/shim/volumes_test.go index 56e4eec09c..f21d7b8106 100644 --- a/runner/internal/shim/volumes_test.go +++ b/runner/internal/shim/volumes_test.go @@ -14,7 +14,7 @@ func TestBindMountedVolume(t *testing.T) { source := t.TempDir() target := filepath.Join(t.TempDir(), "bind") // A provider can leave the directory behind even when its filesystem is missing. - require.ErrorContains(t, bindMountedVolume(source, target), "not a verified mount point") + require.ErrorContains(t, (&DockerRunner{}).bindMountedVolume(source, target), "not a verified mount point") if err := unix.Mount("tmpfs", source, "tmpfs", 0, "size=1m"); errors.Is(err, unix.EPERM) { t.Skip("mounting tmpfs requires CAP_SYS_ADMIN") @@ -25,13 +25,13 @@ func TestBindMountedVolume(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(source, "checkpoint"), []byte("saved"), 0o600)) alias := filepath.Join(t.TempDir(), "mounts") require.NoError(t, os.Symlink(filepath.Dir(source), alias)) - require.ErrorIs(t, bindMountedVolume(filepath.Join(alias, filepath.Base(source)), target), unix.ELOOP) + require.ErrorIs(t, (&DockerRunner{}).bindMountedVolume(filepath.Join(alias, filepath.Base(source)), target), unix.ELOOP) cfg := TaskConfig{ ID: filepath.Base(filepath.Dir(source)), Volumes: []VolumeInfo{{Name: "data", Backend: "massedcompute", MountPath: source}}, VolumeMounts: []VolumeMountPoint{{Name: "data", Path: "/data"}}, } - require.NoError(t, prepareVolumes(t.Context(), cfg)) + require.NoError(t, (&DockerRunner{}).prepareVolumes(t.Context(), cfg)) t.Cleanup(func() { _ = unmountVolumes(t.Context(), cfg) }) mounts, err := getVolumeMounts(cfg) require.NoError(t, err) @@ -54,5 +54,5 @@ func TestPrepareProviderVolumeWithoutMountPath(t *testing.T) { // Older shims ignore mount_path and enter the block-volume path. A missing // mount path on a new shim must fail before looking up or formatting devices too. cfg := TaskConfig{Volumes: []VolumeInfo{{Backend: "massedcompute", Name: "data"}}} - require.ErrorContains(t, prepareVolumes(t.Context(), cfg), "unknown backend") + require.ErrorContains(t, (&DockerRunner{}).prepareVolumes(t.Context(), cfg), "unknown backend") } diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py index 748b08e1ff..6c46ae0026 100644 --- a/src/dstack/_internal/core/backends/massedcompute/compute.py +++ b/src/dstack/_internal/core/backends/massedcompute/compute.py @@ -95,7 +95,7 @@ def create_instance( install_keys = shlex.join(["sudo", "-H", "-u", "Ubuntu", "sh", "-c", key_script]) shim_commands = get_shim_commands( arch=instance_offer.instance.resources.cpu_arch, - backend_shim_env={"DSTACK_SHIM_VOLUME_FLUSH": "1"} + backend_shim_env={"DSTACK_SHIM_VOLUME_FLUSH_USER": "Ubuntu"} if instance_config.volumes else None, ) @@ -125,6 +125,7 @@ def create_instance( data = _instance_provisioning_data(instance_offer, instance_id) data.backend_data = launch.model_dump_json() data.volume_mounts = {k: v.mount_path for k, v in volumes.items()} + data.shim_unix_socket = True return data def _get_launch_volumes(self, volumes: list[Volume]) -> dict[UUID, MassedComputeVolume]: diff --git a/src/dstack/_internal/core/consts.py b/src/dstack/_internal/core/consts.py index 9b60381bdc..678be6ad8c 100644 --- a/src/dstack/_internal/core/consts.py +++ b/src/dstack/_internal/core/consts.py @@ -2,6 +2,7 @@ # shim (runs on the host) HTTP API port DSTACK_SHIM_HTTP_PORT = 10998 +DSTACK_SHIM_SOCKET_PATH = "/run/dstack-shim/control.sock" # runner (runs inside a container) HTTP API port DSTACK_RUNNER_HTTP_PORT = 10999 # ssh server (runs alongside the runner inside a container) listen port diff --git a/src/dstack/_internal/core/models/runs.py b/src/dstack/_internal/core/models/runs.py index db8d760ad2..5244dbf7cb 100644 --- a/src/dstack/_internal/core/models/runs.py +++ b/src/dstack/_internal/core/models/runs.py @@ -355,6 +355,8 @@ class JobProvisioningData(CoreModel): """`backend_data` stores backend-specific data in JSON.""" volume_mounts: Optional[dict[UUID, str]] = Field(default=None, exclude_if=lambda v: v is None) """Host mount paths by dstack volume ID. The backend confirms them before publishing hostname.""" + shim_unix_socket: bool = Field(default=False, exclude_if=lambda v: not v) + """The shim listens on its private Unix socket on the guest. Forward it over SSH.""" volume_mount_boot_id: Optional[UUID] = Field(default=None, exclude_if=lambda v: v is None) """Guest boot on which the volume mounts were admitted. Required before flushing them.""" gpu_driver: Optional[GpuDriverInfo] = None diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py index 5ad798012d..8364c2a0db 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py @@ -3,6 +3,7 @@ from collections.abc import Mapping from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +from http import HTTPStatus from typing import Optional import gpuhunt @@ -385,29 +386,49 @@ async def _process_wait_for_instance_provisioning_data( ) if conn is None: return result - if not await conn.has_volume_mounts(job_provisioning_data.volume_mounts.values()): + if isinstance(compute, ComputeWithVolumeFlushSupport): + if not job_provisioning_data.shim_unix_socket: + raise ProvisioningError( + "A private shim socket is required for volume flushes" + ) + shim = runner_client.ShimClient.from_address( + conn.forwarded_paths()[DSTACK_SHIM_HTTP_PORT] + ) + try: + job_provisioning_data.volume_mount_boot_id = await run_instance_call( + volume_executor, + shim.admit_volume_mounts, + list(job_provisioning_data.volume_mounts.values()), + ) + except runner_client.ShimResponseStatusError as exc: + if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + return result # The provider has not mounted every filesystem yet. + if exc.status_code not in ( + HTTPStatus.BAD_REQUEST, + HTTPStatus.NOT_FOUND, + HTTPStatus.CONFLICT, + HTTPStatus.UNPROCESSABLE_ENTITY, + ): + raise + set_status_update( + update_map=result.instance_update_map, + instance_model=instance_model, + new_status=InstanceStatus.TERMINATING, + termination_reason=InstanceTerminationReason.ERROR, + termination_reason_message=f"Cannot use the instance's mounted volumes: {exc}", + ) + return result + except httpx2.TransportError: + return result # The shim may still be starting. + elif not await conn.has_volume_mounts( + job_provisioning_data.volume_mounts.values() + ): await run_instance_call( volume_executor, instance_connection_pool.drop_by_jpd, job_provisioning_data, ) return result - if isinstance(compute, ComputeWithVolumeFlushSupport): - shim = runner_client.ShimClient.from_address( - conn.forwarded_paths()[DSTACK_SHIM_HTTP_PORT] - ) - health = await run_instance_call(volume_executor, shim.healthcheck) - if health is None: - return result - if ( - health.service != "dstack-shim" - or not health.supports_volume_flush - or not health.boot_id - ): - raise ProvisioningError( - "The shim must be upgraded to flush mounted volumes" - ) - job_provisioning_data.volume_mount_boot_id = uuid.UUID(health.boot_id) result.instance_update_map["job_provisioning_data"] = ( job_provisioning_data.model_dump_json() ) diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py index 064df5bba3..c9abec36b0 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py @@ -181,6 +181,8 @@ def _terminate_with_volumes( # The provider confirmed this VM is gone. Never issue a second lookup or DELETE. return if paths: + if not data.shim_unix_socket: + raise BackendError("Cannot confirm the volume flush through a private shim socket") if data.volume_mount_boot_id is None: raise BackendError( "Cannot confirm the guest boot on which the volumes were mounted" diff --git a/src/dstack/_internal/server/schemas/runner.py b/src/dstack/_internal/server/schemas/runner.py index bd8d369cf9..ae8b2b7e94 100644 --- a/src/dstack/_internal/server/schemas/runner.py +++ b/src/dstack/_internal/server/schemas/runner.py @@ -1,6 +1,7 @@ from base64 import b64decode from enum import Enum from typing import Any, Dict, List, Literal, Optional, Union +from uuid import UUID from pydantic import Field, field_validator @@ -134,8 +135,14 @@ class HealthcheckResponse(CoreModel): service: str version: str supports_volume_mount_path: bool = False - supports_volume_flush: bool = False - boot_id: Optional[str] = None + + +class AdmitVolumeMountsRequest(CoreModel): + paths: list[str] + + +class AdmitVolumeMountsResponse(CoreModel): + boot_id: UUID class FlushVolumesRequest(CoreModel): diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py index 1e869ecd00..6bbd93e9d4 100644 --- a/src/dstack/_internal/server/services/runner/client.py +++ b/src/dstack/_internal/server/services/runner/client.py @@ -24,6 +24,8 @@ from dstack._internal.server import settings as server_settings from dstack._internal.server.schemas.instances import InstanceCheck from dstack._internal.server.schemas.runner import ( + AdmitVolumeMountsRequest, + AdmitVolumeMountsResponse, ComponentInfo, ComponentInstallRequest, ComponentListResponse, @@ -535,6 +537,15 @@ def get_instance_info(self) -> Optional[InstanceInfoResponse]: self._raise_for_status(resp) return self._response(InstanceInfoResponse, resp) + def admit_volume_mounts(self, paths: list[str]) -> uuid.UUID: + """Record and verify the guest filesystems before the first job may write.""" + response = self._request( + "POST", "/api/instance/volume-mounts", AdmitVolumeMountsRequest(paths=paths) + ) + if response.status_code != HTTPStatus.OK: + raise ShimResponseStatusError(response) + return self._response(AdmitVolumeMountsResponse, response).boot_id + def flush_volumes(self, boot_id: uuid.UUID, paths: list[str]) -> FlushVolumesResponse: """Start or check the terminal flush for these mounts on the admitted guest boot.""" body = FlushVolumesRequest(boot_id=str(boot_id), paths=paths) diff --git a/src/dstack/_internal/server/services/runner/pool.py b/src/dstack/_internal/server/services/runner/pool.py index 7623f69352..075bb4bd96 100644 --- a/src/dstack/_internal/server/services/runner/pool.py +++ b/src/dstack/_internal/server/services/runner/pool.py @@ -9,7 +9,11 @@ from typing import Collection, Optional, Union from weakref import WeakValueDictionary -from dstack._internal.core.consts import DSTACK_RUNNER_HTTP_PORT, DSTACK_SHIM_HTTP_PORT +from dstack._internal.core.consts import ( + DSTACK_RUNNER_HTTP_PORT, + DSTACK_SHIM_HTTP_PORT, + DSTACK_SHIM_SOCKET_PATH, +) from dstack._internal.core.errors import SSHError from dstack._internal.core.models.instances import SSHConnectionParams from dstack._internal.core.models.runs import JobProvisioningData, JobRuntimeData @@ -42,6 +46,7 @@ class InstanceConnectionKey: hostname: str port: int ports_to_forward: tuple[int, ...] + shim_unix_socket: bool = False @staticmethod def from_jpd( @@ -53,6 +58,7 @@ def from_jpd( hostname=jpd.hostname, port=jpd.ssh_port, ports_to_forward=tuple(container_to_host_port_map.values()), + shim_unix_socket=jpd.shim_unix_socket, ) @@ -214,7 +220,9 @@ def __init__( port=jpd.ssh_port, identity=InstanceConnection._get_identity(ssh_private_key), control_sock_path=self._control_socket_path, - forwarded_sockets=self._get_forwarded_sockets(self._host_port_to_uds_map), + forwarded_sockets=self._get_forwarded_sockets( + self._host_port_to_uds_map, self._key.shim_unix_socket + ), ssh_proxies=InstanceConnection._get_proxies(ssh_private_key, jpd), options={ **SSH_DEFAULT_OPTIONS, @@ -324,6 +332,8 @@ def _resolve_conn_dir( _get_connections_dir() / f"{key.hostname}:{key.port},{','.join(map(str, key.ports_to_forward))}" ) + if key.shim_unix_socket: + conn_dir = conn_dir.with_name(conn_dir.name + ",shim-unix") conn_dir.mkdir(parents=True, exist_ok=True) # Connection_dir can have a long path that won't be accepted by the ssh command, # so we create a short temporary symlink. @@ -343,11 +353,17 @@ def _get_host_port_to_uds_map( return {port: conn_dir / f"{port}.sock" for port in ports_to_forward} @staticmethod - def _get_forwarded_sockets(host_port_to_uds_map: dict[int, Path]) -> list[SocketPair]: + def _get_forwarded_sockets( + host_port_to_uds_map: dict[int, Path], shim_unix_socket: bool = False + ) -> list[SocketPair]: return [ SocketPair( local=UnixSocket(path=path), - remote=IPSocket(host="localhost", port=port), + remote=( + UnixSocket(path=DSTACK_SHIM_SOCKET_PATH) + if shim_unix_socket and port == DSTACK_SHIM_HTTP_PORT + else IPSocket(host="localhost", port=port) + ), ) for port, path in host_port_to_uds_map.items() ] diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py index 99f1243b6e..af26fac811 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_compute.py +++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py @@ -98,7 +98,11 @@ def launch(lost_reply=False): "ip": "192.0.2.1", } assert http_mock.last_request.json()["volumeIds"] == [VOLUME_ID] - assert 'export "DSTACK_SHIM_VOLUME_FLUSH=1"' in http_mock.last_request.json()["command"] + assert ( + 'export "DSTACK_SHIM_VOLUME_FLUSH_USER=Ubuntu"' + in http_mock.last_request.json()["command"] + ) + assert data.shim_unix_socket assert data.volume_mounts == {volume_config.volumes[0].id: storage["mountPath"]} http_mock.get(f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm]}) return data, vm @@ -114,6 +118,7 @@ def test_omits_volume_ids_for_a_plain_vm(self, compute, http_mock, offer): assert "DSTACK_SHIM_VOLUME_FLUSH" not in http_mock.last_request.json()["command"] assert data.instance_id == VM_ID assert data.backend_data is None and data.volume_mounts is None + assert not data.shim_unix_socket def test_fails_before_launch_if_volume_in_use( self, compute, http_mock, offer, volume_config, storage diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py index 511fde4641..1582ae2df2 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py @@ -2,7 +2,7 @@ import logging import uuid from typing import ClassVar, Optional -from unittest.mock import AsyncMock, Mock +from unittest.mock import Mock import httpx2 import pytest @@ -12,6 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal import settings +from dstack._internal.core.consts import DSTACK_SHIM_HTTP_PORT from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.common import validate_json_extra_ignore from dstack._internal.core.models.fleets import FleetNodesSpec @@ -43,6 +44,7 @@ ) from dstack._internal.server.services.runner.client import ComponentList, ShimClient from dstack._internal.server.testing.common import ( + ComputeMockSpec, create_fleet, create_instance, create_job, @@ -181,23 +183,28 @@ async def test_cloudrift_waits_for_backend_within_timeout( else: backend.compute().update_provisioning_data.assert_called_once() + @pytest.mark.parametrize("status_code", [503, 422]) async def test_deletes_vm_if_volume_never_mounts( self, test_db, session: AsyncSession, worker: InstanceWorker, monkeypatch: pytest.MonkeyPatch, + http_mock, + status_code: int, ): project = await create_project(session) data = get_job_provisioning_data( backend=BackendType.MASSEDCOMPUTE, hostname=None, dockerized=True ) data.volume_mounts = {uuid.uuid4(): "/persistent/checkpoints"} + data.shim_unix_socket = True instance = await create_instance( session, project, status=InstanceStatus.PROVISIONING, job_provisioning_data=data ) instance.started_at = get_current_datetime() backend = Mock() + backend.compute.return_value = Mock(spec=ComputeMockSpec) def set_hostname(data: JobProvisioningData, *args) -> None: data.hostname = "192.0.2.1" @@ -207,23 +214,32 @@ def set_hostname(data: JobProvisioningData, *args) -> None: "dstack._internal.server.services.backends.cache.lease_project_backend_by_type", mock_lease(backend), ) - conn = AsyncMock() - conn.has_volume_mounts.return_value = False + conn = Mock() + conn.forwarded_paths.return_value = {DSTACK_SHIM_HTTP_PORT: DSTACK_SHIM_HTTP_PORT} + http_mock.post( + f"http://localhost:{DSTACK_SHIM_HTTP_PORT}/api/instance/volume-mounts", + status_code=status_code, + text="mount unavailable" if status_code == 503 else "kernel lacks unique mount IDs", + ) monkeypatch.setattr( instances_check.instance_connection_pool, "get_or_open", lambda *_: conn ) await process_instance(session, worker, instance) await session.refresh(instance) - conn.has_volume_mounts.assert_awaited_once() + assert http_mock.last_request.json() == {"paths": ["/persistent/checkpoints"]} assert instance.job_provisioning_data is not None assert ( JobProvisioningData.model_validate_json(instance.job_provisioning_data).hostname is None ) - instance.started_at = get_current_datetime() - dt.timedelta(hours=1) - await process_instance(session, worker, instance) - await session.refresh(instance) + if status_code == 503: + assert instance.status == InstanceStatus.PROVISIONING + instance.started_at = get_current_datetime() - dt.timedelta(hours=1) + await process_instance(session, worker, instance) + await session.refresh(instance) + else: + assert "kernel lacks unique mount IDs" in (instance.termination_reason_message or "") assert instance.status == InstanceStatus.TERMINATING await process_instance(session, worker, instance) await session.refresh(instance) diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py index b0e005dda8..d4df91145d 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py +++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py @@ -284,6 +284,7 @@ async def test_flushes_and_releases_vm_volume_attachments( jpd = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE) jpd.volume_mounts = {volume.id: "/persistent/checkpoints"} jpd.volume_mount_boot_id = uuid.uuid4() + jpd.shim_unix_socket = True instance = await create_instance( session, project, diff --git a/src/tests/_internal/server/services/runner/test_ssh.py b/src/tests/_internal/server/services/runner/test_ssh.py index f2d9435ab9..37d20fd6b5 100644 --- a/src/tests/_internal/server/services/runner/test_ssh.py +++ b/src/tests/_internal/server/services/runner/test_ssh.py @@ -6,8 +6,13 @@ import pydantic import pytest -from dstack._internal.core.consts import DSTACK_SHIM_HTTP_PORT +from dstack._internal.core.consts import ( + DSTACK_RUNNER_HTTP_PORT, + DSTACK_SHIM_HTTP_PORT, + DSTACK_SHIM_SOCKET_PATH, +) from dstack._internal.core.errors import SSHError +from dstack._internal.core.services.ssh.tunnel import IPSocket, UnixSocket from dstack._internal.server.schemas.runner import HealthcheckResponse from dstack._internal.server.services.runner.client import ( LocalAddress, @@ -16,12 +21,30 @@ ShimResponseError, ShimResponseStatusError, ) +from dstack._internal.server.services.runner.pool import InstanceConnection, InstanceConnectionKey from dstack._internal.server.services.runner.ssh import runner_ssh_tunnel from dstack._internal.server.testing.common import get_job_provisioning_data FORWARDED_PATHS = {DSTACK_SHIM_HTTP_PORT: Path("/tmp/shim.sock")} +class TestInstanceConnection: + def test_private_shim_control_uses_a_distinct_tunnel(self): + ordinary = get_job_provisioning_data(dockerized=True) + mounted = ordinary.model_copy(update={"shim_unix_socket": True}) + assert InstanceConnectionKey.from_jpd(mounted, None) != InstanceConnectionKey.from_jpd( + ordinary, None + ) + ports = {**FORWARDED_PATHS, DSTACK_RUNNER_HTTP_PORT: Path("/tmp/runner.sock")} + private, runner = InstanceConnection._get_forwarded_sockets( + ports, mounted.shim_unix_socket + ) + assert private.remote == UnixSocket(path=DSTACK_SHIM_SOCKET_PATH) + assert runner.remote == IPSocket(host="localhost", port=DSTACK_RUNNER_HTTP_PORT) + public, _ = InstanceConnection._get_forwarded_sockets(ports, ordinary.shim_unix_socket) + assert public.remote == IPSocket(host="localhost", port=DSTACK_SHIM_HTTP_PORT) + + def _shim_response(status_code: int, content: bytes) -> httpx2.Response: return httpx2.Response( status_code, From 3387cec4281a73269301bb8dd3c57689b143749f Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 14:44:21 +0100 Subject: [PATCH 4/8] Keep the private shim forward separate from runner TCP ports --- .../_internal/server/services/runner/pool.py | 43 +++++++++-------- .../server/services/runner/test_ssh.py | 48 ++++++++++++++----- 2 files changed, 57 insertions(+), 34 deletions(-) diff --git a/src/dstack/_internal/server/services/runner/pool.py b/src/dstack/_internal/server/services/runner/pool.py index 075bb4bd96..8ef09bc3d1 100644 --- a/src/dstack/_internal/server/services/runner/pool.py +++ b/src/dstack/_internal/server/services/runner/pool.py @@ -58,7 +58,7 @@ def from_jpd( hostname=jpd.hostname, port=jpd.ssh_port, ports_to_forward=tuple(container_to_host_port_map.values()), - shim_unix_socket=jpd.shim_unix_socket, + shim_unix_socket=jpd.dockerized and jpd.shim_unix_socket, ) @@ -208,21 +208,31 @@ def __init__( ) self._control_socket_path = self._effective_conn_dir / "control.sock" self._real_control_socket_path = self._real_conn_dir / "control.sock" - self._container_to_host_port_map = InstanceConnection.get_container_to_host_port_map( - jpd, jrd - ) - self._host_port_to_uds_map = InstanceConnection._get_host_port_to_uds_map( + port_map = InstanceConnection.get_container_to_host_port_map(jpd, jrd) + host_port_to_uds_map = InstanceConnection._get_host_port_to_uds_map( conn_dir=self._effective_conn_dir, ports_to_forward=self._key.ports_to_forward, ) + self._forwarded_paths = { + container_port: host_port_to_uds_map[host_port] + for container_port, host_port in port_map.items() + } + forwarded_sockets = self._get_forwarded_sockets(host_port_to_uds_map) + if self._key.shim_unix_socket: + shim_path = self._effective_conn_dir / "shim.sock" + self._forwarded_paths[DSTACK_SHIM_HTTP_PORT] = shim_path + forwarded_sockets.append( + SocketPair( + local=UnixSocket(path=shim_path), + remote=UnixSocket(path=DSTACK_SHIM_SOCKET_PATH), + ) + ) self._tunnel = SSHTunnel( destination=f"{jpd.username}@{jpd.hostname}", port=jpd.ssh_port, identity=InstanceConnection._get_identity(ssh_private_key), control_sock_path=self._control_socket_path, - forwarded_sockets=self._get_forwarded_sockets( - self._host_port_to_uds_map, self._key.shim_unix_socket - ), + forwarded_sockets=forwarded_sockets, ssh_proxies=InstanceConnection._get_proxies(ssh_private_key, jpd), options={ **SSH_DEFAULT_OPTIONS, @@ -285,10 +295,7 @@ def is_alive(self) -> bool: def forwarded_paths(self) -> dict[int, Path]: """Returns a mapping from container port to the local UDS path.""" - return { - container_port: self._host_port_to_uds_map[host_port] - for container_port, host_port in self._container_to_host_port_map.items() - } + return self._forwarded_paths.copy() def close(self) -> None: self._tunnel.close() @@ -312,7 +319,7 @@ def get_container_to_host_port_map( if jrd is not None and jrd.ports is not None: runner_host_port = jrd.ports.get(DSTACK_RUNNER_HTTP_PORT, runner_host_port) port_map = {DSTACK_RUNNER_HTTP_PORT: runner_host_port} - if jpd.dockerized: + if jpd.dockerized and not jpd.shim_unix_socket: port_map[DSTACK_SHIM_HTTP_PORT] = DSTACK_SHIM_HTTP_PORT return port_map @@ -353,17 +360,11 @@ def _get_host_port_to_uds_map( return {port: conn_dir / f"{port}.sock" for port in ports_to_forward} @staticmethod - def _get_forwarded_sockets( - host_port_to_uds_map: dict[int, Path], shim_unix_socket: bool = False - ) -> list[SocketPair]: + def _get_forwarded_sockets(host_port_to_uds_map: dict[int, Path]) -> list[SocketPair]: return [ SocketPair( local=UnixSocket(path=path), - remote=( - UnixSocket(path=DSTACK_SHIM_SOCKET_PATH) - if shim_unix_socket and port == DSTACK_SHIM_HTTP_PORT - else IPSocket(host="localhost", port=port) - ), + remote=IPSocket(host="localhost", port=port), ) for port, path in host_port_to_uds_map.items() ] diff --git a/src/tests/_internal/server/services/runner/test_ssh.py b/src/tests/_internal/server/services/runner/test_ssh.py index 37d20fd6b5..440930ab80 100644 --- a/src/tests/_internal/server/services/runner/test_ssh.py +++ b/src/tests/_internal/server/services/runner/test_ssh.py @@ -12,7 +12,7 @@ DSTACK_SHIM_SOCKET_PATH, ) from dstack._internal.core.errors import SSHError -from dstack._internal.core.services.ssh.tunnel import IPSocket, UnixSocket +from dstack._internal.core.services.ssh.tunnel import IPSocket, SocketPair, UnixSocket from dstack._internal.server.schemas.runner import HealthcheckResponse from dstack._internal.server.services.runner.client import ( LocalAddress, @@ -21,9 +21,9 @@ ShimResponseError, ShimResponseStatusError, ) -from dstack._internal.server.services.runner.pool import InstanceConnection, InstanceConnectionKey +from dstack._internal.server.services.runner.pool import InstanceConnection from dstack._internal.server.services.runner.ssh import runner_ssh_tunnel -from dstack._internal.server.testing.common import get_job_provisioning_data +from dstack._internal.server.testing.common import get_job_provisioning_data, get_job_runtime_data FORWARDED_PATHS = {DSTACK_SHIM_HTTP_PORT: Path("/tmp/shim.sock")} @@ -32,17 +32,39 @@ class TestInstanceConnection: def test_private_shim_control_uses_a_distinct_tunnel(self): ordinary = get_job_provisioning_data(dockerized=True) mounted = ordinary.model_copy(update={"shim_unix_socket": True}) - assert InstanceConnectionKey.from_jpd(mounted, None) != InstanceConnectionKey.from_jpd( - ordinary, None + # On a private-socket VM, Docker may publish the runner on the unused shim TCP port. + runtime = get_job_runtime_data( + network_mode="bridge", ports={DSTACK_RUNNER_HTTP_PORT: DSTACK_SHIM_HTTP_PORT} ) - ports = {**FORWARDED_PATHS, DSTACK_RUNNER_HTTP_PORT: Path("/tmp/runner.sock")} - private, runner = InstanceConnection._get_forwarded_sockets( - ports, mounted.shim_unix_socket - ) - assert private.remote == UnixSocket(path=DSTACK_SHIM_SOCKET_PATH) - assert runner.remote == IPSocket(host="localhost", port=DSTACK_RUNNER_HTTP_PORT) - public, _ = InstanceConnection._get_forwarded_sockets(ports, ordinary.shim_unix_socket) - assert public.remote == IPSocket(host="localhost", port=DSTACK_SHIM_HTTP_PORT) + target = "dstack._internal.server.services.runner.pool.SSHTunnel" + with patch(target) as tunnel: + private = InstanceConnection("key", mounted, runtime, ephemeral=True) + forwards = tunnel.call_args.kwargs["forwarded_sockets"] + paths = private.forwarded_paths() + assert paths[DSTACK_SHIM_HTTP_PORT] != paths[DSTACK_RUNNER_HTTP_PORT] + assert ( + SocketPair( + local=UnixSocket(path=paths[DSTACK_SHIM_HTTP_PORT]), + remote=UnixSocket(path=DSTACK_SHIM_SOCKET_PATH), + ) + in forwards + ) + assert ( + SocketPair( + local=UnixSocket(path=paths[DSTACK_RUNNER_HTTP_PORT]), + remote=IPSocket(host="localhost", port=DSTACK_SHIM_HTTP_PORT), + ) + in forwards + ) + public = InstanceConnection("key", ordinary, None, ephemeral=True) + assert private.key != public.key + assert ( + SocketPair( + local=UnixSocket(path=public.forwarded_paths()[DSTACK_SHIM_HTTP_PORT]), + remote=IPSocket(host="localhost", port=DSTACK_SHIM_HTTP_PORT), + ) + in tunnel.call_args.kwargs["forwarded_sockets"] + ) def _shim_response(status_code: int, content: bytes) -> httpx2.Response: From 316c02db40911915c48e81007f4cf37edb99b3e2 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 14:48:00 +0100 Subject: [PATCH 5/8] Clarify why dstack retains a stopped MassedCompute volume VM --- src/dstack/_internal/core/backends/massedcompute/compute.py | 4 ++-- .../_internal/core/backends/massedcompute/test_compute.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py index 6c46ae0026..72b897a751 100644 --- a/src/dstack/_internal/core/backends/massedcompute/compute.py +++ b/src/dstack/_internal/core/backends/massedcompute/compute.py @@ -238,8 +238,8 @@ def get_volume_mounts_to_sync( ) if instance.status.lower() == "stopped": raise ComputeError( - "Cannot flush volumes on a stopped MassedCompute VM. " - "Restart the VM to flush its volumes, or terminate it manually in MassedCompute." + "The MassedCompute VM is stopped. dstack will keep it because it cannot " + "confirm that pending volume writes reached storage." ) return list((provisioning_data.volume_mounts or {}).values()) diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py index af26fac811..cfb4114ee6 100644 --- a/src/tests/_internal/core/backends/massedcompute/test_compute.py +++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py @@ -317,7 +317,7 @@ def test_decides_from_confirmed_vm_snapshot(self, compute, http_mock, volume_con f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm] if status else []} ) if status == "Stopped": - with pytest.raises(ComputeError, match="Restart"): + with pytest.raises(ComputeError, match="VM is stopped"): compute.get_volume_mounts_to_sync(data) elif status == "Deleting": with pytest.raises(NotYetTerminated): From 1c04742b0f474b84fd55ac0d2603ab2bdfc757f1 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 20:34:16 +0100 Subject: [PATCH 6/8] Document the MassedCompute volume sync limitation --- mkdocs/docs/concepts/volumes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mkdocs/docs/concepts/volumes.md b/mkdocs/docs/concepts/volumes.md index 3304f4cffe..8d6e4e0f05 100644 --- a/mkdocs/docs/concepts/volumes.md +++ b/mkdocs/docs/concepts/volumes.md @@ -78,6 +78,9 @@ If you use this configuration, `dstack` will create a new volume based on the sp name: my-volume ``` + > If an upload fails, MassedCompute can still report a successful sync. Terminating the VM + > before the changes reach storage can lose recent writes or make deleted files reappear. + ??? info "Kubernetes" Set `region` to a kubeconfig context name enabled in the [backend configuration](backends.md#kubernetes). Omit it only for legacy configurations without `contexts`. From d21517b6eb1580072289917612805283964d42e2 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 20:36:04 +0100 Subject: [PATCH 7/8] Fix shim lint checks for volume flushing --- runner/internal/shim/api/control_socket.go | 2 +- runner/internal/shim/api/server.go | 3 ++- runner/internal/shim/volume_flush.go | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/runner/internal/shim/api/control_socket.go b/runner/internal/shim/api/control_socket.go index 5e31900088..d6a37ef031 100644 --- a/runner/internal/shim/api/control_socket.go +++ b/runner/internal/shim/api/control_socket.go @@ -63,7 +63,7 @@ func listenControlSocket(path, username string) (listener net.Listener, err erro if err != nil { return nil, err } - defer os.RemoveAll(staging) + defer func() { _ = os.RemoveAll(staging) }() tmp := filepath.Join(staging, "s") sock, err := net.ListenUnix("unix", &net.UnixAddr{Name: tmp, Net: "unix"}) if err != nil { diff --git a/runner/internal/shim/api/server.go b/runner/internal/shim/api/server.go index 7392b03a9c..f663bc9f39 100644 --- a/runner/internal/shim/api/server.go +++ b/runner/internal/shim/api/server.go @@ -130,7 +130,8 @@ func (s *ShimServer) listen(controlPath string) (net.Listener, error) { if username := s.runner.VolumeFlushUser(); username != "" { return listenControlSocket(controlPath, username) } - return net.Listen("tcp", s.httpServer.Addr) + var config net.ListenConfig + return config.Listen(s.ctx, "tcp", s.httpServer.Addr) } // processTasks processes tasks periodically until ctx is cancelled by Shutdown() diff --git a/runner/internal/shim/volume_flush.go b/runner/internal/shim/volume_flush.go index bbb7226c07..80f6992456 100644 --- a/runner/internal/shim/volume_flush.go +++ b/runner/internal/shim/volume_flush.go @@ -217,7 +217,7 @@ var readBootID = sync.OnceValues(func() (string, error) { if value := strings.TrimSpace(string(id)); value != "" { return value, nil } - return "", errors.New("Linux boot ID is unavailable") + return "", errors.New("guest boot ID is unavailable") }) const volumeFlushSealName = ".terminal-volume-flush.json" @@ -288,7 +288,7 @@ func (d *DockerRunner) saveVolumeFlushSeal(seal *volumeFlushSeal) error { if err := unix.Unlinkat(dirFD, tmp, 0); err != nil && !errors.Is(err, unix.ENOENT) { return err } - fd, err := unix.Openat(dirFD, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC, 0600) + fd, err := unix.Openat(dirFD, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC, 0o600) if err != nil { return err } From 2a46a6fbb66ab4d0ac07a8f119e373cc02aed761 Mon Sep 17 00:00:00 2001 From: Andrey Cheptsov Date: Tue, 1 Dec 2026 20:38:28 +0100 Subject: [PATCH 8/8] Format the shim volume state permission mask --- runner/internal/shim/volume_flush.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runner/internal/shim/volume_flush.go b/runner/internal/shim/volume_flush.go index 80f6992456..803a85b985 100644 --- a/runner/internal/shim/volume_flush.go +++ b/runner/internal/shim/volume_flush.go @@ -323,7 +323,7 @@ func openVolumeState(dirFD int, path string, kind uint32) (*os.File, error) { return nil, err } var st unix.Stat_t - if err = unix.Fstat(fd, &st); err == nil && (st.Mode&unix.S_IFMT != kind || st.Uid != uint32(os.Geteuid()) || st.Mode&0022 != 0) { + if err = unix.Fstat(fd, &st); err == nil && (st.Mode&unix.S_IFMT != kind || st.Uid != uint32(os.Geteuid()) || st.Mode&0o022 != 0) { err = fmt.Errorf("unsafe ownership, permissions, or file type for volume state %q", path) } if err != nil {