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 mkdocs/docs/concepts/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -1109,7 +1109,7 @@ projects:

</div>

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
Expand Down
22 changes: 20 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,23 @@ 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
```

> 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`.
Expand Down Expand Up @@ -228,7 +245,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.
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
130 changes: 130 additions & 0 deletions runner/docs/shim.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -102,6 +106,96 @@ 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 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
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 shim uses ordinary TCP transport
$ref: "#/components/responses/PlainTextNotFound"
"409":
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
$ref: "#/components/responses/PlainTextInternalError"

/components:
get:
summary: Get components
Expand Down Expand Up @@ -495,11 +589,47 @@ components:
type: string
examples:
- 0.18.34
supports_volume_mount_path:
type: boolean
description: The shim can bind volumes from a provider mount path.
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
properties:
boot_id:
type: string
format: uuid
description: The boot ID recorded when the server admitted this instance.
paths:
$ref: "#/components/schemas/VolumeMountPaths"
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
Expand Down
30 changes: 26 additions & 4 deletions runner/internal/shim/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import (
)

type DummyRunner struct {
tasks map[string]bool
gpus []host.GpuInfo
processed atomic.Int64
mu sync.Mutex
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 {
Expand Down Expand Up @@ -50,6 +52,26 @@ func (ds *DummyRunner) TaskInfo(taskID string) shim.TaskInfo {
return shim.TaskInfo{}
}

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.ErrVolumeConflict
}
return shim.VolumeFlushResult{Status: "pending"}, nil
}

func (ds *DummyRunner) Resources(context.Context) shim.Resources {
return shim.Resources{}
}
Expand Down
95 changes: 95 additions & 0 deletions runner/internal/shim/api/control_socket.go
Original file line number Diff line number Diff line change
@@ -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 func() { _ = 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()) }
Loading
Loading