Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion contributing/ORPHAN-CLEANUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Processing a row:
- Instance found:
- `PENDING`, `TERMINATING`: skip, since the resources may be in flight. An error is logged if a pending instance's resources look stuck.
- `TERMINATED`: orphan.
- `PROVISIONING`, `IDLE`, `BUSY`: tracked if the base backend and `primary_id` match the instance's provisioning data, orphan otherwise.
- `PROVISIONING`, `IDLE`, `BUSY`: tracked if the base backend and `primary_id` match the instance's provisioning data, orphan otherwise. A backend that uses the exact launch name until it learns the provider ID can also supply `primary_name` for this match.
- Without provisioning data: ignored with an error log.
- Record found without an instance: orphan. The owner was deleted, e.g. a placeholder instance after a failed `run_job()`, so nothing can be creating its resources anymore.
- No record: ignored. Resources of other servers and projects are never touched.
Expand Down
1 change: 1 addition & 0 deletions frontend/src/types/backend.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ declare type TBackendType =
| 'kubernetes'
| 'lambda'
| 'lium'
| 'massedcompute'
| 'local'
| 'nebius'
| 'remote'
Expand Down
22 changes: 22 additions & 0 deletions mkdocs/docs/concepts/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,28 @@ projects:

</div>

### MassedCompute

