ansys-hps-data-transfer-client 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ansys/hps/data_transfer/client/__init__.py +27 -0
- ansys/hps/data_transfer/client/__version__.py +32 -0
- ansys/hps/data_transfer/client/api/__init__.py +24 -0
- ansys/hps/data_transfer/client/api/api.py +327 -0
- ansys/hps/data_transfer/client/api/async_api.py +249 -0
- ansys/hps/data_transfer/client/api/retry.py +95 -0
- ansys/hps/data_transfer/client/authenticate.py +122 -0
- ansys/hps/data_transfer/client/binary.py +407 -0
- ansys/hps/data_transfer/client/client.py +618 -0
- ansys/hps/data_transfer/client/exceptions.py +150 -0
- ansys/hps/data_transfer/client/models/__init__.py +29 -0
- ansys/hps/data_transfer/client/models/common.py +38 -0
- ansys/hps/data_transfer/client/models/core.py +31 -0
- ansys/hps/data_transfer/client/models/metadata.py +43 -0
- ansys/hps/data_transfer/client/models/msg.py +142 -0
- ansys/hps/data_transfer/client/models/ops.py +57 -0
- ansys/hps/data_transfer/client/models/permissions.py +71 -0
- ansys/hps/data_transfer/client/models/rest.py +31 -0
- ansys/hps/data_transfer/client/models/storage.py +34 -0
- ansys/hps/data_transfer/client/token.py +31 -0
- ansys/hps/data_transfer/client/utils/__init__.py +22 -0
- ansys/hps/data_transfer/client/utils/jitter.py +48 -0
- ansys/hps/data_transfer/client/utils/otel_config.py +47 -0
- ansys_hps_data_transfer_client-0.2.0.dist-info/LICENSE +21 -0
- ansys_hps_data_transfer_client-0.2.0.dist-info/METADATA +156 -0
- ansys_hps_data_transfer_client-0.2.0.dist-info/RECORD +27 -0
- ansys_hps_data_transfer_client-0.2.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
#
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""PyHPS Data Transfer is a Python client for Ansys HPC Platform Services (HPS) data transfer."""
|
|
23
|
+
|
|
24
|
+
from .__version__ import __version__
|
|
25
|
+
from .api import AsyncDataTransferApi, DataTransferApi
|
|
26
|
+
from .client import AsyncClient, Client
|
|
27
|
+
from .exceptions import APIError, ClientError, HPSError
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
#
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
"""This module defines the version of the Ansys HPS Data Transfer Client package."""
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
import importlib.metadata as importlib_metadata
|
|
27
|
+
except ModuleNotFoundError: # pragma: no cover
|
|
28
|
+
import importlib_metadata
|
|
29
|
+
|
|
30
|
+
# Read from the pyproject.toml
|
|
31
|
+
# major, minor, patch
|
|
32
|
+
__version__ = importlib_metadata.version("ansys-hps-data-transfer-client")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
#
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
from .api import DataTransferApi
|
|
24
|
+
from .async_api import AsyncDataTransferApi
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
#
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
"""This module provides the core API functionality for interacting with the
|
|
24
|
+
Ansys HPS Data Transfer Client. It includes methods and utilities for performing
|
|
25
|
+
data transfer operations, managing resources, and handling client interactions.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
import textwrap
|
|
30
|
+
import time
|
|
31
|
+
from typing import Dict, List
|
|
32
|
+
|
|
33
|
+
import backoff
|
|
34
|
+
|
|
35
|
+
log = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
import humanfriendly as hf
|
|
38
|
+
|
|
39
|
+
from ..client import Client
|
|
40
|
+
from ..exceptions import TimeoutError
|
|
41
|
+
from ..models.metadata import DataAssignment
|
|
42
|
+
from ..models.msg import (
|
|
43
|
+
CheckPermissionsResponse,
|
|
44
|
+
GetPermissionsResponse,
|
|
45
|
+
OpIdResponse,
|
|
46
|
+
OpsResponse,
|
|
47
|
+
SetMetadataRequest,
|
|
48
|
+
SrcDst,
|
|
49
|
+
Status,
|
|
50
|
+
StorageConfigResponse,
|
|
51
|
+
StoragePath,
|
|
52
|
+
)
|
|
53
|
+
from ..models.ops import Operation, OperationState
|
|
54
|
+
from ..models.permissions import RoleAssignment, RoleQuery
|
|
55
|
+
from ..utils.jitter import get_expo_backoff
|
|
56
|
+
from .retry import retry
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DataTransferApi:
|
|
60
|
+
"""Class for Data transfer API.
|
|
61
|
+
|
|
62
|
+
Parameters
|
|
63
|
+
----------
|
|
64
|
+
client: Client
|
|
65
|
+
Client object.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, client: Client):
|
|
69
|
+
self.dump_mode = "json"
|
|
70
|
+
self.client = client
|
|
71
|
+
|
|
72
|
+
@retry()
|
|
73
|
+
def status(self, wait=False, sleep=5, jitter=True, timeout: float | None = 20.0):
|
|
74
|
+
"""Status of worker binary."""
|
|
75
|
+
|
|
76
|
+
def _sleep():
|
|
77
|
+
log.info(f"Waiting for the worker to be ready on port {self.client.binary_config.port} ...")
|
|
78
|
+
s = backoff.full_jitter(sleep) if jitter else sleep
|
|
79
|
+
time.sleep(s)
|
|
80
|
+
|
|
81
|
+
url = "/"
|
|
82
|
+
start = time.time()
|
|
83
|
+
while True:
|
|
84
|
+
if timeout is not None and (time.time() - start) > timeout:
|
|
85
|
+
raise TimeoutError("Timeout waiting for worker to be ready")
|
|
86
|
+
|
|
87
|
+
resp = self.client.session.get(url)
|
|
88
|
+
json = resp.json()
|
|
89
|
+
s = Status(**json)
|
|
90
|
+
if wait and not s.ready:
|
|
91
|
+
_sleep()
|
|
92
|
+
continue
|
|
93
|
+
return s
|
|
94
|
+
|
|
95
|
+
@retry()
|
|
96
|
+
def operations(self, ids: List[str]):
|
|
97
|
+
"""Get a list of operations.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
ids: List[str]
|
|
102
|
+
List of ids.
|
|
103
|
+
"""
|
|
104
|
+
return self._operations(ids)
|
|
105
|
+
|
|
106
|
+
def storages(self):
|
|
107
|
+
"""Get types of storages available on the storage backend."""
|
|
108
|
+
url = "/storage"
|
|
109
|
+
resp = self.client.session.get(url)
|
|
110
|
+
json = resp.json()
|
|
111
|
+
return StorageConfigResponse(**json).storage
|
|
112
|
+
|
|
113
|
+
def copy(self, operations: List[SrcDst]):
|
|
114
|
+
"""Get API response for copying a list of files.
|
|
115
|
+
|
|
116
|
+
Parameters
|
|
117
|
+
----------
|
|
118
|
+
operations: List[SrcDst]
|
|
119
|
+
"""
|
|
120
|
+
return self._exec_operation_req("copy", operations)
|
|
121
|
+
|
|
122
|
+
def exists(self, operations: List[StoragePath]):
|
|
123
|
+
"""Check if a path exists.
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
operations: List[StoragePath]
|
|
128
|
+
"""
|
|
129
|
+
return self._exec_operation_req("exists", operations)
|
|
130
|
+
|
|
131
|
+
def list(self, operations: List[StoragePath]):
|
|
132
|
+
"""List files in a path.
|
|
133
|
+
|
|
134
|
+
Parameters
|
|
135
|
+
----------
|
|
136
|
+
operations: List[StoragePath]
|
|
137
|
+
"""
|
|
138
|
+
return self._exec_operation_req("list", operations)
|
|
139
|
+
|
|
140
|
+
def mkdir(self, operations: List[StoragePath]):
|
|
141
|
+
"""Create a dir.
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
operations: List[StoragePath]
|
|
146
|
+
"""
|
|
147
|
+
return self._exec_operation_req("mkdir", operations)
|
|
148
|
+
|
|
149
|
+
def move(self, operations: List[SrcDst]):
|
|
150
|
+
"""Move a file on the backend storage.
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
operations: List[SrcDst]
|
|
155
|
+
"""
|
|
156
|
+
return self._exec_operation_req("move", operations)
|
|
157
|
+
|
|
158
|
+
def remove(self, operations: List[StoragePath]):
|
|
159
|
+
"""Delete a file.
|
|
160
|
+
|
|
161
|
+
Parameters
|
|
162
|
+
----------
|
|
163
|
+
operations: List[StoragePath]
|
|
164
|
+
"""
|
|
165
|
+
return self._exec_operation_req("remove", operations)
|
|
166
|
+
|
|
167
|
+
def rmdir(self, operations: List[StoragePath]):
|
|
168
|
+
"""Delete a dir.
|
|
169
|
+
|
|
170
|
+
Parameters
|
|
171
|
+
----------
|
|
172
|
+
operations: List[StoragePath]
|
|
173
|
+
"""
|
|
174
|
+
return self._exec_operation_req("rmdir", operations)
|
|
175
|
+
|
|
176
|
+
@retry()
|
|
177
|
+
def _exec_operation_req(self, storage_operation: str, operations: List[StoragePath] | List[SrcDst]):
|
|
178
|
+
url = f"/storage:{storage_operation}"
|
|
179
|
+
payload = {"operations": [operation.model_dump(mode=self.dump_mode) for operation in operations]}
|
|
180
|
+
resp = self.client.session.post(url, json=payload)
|
|
181
|
+
json = resp.json()
|
|
182
|
+
r = OpIdResponse(**json)
|
|
183
|
+
return r
|
|
184
|
+
|
|
185
|
+
def _operations(self, ids: List[str]):
|
|
186
|
+
url = "/operations"
|
|
187
|
+
resp = self.client.session.get(url, params={"ids": ids})
|
|
188
|
+
json = resp.json()
|
|
189
|
+
return OpsResponse(**json).operations
|
|
190
|
+
|
|
191
|
+
@retry()
|
|
192
|
+
def check_permissions(self, permissions: List[RoleAssignment]):
|
|
193
|
+
"""Checks permissions of a path (including parent directory) using a list of RoleAssignment objects.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
permissions: List[RoleAssignment]
|
|
198
|
+
"""
|
|
199
|
+
url = "/permissions:check"
|
|
200
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
201
|
+
resp = self.client.session.post(url, json=payload)
|
|
202
|
+
json = resp.json()
|
|
203
|
+
return CheckPermissionsResponse(**json)
|
|
204
|
+
|
|
205
|
+
@retry()
|
|
206
|
+
def get_permissions(self, permissions: List[RoleQuery]):
|
|
207
|
+
"""Return permissions of a file from a list of RoleQuery objects.
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
permissions: List[RoleQuery]
|
|
212
|
+
"""
|
|
213
|
+
url = "/permissions:get"
|
|
214
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
215
|
+
resp = self.client.session.post(url, json=payload)
|
|
216
|
+
json = resp.json()
|
|
217
|
+
return GetPermissionsResponse(**json)
|
|
218
|
+
|
|
219
|
+
@retry()
|
|
220
|
+
def remove_permissions(self, permissions: List[RoleAssignment]):
|
|
221
|
+
"""Remove permissions using a list of RoleAssignment objects.
|
|
222
|
+
|
|
223
|
+
Parameters
|
|
224
|
+
----------
|
|
225
|
+
permissions: List[RoleAssignment]
|
|
226
|
+
"""
|
|
227
|
+
url = "/permissions:remove"
|
|
228
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
229
|
+
self.client.session.post(url, json=payload)
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
@retry()
|
|
233
|
+
def set_permissions(self, permissions: List[RoleAssignment]):
|
|
234
|
+
"""Set permissions using a list of RoleAssignment objects.
|
|
235
|
+
|
|
236
|
+
Parameters
|
|
237
|
+
----------
|
|
238
|
+
permissions: List[RoleAssignment]
|
|
239
|
+
"""
|
|
240
|
+
url = "/permissions:set"
|
|
241
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
242
|
+
self.client.session.post(url, json=payload)
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
@retry()
|
|
246
|
+
def get_metadata(self, paths: List[str | StoragePath]):
|
|
247
|
+
"""Get metadata of a path on backend storage.
|
|
248
|
+
|
|
249
|
+
Parameters
|
|
250
|
+
----------
|
|
251
|
+
paths: List[str | StoragePath]
|
|
252
|
+
"""
|
|
253
|
+
url = "/metadata:get"
|
|
254
|
+
paths = [p if isinstance(p, str) else p.path for p in paths]
|
|
255
|
+
payload = {"paths": paths}
|
|
256
|
+
resp = self.client.session.post(url, json=payload)
|
|
257
|
+
json = resp.json()
|
|
258
|
+
return OpIdResponse(**json)
|
|
259
|
+
|
|
260
|
+
@retry()
|
|
261
|
+
def set_metadata(self, asgs: Dict[str | StoragePath, DataAssignment]):
|
|
262
|
+
"""Setting metadata for a path on backend storage.
|
|
263
|
+
|
|
264
|
+
Parameters
|
|
265
|
+
----------
|
|
266
|
+
asgs: Dict[str | StoragePath, DataAssignment]
|
|
267
|
+
List of paths with key of type string or StoragePath and value of DataAssignment
|
|
268
|
+
"""
|
|
269
|
+
url = "/metadata:set"
|
|
270
|
+
d = {k if isinstance(k, str) else k.path: v for k, v in asgs.items()}
|
|
271
|
+
req = SetMetadataRequest(metadata=d)
|
|
272
|
+
resp = self.client.session.post(url, json=req.model_dump(mode=self.dump_mode))
|
|
273
|
+
json = resp.json()
|
|
274
|
+
return OpIdResponse(**json)
|
|
275
|
+
|
|
276
|
+
def wait_for(
|
|
277
|
+
self,
|
|
278
|
+
operation_ids: List[str | Operation | OpIdResponse],
|
|
279
|
+
timeout: float | None = None,
|
|
280
|
+
interval: float = 0.1,
|
|
281
|
+
cap: float = 2.0,
|
|
282
|
+
raise_on_error: bool = False,
|
|
283
|
+
):
|
|
284
|
+
"""Wait for operations to complete."""
|
|
285
|
+
if not isinstance(operation_ids, list):
|
|
286
|
+
operation_ids = [operation_ids]
|
|
287
|
+
operation_ids = [op.id if isinstance(op, (Operation, OpIdResponse)) else op for op in operation_ids]
|
|
288
|
+
start = time.time()
|
|
289
|
+
attempt = 0
|
|
290
|
+
op_str = textwrap.wrap(", ".join(operation_ids), width=60, placeholder="...")
|
|
291
|
+
# log.debug(f"Waiting for operations to complete: {op_str}")
|
|
292
|
+
while True:
|
|
293
|
+
attempt += 1
|
|
294
|
+
try:
|
|
295
|
+
ops = self._operations(operation_ids)
|
|
296
|
+
so_far = hf.format_timespan(time.time() - start)
|
|
297
|
+
log.debug(f"Waiting for {len(operation_ids)} operations to complete, {so_far} so far")
|
|
298
|
+
if self.client.binary_config.debug:
|
|
299
|
+
for op in ops:
|
|
300
|
+
fields = [
|
|
301
|
+
f"id={op.id}",
|
|
302
|
+
f"state={op.state}",
|
|
303
|
+
f"start={op.started_at}",
|
|
304
|
+
f"succeeded_on={op.succeeded_on}",
|
|
305
|
+
]
|
|
306
|
+
if op.progress > 0:
|
|
307
|
+
fields.append(f"progress={op.progress:.3f}")
|
|
308
|
+
log.debug(f"- Operation '{op.description}' {' '.join(fields)}")
|
|
309
|
+
if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
|
|
310
|
+
break
|
|
311
|
+
except Exception as e:
|
|
312
|
+
log.debug(f"Error getting operations: {e}")
|
|
313
|
+
if raise_on_error:
|
|
314
|
+
raise
|
|
315
|
+
|
|
316
|
+
if timeout is not None and (time.time() - start) > timeout:
|
|
317
|
+
raise TimeoutError("Timeout waiting for operations to complete")
|
|
318
|
+
|
|
319
|
+
# TODO: Adjust based on transfer speed and file size
|
|
320
|
+
duration = get_expo_backoff(interval, attempts=attempt, cap=cap, jitter=True)
|
|
321
|
+
if self.client.binary_config.debug:
|
|
322
|
+
log.debug(f"Next check in {hf.format_timespan(duration)} ...")
|
|
323
|
+
time.sleep(duration)
|
|
324
|
+
|
|
325
|
+
duration = hf.format_timespan(time.time() - start)
|
|
326
|
+
log.debug(f"Operations completed after {duration}: {op_str}")
|
|
327
|
+
return ops
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Copyright (C) 2022 - 2025 ANSYS, Inc. and/or its affiliates.
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
#
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
"""This module provides asynchronous API functionality for interacting with the
|
|
24
|
+
Ansys HPS Data Transfer Client. It includes methods and utilities for performing
|
|
25
|
+
data transfer operations asynchronously, managing resources, and handling client interactions.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import asyncio
|
|
29
|
+
import logging
|
|
30
|
+
import textwrap
|
|
31
|
+
import time
|
|
32
|
+
from typing import Dict, List
|
|
33
|
+
|
|
34
|
+
import backoff
|
|
35
|
+
import humanfriendly as hf
|
|
36
|
+
|
|
37
|
+
from ..client import AsyncClient
|
|
38
|
+
from ..exceptions import TimeoutError
|
|
39
|
+
from ..models.metadata import DataAssignment
|
|
40
|
+
from ..models.msg import (
|
|
41
|
+
CheckPermissionsResponse,
|
|
42
|
+
GetPermissionsResponse,
|
|
43
|
+
OpIdResponse,
|
|
44
|
+
OpsResponse,
|
|
45
|
+
SetMetadataRequest,
|
|
46
|
+
SrcDst,
|
|
47
|
+
Status,
|
|
48
|
+
StorageConfigResponse,
|
|
49
|
+
StoragePath,
|
|
50
|
+
)
|
|
51
|
+
from ..models.ops import Operation, OperationState
|
|
52
|
+
from ..models.permissions import RoleAssignment, RoleQuery
|
|
53
|
+
from ..utils.jitter import get_expo_backoff
|
|
54
|
+
from .retry import retry
|
|
55
|
+
|
|
56
|
+
log = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AsyncDataTransferApi:
|
|
60
|
+
"""Wrapper for the Data Transfer Worker REST API, offering an async interface."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, client: AsyncClient):
|
|
63
|
+
self.dump_mode = "json"
|
|
64
|
+
self.client = client
|
|
65
|
+
|
|
66
|
+
@retry()
|
|
67
|
+
async def status(self, wait=False, sleep=5, jitter=True, timeout: float | None = 20.0):
|
|
68
|
+
"""Async interface to get the status of the worker."""
|
|
69
|
+
|
|
70
|
+
async def _sleep():
|
|
71
|
+
log.info(f"Waiting for the worker to be ready on port {self.client.binary_config.port} ...")
|
|
72
|
+
s = backoff.full_jitter(sleep) if jitter else sleep
|
|
73
|
+
|
|
74
|
+
await asyncio.sleep(s)
|
|
75
|
+
|
|
76
|
+
url = "/"
|
|
77
|
+
start = time.time()
|
|
78
|
+
while True:
|
|
79
|
+
if timeout is not None and (time.time() - start) > timeout:
|
|
80
|
+
raise TimeoutError("Timeout waiting for worker to be ready")
|
|
81
|
+
|
|
82
|
+
resp = await self.client.session.get(url)
|
|
83
|
+
json = resp.json()
|
|
84
|
+
s = Status(**json)
|
|
85
|
+
if wait and not s.ready:
|
|
86
|
+
await _sleep()
|
|
87
|
+
continue
|
|
88
|
+
return s
|
|
89
|
+
|
|
90
|
+
@retry()
|
|
91
|
+
async def operations(self, ids: List[str]):
|
|
92
|
+
"""Async interface to get a list of operations by their ids."""
|
|
93
|
+
return await self._operations(ids)
|
|
94
|
+
|
|
95
|
+
async def storages(self):
|
|
96
|
+
"""Async interface to get the list of storage configurations."""
|
|
97
|
+
url = "/storage"
|
|
98
|
+
resp = await self.client.session.get(url)
|
|
99
|
+
json = resp.json()
|
|
100
|
+
return StorageConfigResponse(**json).storage
|
|
101
|
+
|
|
102
|
+
async def copy(self, operations: List[SrcDst]):
|
|
103
|
+
"""Async interface to copy a list of SrcDst objects."""
|
|
104
|
+
return await self._exec_async_operation_req("copy", operations)
|
|
105
|
+
|
|
106
|
+
async def exists(self, operations: List[StoragePath]):
|
|
107
|
+
"""Async interface to check if a list of StoragePath objects exist."""
|
|
108
|
+
return await self._exec_async_operation_req("exists", operations)
|
|
109
|
+
|
|
110
|
+
async def list(self, operations: List[StoragePath]):
|
|
111
|
+
"""Async interface to list a list of StoragePath objects."""
|
|
112
|
+
return await self._exec_async_operation_req("list", operations)
|
|
113
|
+
|
|
114
|
+
async def mkdir(self, operations: List[StoragePath]):
|
|
115
|
+
"""Async interface to create a list of directories on remote backend."""
|
|
116
|
+
return await self._exec_async_operation_req("mkdir", operations)
|
|
117
|
+
|
|
118
|
+
async def move(self, operations: List[SrcDst]):
|
|
119
|
+
"""Async interface to move a list of SrcDst objects in the remote backend."""
|
|
120
|
+
return await self._exec_async_operation_req("move", operations)
|
|
121
|
+
|
|
122
|
+
async def remove(self, operations: List[StoragePath]):
|
|
123
|
+
"""Async interface to remove files in the remote backend."""
|
|
124
|
+
return await self._exec_async_operation_req("remove", operations)
|
|
125
|
+
|
|
126
|
+
async def rmdir(self, operations: List[StoragePath]):
|
|
127
|
+
"""Async interface to remove directories in the remote backend."""
|
|
128
|
+
return await self._exec_async_operation_req("rmdir", operations)
|
|
129
|
+
|
|
130
|
+
@retry()
|
|
131
|
+
async def _exec_async_operation_req(self, storage_operation: str, operations: List[StoragePath] | List[SrcDst]):
|
|
132
|
+
url = f"/storage:{storage_operation}"
|
|
133
|
+
payload = {"operations": [operation.model_dump(mode=self.dump_mode) for operation in operations]}
|
|
134
|
+
resp = await self.client.session.post(url, json=payload)
|
|
135
|
+
json = resp.json()
|
|
136
|
+
return OpIdResponse(**json)
|
|
137
|
+
|
|
138
|
+
async def _operations(self, ids: List[str]):
|
|
139
|
+
url = "/operations"
|
|
140
|
+
resp = await self.client.session.get(url, params={"ids": ids})
|
|
141
|
+
json = resp.json()
|
|
142
|
+
return OpsResponse(**json).operations
|
|
143
|
+
|
|
144
|
+
@retry()
|
|
145
|
+
async def check_permissions(self, permissions: List[RoleAssignment]):
|
|
146
|
+
"""Async interface to check permissions of a list of RoleAssignment objects."""
|
|
147
|
+
url = "/permissions:check"
|
|
148
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
149
|
+
resp = await self.client.session.post(url, json=payload)
|
|
150
|
+
json = resp.json()
|
|
151
|
+
return CheckPermissionsResponse(**json)
|
|
152
|
+
|
|
153
|
+
@retry()
|
|
154
|
+
async def get_permissions(self, permissions: List[RoleQuery]):
|
|
155
|
+
"""Async interface to get permissions of a list of RoleQuery objects."""
|
|
156
|
+
url = "/permissions:get"
|
|
157
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
158
|
+
resp = await self.client.session.post(url, json=payload)
|
|
159
|
+
json = resp.json()
|
|
160
|
+
return GetPermissionsResponse(**json)
|
|
161
|
+
|
|
162
|
+
@retry()
|
|
163
|
+
async def remove_permissions(self, permissions: List[RoleAssignment]):
|
|
164
|
+
"""Async interface to remove permissions of a list of RoleAssignment objects."""
|
|
165
|
+
url = "/permissions:remove"
|
|
166
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
167
|
+
await self.client.session.post(url, json=payload)
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
@retry()
|
|
171
|
+
async def set_permissions(self, permissions: List[RoleAssignment]):
|
|
172
|
+
"""Async interface to set permissions of a list of RoleAssignment objects."""
|
|
173
|
+
url = "/permissions:set"
|
|
174
|
+
payload = {"permissions": [permission.model_dump(mode=self.dump_mode) for permission in permissions]}
|
|
175
|
+
await self.client.session.post(url, json=payload)
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
@retry()
|
|
179
|
+
async def get_metadata(self, paths: List[str | StoragePath]):
|
|
180
|
+
"""Async interface to get metadata of a list of StoragePath objects."""
|
|
181
|
+
url = "/metadata:get"
|
|
182
|
+
paths = [p if isinstance(p, str) else p.path for p in paths]
|
|
183
|
+
payload = {"paths": paths}
|
|
184
|
+
resp = await self.client.session.post(url, json=payload)
|
|
185
|
+
json = resp.json()
|
|
186
|
+
return OpIdResponse(**json)
|
|
187
|
+
|
|
188
|
+
@retry()
|
|
189
|
+
async def set_metadata(self, asgs: Dict[str | StoragePath, DataAssignment]):
|
|
190
|
+
"""Async interface to set metadata of a list of DataAssignment objects."""
|
|
191
|
+
url = "/metadata:set"
|
|
192
|
+
d = {k if isinstance(k, str) else k.path: v for k, v in asgs.items()}
|
|
193
|
+
req = SetMetadataRequest(metadata=d)
|
|
194
|
+
resp = await self.client.session.post(url, json=req.model_dump(mode=self.dump_mode))
|
|
195
|
+
json = resp.json()
|
|
196
|
+
return OpIdResponse(**json)
|
|
197
|
+
|
|
198
|
+
async def wait_for(
|
|
199
|
+
self,
|
|
200
|
+
operation_ids: List[str | Operation],
|
|
201
|
+
timeout: float | None = None,
|
|
202
|
+
interval: float = 0.1,
|
|
203
|
+
cap: float = 2.0,
|
|
204
|
+
raise_on_error: bool = False,
|
|
205
|
+
):
|
|
206
|
+
"""Async interface to wait for a list of operations to complete."""
|
|
207
|
+
if not isinstance(operation_ids, list):
|
|
208
|
+
operation_ids = [operation_ids]
|
|
209
|
+
operation_ids = [op.id if isinstance(op, (Operation, OpIdResponse)) else op for op in operation_ids]
|
|
210
|
+
start = time.time()
|
|
211
|
+
attempt = 0
|
|
212
|
+
op_str = textwrap.wrap(", ".join(operation_ids), width=60, placeholder="...")
|
|
213
|
+
# log.debug(f"Waiting for operations to complete: {op_str}")
|
|
214
|
+
while True:
|
|
215
|
+
attempt += 1
|
|
216
|
+
try:
|
|
217
|
+
ops = await self._operations(operation_ids)
|
|
218
|
+
so_far = hf.format_timespan(time.time() - start)
|
|
219
|
+
log.debug(f"Waiting for {len(operation_ids)} operations to complete, {so_far} so far")
|
|
220
|
+
if self.client.binary_config.debug:
|
|
221
|
+
for op in ops:
|
|
222
|
+
fields = [
|
|
223
|
+
f"id={op.id}",
|
|
224
|
+
f"state={op.state}",
|
|
225
|
+
f"start={op.started_at}",
|
|
226
|
+
f"succeeded_on={op.succeeded_on}",
|
|
227
|
+
]
|
|
228
|
+
if op.progress > 0:
|
|
229
|
+
fields.append(f"progress={op.progress:.3f}")
|
|
230
|
+
log.debug(f"- Operation '{op.description}' {' '.join(fields)}")
|
|
231
|
+
if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
|
|
232
|
+
break
|
|
233
|
+
except Exception as e:
|
|
234
|
+
log.debug(f"Error getting operations: {e}")
|
|
235
|
+
if raise_on_error:
|
|
236
|
+
raise
|
|
237
|
+
|
|
238
|
+
if timeout is not None and (time.time() - start) > timeout:
|
|
239
|
+
raise TimeoutError("Timeout waiting for operations to complete")
|
|
240
|
+
|
|
241
|
+
# TODO: Adjust based on transfer speed and file size
|
|
242
|
+
duration = get_expo_backoff(interval, attempts=attempt, cap=cap, jitter=True)
|
|
243
|
+
if self.client.binary_config.debug:
|
|
244
|
+
log.debug(f"Next check in {hf.format_timespan(duration)} ...")
|
|
245
|
+
await asyncio.sleep(duration)
|
|
246
|
+
|
|
247
|
+
duration = hf.format_timespan(time.time() - start)
|
|
248
|
+
log.debug(f"Operations completed after {duration}: {op_str}")
|
|
249
|
+
return ops
|