-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvmm-cli.py
More file actions
executable file
·1639 lines (1407 loc) · 62 KB
/
vmm-cli.py
File metadata and controls
executable file
·1639 lines (1407 loc) · 62 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
import os
import sys
import json
import argparse
import hashlib
import re
import socket
import http.client
import urllib.parse
import ssl
import base64
from typing import Optional, Dict, List, Tuple, Union, BinaryIO, Any
# Optional cryptography imports - only needed for encrypted environment variables
try:
from cryptography.hazmat.primitives.asymmetric import x25519
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import serialization
from eth_keys import keys
from eth_utils import keccak
CRYPTO_AVAILABLE = True
except ImportError:
CRYPTO_AVAILABLE = False
# Default config file locations
DEFAULT_CONFIG_PATH = os.path.expanduser("~/.dstack-vmm/config.json")
DEFAULT_KMS_WHITELIST_PATH = os.path.expanduser(
"~/.dstack-vmm/kms-whitelist.json")
def load_config() -> Dict[str, Any]:
"""
Load configuration from the default config file.
Returns:
Dictionary with configuration values (url, auth_user, auth_password)
"""
if not os.path.exists(DEFAULT_CONFIG_PATH):
return {}
try:
with open(DEFAULT_CONFIG_PATH, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
return {}
def encrypt_env(envs, hex_public_key: str) -> str:
"""
Encrypts environment variables using a one-time X25519 key exchange and AES-GCM.
This function does the following:
1. Converts the given environment variables to JSON bytes.
2. Removes a leading "0x" from the provided public key (if present) and converts it to bytes.
3. Generates an ephemeral X25519 key pair.
4. Computes a shared secret using this ephemeral private key and the remote public key.
5. Uses the shared key directly as the 32-byte key for AES-GCM.
6. Encrypts the JSON string with AES-GCM using a randomly generated IV.
7. Concatenates the ephemeral public key, IV, and ciphertext and returns it as a hex string.
Args:
envs: The environment variables to encrypt. This can be any JSON-serializable data structure.
hex_public_key: The remote encryption public key in hexadecimal format.
Returns:
A hexadecimal string that is the concatenation of:
(ephemeral public key || IV || ciphertext).
"""
if not CRYPTO_AVAILABLE:
raise ImportError(
"Cryptography libraries not available. Please install them with:\n"
"pip install cryptography eth-keys eth-utils"
)
# Serialize the environment variables to JSON and encode to bytes.
envs_json = json.dumps({"env": envs}).encode("utf-8")
# Remove the "0x" prefix if present.
if hex_public_key.startswith("0x"):
hex_public_key = hex_public_key[2:]
# Convert the hexadecimal public key to bytes.
remote_pubkey_bytes = bytes.fromhex(hex_public_key)
# Generate an ephemeral X25519 key pair.
ephemeral_private_key = x25519.X25519PrivateKey.generate()
ephemeral_public_key = ephemeral_private_key.public_key()
# Compute the shared secret using X25519.
peer_public_key = x25519.X25519PublicKey.from_public_bytes(
remote_pubkey_bytes)
shared = ephemeral_private_key.exchange(peer_public_key)
# Use the shared secret as a key for AES-GCM encryption (AES-256 needs 32 bytes).
aesgcm = AESGCM(shared)
iv = os.urandom(12) # 12-byte nonce (IV) for AES-GCM.
ciphertext = aesgcm.encrypt(iv, envs_json, None)
# Serialize the ephemeral public key to raw bytes.
ephemeral_public_bytes = ephemeral_public_key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw
)
# Combine ephemeral public key, IV, and ciphertext.
result = ephemeral_public_bytes + iv + ciphertext
# Return the result as a hexadecimal string.
return result.hex()
def parse_port_mapping(port_str: str) -> Dict:
"""Parse a port mapping string into a dictionary"""
parts = port_str.split(':')
if len(parts) == 3:
return {
"protocol": parts[0],
"host_address": "127.0.0.1",
"host_port": int(parts[1]),
"vm_port": int(parts[2])
}
elif len(parts) == 4:
return {
"protocol": parts[0],
"host_address": parts[1],
"host_port": int(parts[2]),
"vm_port": int(parts[3])
}
else:
raise argparse.ArgumentTypeError(
f"Invalid port mapping format: {port_str}")
def read_utf8(filepath: str) -> str:
with open(filepath, 'rb') as f:
return f.read().decode('utf-8')
class UnixSocketHTTPConnection(http.client.HTTPConnection):
"""HTTPConnection that connects to a Unix domain socket."""
def __init__(self, socket_path, timeout=None):
super().__init__('localhost', timeout=timeout)
self.socket_path = socket_path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if self.timeout:
sock.settimeout(self.timeout)
sock.connect(self.socket_path)
self.sock = sock
class VmmClient:
"""A unified HTTP client that supports both regular HTTP and Unix Domain Sockets."""
def __init__(self, base_url: str, auth_user: Optional[str] = None, auth_password: Optional[str] = None):
self.base_url = base_url.rstrip('/')
self.use_uds = self.base_url.startswith('unix:')
self.auth_user = auth_user
self.auth_password = auth_password
if self.use_uds:
self.uds_path = self.base_url[5:] # Remove 'unix:' prefix
else:
# Parse the base URL for regular HTTP connections
self.parsed_url = urllib.parse.urlparse(self.base_url)
self.host = self.parsed_url.netloc
self.is_https = self.parsed_url.scheme == 'https'
def request(self, method: str, path: str, headers: Dict[str, str] = None,
body: Any = None, stream: bool = False) -> Tuple[int, Union[Dict, str, BinaryIO]]:
"""
Make an HTTP request to the server.
Args:
method: HTTP method (GET, POST, etc.)
path: URL path
headers: HTTP headers
body: Request body (will be JSON serialized if a dict)
stream: If True, return a file-like object for reading the response
Returns:
Tuple of (status_code, response_data)
"""
if headers is None:
headers = {}
# Add Basic Authentication header if credentials are provided
if self.auth_user and self.auth_password:
credentials = f"{self.auth_user}:{self.auth_password}"
encoded_credentials = base64.b64encode(
credentials.encode('utf-8')).decode('ascii')
headers['Authorization'] = f'Basic {encoded_credentials}'
# Prepare the body
if isinstance(body, dict):
body = json.dumps(body).encode('utf-8')
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
# Create the appropriate connection
if self.use_uds:
conn = UnixSocketHTTPConnection(self.uds_path)
else:
if self.is_https:
# TODO: we should verify TLS cert.
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection(self.host, context=context)
else:
conn = http.client.HTTPConnection(self.host)
try:
# Make the request
conn.request(method, path, body=body, headers=headers)
response = conn.getresponse()
status = response.status
# Handle the response based on the stream parameter
if stream:
return status, response
else:
data = response.read()
# Try to parse as JSON if it looks like JSON
content_type = response.getheader('Content-Type', '')
if 'application/json' in content_type or data.startswith(b'{') or data.startswith(b'['):
try:
return status, json.loads(data.decode('utf-8'))
except json.JSONDecodeError:
pass
# Return as string if not JSON
return status, data.decode('utf-8')
except Exception as e:
if not stream:
conn.close()
raise e
# Note: when stream=True, the caller must close the connection when done
class VmmCLI:
def __init__(self, base_url: str, auth_user: Optional[str] = None, auth_password: Optional[str] = None):
self.base_url = base_url.rstrip('/')
self.headers = {
'Content-Type': 'application/json'
}
self.client = VmmClient(base_url, auth_user, auth_password)
def rpc_call(self, method: str, params: Optional[Dict] = None) -> Dict:
"""Make an RPC call to the dstack-vmm API"""
path = f"/prpc/{method}?json"
status, response = self.client.request(
'POST', path, headers=self.headers, body=params or {})
if status != 200:
if isinstance(response, str):
error_msg = response
else:
error_msg = str(response)
raise Exception(f"API call failed: {error_msg}")
return response
def list_vms(self, verbose: bool = False, json_output: bool = False) -> None:
"""List all VMs and their status"""
response = self.rpc_call('Status')
vms = response['vms']
if json_output:
# Return raw JSON data for automation/testing
print(json.dumps(vms, indent=2))
return
if not vms:
print("No VMs found")
return
headers = ['VM ID', 'App ID', 'Name', 'Status', 'Uptime']
if verbose:
headers.extend(['Instance ID', 'vCPU', 'Memory', 'Disk', 'Image', 'GPUs'])
rows = []
for vm in vms:
row = [
vm['id'],
vm['app_id'],
vm['name'],
vm['status'],
vm.get('uptime', '-')
]
if verbose:
config = vm.get('configuration', {})
gpu_info = self._format_gpu_info(config.get('gpus'))
row.extend([
vm.get('instance_id', '-') or '-',
config.get('vcpu', '-'),
f"{config.get('memory', '-')}MB",
f"{config.get('disk_size', '-')}GB",
config.get('image', '-'),
gpu_info
])
rows.append(row)
print(format_table(rows, headers))
def _format_gpu_info(self, gpu_config):
"""Format GPU configuration for display"""
if not gpu_config:
return '-'
attach_mode = gpu_config.get('attach_mode', '')
gpus = gpu_config.get('gpus', [])
if attach_mode == 'all':
return 'All GPUs'
elif attach_mode == 'listed' and gpus:
gpu_slots = [gpu.get('slot', 'Unknown') for gpu in gpus]
return ', '.join(gpu_slots)
else:
return '-'
def start_vm(self, vm_id: str) -> None:
"""Start a VM"""
self.rpc_call('StartVm', {'id': vm_id})
print(f"Started VM {vm_id}")
def stop_vm(self, vm_id: str, force: bool = False) -> None:
"""Stop a VM"""
if force:
self.rpc_call('StopVm', {'id': vm_id})
print(f"Forcefully stopped VM {vm_id}")
else:
self.rpc_call('ShutdownVm', {'id': vm_id})
print(f"Gracefully shutting down VM {vm_id}")
def remove_vm(self, vm_id: str) -> None:
"""Remove a VM"""
self.rpc_call('RemoveVm', {'id': vm_id})
print(f"Removed VM {vm_id}")
def resize_vm(
self,
vm_id: str,
vcpu: Optional[int] = None,
memory: Optional[int] = None,
disk_size: Optional[int] = None,
image: Optional[str] = None,
) -> None:
"""Resize a VM"""
params = {"id": vm_id}
if vcpu is not None:
params["vcpu"] = vcpu
if memory is not None:
params["memory"] = memory
if disk_size is not None:
params["disk_size"] = disk_size
if image is not None:
params["image"] = image
if len(params) == 1:
raise Exception(
"at least one parameter must be specified for resize: --vcpu, --memory, --disk, or --image"
)
self.rpc_call("ResizeVm", params)
print(f"Resized VM {vm_id}")
def show_logs(self, vm_id: str, lines: int = 20, follow: bool = False) -> None:
"""Show VM logs"""
path = f"/logs?id={vm_id}&follow={str(follow).lower()}&ansi=false&lines={lines}"
status, response = self.client.request(
'GET', path, headers=self.headers, stream=follow)
if status != 200:
if isinstance(response, str):
error_msg = response
else:
error_msg = str(response)
print(f"Failed to get logs: {error_msg}")
return
if follow:
try:
# For streamed responses, response is a file-like object
while True:
line = response.readline()
if not line:
break
print(line.decode('utf-8').rstrip())
except KeyboardInterrupt:
# Allow clean exit with Ctrl+C
return
finally:
# Close the connection when done
response.close()
else:
# For non-streamed responses, response is already the data
print(response)
def list_images(self, json_output: bool = False) -> None:
"""Get list of available images"""
response = self.rpc_call('ListImages')
images = response['images']
if json_output:
# Return raw JSON data for automation/testing
print(json.dumps(images, indent=2))
return
if not images:
print("No images found")
return
headers = ['Name', 'Version']
rows = [[img['name'], img.get('version', '-')] for img in images]
print(format_table(rows, headers))
def get_app_env_encrypt_pub_key(self, app_id: str, kms_url: Optional[str] = None) -> Dict:
"""Get the encryption public key for the specified application ID"""
if kms_url:
client = VmmClient(kms_url)
path = f"/prpc/GetAppEnvEncryptPubKey?json"
status, response = client.request(
'POST', path, headers={
'Content-Type': 'application/json'
}, body={'app_id': app_id})
print(f"Getting encryption public key for {app_id} from {kms_url}")
else:
response = self.rpc_call(
'GetAppEnvEncryptPubKey', {'app_id': app_id})
# Verify the signature if available
if 'signature' not in response and 'signature_v1' not in response:
if not self.confirm_untrusted_signer("none"):
raise Exception("Aborted due to invalid signature")
return response['public_key']
public_key = bytes.fromhex(response['public_key'])
# Prefer signature_v1 (with timestamp) if available
signer_pubkey = None
if 'signature_v1' in response and 'timestamp' in response:
signature_v1 = bytes.fromhex(response['signature_v1'])
timestamp = response['timestamp']
signer_pubkey = verify_signature_v1(public_key, signature_v1, app_id, timestamp)
if signer_pubkey:
print(f"Verified signature_v1 (with timestamp) from: {signer_pubkey}")
# Fall back to legacy signature if signature_v1 verification failed or not available
if not signer_pubkey and 'signature' in response:
print("WARNING: Using legacy signature without timestamp protection. "
"Consider upgrading your KMS to support signature_v1.", file=sys.stderr)
signature = bytes.fromhex(response['signature'])
signer_pubkey = verify_signature(public_key, signature, app_id)
if signer_pubkey:
print(f"Verified legacy signature from: {signer_pubkey}")
if signer_pubkey:
whitelist = load_whitelist()
if whitelist and signer_pubkey not in whitelist:
print(
f"WARNING: Signer {signer_pubkey} is not in the trusted whitelist!")
if not self.confirm_untrusted_signer(signer_pubkey):
raise Exception("Aborted due to untrusted signer")
else:
print("WARNING: Could not verify signature!")
if not self.confirm_untrusted_signer("unknown"):
raise Exception("Aborted due to invalid signature")
return response['public_key']
def confirm_untrusted_signer(self, signer: str) -> bool:
"""Ask user to confirm using an untrusted signer"""
response = input(f"Continue with untrusted signer {signer}? (y/N): ")
return response.lower() in ('y', 'yes')
def manage_kms_whitelist(self, action: str, pubkey: str = None) -> None:
"""Manage the whitelist of trusted signers"""
whitelist = load_whitelist()
if action == 'list':
if not whitelist:
print("Whitelist is empty")
else:
print("Trusted signers:")
for addr in whitelist:
print(f" {addr}")
return
# Normalize pubkey format - trim 0x prefix if present
if pubkey and pubkey.startswith('0x'):
pubkey = pubkey[2:]
# Convert to bytes for validation
try:
pubkey = bytes.fromhex(pubkey)
except ValueError:
raise Exception(f"Invalid public key format: {pubkey}")
if len(pubkey) != 33:
raise Exception(f"Invalid public key length: {len(pubkey)}")
pubkey = pubkey.hex()
if action == 'add':
if pubkey in whitelist:
print(f"Public key {pubkey} is already in the whitelist")
else:
whitelist.append(pubkey)
save_whitelist(whitelist)
print(f"Added {pubkey} to the whitelist")
elif action == 'remove':
if pubkey not in whitelist:
print(f"Public key {pubkey} is not in the whitelist")
else:
whitelist.remove(pubkey)
save_whitelist(whitelist)
print(f"Removed {pubkey} from the whitelist")
else:
raise Exception(f"Unknown action: {action}")
def calc_app_id(self, compose_file: str) -> str:
"""Calculate the application ID from the compose file"""
compose_hash = hashlib.sha256(compose_file.encode()).hexdigest()
return compose_hash[:40]
def create_app_compose(self, args) -> None:
"""Create a new app compose file"""
envs = parse_env_file(args.env_file) or {}
# Validate: --env-file requires --kms
if envs and not args.kms:
raise Exception("--env-file requires --kms to enable KMS for environment variable decryption")
app_compose = {
"manifest_version": 2,
"name": args.name,
"runner": "docker-compose",
"docker_compose_file": open(args.docker_compose, 'rb').read().decode('utf-8'),
"kms_enabled": args.kms,
"gateway_enabled": args.gateway,
"local_key_provider_enabled": args.local_key_provider,
"key_provider_id": args.key_provider_id or "",
"public_logs": args.public_logs,
"public_sysinfo": args.public_sysinfo,
"allowed_envs": [k for k in envs.keys()],
"no_instance_id": args.no_instance_id,
"secure_time": args.secure_time,
}
if args.key_provider:
app_compose["key_provider"] = args.key_provider
if args.prelaunch_script:
app_compose["pre_launch_script"] = open(
args.prelaunch_script, 'rb').read().decode('utf-8')
if args.swap is not None:
swap_bytes = max(0, int(round(args.swap)) * 1024 * 1024)
if swap_bytes > 0:
app_compose["swap_size"] = swap_bytes
else:
app_compose.pop("swap_size", None)
compose_file = json.dumps(
app_compose, indent=4, ensure_ascii=False).encode('utf-8')
compose_hash = hashlib.sha256(compose_file).hexdigest()
with open(args.output, 'wb') as f:
f.write(compose_file)
print(f"App compose file created at: {args.output}")
print(f"Compose hash: {compose_hash}")
def create_vm(self, args) -> None:
"""Create a new VM"""
# Read and validate compose file
if not os.path.exists(args.compose):
raise Exception(f"Compose file not found: {args.compose}")
compose_content = read_utf8(args.compose)
envs = parse_env_file(args.env_file)
# Validate: --env-file requires --kms-url and kms_enabled in compose
if envs:
if not args.kms_url:
raise Exception("--env-file requires --kms-url to encrypt environment variables")
try:
compose_json = json.loads(compose_content)
if not compose_json.get('kms_enabled', False):
raise Exception("--env-file requires kms_enabled=true in the compose file (use --kms when creating compose)")
except json.JSONDecodeError:
pass # Let the server handle invalid JSON
# Read user config file if provided
user_config = ""
if args.user_config:
user_config = read_utf8(args.user_config)
# Create VM request
params = {
"name": args.name,
"image": args.image,
"compose_file": compose_content,
"vcpu": args.vcpu,
"memory": args.memory,
"disk_size": args.disk,
"app_id": args.app_id,
"user_config": user_config,
"ports": [parse_port_mapping(port) for port in args.port or []],
"hugepages": args.hugepages,
"pin_numa": args.pin_numa,
"stopped": args.stopped,
"no_tee": args.no_tee,
}
if args.swap is not None:
swap_bytes = max(0, int(round(args.swap)) * 1024 * 1024)
if swap_bytes > 0:
params["swap_size"] = swap_bytes
if args.ppcie or (args.gpu and "all" in args.gpu):
params["gpus"] = {
"attach_mode": "all"
}
elif args.gpu:
params["gpus"] = {
"attach_mode": "listed",
"gpus": [{"slot": gpu} for gpu in args.gpu or []]
}
if args.kms_url:
params["kms_urls"] = args.kms_url
if args.gateway_url:
params["gateway_urls"] = args.gateway_url
if args.net:
params["networking"] = {"mode": args.net}
app_id = args.app_id or self.calc_app_id(compose_content)
print(f"App ID: {app_id}")
if envs:
encrypt_pubkey = self.get_app_env_encrypt_pub_key(
app_id, args.kms_url[0] if args.kms_url else None)
print(
f"Encrypting environment variables with key: {encrypt_pubkey}")
envs_list = [{"key": k, "value": v} for k, v in envs.items()]
params["encrypted_env"] = encrypt_env(envs_list, encrypt_pubkey)
response = self.rpc_call('CreateVm', params)
print(f"Created VM with ID: {response.get('id')}")
return response.get('id')
def update_vm_env(self, vm_id: str, envs: Dict[str, str], kms_urls: Optional[List[str]] = None) -> None:
"""Update environment variables for a VM"""
# Validate: requires --kms-url
if not kms_urls:
raise Exception("--kms-url is required to encrypt environment variables")
envs = envs or {}
# First get the VM info to retrieve the app_id
vm_info_response = self.rpc_call('GetInfo', {'id': vm_id})
if not vm_info_response.get('found', False) or 'info' not in vm_info_response:
raise Exception(f"VM with ID {vm_id} not found")
app_id = vm_info_response['info']['app_id']
print(f"Retrieved app ID: {app_id}")
vm_configuration = vm_info_response['info'].get('configuration') or {}
compose_file = vm_configuration.get('compose_file')
# Now get the encryption key for the app
encrypt_pubkey = self.get_app_env_encrypt_pub_key(
app_id, kms_urls[0] if kms_urls else None)
print(f"Encrypting environment variables with key: {encrypt_pubkey}")
envs_list = [{"key": k, "value": v} for k, v in envs.items()]
encrypted_env = encrypt_env(envs_list, encrypt_pubkey)
# Use UpdateApp with the VM ID
payload = {'id': vm_id, 'encrypted_env': encrypted_env}
if compose_file:
try:
app_compose = json.loads(compose_file)
except json.JSONDecodeError:
app_compose = {}
compose_changed = False
allowed_envs = list(envs.keys())
if app_compose.get('allowed_envs') != allowed_envs:
app_compose['allowed_envs'] = allowed_envs
compose_changed = True
launch_token_value = envs.get('APP_LAUNCH_TOKEN')
if launch_token_value is not None:
launch_token_hash = hashlib.sha256(
launch_token_value.encode('utf-8')
).hexdigest()
if app_compose.get('launch_token_hash') != launch_token_hash:
app_compose['launch_token_hash'] = launch_token_hash
compose_changed = True
if compose_changed:
payload['compose_file'] = json.dumps(
app_compose, indent=4, ensure_ascii=False)
self.rpc_call('UpgradeApp', payload)
print(f"Environment variables updated for VM {vm_id}")
def update_vm_user_config(self, vm_id: str, user_config: str) -> None:
"""Update user config for a VM"""
self.rpc_call('UpgradeApp', {'id': vm_id,
'user_config': user_config})
print(f"User config updated for VM {vm_id}")
def update_vm_app_compose(self, vm_id: str, app_compose: str) -> None:
"""Update app compose for a VM"""
self.rpc_call('UpgradeApp', {'id': vm_id,
'compose_file': app_compose})
print(f"App compose updated for VM {vm_id}")
def update_vm_ports(self, vm_id: str, ports: List[str]) -> None:
"""Update port mapping for a VM"""
port_mappings = [parse_port_mapping(port) for port in ports]
self.rpc_call(
"UpgradeApp", {"id": vm_id,
"update_ports": True, "ports": port_mappings}
)
print(f"Port mapping updated for VM {vm_id}")
def update_vm(
self,
vm_id: str,
vcpu: Optional[int] = None,
memory: Optional[int] = None,
disk_size: Optional[int] = None,
image: Optional[str] = None,
docker_compose_content: Optional[str] = None,
prelaunch_script: Optional[str] = None,
swap_size: Optional[int] = None,
env_file: Optional[str] = None,
user_config: Optional[str] = None,
ports: Optional[List[str]] = None,
no_ports: bool = False,
gpu_slots: Optional[List[str]] = None,
attach_all: bool = False,
no_gpus: bool = False,
kms_urls: Optional[List[str]] = None,
no_tee: Optional[bool] = None,
) -> None:
"""Update multiple aspects of a VM in one command"""
# Validate: --env-file requires --kms-url
if env_file and not kms_urls:
raise Exception("--env-file requires --kms-url to encrypt environment variables")
updates = []
# handle resize operations (vcpu, memory, disk, image)
resize_params = {}
if vcpu is not None:
resize_params["vcpu"] = vcpu
updates.append(f"vCPU: {vcpu}")
if memory is not None:
resize_params["memory"] = memory
updates.append(f"memory: {memory}MB")
if disk_size is not None:
resize_params["disk_size"] = disk_size
updates.append(f"disk: {disk_size}GB")
if image is not None:
resize_params["image"] = image
updates.append(f"image: {image}")
if resize_params:
resize_params["id"] = vm_id
self.rpc_call("ResizeVm", resize_params)
# handle upgrade operations (compose, env, user_config, ports, gpu)
upgrade_params = {"id": vm_id}
# handle compose file updates (docker-compose, prelaunch script, swap)
needs_compose_update = docker_compose_content or prelaunch_script is not None or swap_size is not None
vm_info_response = None
if needs_compose_update or env_file:
vm_info_response = self.rpc_call('GetInfo', {'id': vm_id})
if not vm_info_response.get('found', False) or 'info' not in vm_info_response:
raise Exception(f"VM with ID {vm_id} not found")
if needs_compose_update:
vm_configuration = vm_info_response['info'].get('configuration') or {}
compose_file_content = vm_configuration.get('compose_file')
try:
app_compose = json.loads(compose_file_content) if compose_file_content else {}
except json.JSONDecodeError:
app_compose = {}
if docker_compose_content:
app_compose['docker_compose_file'] = docker_compose_content
updates.append("docker compose")
if prelaunch_script is not None:
script_stripped = prelaunch_script.strip()
if script_stripped:
app_compose['pre_launch_script'] = script_stripped
updates.append("prelaunch script")
elif 'pre_launch_script' in app_compose:
del app_compose['pre_launch_script']
updates.append("prelaunch script (removed)")
if swap_size is not None:
swap_bytes = max(0, int(round(swap_size)) * 1024 * 1024)
if swap_bytes > 0:
app_compose['swap_size'] = swap_bytes
updates.append(f"swap: {swap_size}MB")
elif 'swap_size' in app_compose:
del app_compose['swap_size']
updates.append("swap (disabled)")
upgrade_params['compose_file'] = json.dumps(app_compose, indent=4, ensure_ascii=False)
if env_file:
envs = parse_env_file(env_file)
if envs:
app_id = vm_info_response['info']['app_id']
vm_configuration = vm_info_response['info'].get('configuration') or {}
compose_file_content = vm_configuration.get('compose_file')
encrypt_pubkey = self.get_app_env_encrypt_pub_key(
app_id, kms_urls[0] if kms_urls else None)
envs_list = [{"key": k, "value": v} for k, v in envs.items()]
upgrade_params["encrypted_env"] = encrypt_env(envs_list, encrypt_pubkey)
updates.append("environment variables")
# update allowed_envs in compose file if needed
if compose_file_content:
try:
app_compose = json.loads(compose_file_content)
except json.JSONDecodeError:
app_compose = {}
compose_changed = False
allowed_envs = list(envs.keys())
if app_compose.get('allowed_envs') != allowed_envs:
app_compose['allowed_envs'] = allowed_envs
compose_changed = True
launch_token_value = envs.get('APP_LAUNCH_TOKEN')
if launch_token_value is not None:
launch_token_hash = hashlib.sha256(
launch_token_value.encode('utf-8')
).hexdigest()
if app_compose.get('launch_token_hash') != launch_token_hash:
app_compose['launch_token_hash'] = launch_token_hash
compose_changed = True
if compose_changed:
upgrade_params['compose_file'] = json.dumps(
app_compose, indent=4, ensure_ascii=False)
if user_config:
upgrade_params["user_config"] = user_config
updates.append("user config")
# handle port updates - only update if --port or --no-ports is specified
if no_ports or ports is not None:
if no_ports:
port_mappings = []
updates.append("port mappings (removed)")
elif ports:
port_mappings = [parse_port_mapping(port) for port in ports]
updates.append("port mappings")
else:
# ports is an empty list - shouldn't happen with mutually exclusive group
port_mappings = []
updates.append("port mappings (none)")
upgrade_params["update_ports"] = True
upgrade_params["ports"] = port_mappings
# handle GPU updates - only update if one of the GPU flags is set
gpu_all = gpu_slots and "all" in gpu_slots
if attach_all or gpu_all or no_gpus or gpu_slots is not None:
if attach_all or gpu_all:
gpu_config = {"attach_mode": "all"}
updates.append("GPUs (all)")
elif no_gpus:
gpu_config = {
"attach_mode": "listed",
"gpus": []
}
updates.append("GPUs (detached)")
elif gpu_slots:
gpu_config = {
"attach_mode": "listed",
"gpus": [{"slot": gpu} for gpu in gpu_slots]
}
updates.append(f"GPUs ({len(gpu_slots)} devices)")
else:
# gpu_slots is an empty list ([] not None) - shouldn't happen with mutually exclusive group
gpu_config = {
"attach_mode": "listed",
"gpus": []
}
updates.append("GPUs (none)")
upgrade_params["gpus"] = gpu_config
if no_tee is not None:
upgrade_params["no_tee"] = no_tee
updates.append("TEE disabled" if no_tee else "TEE enabled")
if len(upgrade_params) > 1: # more than just the id
self.rpc_call("UpgradeApp", upgrade_params)
if updates:
print(f"Updated VM {vm_id}: {', '.join(updates)}")
else:
print(f"No updates specified for VM {vm_id}")
def show_info(self, vm_id: str, json_output: bool = False) -> None:
"""Show detailed information about a VM"""
response = self.rpc_call('GetInfo', {'id': vm_id})
if not response.get('found', False) or 'info' not in response:
print(f"VM with ID {vm_id} not found")
return
info = response['info']
if json_output:
print(json.dumps(info, indent=2))
return
config = info.get('configuration', {})
print(f"VM ID: {info.get('id', '-')}")
print(f"Name: {info.get('name', '-')}")
print(f"Status: {info.get('status', '-')}")
print(f"Uptime: {info.get('uptime', '-')}")
print(f"App ID: {info.get('app_id', '-')}")
print(f"Instance ID: {info.get('instance_id', '-') or '-'}")
print(f"App URL: {info.get('app_url', '-') or '-'}")
print(f"Image: {config.get('image', '-')}")
print(f"Image Version: {info.get('image_version', '-')}")
print(f"vCPU: {config.get('vcpu', '-')}")
print(f"Memory: {config.get('memory', '-')}MB")
print(f"Disk: {config.get('disk_size', '-')}GB")
print(f"GPUs: {self._format_gpu_info(config.get('gpus'))}")
print(f"Boot Progress: {info.get('boot_progress', '-')}")
if info.get('boot_error'):
print(f"Boot Error: {info['boot_error']}")
if info.get('exited_at'):
print(f"Exited At: {info['exited_at']}")
if info.get('shutdown_progress'):
print(f"Shutdown: {info['shutdown_progress']}")
events = info.get('events', [])
if events:
print(f"\nRecent Events:")
for event in events[-10:]:
ts = event.get('timestamp', 0)
print(f" [{event.get('event', '')}] {event.get('body', '')} (ts: {ts})")
def list_gpus(self, json_output: bool = False) -> None:
"""List all available GPUs"""
response = self.rpc_call('ListGpus')
gpus = response.get('gpus', [])
if json_output:
# Return raw JSON data for automation/testing
print(json.dumps(gpus, indent=2))
return
if not gpus:
print("No GPUs found")
return
headers = ['Slot', 'Product ID', 'Description', 'Available']
rows = []
for gpu in gpus:
row = [
gpu.get('slot', '-'),
gpu.get('product_id', '-'),
gpu.get('description', '-'),
'Yes' if gpu.get('is_free', False) else 'No'
]
rows.append(row)
print(format_table(rows, headers))
def format_table(rows, headers):
"""Simple table formatter"""
if not rows:
return ""
# Calculate column widths
widths = [len(h) for h in headers]
for row in rows:
for i, cell in enumerate(row):
widths[i] = max(widths[i], len(str(cell)))
# Create format string