-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathdstack-cloud
More file actions
executable file
·3673 lines (3224 loc) · 148 KB
/
Copy pathdstack-cloud
File metadata and controls
executable file
·3673 lines (3224 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-FileCopyrightText: © 2025 Phala Network <dstack@phala.network>
#
# SPDX-License-Identifier: Apache-2.0
"""
dstack-cloud: Multi-cloud VM lifecycle management tool
A production-grade CLI for managing dstack VMs on various cloud platforms
(GCP TDX and AWS EC2 NitroTPM). Supports local configuration files similar
to git's working model.
Usage:
dstack-cloud new <name> [--platform gcp|aws]
dstack-cloud config-edit # Edit global configuration
dstack-cloud prepare # Generate shared files (.sys-config + compose)
dstack-cloud deploy # Deploy VM to cloud (GCP or AWS)
dstack-cloud status # Check deployment status
dstack-cloud logs [--follow] # View serial console logs
dstack-cloud stop / start / remove # Lifecycle
dstack-cloud list # List deployments (GCP)
dstack-cloud fw allow|deny|list ... # Firewall (GCP)
AWS projects set "platform": "aws" in app.json and fill aws_config
(region, networking, …). Local RAW disks are written directly to EBS snapshots.
prepare/deploy only *embed* aws_measurement
from the release UKI package (digest.txt + sha256sum.txt + measurement.aws.cbor
produced at image assemble time). They never recompute PCRs or os_image_hash.
"""
import argparse
import base64
import concurrent.futures
import hashlib
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Dict, Any
# Try to import cryptography libraries for env encryption
CRYPTO_AVAILABLE = False
ETH_CRYPTO_AVAILABLE = False
try:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.asymmetric import x25519
from cryptography.hazmat.primitives import serialization
CRYPTO_AVAILABLE = True
except Exception:
pass
try:
from eth_keys import keys
from eth_utils import keccak
ETH_CRYPTO_AVAILABLE = True
except Exception:
pass
# Default whitelist file location
DEFAULT_KMS_WHITELIST_PATH = os.path.expanduser("~/.config/dstack-cloud/kms-whitelist.json")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Configuration file names
APP_CONFIG_FILE = "app.json"
STATE_FILE = "state.json"
# Global config location. Overridable via DSTACK_CLOUD_CONFIG so a caller can use
# a local/throwaway config (e.g. a vendor computing an OS-image hash) without
# polluting the user's global ~/.config/dstack-cloud.
GLOBAL_CONFIG_PATH = os.path.expanduser(
os.environ.get("DSTACK_CLOUD_CONFIG") or "~/.config/dstack-cloud/config.json"
)
DEFAULT_OS_IMAGE = "dstack-0.6.0"
MONOREPO_GUEST_OS_MIN_VERSION = (0, 6, 0)
AWS_EBS_BLOCK_SIZE = 512 * 1024
AWS_EBS_UPLOAD_WORKERS = 8
AWS_EBS_UPLOAD_QUEUE_DEPTH = AWS_EBS_UPLOAD_WORKERS * 2
def guest_os_release_url(os_image: str, version: str) -> str:
"""Return the UKI release URL for a versioned guest image."""
match = re.fullmatch(
r'(\d+)\.(\d+)\.(\d+)(?:[-.][0-9A-Za-z][0-9A-Za-z.-]*)?',
version,
)
if not match:
raise ValueError(f"Invalid guest OS version: {version}")
core = tuple(int(part) for part in match.groups())
if core < MONOREPO_GUEST_OS_MIN_VERSION:
return (
"https://github.com/Dstack-TEE/meta-dstack/releases/download/"
f"v{version}/{os_image}-uki.tar.gz"
)
return (
"https://github.com/Dstack-TEE/dstack/releases/download/"
f"guest-os-v{version}/{os_image}-uki.tar.gz"
)
@dataclass
class App:
"""Application configuration."""
# App name
name: str = "myapp"
# OS image
os_image: str = DEFAULT_OS_IMAGE
# Target cloud platform: "gcp" or "aws"
platform: str = "gcp"
# GCP cloud configuration
gcp_config: 'GcpConfig' = field(default_factory=lambda: GcpConfig())
# AWS cloud configuration
aws_config: 'AwsConfig' = field(default_factory=lambda: AwsConfig())
# Docker compose file name (relative to project root)
docker_compose_file: str = "docker-compose.yaml"
# Pre-built app-compose.json to ship VERBATIM (relative to project root).
# When set, its exact bytes become shared/app-compose.json instead of being
# generated from docker_compose_file — required for externally-built composes
# (e.g. self-contained apps) whose compose-hash is computed over their own
# serialization. Empty (default) keeps the normal generated behavior.
app_compose_file: str = ""
# Prelaunch script name (relative to project root)
prelaunch_script: str = "prelaunch.sh"
# Environment file name (relative to project root)
env_file: str = ".env"
# Instance identity
instance_id_seed: str = ""
app_id: str = ""
# Gateway settings
gateway_enabled: bool = True
public_logs: bool = True
public_sysinfo: bool = True
public_tcbinfo: bool = True
# KMS settings
key_provider: str = "kms"
# Storage
storage_fs: str = "ext4"
# Instance settings
no_instance_id: bool = False
secure_time: bool = False
# Allowed environments
allowed_envs: List[str] = field(default_factory=list)
key_provider_id: str = ""
def to_dict(self) -> Dict[str, Any]:
# asdict() recursively converts the nested config dataclasses too
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'App':
known_fields = {f.name for f in cls.__dataclass_fields__.values()}
filtered = {k: v for k, v in data.items() if k in known_fields}
# Convert nested config dicts
if "gcp_config" in filtered and isinstance(filtered["gcp_config"], dict):
filtered["gcp_config"] = GcpConfig.from_dict(filtered["gcp_config"])
if "aws_config" in filtered and isinstance(filtered["aws_config"], dict):
filtered["aws_config"] = AwsConfig.from_dict(filtered["aws_config"])
if "platform" in filtered and isinstance(filtered["platform"], str):
filtered["platform"] = filtered["platform"].lower()
return cls(**filtered)
@classmethod
def get_template(cls) -> Dict[str, Any]:
"""Get default template for new projects."""
import secrets
# Generate random instance_id_seed (40 hex chars)
instance_id_seed = secrets.token_hex(20)
# Generate random app_id (40 hex chars)
app_id = secrets.token_hex(20)
return {
"name": "myapp",
"os_image": DEFAULT_OS_IMAGE,
"platform": "gcp",
"gcp_config": GcpConfig.get_template(),
"aws_config": AwsConfig.get_template(),
"instance_id_seed": instance_id_seed,
"app_id": app_id,
"docker_compose_file": "docker-compose.yaml",
"prelaunch_script": "prelaunch.sh",
"env_file": ".env",
"gateway_enabled": True,
"public_logs": True,
"public_sysinfo": True,
"public_tcbinfo": True,
"key_provider": "kms",
"storage_fs": "ext4",
"no_instance_id": False,
"secure_time": False,
"allowed_envs": [],
"key_provider_id": ""
}
@dataclass
class GcpConfig:
"""GCP deployment configuration."""
# Required settings
project: str = ""
zone: str = "us-central1-a"
# Instance settings
instance_name: str = "" # Required, no default
machine_type: str = "c3-standard-4"
# Boot image settings
boot_image: str = "" # GCP image name (auto-derived from app.os_image if empty)
boot_image_tar: str = "" # Explicit tar file path (overrides search)
# Data disk settings
data_image: str = "dstack-data-disk"
data_size: int = 20
# Storage settings
bucket: str = ""
# Network settings
network: str = "default"
subnet: str = ""
private_ip: str = "" # static internal IP to bind (--private-network-ip)
no_public_ip: bool = False # network-isolated: no external IP (--no-address); reach via IAP
# Identity settings
service_account: str = ""
scopes: List[str] = field(default_factory=list)
# Tags and labels
tags: List[str] = field(default_factory=list)
labels: Dict[str, str] = field(default_factory=dict)
# Scheduling: provisioning model. "STANDARD" (default) or "SPOT".
# SPOT instances are required on projects without on-demand
# NVIDIA_H100_GPUS quota (most projects, as of 2026); GCP
# preempts them with ~30s notice and a max ~24h lifetime, but
# they're billed at a steep discount.
provisioning_model: str = "STANDARD"
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'GcpConfig':
known_fields = {f.name for f in cls.__dataclass_fields__.values()}
filtered = {k: v for k, v in data.items() if k in known_fields}
return cls(**filtered)
@classmethod
def get_template(cls) -> Dict[str, Any]:
"""Get default template for new projects."""
return {
"project": "",
"zone": "us-central1-a",
"instance_name": "dstack-vm",
"machine_type": "c3-standard-4",
"boot_image": "",
"boot_image_tar": "",
"data_image": "dstack-data-disk",
"data_size": 20,
"bucket": "",
"network": "default",
"subnet": "",
"private_ip": "",
"no_public_ip": False,
"service_account": "",
"scopes": [],
"tags": [],
"labels": {},
"provisioning_model": "STANDARD"
}
@dataclass
class AwsConfig:
"""AWS EC2 NitroTPM deployment configuration."""
# Required settings
region: str = "us-east-1"
instance_name: str = "" # Name tag / logical name
# Instance settings
instance_type: str = "m6i.large"
ami_id: str = "" # If empty, import local UKI disk.raw as attestable AMI
ami_name: str = "" # Name used when importing AMI
# Local boot image (UKI package with disk.raw + measurement.aws.cbor)
boot_image: str = "" # directory name under image_search_paths
boot_image_tar: str = "" # explicit path override
# Data disk
data_size: int = 20 # GiB for the volume created from the labeled template
data_snapshot: str = "" # optional existing snapshot for data disk
# Shared-disk device names (dstack host-shared + data)
shared_device_name: str = "/dev/sdf"
data_device_name: str = "/dev/sdg"
root_device_name: str = "/dev/sda1"
volume_type: str = "gp3"
# Network
subnet_id: str = ""
security_group_ids: List[str] = field(default_factory=list)
iam_instance_profile: str = "" # name or ARN
# Metadata options. Hop limit 1 keeps IMDSv2 tokens (and any instance-role
# credentials) unreachable from app containers behind the docker bridge;
# dstack itself never talks to IMDS. Set to 2 only if your containers
# legitimately need the instance role.
metadata_hop_limit: int = 1
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'AwsConfig':
known_fields = {f.name for f in cls.__dataclass_fields__.values()}
filtered = {k: v for k, v in data.items() if k in known_fields}
return cls(**filtered)
@classmethod
def get_template(cls) -> Dict[str, Any]:
"""Get default template for new projects."""
return {
"region": "us-east-1",
"instance_name": "dstack-vm",
"instance_type": "m6i.large",
"ami_id": "",
"ami_name": "",
"boot_image": "",
"boot_image_tar": "",
"data_size": 20,
"data_snapshot": "",
"shared_device_name": "/dev/sdf",
"data_device_name": "/dev/sdg",
"root_device_name": "/dev/sda1",
"volume_type": "gp3",
"subnet_id": "",
"security_group_ids": [],
"iam_instance_profile": "",
"metadata_hop_limit": 1,
}
@dataclass
class DeploymentState:
"""Deployment state tracking."""
platform: str = "gcp"
instance_name: str = ""
project: str = ""
zone: str = ""
region: str = ""
instance_id: str = ""
ami_id: str = ""
shared_snapshot: str = ""
data_snapshot: str = "" # Data template snapshot created by dstack-cloud
external_ip: str = ""
internal_ip: str = ""
status: str = "" # RUNNING, STOPPED, TERMINATED, etc.
created_at: str = ""
updated_at: str = ""
boot_image: str = ""
data_image: str = ""
shared_image: str = ""
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'DeploymentState':
known_fields = {f.name for f in cls.__dataclass_fields__.values()}
filtered = {k: v for k, v in data.items() if k in known_fields}
return cls(**filtered)
class CloudDeploymentManager:
"""Manages multi-cloud VM deployments."""
def __init__(self, work_dir: Optional[str] = None):
self.work_dir = Path(work_dir) if work_dir else Path.cwd()
def _load_global_config(self) -> Dict[str, Any]:
"""Load global configuration."""
if os.path.exists(GLOBAL_CONFIG_PATH):
with open(GLOBAL_CONFIG_PATH, 'r') as f:
return json.load(f)
return {}
def _save_global_config(self, config: Dict[str, Any]) -> None:
"""Save global configuration."""
os.makedirs(os.path.dirname(GLOBAL_CONFIG_PATH), exist_ok=True)
with open(GLOBAL_CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=2)
def _get_shared_dir(self) -> Path:
"""Get the shared directory path (at project root)."""
return self.work_dir / "shared"
def _merge_platform_config(self, local: Dict[str, Any], global_section: Dict[str, Any]) -> Dict[str, Any]:
"""Merge global platform defaults with local project overrides."""
merged = {**global_section}
for key, value in local.items():
if value or value is False or value == 0:
merged[key] = value
return merged
def load_gcp_config(self) -> 'GcpConfig':
"""Load GCP configuration from app.gcp_config."""
app = self.load_app_config()
local_gcp = app.gcp_config.to_dict()
global_config = self._load_global_config()
global_gcp = global_config.get("gcp", {})
return GcpConfig.from_dict(self._merge_platform_config(local_gcp, global_gcp))
def save_gcp_config(self, config: GcpConfig) -> None:
"""Save GCP configuration to app.gcp_config."""
app = self.load_app_config()
app.gcp_config = config
self.save_app_config(app)
def load_aws_config(self) -> 'AwsConfig':
"""Load AWS configuration from app.aws_config (+ global aws defaults)."""
app = self.load_app_config()
local_aws = app.aws_config.to_dict()
global_config = self._load_global_config()
global_aws = global_config.get("aws", {})
return AwsConfig.from_dict(self._merge_platform_config(local_aws, global_aws))
def load_app_config(self, required: bool = False) -> App:
"""Load application configuration.
Args:
required: If True, raise error when app.json doesn't exist
"""
app_config_path = self.work_dir / APP_CONFIG_FILE
if not app_config_path.exists():
if required:
raise FileNotFoundError(
f"No {APP_CONFIG_FILE} found in {self.work_dir}. "
f"Run 'dstack-cloud new <name>' to create a project."
)
# Return default config if file doesn't exist
return App()
with open(app_config_path, 'r') as f:
return App.from_dict(json.load(f))
def save_app_config(self, app: App) -> None:
"""Save application configuration."""
app_config_path = self.work_dir / APP_CONFIG_FILE
with open(app_config_path, 'w') as f:
json.dump(app.to_dict(), f, indent=2)
def _generate_app_compose(self, app: App, env_names: Optional[List[str]] = None) -> Dict[str, Any]:
"""Generate app-compose.json content from App configuration."""
# Read docker-compose.yaml content
docker_compose_path = self.work_dir / app.docker_compose_file
if not docker_compose_path.exists():
docker_compose_content = ""
else:
with open(docker_compose_path, 'r') as f:
docker_compose_content = f.read()
# Read prelaunch script content
prelaunch_path = self.work_dir / app.prelaunch_script
if not prelaunch_path.exists():
prelaunch_content = ""
else:
with open(prelaunch_path, 'r') as f:
prelaunch_content = f.read()
# Merge app.allowed_envs with env_names from .env file
allowed_envs = list(app.allowed_envs) if app.allowed_envs else []
if env_names:
allowed_envs.extend(env_names)
# Remove duplicates
allowed_envs = list(set(allowed_envs))
return {
"manifest_version": 2,
"name": app.name,
"runner": "docker-compose",
"docker_compose_file": docker_compose_content,
"gateway_enabled": app.gateway_enabled,
"public_logs": app.public_logs,
"public_sysinfo": app.public_sysinfo,
"public_tcbinfo": app.public_tcbinfo,
"key_provider_id": app.key_provider_id,
"allowed_envs": allowed_envs,
"no_instance_id": app.no_instance_id,
"secure_time": app.secure_time,
"key_provider": app.key_provider,
"storage_fs": app.storage_fs,
"pre_launch_script": prelaunch_content
}
def _emit_app_compose(self, app: App, shared_dir: Path,
env_names: Optional[List[str]] = None) -> None:
"""Write shared/app-compose.json.
If app.app_compose_file is set, ship that file's EXACT bytes (verbatim):
the measured compose-hash is sha256 of the bytes on the shared disk, so
re-serializing would change the hash and break an externally-built
compose. Verbatim mode intentionally bypasses the docker-compose /
allowed-envs generation — the supplied compose is the source of truth.
Otherwise, generate from the App config as before.
"""
app_compose_path = shared_dir / "app-compose.json"
if app.app_compose_file:
src = self.work_dir / app.app_compose_file
if not src.exists():
raise FileNotFoundError(f"app_compose_file not found: {src}")
# raw byte copy — do NOT json.load/dump (would change hashed bytes)
with open(src, 'rb') as fsrc, open(app_compose_path, 'wb') as fdst:
fdst.write(fsrc.read())
logger.info(f"Using verbatim app-compose: {src} -> {app_compose_path}")
else:
content = self._generate_app_compose(app, env_names=env_names)
with open(app_compose_path, 'w') as f:
json.dump(content, f, indent=2)
logger.info(f"Generated {app_compose_path}")
def _find_local_image_dir(
self,
global_config: Dict[str, Any],
image_names: List[str],
explicit_image_path: str = "",
) -> Path:
"""Find a local image directory from configured image_search_paths."""
if explicit_image_path:
image_path = Path(os.path.expanduser(explicit_image_path))
image_dir = image_path if image_path.is_dir() else image_path.parent
if image_dir.exists() and image_dir.is_dir():
return image_dir
search_paths = global_config.get("image_search_paths", [])
if not search_paths:
raise FileNotFoundError("No image_search_paths configured in global config")
candidates = [name for name in dict.fromkeys(image_names) if name]
for search_path in search_paths:
search_path = os.path.expanduser(search_path)
if not os.path.isabs(search_path):
search_path = os.path.join(self.work_dir, search_path)
for image_name in candidates:
image_dir = Path(search_path) / image_name
if image_dir.exists() and image_dir.is_dir():
return image_dir
raise FileNotFoundError(
"Could not find local image directory for "
f"{', '.join(candidates)} in image_search_paths"
)
def _generate_sys_config(self, global_config: Dict[str, Any], app: App) -> Dict[str, Any]:
"""Generate .sys-config.json content for the app's target platform."""
services = global_config.get("services", {})
kms_urls = services.get("kms_urls") or ["https://kms.tdxlab.dstack.org:12001"]
gateway_urls = services.get("gateway_urls") or ["https://gateway.tdxlab.dstack.org:12002"]
pccs_url = services.get("pccs_url", "")
nvidia_attestation_proxy_url = services.get("nvidia_attestation_proxy_url")
platform = (app.platform or "gcp").lower()
if platform == "gcp":
platform_config = self.load_gcp_config()
elif platform == "aws":
platform_config = self.load_aws_config()
else:
raise ValueError(f"unsupported platform: {platform!r} (expected 'gcp' or 'aws')")
image_dir = self._find_local_image_dir(
global_config,
[platform_config.boot_image, app.os_image],
platform_config.boot_image_tar,
)
digest_file = image_dir / "digest.txt"
checksum_file = image_dir / "sha256sum.txt"
measurement_name = f"measurement.{platform}.cbor"
measurement_file = image_dir / measurement_name
for required in (digest_file, checksum_file, measurement_file):
if not required.exists():
message = f"required {platform.upper()} image file not found: {required}"
if platform == "aws":
message += (
". Use a release UKI package built by os/image/assemble.sh "
"(measurement.aws.cbor is fixed at assemble time into "
"os_image_hash; prepare does not recompute it)."
)
raise FileNotFoundError(message)
os_image_hash = digest_file.read_text().strip()
checksum_bytes = checksum_file.read_bytes()
measurement_bytes = measurement_file.read_bytes()
if platform == "aws":
# Sanity: digest.txt must equal sha256(sha256sum.txt)
actual = hashlib.sha256(checksum_bytes).hexdigest()
if os_image_hash != actual:
raise ValueError(
f"digest.txt ({os_image_hash}) does not match sha256(sha256sum.txt) ({actual})"
)
# Sanity: measurement.aws.cbor must be committed by sha256sum.txt
meas_hash = hashlib.sha256(measurement_bytes).hexdigest()
checksum_text = checksum_bytes.decode("utf-8", errors="replace")
committed = any(
len(parts) >= 2
and parts[0] == meas_hash
and parts[1].lstrip("*") == measurement_name
for parts in (line.split() for line in checksum_text.splitlines())
)
if not committed:
raise ValueError(
"measurement.aws.cbor is not committed by sha256sum.txt; "
"rebuild the image with assemble.sh"
)
logger.info(f"read fixed AWS os_image_hash from {digest_file} (assemble-time)")
else:
logger.info(f"read unified OS image hash from {digest_file}")
vm_config = {
"spec_version": 2,
"os_image_hash": os_image_hash,
f"{platform}_measurement": {
"checksum_file": base64.b64encode(checksum_bytes).decode("ascii"),
"measurement": base64.b64encode(measurement_bytes).decode("ascii"),
},
}
sys_config = {
"kms_urls": kms_urls,
"gateway_urls": gateway_urls,
"pccs_url": pccs_url,
"vm_config": json.dumps(vm_config),
}
if nvidia_attestation_proxy_url:
sys_config["nvidia_attestation_proxy_url"] = nvidia_attestation_proxy_url
return sys_config
def load_state(self) -> Optional[DeploymentState]:
"""Load deployment state."""
state_path = self.work_dir / STATE_FILE
if not state_path.exists():
return None
with open(state_path, 'r') as f:
return DeploymentState.from_dict(json.load(f))
def save_state(self, state: DeploymentState) -> None:
"""Save deployment state."""
state_path = self.work_dir / STATE_FILE
state.updated_at = datetime.now().isoformat()
with open(state_path, 'w') as f:
json.dump(state.to_dict(), f, indent=2)
def _run_gcloud(self, args: List[str], capture: bool = True,
check: bool = True) -> subprocess.CompletedProcess:
"""Run a gcloud command."""
cmd = ["gcloud"] + args
logger.debug(f"Running: {' '.join(cmd)}")
if capture:
result = subprocess.run(cmd, capture_output=True, text=True)
else:
result = subprocess.run(cmd)
if check and result.returncode != 0:
error_msg = result.stderr if capture else "Command failed"
raise RuntimeError(f"gcloud command failed: {error_msg}")
return result
def _run_gsutil(self, args: List[str], check: bool = True) -> subprocess.CompletedProcess:
"""Run a gsutil command."""
cmd = ["gsutil"] + args
logger.debug(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if check and result.returncode != 0:
raise RuntimeError(f"gsutil command failed: {result.stderr}")
return result
def _ensure_data_disk_image(self, config: GcpConfig) -> str:
"""Ensure the data disk image exists, creating it if necessary.
Creates a minimal disk image with GPT partition table and a partition
labeled 'dstack-data' so the guest can discover it.
Returns the image name to use.
"""
image_name = config.data_image
# Check if image already exists
result = self._run_gcloud([
"compute", "images", "describe", image_name,
f"--project={config.project}"
], check=False)
if result.returncode == 0:
logger.debug(f"Data disk image '{image_name}' already exists")
return image_name
logger.info(f"Data disk image '{image_name}' not found, creating...")
# Create a minimal raw disk image with GPT partition table
with tempfile.TemporaryDirectory() as tmpdir:
self._build_data_raw_disk(Path(tmpdir))
# Compress to tar.gz for upload
tar_file = os.path.join(tmpdir, "disk.tar.gz")
result = subprocess.run(
["tar", "-czf", tar_file, "-C", tmpdir, "disk.raw"],
capture_output=True, text=True
)
if result.returncode != 0:
raise RuntimeError(f"Failed to create tar.gz: {result.stderr}")
# Upload to GCS
gcs_path = f"{config.bucket}/{image_name}.tar.gz"
logger.info(f"Uploading data disk image to {gcs_path}...")
self._run_gsutil(["cp", tar_file, gcs_path])
# Create GCP image from the uploaded file
logger.info(f"Creating GCP image '{image_name}'...")
self._run_gcloud([
"compute", "images", "create", image_name,
f"--project={config.project}",
f"--source-uri={gcs_path}",
"--guest-os-features=GVNIC"
])
# Clean up GCS file
self._run_gsutil(["rm", gcs_path], check=False)
logger.info(f"Created data disk image '{image_name}'")
return image_name
def new(
self,
name: str,
os_image: Optional[str] = None,
app_id: Optional[str] = None,
gateway_enabled: Optional[bool] = None,
key_provider: Optional[str] = None,
storage_fs: Optional[str] = None,
secure_time: Optional[bool] = None,
no_instance_id: Optional[bool] = None,
platform: Optional[str] = None,
project: Optional[str] = None,
zone: Optional[str] = None,
region: Optional[str] = None,
instance_name: Optional[str] = None,
machine_type: Optional[str] = None,
data_size: Optional[int] = None
) -> None:
"""Create a new project directory with template configuration."""
project_dir = Path.cwd() / name
if project_dir.exists():
raise FileExistsError(f"Directory '{name}' already exists.")
# Create project directory
project_dir.mkdir()
# Update work_dir to the new project directory
self.work_dir = project_dir
if not instance_name:
instance_name = f"dstack-{name}"
# Initialize the project (non-interactive by default for new command)
self._init_project(
force=False,
interactive=False,
app_name=name,
os_image=os_image,
app_id=app_id,
gateway_enabled=gateway_enabled,
key_provider=key_provider,
storage_fs=storage_fs,
secure_time=secure_time,
no_instance_id=no_instance_id,
platform=platform,
project=project,
zone=zone,
region=region,
instance_name=instance_name,
machine_type=machine_type,
data_size=data_size
)
logger.info(f"Created new project: {name}")
logger.info(f"Project directory: {project_dir}")
logger.info("")
def _init_project(
self,
force: bool = False,
interactive: bool = True,
app_name: Optional[str] = None,
os_image: Optional[str] = None,
app_id: Optional[str] = None,
gateway_enabled: Optional[bool] = None,
key_provider: Optional[str] = None,
storage_fs: Optional[str] = None,
secure_time: Optional[bool] = None,
no_instance_id: Optional[bool] = None,
platform: Optional[str] = None,
project: Optional[str] = None,
zone: Optional[str] = None,
region: Optional[str] = None,
instance_name: Optional[str] = None,
machine_type: Optional[str] = None,
data_size: Optional[int] = None
) -> None:
"""Initialize project configuration."""
# Interactive prompts for required fields (only if not provided via CLI)
instance_name_cli = instance_name
if interactive:
print(f"\n=== dstack-cloud Project Initialization ===\n")
# Prompt for app name if not provided
if app_name is None:
while True:
app_name = input("App name [myapp]: ").strip()
if not app_name:
app_name = "myapp"
if app_name:
break
print("App name cannot be empty.")
# Prompt for instance name (required)
if not instance_name_cli:
while True:
instance_name = input("GCP instance name: ").strip()
if instance_name:
break
print("Instance name is required.")
else:
instance_name = instance_name_cli
print("") # Empty line for readability
else:
# Non-interactive mode: use CLI provided values or fail
if app_name is None:
app_name = "myapp"
if not instance_name_cli:
raise ValueError("instance_name is required. Use --instance-name to specify it.")
instance_name = instance_name_cli
# Create shared directory at project root (for system-generated files)
shared_dir = self.work_dir / "shared"
shared_dir.mkdir(parents=True, exist_ok=True)
# Generate app config template with embedded platform configs
app_template = App.get_template()
# Apply CLI-provided values (only if specified)
if app_name:
app_template["name"] = app_name
if os_image:
app_template["os_image"] = os_image
if platform:
platform = platform.lower()
if platform not in ("gcp", "aws"):
raise ValueError("platform must be 'gcp' or 'aws'")
app_template["platform"] = platform
if app_id:
# Validate app_id format (40 hex chars)
if len(app_id) != 40 or not all(c in '0123456789abcdef' for c in app_id.lower()):
raise ValueError("app_id must be exactly 40 hexadecimal characters")
app_template["app_id"] = app_id
if gateway_enabled is not None:
app_template["gateway_enabled"] = gateway_enabled
if key_provider is not None:
app_template["key_provider"] = key_provider
# Auto-disable gateway when key_provider is not "kms"
if app_template["key_provider"] != "kms":
app_template["gateway_enabled"] = False
# Also set no_instance_id=True when KMS is not available
app_template["no_instance_id"] = True
# Remove env_file since .env is only supported in KMS mode
app_template.pop("env_file", None)
if storage_fs is not None:
app_template["storage_fs"] = storage_fs
if secure_time is not None:
app_template["secure_time"] = secure_time
if no_instance_id is not None:
app_template["no_instance_id"] = no_instance_id
# Apply GCP config values
if instance_name:
app_template["gcp_config"]["instance_name"] = instance_name
app_template["aws_config"]["instance_name"] = instance_name
if project:
app_template["gcp_config"]["project"] = project
if zone:
app_template["gcp_config"]["zone"] = zone
if region:
app_template["aws_config"]["region"] = region
if machine_type:
app_template["gcp_config"]["machine_type"] = machine_type
# Only map machine_type to AWS instance_type when platform is aws
if app_template.get("platform") == "aws":
app_template["aws_config"]["instance_type"] = machine_type
if data_size is not None:
app_template["gcp_config"]["data_size"] = data_size
app_template["aws_config"]["data_size"] = data_size
# Create app.json at project root (not in .dstack/)
app_config_path = self.work_dir / APP_CONFIG_FILE
if not app_config_path.exists() or force:
with open(app_config_path, 'w') as f:
json.dump(app_template, f, indent=2)
# Note: app-compose.json and .sys-config.json will be generated during deploy
# Create docker-compose.yaml template at project root
docker_compose = self.work_dir / "docker-compose.yaml"
if not docker_compose.exists() or force:
with open(docker_compose, 'w') as f:
f.write("services:\n")
f.write(" nginx:\n")
f.write(" image: nginx:alpine\n")
f.write(" ports:\n")
f.write(" - \"80:80\"\n")
f.write(" restart: unless-stopped\n")
# Create prelaunch.sh template at project root
prelaunch = self.work_dir / "prelaunch.sh"
if not prelaunch.exists() or force:
with open(prelaunch, 'w') as f:
f.write("#!/bin/sh\n")
f.write("# Prelaunch script - runs before starting containers\n")
os.chmod(prelaunch, 0o755)
# Create .env template at project root (only for KMS mode)
if app_template["key_provider"] == "kms":
env_file = self.work_dir / ".env"
if not env_file.exists() or force:
with open(env_file, 'w') as f:
f.write("# Environment variables\n")
# Create user-config template at project root
user_config = self.work_dir / ".user-config"
if not user_config.exists() or force:
with open(user_config, 'w') as f:
json.dump({}, f, indent=2)
logger.info(f"Initialized project in {self.work_dir}")
logger.info("")
if interactive:
logger.info("Configuration:")
logger.info(f" App name: {app_name}")
logger.info(f" Instance name: {instance_name}")
logger.info("")
logger.info("Created files:")
logger.info(f" {app_config_path.name} - Application configuration (platform configs embedded)")
logger.info(f" shared/ - System-generated files")
logger.info(f" {docker_compose.name} - Docker compose file")
logger.info(f" {prelaunch.name} - Prelaunch script")
if app_template["key_provider"] == "kms":
logger.info(f" .env - Environment variables")
logger.info(f" .user-config - User configuration")
logger.info("")
logger.info("Edit the configuration files to customize your deployment.")
def config_edit(self) -> None:
"""Edit global configuration with $EDITOR."""
# Create global config if it doesn't exist
global_config_dir = os.path.dirname(GLOBAL_CONFIG_PATH)