Create a full-access API key in [MassedCompute settings](https://vm-docs.massedcompute.com/docs/settings/api-settings)
and configure the backend in the server configuration.

<div editor-title="~/.dstack/server/config.yml">

```yaml
projects:
- name: main
backends:
- type: massedcompute
creds:
type: api_key
api_key: YOUR_MASSEDCOMPUTE_API_KEY
```

</div>

MassedCompute provisions single-node, on-demand CPU and GPU VMs and selects the site at launch
(region `any`). It also supports experimental [network volumes](volumes.md#network-volumes).

### Vultr

Log into your [Vultr](https://www.vultr.com/) account, click `Account` in the sidebar, select `API`, find the `Personal Access Token` panel and click the `Enable API` button. In the `Access Control` panel, allow API requests from all addresses or from the subnet where your `dstack` server is deployed.
Expand Down
16 changes: 14 additions & 2 deletions mkdocs/docs/concepts/volumes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -64,6 +64,18 @@ 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. Enable Persistent Storage in your MassedCompute account and omit `size` and `region`.
A VM can attach up to eight volumes at launch. Delete the VM before using a volume on another VM.

```yaml
type: volume
backend: massedcompute
name: my-volume
```

> If a VM loses its connection to storage, deleting it can lose recent writes. See [storage limitations](https://vm-docs.massedcompute.com/docs/persistent-storage/limitations).

??? 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`.
Expand Down Expand Up @@ -228,7 +240,7 @@ and its contents will persist across runs.

### Detach a volume { #detach-network-volume }

`dstack` automatically detaches volumes from instances when a run stops.
`dstack` automatically detaches volumes when a run stops if the backend supports detaching them.

!!! info "Force detach"
In some clouds such as AWS a volume may stuck in the detaching state.
Expand Down
8 changes: 8 additions & 0 deletions mkdocs/docs/reference/dstack.yml/volume.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions mkdocs/docs/reference/server/config.yml.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,23 @@ to configure [backends](../../concepts/backends.md) and other [server-level sett
type:
required: true

##### `projects[n].backends[type=massedcompute]` { #massedcompute data-toc-label="massedcompute" }

#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeBackendConfigWithCreds
overrides:
show_root_heading: false
type:
required: true
item_id_prefix: massedcompute-

###### `projects[n].backends[type=massedcompute].creds` { #massedcompute-creds data-toc-label="creds" }

#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeAPIKeyCreds
overrides:
show_root_heading: false
type:
required: true

##### `projects[n].backends[type=nebius]` { #nebius data-toc-label="nebius" }

#SCHEMA# dstack._internal.core.backends.nebius.models.NebiusBackendFileConfigWithCreds
Expand Down
7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ dependencies = [
"python-multipart>=0.0.31",
"filelock",
"psutil",
"gpuhunt==0.1.36",
# Replace with the gpuhunt release containing the MassedCompute provider before merging.
"gpuhunt @ git+https://github.com/dstackai/gpuhunt.git@bc78a82599800bd2612a180292747016bbe328ed",
"argcomplete>=3.5.0",
"ignore-python>=0.2.0",
"apscheduler<4",
Expand All @@ -56,6 +57,10 @@ dstack = "dstack._internal.cli.main:main"
[tool.hatch.version]
path = "src/dstack/version.py"

[tool.hatch.metadata]
# Remove after pinning the released gpuhunt package.
allow-direct-references = true

[tool.hatch.build.targets.sdist]
artifacts = [
"src/dstack/_internal/server/statics/**",
Expand Down
17 changes: 13 additions & 4 deletions runner/internal/shim/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -979,7 +979,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)
}
Expand Down Expand Up @@ -1328,10 +1328,19 @@ 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 != "" {
sources[volume.Name] = taskVolumeMountPoint(cfg.ID, volume)
}
}
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
Expand Down
1 change: 1 addition & 0 deletions runner/internal/shim/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
53 changes: 52 additions & 1 deletion runner/internal/shim/volumes.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ func prepareVolumes(ctx context.Context, taskConfig TaskConfig) error {
}
log.Debug(ctx, "Preparing volumes...")
for _, volume := range taskConfig.Volumes {
if volume.MountPath != "" {
if err := bindMountedVolume(volume.MountPath, taskVolumeMountPoint(taskConfig.ID, volume)); 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)
Expand All @@ -38,12 +44,23 @@ 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 := taskVolumeMountPoint(taskConfig.ID, volume)
cmd := exec.CommandContext(ctx, "mountpoint", mountPoint)
if output, err := cmd.CombinedOutput(); err != nil {
log.Info(ctx, "skipping", "mountpoint", mountPoint, "output", output)
continue
}
if volume.MountPath != "" {
// MNT_FORCE can abort the underlying FUSE connection, including the provider's mount.
if err := unix.Unmount(mountPoint, 0); err != nil {
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, "umount", "-qf", mountPoint)
if output, err := cmd.CombinedOutput(); err != nil {
log.Error(ctx, "failed to unmount", "mountpoint", mountPoint, "output", output)
Expand All @@ -58,6 +75,40 @@ 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 {
fd, err := unix.Open(source, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
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)
}
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
if err := unix.Mount(fmt.Sprintf("/proc/self/fd/%d", fd), target, "", unix.MS_BIND, ""); err != nil {
return err
}
return unix.Mount("", target, "", unix.MS_PRIVATE, "")
}

func taskVolumeMountPoint(taskID string, volume VolumeInfo) string {
if volume.MountPath != "" {
return filepath.Join("/mnt/disks/dstack-task-volumes", taskID, volume.Name)
}
return getVolumeMountPoint(volume.Name)
}

func formatAndMountVolume(ctx context.Context, volume VolumeInfo) error {
backend, err := backends.GetBackend(volume.Backend)
if err != nil {
Expand Down
35 changes: 35 additions & 0 deletions runner/internal/shim/volumes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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))
require.NoError(t, bindMountedVolume(source, target))
t.Cleanup(func() { _ = unix.Unmount(target, 0) })

// 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"))
}
8 changes: 8 additions & 0 deletions src/dstack/_internal/core/backends/base/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,14 @@ def delete_volume(self, volume: Volume):
"""
raise NotImplementedError()

def get_volume_mounts_to_sync(self, provisioning_data: JobProvisioningData) -> list[str]:
"""Return host mounts to flush before terminating the instance.

Called only for VMs with provider-mounted filesystems and an SSH address.
Exclude mounts when the provider confirms the VM is already stopped or gone.
"""
return list((provisioning_data.volume_mounts or {}).values())

def attach_volume(
self, volume: Volume, provisioning_data: JobProvisioningData
) -> VolumeAttachmentData:
Expand Down
7 changes: 7 additions & 0 deletions src/dstack/_internal/core/backends/configurators.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@
except ImportError:
pass

try:
from dstack._internal.core.backends.massedcompute.configurator import MassedComputeConfigurator

_CONFIGURATOR_CLASSES.append(MassedComputeConfigurator)
except ImportError:
pass

try:
from dstack._internal.core.backends.nebius.configurator import (
NebiusConfigurator,
Expand Down
Empty file.
Loading
Loading