|
| 1 | +import datetime |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple |
| 5 | +from urllib.parse import urlparse |
| 6 | + |
| 7 | +import aiohttp |
| 8 | +from aleph_message.models import ItemHash |
| 9 | +from eth_account.messages import encode_defunct |
| 10 | +from jwcrypto import jwk |
| 11 | + |
| 12 | +from aleph.sdk.types import Account |
| 13 | +from aleph.sdk.utils import ( |
| 14 | + create_vm_control_payload, |
| 15 | + sign_vm_control_payload, |
| 16 | + to_0x_hex, |
| 17 | +) |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class VmClient: |
| 23 | + account: Account |
| 24 | + ephemeral_key: jwk.JWK |
| 25 | + node_url: str |
| 26 | + pubkey_payload: Dict[str, Any] |
| 27 | + pubkey_signature_header: str |
| 28 | + session: aiohttp.ClientSession |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + account: Account, |
| 33 | + node_url: str = "", |
| 34 | + session: Optional[aiohttp.ClientSession] = None, |
| 35 | + ): |
| 36 | + self.account = account |
| 37 | + self.ephemeral_key = jwk.JWK.generate(kty="EC", crv="P-256") |
| 38 | + self.node_url = node_url |
| 39 | + self.pubkey_payload = self._generate_pubkey_payload() |
| 40 | + self.pubkey_signature_header = "" |
| 41 | + self.session = session or aiohttp.ClientSession() |
| 42 | + |
| 43 | + def _generate_pubkey_payload(self) -> Dict[str, Any]: |
| 44 | + return { |
| 45 | + "pubkey": json.loads(self.ephemeral_key.export_public()), |
| 46 | + "alg": "ECDSA", |
| 47 | + "domain": self.node_domain, |
| 48 | + "address": self.account.get_address(), |
| 49 | + "expires": ( |
| 50 | + datetime.datetime.utcnow() + datetime.timedelta(days=1) |
| 51 | + ).isoformat() |
| 52 | + + "Z", |
| 53 | + } |
| 54 | + |
| 55 | + async def _generate_pubkey_signature_header(self) -> str: |
| 56 | + pubkey_payload = json.dumps(self.pubkey_payload).encode("utf-8").hex() |
| 57 | + signable_message = encode_defunct(hexstr=pubkey_payload) |
| 58 | + buffer_to_sign = signable_message.body |
| 59 | + |
| 60 | + signed_message = await self.account.sign_raw(buffer_to_sign) |
| 61 | + pubkey_signature = to_0x_hex(signed_message) |
| 62 | + |
| 63 | + return json.dumps( |
| 64 | + { |
| 65 | + "sender": self.account.get_address(), |
| 66 | + "payload": pubkey_payload, |
| 67 | + "signature": pubkey_signature, |
| 68 | + "content": {"domain": self.node_domain}, |
| 69 | + } |
| 70 | + ) |
| 71 | + |
| 72 | + async def _generate_header( |
| 73 | + self, vm_id: ItemHash, operation: str, method: str |
| 74 | + ) -> Tuple[str, Dict[str, str]]: |
| 75 | + payload = create_vm_control_payload( |
| 76 | + vm_id, operation, domain=self.node_domain, method=method |
| 77 | + ) |
| 78 | + signed_operation = sign_vm_control_payload(payload, self.ephemeral_key) |
| 79 | + |
| 80 | + if not self.pubkey_signature_header: |
| 81 | + self.pubkey_signature_header = ( |
| 82 | + await self._generate_pubkey_signature_header() |
| 83 | + ) |
| 84 | + |
| 85 | + headers = { |
| 86 | + "X-SignedPubKey": self.pubkey_signature_header, |
| 87 | + "X-SignedOperation": signed_operation, |
| 88 | + } |
| 89 | + |
| 90 | + path = payload["path"] |
| 91 | + return f"{self.node_url}{path}", headers |
| 92 | + |
| 93 | + @property |
| 94 | + def node_domain(self) -> str: |
| 95 | + domain = urlparse(self.node_url).hostname |
| 96 | + if not domain: |
| 97 | + raise Exception("Could not parse node domain") |
| 98 | + return domain |
| 99 | + |
| 100 | + async def perform_operation( |
| 101 | + self, vm_id: ItemHash, operation: str, method: str = "POST" |
| 102 | + ) -> Tuple[Optional[int], str]: |
| 103 | + if not self.pubkey_signature_header: |
| 104 | + self.pubkey_signature_header = ( |
| 105 | + await self._generate_pubkey_signature_header() |
| 106 | + ) |
| 107 | + |
| 108 | + url, header = await self._generate_header( |
| 109 | + vm_id=vm_id, operation=operation, method=method |
| 110 | + ) |
| 111 | + |
| 112 | + try: |
| 113 | + async with self.session.request( |
| 114 | + method=method, url=url, headers=header |
| 115 | + ) as response: |
| 116 | + response_text = await response.text() |
| 117 | + return response.status, response_text |
| 118 | + |
| 119 | + except aiohttp.ClientError as e: |
| 120 | + logger.error(f"HTTP error during operation {operation}: {str(e)}") |
| 121 | + return None, str(e) |
| 122 | + |
| 123 | + async def get_logs(self, vm_id: ItemHash) -> AsyncGenerator[str, None]: |
| 124 | + if not self.pubkey_signature_header: |
| 125 | + self.pubkey_signature_header = ( |
| 126 | + await self._generate_pubkey_signature_header() |
| 127 | + ) |
| 128 | + |
| 129 | + payload = create_vm_control_payload( |
| 130 | + vm_id, "stream_logs", method="get", domain=self.node_domain |
| 131 | + ) |
| 132 | + signed_operation = sign_vm_control_payload(payload, self.ephemeral_key) |
| 133 | + path = payload["path"] |
| 134 | + ws_url = f"{self.node_url}{path}" |
| 135 | + |
| 136 | + async with self.session.ws_connect(ws_url) as ws: |
| 137 | + auth_message = { |
| 138 | + "auth": { |
| 139 | + "X-SignedPubKey": json.loads(self.pubkey_signature_header), |
| 140 | + "X-SignedOperation": json.loads(signed_operation), |
| 141 | + } |
| 142 | + } |
| 143 | + await ws.send_json(auth_message) |
| 144 | + |
| 145 | + async for msg in ws: # msg is of type aiohttp.WSMessage |
| 146 | + if msg.type == aiohttp.WSMsgType.TEXT: |
| 147 | + yield msg.data |
| 148 | + elif msg.type == aiohttp.WSMsgType.ERROR: |
| 149 | + break |
| 150 | + |
| 151 | + async def start_instance(self, vm_id: ItemHash) -> Tuple[int, str]: |
| 152 | + return await self.notify_allocation(vm_id) |
| 153 | + |
| 154 | + async def stop_instance(self, vm_id: ItemHash) -> Tuple[Optional[int], str]: |
| 155 | + return await self.perform_operation(vm_id, "stop") |
| 156 | + |
| 157 | + async def reboot_instance(self, vm_id: ItemHash) -> Tuple[Optional[int], str]: |
| 158 | + return await self.perform_operation(vm_id, "reboot") |
| 159 | + |
| 160 | + async def erase_instance(self, vm_id: ItemHash) -> Tuple[Optional[int], str]: |
| 161 | + return await self.perform_operation(vm_id, "erase") |
| 162 | + |
| 163 | + async def expire_instance(self, vm_id: ItemHash) -> Tuple[Optional[int], str]: |
| 164 | + return await self.perform_operation(vm_id, "expire") |
| 165 | + |
| 166 | + async def notify_allocation(self, vm_id: ItemHash) -> Tuple[int, str]: |
| 167 | + json_data = {"instance": vm_id} |
| 168 | + |
| 169 | + async with self.session.post( |
| 170 | + f"{self.node_url}/control/allocation/notify", json=json_data |
| 171 | + ) as session: |
| 172 | + form_response_text = await session.text() |
| 173 | + |
| 174 | + return session.status, form_response_text |
| 175 | + |
| 176 | + async def manage_instance( |
| 177 | + self, vm_id: ItemHash, operations: List[str] |
| 178 | + ) -> Tuple[int, str]: |
| 179 | + for operation in operations: |
| 180 | + status, response = await self.perform_operation(vm_id, operation) |
| 181 | + if status != 200 and status: |
| 182 | + return status, response |
| 183 | + return 200, "All operations completed successfully" |
| 184 | + |
| 185 | + async def close(self): |
| 186 | + await self.session.close() |
| 187 | + |
| 188 | + async def __aenter__(self): |
| 189 | + return self |
| 190 | + |
| 191 | + async def __aexit__(self, exc_type, exc_value, traceback): |
| 192 | + await self.close() |
0 commit comments