|
| 1 | +from pathlib import Path |
| 2 | +from typing import Optional, Union, List, Any |
| 3 | +from pydantic import ConfigDict |
| 4 | +import sys |
| 5 | +import math |
| 6 | + |
| 7 | +from .._utils import _ASYNC_SLEEP |
| 8 | +from ..paths import AsyncRemotePath |
| 9 | +from .._utils import check_auth |
| 10 | + |
| 11 | +from .compute import Machine |
| 12 | +from .._models import ( |
| 13 | + AppRoutersStatusModelsStatus as StorageBase, |
| 14 | + GlobusTransfer as GlobusTransferModel, |
| 15 | + BodyStartGlobusTransferStorageGlobusTransferPost as GlobusBodyPost, |
| 16 | + GlobusTransferResult, |
| 17 | + GlobusStatus, |
| 18 | +) |
| 19 | + |
| 20 | +GLOBUS_TERMINAL_STATES = [ |
| 21 | + GlobusStatus.CANCELED, |
| 22 | + GlobusStatus.FAILED, |
| 23 | + GlobusStatus.SUCCEEDED, |
| 24 | +] |
| 25 | + |
| 26 | + |
| 27 | +class AsyncStorage: |
| 28 | + def __init__(self, client: "AsyncClient"): # noqa: F821 |
| 29 | + self.client = client |
| 30 | + |
| 31 | + async def globus( |
| 32 | + self, |
| 33 | + ): |
| 34 | + """Create a globus transfer object to start and monitor transfers |
| 35 | +
|
| 36 | + - Must select the Globus option when creating the SuperFacility key |
| 37 | +
|
| 38 | + ```python |
| 39 | + >>> from sfapi_client import AsyncClient |
| 40 | + >>> async with AsyncClient(client_id, client_secret) as client: |
| 41 | + >>> globus = client.storage.globus() |
| 42 | + ``` |
| 43 | +
|
| 44 | + :return AsyncGlobusStorage: Globus object to start and monitor transfers |
| 45 | + """ |
| 46 | + response = await self.client.get("status/globus") |
| 47 | + values = response.json() |
| 48 | + values["client"] = self.client |
| 49 | + _globus = AsyncGlobusStorage.model_validate(values) |
| 50 | + |
| 51 | + return _globus |
| 52 | + |
| 53 | + |
| 54 | +class AsyncGlobusTransfer(GlobusTransferResult): |
| 55 | + globus: Optional["AsyncGlobusStorage"] # noqa: F821 |
| 56 | + transfer_id: str |
| 57 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 58 | + |
| 59 | + async def update(self): |
| 60 | + """Updates the status of the transfer""" |
| 61 | + job_state = await self._fetch_state() |
| 62 | + self._update(job_state) |
| 63 | + |
| 64 | + def _update(self, new_job_state: Any): |
| 65 | + for k in new_job_state.model_fields_set: |
| 66 | + v = getattr(new_job_state, k) |
| 67 | + setattr(self, k, v) |
| 68 | + |
| 69 | + return self |
| 70 | + |
| 71 | + async def _wait_until(self, states: List[GlobusStatus], timeout: int = sys.maxsize): |
| 72 | + max_iteration = math.ceil(timeout / self.globus.client._wait_interval) |
| 73 | + iteration = 0 |
| 74 | + |
| 75 | + while self.globus_status not in states: |
| 76 | + await self.update() |
| 77 | + await _ASYNC_SLEEP(self.globus.client._wait_interval) |
| 78 | + |
| 79 | + if iteration == max_iteration: |
| 80 | + raise TimeoutError() |
| 81 | + |
| 82 | + iteration += 1 |
| 83 | + |
| 84 | + return self.globus_status |
| 85 | + |
| 86 | + async def _wait_until_complete(self, timeout: int = sys.maxsize): |
| 87 | + return await self._wait_until(GLOBUS_TERMINAL_STATES, timeout) |
| 88 | + |
| 89 | + def __await__(self): |
| 90 | + return self._wait_until_complete().__await__() |
| 91 | + |
| 92 | + async def complete(self, timeout: int = sys.maxsize): |
| 93 | + """Wait for the transfer to complete |
| 94 | +
|
| 95 | + >>> from sfapi_client import AsyncClient |
| 96 | + >>> async with AsyncClient(client_id, client_secret) as client: |
| 97 | + >>> globus = client.storage.globus() |
| 98 | + >>> res = await globus.transfer( |
| 99 | + "globus-transfer-uuid" |
| 100 | + ) |
| 101 | + >>> await res.complete() |
| 102 | +
|
| 103 | + :param int timeout: time to wait for the transfer to complete, defaults to sys.maxsize |
| 104 | + :return GlobusStart: Gives the file status for the transfer |
| 105 | + """ |
| 106 | + return await self._wait_until_complete(timeout) |
| 107 | + |
| 108 | + async def _fetch_state(self): |
| 109 | + r = await self.globus.client.get(f"storage/globus/transfer/{self.transfer_id}") |
| 110 | + json_response = r.json() |
| 111 | + json_response["transfer_id"] = self.transfer_id |
| 112 | + json_response["globus"] = self.globus |
| 113 | + transfer = AsyncGlobusTransfer.model_validate(json_response) |
| 114 | + return transfer |
| 115 | + |
| 116 | + |
| 117 | +class AsyncGlobusStorage(StorageBase): |
| 118 | + client: Optional["AsyncClient"] # noqa: F821 |
| 119 | + model_config = ConfigDict(arbitrary_types_allowed=True) |
| 120 | + |
| 121 | + def __init__(self, **kwargs): |
| 122 | + super().__init__(**kwargs) |
| 123 | + |
| 124 | + @check_auth |
| 125 | + async def start_transfer( |
| 126 | + self, |
| 127 | + source_machine: Union[Machine, str], |
| 128 | + target_machine: Union[Machine, str], |
| 129 | + source_dir: Union[str, Path, AsyncRemotePath], |
| 130 | + target_dir: Union[str, Path, AsyncRemotePath], |
| 131 | + label: Optional[str] = None, |
| 132 | + ) -> AsyncGlobusTransfer: |
| 133 | + """Start a Globus transfer throught the SuperFacility API |
| 134 | +
|
| 135 | + - Must select the Globus option when creating the SuperFacility key |
| 136 | +
|
| 137 | + ```python |
| 138 | + >>> from sfapi_client import AsyncClient |
| 139 | + >>> async with AsyncClient(client_id, client_secret) as client: |
| 140 | + >>> globus_client = client.storage.globus() |
| 141 | + >>> res = await globus_client.start_transfer( |
| 142 | + Machine.Perlmutter, |
| 143 | + "/pscratch/sd/u/user/globus", |
| 144 | + Machine.dtns, |
| 145 | + "/global/cfs/cdirs/m0000/globus" |
| 146 | + ) |
| 147 | + ``` |
| 148 | +
|
| 149 | + :param str source_dir: Path to file or directory on the source to transfer |
| 150 | + :param str target_dir: Path to directory on the target to transfer files to |
| 151 | + :param Optional[str] label: Label for the transfer, |
| 152 | + defaults to None and the API will create a label for the transfer |
| 153 | + :return AsyncGlobusTransfer |
| 154 | + """ |
| 155 | + |
| 156 | + if None in [source_machine, source_dir, target_machine, target_dir]: |
| 157 | + # Check that all parametes are not none |
| 158 | + raise ValueError("sources, and targets cannot be None") |
| 159 | + |
| 160 | + # Make machine names match those in the API endpoint |
| 161 | + source_name = ( |
| 162 | + "dtn" if source_machine in [Machine.dtns, Machine.dtn01] else source_machine |
| 163 | + ) |
| 164 | + target_name = ( |
| 165 | + "dtn" if target_machine in [Machine.dtns, Machine.dtn01] else target_machine |
| 166 | + ) |
| 167 | + |
| 168 | + body = GlobusBodyPost( |
| 169 | + source_uuid=source_name, |
| 170 | + target_uuid=target_name, |
| 171 | + source_dir=str(source_dir), |
| 172 | + target_dir=str(target_dir), |
| 173 | + label=label, |
| 174 | + ) |
| 175 | + |
| 176 | + r = await self.client.post("storage/globus/transfer", data=body.model_dump()) |
| 177 | + new_transfer = GlobusTransferModel.model_validate(r.json()) |
| 178 | + transfer_id = new_transfer.transfer_id |
| 179 | + r = await self.client.get(f"storage/globus/transfer/{transfer_id}") |
| 180 | + json_response = r.json() |
| 181 | + json_response["transfer_id"] = transfer_id |
| 182 | + json_response["globus"] = self |
| 183 | + transfer = AsyncGlobusTransfer.model_validate(json_response) |
| 184 | + return transfer |
| 185 | + |
| 186 | + @check_auth |
| 187 | + async def transfer(self, transfer_id: str) -> GlobusTransferResult: |
| 188 | + """Check on Globus transfer status |
| 189 | +
|
| 190 | + - Must select the Globus option when creating the SuperFacility key |
| 191 | +
|
| 192 | + >>> from sfapi_client import AsyncClient |
| 193 | + >>> async with AsyncClient(client_id, client_secret) as client: |
| 194 | + >>> globus = client.storage.globus() |
| 195 | + >>> res = await globus.transfer( |
| 196 | + "globus-transfer-uuid" |
| 197 | + ) |
| 198 | +
|
| 199 | + :param str transfer_uuid: Globus UUID for the transfer |
| 200 | + :return GlobusTransferResult |
| 201 | + """ |
| 202 | + if transfer_id is None: |
| 203 | + raise ValueError("Must provide a transfer_uuid") |
| 204 | + |
| 205 | + r = await self.client.get(f"storage/globus/transfer/{transfer_id}") |
| 206 | + json_response = r.json() |
| 207 | + json_response["transfer_id"] = transfer_id |
| 208 | + json_response["globus"] = self |
| 209 | + transfer = AsyncGlobusTransfer.model_validate(json_response) |
| 210 | + return transfer |
0 commit comments