-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path__init__.py
1257 lines (1132 loc) · 52.3 KB
/
__init__.py
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
from __future__ import annotations
import asyncio
import json
import logging
import shutil
from decimal import Decimal
from math import ceil
from pathlib import Path
from typing import List, Optional, Tuple, Union, cast
import aiohttp
import typer
from aleph.sdk import AlephHttpClient, AuthenticatedAlephHttpClient
from aleph.sdk.account import _load_account
from aleph.sdk.chains.ethereum import ETHAccount
from aleph.sdk.client.vm_client import VmClient
from aleph.sdk.client.vm_confidential_client import VmConfidentialClient
from aleph.sdk.conf import load_main_configuration, settings
from aleph.sdk.evm_utils import get_chains_with_holding, get_chains_with_super_token
from aleph.sdk.exceptions import (
ForgottenMessageError,
InsufficientFundsError,
MessageNotFoundError,
)
from aleph.sdk.query.filters import MessageFilter
from aleph.sdk.query.responses import PriceResponse
from aleph.sdk.types import StorageEnum
from aleph.sdk.utils import calculate_firmware_hash
from aleph_message.models import InstanceMessage, StoreMessage
from aleph_message.models.base import Chain, MessageType
from aleph_message.models.execution.base import Payment, PaymentType
from aleph_message.models.execution.environment import (
HostRequirements,
HypervisorType,
NodeRequirements,
TrustedExecutionEnvironment,
)
from aleph_message.models.item_hash import ItemHash
from click import echo
from rich import box
from rich.console import Console
from rich.prompt import Confirm, Prompt
from rich.table import Table
from rich.text import Text
from aleph_client.commands import help_strings
from aleph_client.commands.instance.display import CRNTable
from aleph_client.commands.instance.network import (
fetch_crn_info,
fetch_vm_info,
find_crn_of_vm,
sanitize_url,
)
from aleph_client.commands.instance.superfluid import FlowUpdate, update_flow
from aleph_client.commands.node import NodeInfo, _fetch_nodes
from aleph_client.commands.utils import (
filter_only_valid_messages,
get_or_prompt_volumes,
safe_getattr,
setup_logging,
str_to_datetime,
validate_ssh_pubkey_file,
validated_int_prompt,
validated_prompt,
wait_for_confirmed_flow,
wait_for_processed_instance,
)
from aleph_client.models import CRNInfo
from aleph_client.utils import AsyncTyper
logger = logging.getLogger(__name__)
app = AsyncTyper(no_args_is_help=True)
# TODO: This should be put on the API to get always from there
FLOW_INSTANCE_PRICE_PER_SECOND = Decimal(0.0000155) # 0.055/h
@app.command()
async def create(
payment_type: Optional[str] = typer.Option(
None,
help=help_strings.PAYMENT_TYPE,
callback=lambda pt: None if pt is None else pt.lower(),
# callback=lambda pt: None if pt is None else PaymentType.hold if pt == "nft" else PaymentType(pt),
metavar=f"[{'|'.join(PaymentType)}|nft]",
),
payment_chain: Optional[Chain] = typer.Option(
None, help=help_strings.PAYMENT_CHAIN, metavar=f"[{'|'.join([Chain.ETH, Chain.AVAX, Chain.BASE, Chain.SOL])}]"
),
hypervisor: Optional[HypervisorType] = typer.Option(None, help=help_strings.HYPERVISOR),
name: Optional[str] = typer.Option(None, help=help_strings.INSTANCE_NAME),
rootfs: Optional[str] = typer.Option(None, help=help_strings.ROOTFS),
rootfs_size: Optional[int] = typer.Option(None, help=help_strings.ROOTFS_SIZE),
vcpus: Optional[int] = typer.Option(None, help=help_strings.VCPUS),
memory: Optional[int] = typer.Option(None, help=help_strings.MEMORY),
timeout_seconds: float = typer.Option(
settings.DEFAULT_VM_TIMEOUT,
help=help_strings.TIMEOUT_SECONDS,
),
ssh_pubkey_file: Path = typer.Option(
Path("~/.ssh/id_rsa.pub").expanduser(),
help=help_strings.SSH_PUBKEY_FILE,
),
crn_hash: Optional[str] = typer.Option(None, help=help_strings.CRN_HASH),
crn_url: Optional[str] = typer.Option(None, help=help_strings.CRN_URL),
confidential: bool = typer.Option(False, help=help_strings.CONFIDENTIAL_OPTION),
confidential_firmware: str = typer.Option(
default=settings.DEFAULT_CONFIDENTIAL_FIRMWARE, help=help_strings.CONFIDENTIAL_FIRMWARE
),
skip_volume: bool = typer.Option(False, help=help_strings.SKIP_VOLUME),
persistent_volume: Optional[List[str]] = typer.Option(None, help=help_strings.PERSISTENT_VOLUME),
ephemeral_volume: Optional[List[str]] = typer.Option(None, help=help_strings.EPHEMERAL_VOLUME),
immutable_volume: Optional[List[str]] = typer.Option(
None,
help=help_strings.IMMUTABLE_VOLUME,
),
channel: Optional[str] = typer.Option(default=settings.DEFAULT_CHANNEL, help=help_strings.CHANNEL),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
print_messages: bool = typer.Option(False),
verbose: bool = typer.Option(True),
debug: bool = False,
) -> Tuple[ItemHash, Optional[str], Chain]:
"""Create and register a new instance on aleph.im"""
setup_logging(debug)
console = Console()
# Loads ssh pubkey
try:
ssh_pubkey_file = validate_ssh_pubkey_file(ssh_pubkey_file)
except ValueError:
ssh_pubkey_file = Path(
validated_prompt(
f"{ssh_pubkey_file} does not exist.\nPlease enter the path to a ssh pubkey to access your instance",
validate_ssh_pubkey_file,
)
)
ssh_pubkey: str = ssh_pubkey_file.read_text(encoding="utf-8").strip()
# Loads default configuration if no chain is set
if payment_chain is None:
config = load_main_configuration(settings.CONFIG_FILE)
if config is not None:
payment_chain = config.chain
else:
console.print("No active chain selected in configuration.")
# Populates payment type if not set
if not payment_type:
payment_type = Prompt.ask(
"Which payment type do you want to use?",
choices=[ptype.value for ptype in PaymentType] + ["nft"],
default=PaymentType.superfluid.value,
)
# Force-switches if NFT payment-type
if payment_type == "nft":
payment_chain = Chain.AVAX
payment_type = PaymentType.hold
console.print(
"[yellow]NFT[/yellow] payment-type selected: Auto-switch to [cyan]AVAX[/cyan] with [red]HOLD[/red]"
)
elif payment_type in [ptype.value for ptype in PaymentType]:
payment_type = PaymentType(payment_type)
else:
raise ValueError(f"Invalid payment-type: {payment_type}")
is_stream = payment_type != PaymentType.hold
hold_chains = get_chains_with_holding() + [Chain.SOL.value]
super_token_chains = get_chains_with_super_token()
# Checks if payment-chain is compatible with PAYG
if is_stream:
if payment_chain == Chain.SOL:
console.print(
"[yellow]SOL[/yellow] chain selected: [red]Not compatible yet with Pay-As-You-Go.[/red]\nChange your configuration or provide another chain using arguments (but EVM address will be used)."
)
raise typer.Exit(code=1)
elif payment_chain is None or payment_chain not in super_token_chains:
payment_chain = Chain(
Prompt.ask(
"Which chain do you want to use for Pay-As-You-Go?",
choices=super_token_chains,
default=Chain.AVAX.value,
)
)
# Fallback for Hold-tier if no config / no chain is set
elif payment_chain is None:
payment_chain = Chain(
Prompt.ask(
"Which chain do you want to use for Hold-tier?",
choices=hold_chains,
default=Chain.ETH.value,
)
)
# Populates account
account = _load_account(private_key, private_key_file, chain=payment_chain)
# Checks required balances (Gas + Aleph ERC20) for superfluid payment
if is_stream and isinstance(account, ETHAccount):
if account.CHAIN != payment_chain:
account.switch_chain(payment_chain)
if account.superfluid_connector and hasattr(account.superfluid_connector, "can_start_flow"):
try: # Quick check with theoretical min price
account.superfluid_connector.can_start_flow(FLOW_INSTANCE_PRICE_PER_SECOND) # 0.055/h
except Exception as e:
echo(e)
raise typer.Exit(code=1)
else:
echo("Superfluid connector not available on this chain.")
raise typer.Exit(code=1)
# Checks if Hypervisor is compatible with confidential
if confidential:
if hypervisor and hypervisor != HypervisorType.qemu:
echo("Only QEMU is supported as an hypervisor for confidential")
raise typer.Exit(code=1)
elif not hypervisor:
echo("Using QEMU as hypervisor for confidential")
hypervisor = HypervisorType.qemu
available_hypervisors = {
HypervisorType.firecracker: {
"ubuntu22": settings.UBUNTU_22_ROOTFS_ID,
"debian12": settings.DEBIAN_12_ROOTFS_ID,
"debian11": settings.DEBIAN_11_ROOTFS_ID,
},
HypervisorType.qemu: {
"ubuntu22": settings.UBUNTU_22_QEMU_ROOTFS_ID,
"debian12": settings.DEBIAN_12_QEMU_ROOTFS_ID,
"debian11": settings.DEBIAN_11_QEMU_ROOTFS_ID,
},
}
if hypervisor is None:
hypervisor_choice = HypervisorType[
Prompt.ask(
"Which hypervisor you want to use?",
default=settings.DEFAULT_HYPERVISOR.name,
choices=[x.name for x in available_hypervisors],
)
]
hypervisor = HypervisorType(hypervisor_choice)
is_qemu = hypervisor == HypervisorType.qemu
os_choices = available_hypervisors[hypervisor]
if not rootfs or len(rootfs) != 64:
if confidential:
# Confidential only support custom rootfs
rootfs = "custom"
elif not rootfs or rootfs not in os_choices:
rootfs = Prompt.ask(
"Use a custom rootfs or one of the following prebuilt ones:",
default="ubuntu22",
choices=[*os_choices, "custom"],
)
if rootfs == "custom":
rootfs = validated_prompt(
"Enter the item hash of the rootfs to use for your instance",
lambda x: len(x) == 64,
)
else:
rootfs = os_choices[rootfs]
# Validate rootfs message exist
async with AlephHttpClient(api_server=settings.API_HOST) as client:
rootfs_message: StoreMessage = await client.get_message(item_hash=rootfs, message_type=StoreMessage)
if not rootfs_message:
echo("Given rootfs volume does not exist on aleph.im")
raise typer.Exit(code=1)
if rootfs_size is None and rootfs_message.content.size:
rootfs_size = rootfs_message.content.size
# Validate confidential firmware message exist
confidential_firmware_as_hash = None
if confidential:
async with AlephHttpClient(api_server=settings.API_HOST) as client:
confidential_firmware_as_hash = ItemHash(confidential_firmware)
firmware_message: StoreMessage = await client.get_message(
item_hash=confidential_firmware, message_type=StoreMessage
)
if not firmware_message:
echo("Confidential Firmware hash does not exist on aleph.im")
raise typer.Exit(code=1)
name = name or validated_prompt("Instance name", lambda x: len(x) < 65)
rootfs_size = rootfs_size or validated_int_prompt(
"Disk size in MiB", default=settings.DEFAULT_ROOTFS_SIZE, min_value=10_240, max_value=542_288
)
vcpus = vcpus or validated_int_prompt(
"Number of virtual cpus to allocate", default=settings.DEFAULT_VM_VCPUS, min_value=1, max_value=4
)
memory = memory or validated_int_prompt(
"Maximum memory allocation on vm in MiB",
default=settings.DEFAULT_INSTANCE_MEMORY,
min_value=2_048,
max_value=12_288,
)
volumes = []
if not skip_volume:
volumes = get_or_prompt_volumes(
persistent_volume=persistent_volume,
ephemeral_volume=ephemeral_volume,
immutable_volume=immutable_volume,
)
stream_reward_address = None
crn = None
if is_stream or confidential:
if crn_url and crn_hash:
crn_url = sanitize_url(crn_url)
try:
crn_name, score, reward_addr = "?", 0, ""
nodes: NodeInfo = await _fetch_nodes()
for node in nodes.nodes:
if node["address"].rstrip("/") == crn_url:
crn_name = node["name"]
score = node["score"]
reward_addr = node["stream_reward"]
break
crn_info = await fetch_crn_info(crn_url)
if crn_info:
crn = CRNInfo(
hash=ItemHash(crn_hash),
name=crn_name or "?",
url=crn_url,
version=crn_info.get("version", ""),
score=score,
stream_reward_address=str(crn_info.get("payment", {}).get("PAYMENT_RECEIVER_ADDRESS"))
or reward_addr
or "",
machine_usage=crn_info.get("machine_usage"),
qemu_support=bool(crn_info.get("computing", {}).get("ENABLE_QEMU_SUPPORT", False)),
confidential_computing=bool(
crn_info.get("computing", {}).get("ENABLE_CONFIDENTIAL_COMPUTING", False)
),
)
echo("\n* Selected CRN *")
crn.display_crn_specs()
echo()
except Exception as e:
echo(f"Unable to fetch CRN config: {e}")
raise typer.Exit(1)
while not crn:
crn_table = CRNTable(only_reward_address=is_stream, only_qemu=is_qemu, only_confidentials=confidential)
crn = await crn_table.run_async()
if not crn:
# User has ctrl-c
raise typer.Exit(1)
echo("\n* Selected CRN *")
crn.display_crn_specs()
if not Confirm.ask("\nDeploy on this node ?"):
crn = None
continue
elif crn_url or crn_hash:
logger.debug(
f"`--crn-url` and/or `--crn-hash` arguments have been ignored.\nHold-tier regular instances are scheduled automatically on available CRNs by the Aleph.im network."
)
if crn:
stream_reward_address = crn.stream_reward_address if hasattr(crn, "stream_reward_address") else ""
if is_stream and not stream_reward_address:
echo("Selected CRN does not have a defined receiver address.")
raise typer.Exit(1)
if is_qemu and (not hasattr(crn, "qemu_support") or not crn.qemu_support):
echo("Selected CRN does not support QEMU hypervisor.")
raise typer.Exit(1)
if confidential and (not hasattr(crn, "confidential_computing") or not crn.confidential_computing):
echo("Selected CRN does not support confidential computing.")
raise typer.Exit(1)
async with AuthenticatedAlephHttpClient(account=account, api_server=settings.API_HOST) as client:
payment = Payment(
chain=payment_chain,
receiver=stream_reward_address if stream_reward_address else None,
type=payment_type,
)
try:
message, status = await client.create_instance(
sync=True,
rootfs=rootfs,
rootfs_size=rootfs_size,
storage_engine=StorageEnum.storage,
channel=channel,
metadata={"name": name},
memory=memory,
vcpus=vcpus,
timeout_seconds=timeout_seconds,
volumes=volumes,
ssh_keys=[ssh_pubkey],
hypervisor=hypervisor,
payment=payment,
requirements=HostRequirements(node=NodeRequirements(node_hash=crn.hash)) if crn else None,
trusted_execution=(
TrustedExecutionEnvironment(firmware=confidential_firmware_as_hash) if confidential else None
),
)
except InsufficientFundsError as e:
echo(
f"Instance creation failed due to insufficient funds.\n"
f"{account.get_address()} on {account.CHAIN} has {e.available_funds} ALEPH but needs {e.required_funds} ALEPH."
)
raise typer.Exit(code=1)
if print_messages:
echo(f"{message.json(indent=4)}")
item_hash: ItemHash = message.item_hash
item_hash_text = Text(item_hash, style="bright_cyan")
# Instances that need to be started by notifying a specific CRN
crn_url = crn.url if crn and crn.url else None
if crn and (is_stream or confidential):
if not crn_url:
# Not the ideal solution
logger.debug(f"Cannot allocate {item_hash}: no CRN url")
return item_hash, crn_url, payment_chain
# Wait for the instance message to be processed
async with aiohttp.ClientSession() as session:
await wait_for_processed_instance(session, item_hash)
# Pay-As-You-Go
if payment_type == PaymentType.superfluid:
price: PriceResponse = await client.get_program_price(item_hash)
ceil_factor = 10**18
required_tokens = ceil(Decimal(price.required_tokens) * ceil_factor) / ceil_factor
if isinstance(account, ETHAccount) and account.superfluid_connector:
try: # Double check with effective price
account.superfluid_connector.can_start_flow(FLOW_INSTANCE_PRICE_PER_SECOND) # Min for 0.11/h
except Exception as e:
echo(e)
raise typer.Exit(code=1)
flow_hash = await update_flow(
account=account,
receiver=crn.stream_reward_address,
flow=Decimal(required_tokens),
update_type=FlowUpdate.INCREASE,
)
# Wait for the flow transaction to be confirmed
await wait_for_confirmed_flow(account, message.content.payment.receiver)
if flow_hash:
echo(
f"Flow {flow_hash} has been created:\n - Aleph cost summary:\n {price.required_tokens:.7f}/sec | {3600*price.required_tokens:.2f}/hour | {86400*price.required_tokens:.2f}/day | {2592000*price.required_tokens:.2f}/month\n - CRN receiver address: {crn.stream_reward_address}"
)
# Notify CRN
async with VmClient(account, crn.url) as crn_client:
status, result = await crn_client.start_instance(vm_id=item_hash)
logger.debug(status, result)
if int(status) != 200:
echo(f"Could not allocate instance {item_hash} on CRN.")
return item_hash, crn_url, payment_chain
console.print(f"Your instance {item_hash_text} has been deployed on aleph.im.")
if verbose:
# PAYG-tier non-confidential instances
if not confidential:
console.print(
"\n\nTo get the IPv6 address of the instance, check out:\n\n",
Text.assemble(
" aleph instance list\n",
style="italic",
),
)
# All confidential instances
else:
console.print(
"\n\nInitialize a confidential session using:\n\n",
# Text.assemble(
# " aleph instance confidential-init-session ",
# item_hash_text,
# style="italic",
# ),
# "\n\nThen start it using:\n\n",
# Text.assemble(
# " aleph instance confidential-start ",
# item_hash_text,
# style="italic",
# ),
# "\n\nOr just use the all-in-one command:\n\n",
Text.assemble(
" aleph instance confidential ",
item_hash_text,
"\n",
style="italic",
),
)
# Instances started automatically by the scheduler (hold-tier non-confidential)
else:
console.print(
f"Your instance {item_hash_text} is registered to be deployed on aleph.im.",
"\nThe scheduler usually takes a few minutes to set it up and start it.",
)
if verbose:
console.print(
"\n\nTo get the IPv6 address of the instance, check out:\n\n",
Text.assemble(
" aleph instance list\n",
style="italic",
),
)
return item_hash, crn_url, payment_chain
@app.command()
async def delete(
item_hash: str = typer.Argument(..., help="Instance item hash to forget"),
reason: str = typer.Option("User deletion", help="Reason for deleting the instance"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.ADDRESS_CHAIN),
crn_url: Optional[str] = typer.Option(None, help=help_strings.CRN_URL_VM_DELETION),
private_key: Optional[str] = settings.PRIVATE_KEY_STRING,
private_key_file: Optional[Path] = settings.PRIVATE_KEY_FILE,
print_message: bool = typer.Option(False),
debug: bool = False,
):
"""Delete an instance, unallocating all resources associated with it. Associated VM will be stopped and erased. Immutable volumes will not be deleted."""
setup_logging(debug)
account = _load_account(private_key, private_key_file, chain=chain)
async with AuthenticatedAlephHttpClient(account=account, api_server=settings.API_HOST) as client:
try:
existing_message: InstanceMessage = await client.get_message(
item_hash=ItemHash(item_hash), message_type=InstanceMessage
)
except MessageNotFoundError:
echo("Instance does not exist")
raise typer.Exit(code=1)
except ForgottenMessageError:
echo("Instance already forgotten")
raise typer.Exit(code=1)
if existing_message.sender != account.get_address():
echo("You are not the owner of this instance")
raise typer.Exit(code=1)
# If PAYG, retrieve flow price
payment: Optional[Payment] = existing_message.content.payment
price: Optional[PriceResponse] = None
if safe_getattr(payment, "type") == PaymentType.superfluid:
price = await client.get_program_price(item_hash)
# Ensure correct chain
chain = existing_message.content.payment.chain # type: ignore
# Check status of the instance and eventually erase associated VM
node_list: NodeInfo = await _fetch_nodes()
_, info = await fetch_vm_info(existing_message, node_list)
auto_scheduled = info["allocation_type"] == help_strings.ALLOCATION_AUTO
crn_url = str(info["crn_url"])
if not auto_scheduled and crn_url:
try:
status = await erase(
vm_id=item_hash,
domain=crn_url,
chain=chain,
private_key=private_key,
private_key_file=private_key_file,
silent=True,
debug=debug,
)
if status == 1:
echo(f"No associated VM on {crn_url}. Skipping...")
except Exception as e:
logger.debug(f"Error while deleting associated VM on {crn_url}: {str(e)}")
echo(f"Failed to erase associated VM on {crn_url}. Skipping...")
else:
echo(f"Instance {item_hash} was auto-scheduled, VM will be erased automatically.")
# Check for streaming payment and eventually stop it
if payment and payment.type == PaymentType.superfluid and payment.receiver and isinstance(account, ETHAccount):
if account.CHAIN != payment.chain:
account.switch_chain(payment.chain)
if account.superfluid_connector and price:
flow_hash = await update_flow(
account, payment.receiver, Decimal(price.required_tokens), FlowUpdate.REDUCE
)
if flow_hash:
echo(f"Flow {flow_hash} has been deleted.")
message, status = await client.forget(hashes=[ItemHash(item_hash)], reason=reason)
if print_message:
echo(f"{message.json(indent=4)}")
echo(f"Instance {item_hash} has been deleted.")
async def _show_instances(messages: List[InstanceMessage], node_list: NodeInfo):
table = Table(box=box.SIMPLE_HEAVY)
table.add_column(f"Instances [{len(messages)}]", style="blue", overflow="fold")
table.add_column("Specifications", style="magenta")
table.add_column("Logs", style="blue", overflow="fold")
scheduler_responses = dict(await asyncio.gather(*[fetch_vm_info(message, node_list) for message in messages]))
uninitialized_confidential_found = False
for message in messages:
info = scheduler_responses[message.item_hash]
if info["ipv6_logs"] == help_strings.VM_NOT_READY:
uninitialized_confidential_found = True
name = Text(
(
message.content.metadata["name"]
if hasattr(message.content, "metadata")
and isinstance(message.content.metadata, dict)
and "name" in message.content.metadata
else "-"
),
style="orchid",
)
link = f"https://explorer.aleph.im/address/ETH/{message.sender}/message/INSTANCE/{message.item_hash}"
# link = f"{settings.API_HOST}/api/v0/messages/{message.item_hash}"
item_hash_link = Text.from_markup(f"[link={link}]{message.item_hash}[/link]", style="bright_cyan")
is_hold = str(info["payment"]).startswith("hold")
payment = Text.assemble(
"Payment: ",
Text(
str(info["payment"]).capitalize(),
style="red" if is_hold else "orange3",
),
)
cost: Text | str = ""
if not is_hold:
async with AlephHttpClient(api_server=settings.API_HOST) as client:
price: PriceResponse = await client.get_program_price(message.item_hash)
psec = Text(f"{price.required_tokens:.7f}/sec", style="bright_magenta")
phour = Text(f"{3600*price.required_tokens:.2f}/hour", style="bright_magenta")
pday = Text(f"{86400*price.required_tokens:.2f}/day", style="bright_magenta")
pmonth = Text(f"{2592000*price.required_tokens:.2f}/month", style="bright_magenta")
cost = Text.assemble("Aleph cost: ", psec, " | ", phour, " | ", pday, " | ", pmonth, "\n")
confidential = (
Text.assemble("Type: ", Text("Confidential", style="green"))
if info["confidential"]
else Text.assemble("Type: ", Text("Regular", style="grey50"))
)
chain_label, chain_color = str(info["chain"]), "steel_blue"
if chain_label == "AVAX":
chain_label, chain_color = "AVAX", "bright_red"
elif chain_label == "BASE":
chain_label, chain_color = "BASE", "blue3"
elif chain_label == "SOL":
chain_label, chain_color = "SOL ", "medium_spring_green"
else: # ETH
chain_label += " "
chain = Text.assemble("Chain: ", Text(chain_label, style=chain_color))
created_at_parsed = str(str_to_datetime(str(info["created_at"]))).split(".")[0]
created_at = Text.assemble("\t Created at: ", Text(created_at_parsed, style="magenta"))
instance = Text.assemble(
"Item Hash ↓\t Name: ",
name,
"\n",
item_hash_link,
"\n",
payment,
" ",
confidential,
"\n",
cost,
chain,
created_at,
)
specifications = (
f"vCPUs: {message.content.resources.vcpus}\n"
f"RAM: {message.content.resources.memory / 1_024:.2f} GiB\n"
f"Disk: {message.content.rootfs.size_mib / 1_024:.2f} GiB\n"
f"HyperV: {safe_getattr(message, 'content.environment.hypervisor.value').capitalize() if safe_getattr(message, 'content.environment.hypervisor') else 'Firecracker'}\n"
)
status_column = Text.assemble(
Text.assemble(
Text("Allocation: ", style="blue"),
Text(
str(info["allocation_type"]) + "\n",
style="magenta3" if info["allocation_type"] == help_strings.ALLOCATION_MANUAL else "deep_sky_blue1",
),
),
Text.assemble(
Text("Target CRN: ", style="blue"),
Text(
str(info["crn_url"]) + "\n",
style="green1" if str(info["crn_url"]).startswith("http") else "dark_slate_gray1",
),
),
Text.assemble(
Text("IPv6: ", style="blue"),
Text(str(info["ipv6_logs"])),
style="bright_yellow" if len(str(info["ipv6_logs"]).split(":")) == 8 else "dark_orange",
),
)
table.add_row(instance, specifications, status_column)
table.add_section()
console = Console()
console.print(
f"\n[bold]Address:[/bold] {messages[0].content.address}",
)
console.print(table)
if uninitialized_confidential_found:
item_hash_field = Text("<vm-item-hash>", style="bright_cyan")
console.print(
"To start uninitialized confidential instance(s), use:\n\n",
# Text.assemble(
# " aleph instance confidential-init-session ",
# item_hash_field,
# "\n",
# style="italic",
# ),
# Text.assemble(
# " aleph instance confidential-start ",
# item_hash_field,
# style="italic",
# ),
# "\n\nOr just use the all-in-one command:\n\n",
Text.assemble(
" aleph instance confidential ",
item_hash_field,
"\n",
style="italic",
),
)
console.print(
"To connect to an instance, use:\n\n",
Text.assemble(
" ssh root@",
Text("<ipv6-address>", style="yellow"),
" -i ",
Text("<ssh-pubkey-file>", style="orange3"),
"\n",
style="italic",
),
)
@app.command()
async def list(
address: Optional[str] = typer.Option(None, help="Owner address of the instance"),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
chain: Optional[Chain] = typer.Option(None, help=help_strings.ADDRESS_CHAIN),
json: bool = typer.Option(default=False, help="Print as json instead of rich table"),
debug: bool = False,
):
"""List all instances associated to an account"""
setup_logging(debug)
if address is None:
account = _load_account(private_key, private_key_file, chain=chain)
address = account.get_address()
async with AlephHttpClient(api_server=settings.API_HOST) as client:
resp = await client.get_messages(
message_filter=MessageFilter(
message_types=[MessageType.instance],
addresses=[address],
),
page_size=100,
)
messages = await filter_only_valid_messages(resp.messages)
if not messages:
echo(f"Address: {address}\n\nNo instance found\n")
raise typer.Exit(code=1)
if json:
echo(messages.json(indent=4))
else:
# Since we filtered on message type, we can safely cast as InstanceMessage.
messages = cast(List[InstanceMessage], messages)
resource_nodes: NodeInfo = await _fetch_nodes()
await _show_instances(messages, resource_nodes)
@app.command()
async def expire(
vm_id: str = typer.Argument(..., help="VM item hash to expire"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM is running"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"""Expire an instance"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the VM is running")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
status, result = await manager.expire_instance(vm_id=vm_id)
if status != 200:
echo(f"Status: {status}")
return 1
echo(f"VM expired on CRN: {domain}")
@app.command()
async def erase(
vm_id: str = typer.Argument(..., help="VM item hash to erase"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM is stored or running"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
silent: bool = False,
debug: bool = False,
):
"""Erase an instance stored or running on a CRN"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the VM is stored or running")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
status, result = await manager.erase_instance(vm_id=vm_id)
if status != 200:
if not silent:
echo(f"Status: {status}")
return 1
echo(f"VM erased on CRN: {domain}")
@app.command()
async def reboot(
vm_id: str = typer.Argument(..., help="VM item hash to reboot"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM is running"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"""Reboot an instance"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the VM is running")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
status, result = await manager.reboot_instance(vm_id=vm_id)
if status != 200:
echo(f"Status: {status}")
return 1
echo(f"VM rebooted on CRN: {domain}")
@app.command()
async def allocate(
vm_id: str = typer.Argument(..., help="VM item hash to allocate"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM will be allocated"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"""Notify a CRN to start an instance (for Pay-As-You-Go and confidential instances only)"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the VM will be allocated")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
status, result = await manager.start_instance(vm_id=vm_id)
if status != 200:
echo(f"Status: {status}\n{result}")
return 1
echo(f"VM allocated on CRN: {domain}")
@app.command()
async def logs(
vm_id: str = typer.Argument(..., help="VM item hash to retrieve the logs from"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM is running"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"""Retrieve the logs of an instance"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the instance is running")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
try:
async for log in manager.get_logs(vm_id=vm_id):
log_data = json.loads(log)
if "message" in log_data:
echo(log_data["message"])
except aiohttp.ClientConnectorError as e:
echo(f"Unable to connect to domain: {domain}\nError: {e}")
except aiohttp.ClientResponseError:
echo(f"No VM associated with {vm_id} are currently running on {domain}")
@app.command()
async def stop(
vm_id: str = typer.Argument(..., help="VM item hash to stop"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the VM is running"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"""Stop an instance"""
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the instance is running")
)
account = _load_account(private_key, private_key_file, chain=chain)
async with VmClient(account, domain) as manager:
status, result = await manager.stop_instance(vm_id=vm_id)
if status != 200:
echo(f"Status : {status}")
return 1
echo(f"VM stopped on CRN: {domain}")
@app.command()
async def confidential_init_session(
vm_id: str = typer.Argument(..., help="VM item hash to initialize the session for"),
domain: Optional[str] = typer.Option(None, help="CRN domain on which the session will be initialized"),
chain: Optional[Chain] = typer.Option(None, help=help_strings.PAYMENT_CHAIN_USED),
policy: int = typer.Option(default=0x1),
keep_session: bool = typer.Option(None, help=help_strings.KEEP_SESSION),
private_key: Optional[str] = typer.Option(settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY),
private_key_file: Optional[Path] = typer.Option(settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE),
debug: bool = False,
):
"Initialize a confidential communication session with the VM"
assert settings.CONFIG_HOME
session_dir = Path(settings.CONFIG_HOME) / "confidential_sessions" / vm_id
session_dir.mkdir(exist_ok=True, parents=True)
setup_logging(debug)
domain = (
(domain and sanitize_url(domain))
or await find_crn_of_vm(vm_id)
or Prompt.ask("URL of the CRN (Compute node) on which the session will be initialized")
)
account = _load_account(private_key, private_key_file, chain=chain)
sevctl_path = find_sevctl_or_exit()
client = VmConfidentialClient(account, sevctl_path, domain)
godh_path = session_dir / "vm_godh.b64"
if godh_path.exists() and keep_session is None:
keep_session = not Confirm.ask(
"Session already initiated for this instance, are you sure you want to override the previous one? You won't be able to communicate with already running VM"
)
if keep_session:
echo("Keeping already initiated session")
# Generate sessions certificate files
if not ((session_dir / "vm_godh.b64").exists() and keep_session):
code, platform_file = await client.get_certificates()
if code != 200:
echo(
"Failed to retrieve platform certificate from the CRN. This node might be temporary down, please try again later. If the problem persist, contact the node operator."
)
return 1