ansys-hps-data-transfer-client 0.3.0__tar.gz → 0.4.dev0__tar.gz

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.
Files changed (28) hide show
  1. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/PKG-INFO +5 -5
  2. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/pyproject.toml +5 -5
  3. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/__init__.py +1 -0
  4. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/api/__init__.py +1 -0
  5. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/api/api.py +25 -32
  6. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/api/async_api.py +27 -27
  7. ansys_hps_data_transfer_client-0.4.dev0/src/ansys/hps/data_transfer/client/api/handler.py +123 -0
  8. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/binary.py +85 -47
  9. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/client.py +58 -16
  10. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/ops.py +5 -0
  11. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/LICENSE +0 -0
  12. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/README.rst +0 -0
  13. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/__version__.py +0 -0
  14. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/api/retry.py +0 -0
  15. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/authenticate.py +0 -0
  16. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/exceptions.py +0 -0
  17. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/__init__.py +0 -0
  18. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/common.py +0 -0
  19. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/core.py +0 -0
  20. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/metadata.py +0 -0
  21. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/msg.py +0 -0
  22. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/permissions.py +0 -0
  23. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/rest.py +0 -0
  24. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/models/storage.py +0 -0
  25. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/token.py +0 -0
  26. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/utils/__init__.py +0 -0
  27. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/utils/jitter.py +0 -0
  28. {ansys_hps_data_transfer_client-0.3.0 → ansys_hps_data_transfer_client-0.4.dev0}/src/ansys/hps/data_transfer/client/utils/otel_config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: ansys-hps-data-transfer-client
3
- Version: 0.3.0
3
+ Version: 0.4.dev0
4
4
  Summary: Python client library for hps data transfer service
5
5
  Author-email: "ANSYS, Inc." <pyansys.core@ansys.com>
6
6
  Maintainer-email: "ANSYS, Inc." <pyansys.core@ansys.com>
@@ -24,8 +24,8 @@ Requires-Dist: asyncio-atexit>=1.0.0
24
24
  Requires-Dist: build==1.2.2.post1 ; extra == "build"
25
25
  Requires-Dist: twine==6.1.0 ; extra == "build"
26
26
  Requires-Dist: wheel ; extra == "build"
27
- Requires-Dist: datamodel-code-generator==0.32.0 ; extra == "build"
28
- Requires-Dist: pre-commit==4.2.0 ; extra == "build"
27
+ Requires-Dist: datamodel-code-generator==0.33.0 ; extra == "build"
28
+ Requires-Dist: pre-commit==4.3.0 ; extra == "build"
29
29
  Requires-Dist: importlib_metadata>=7.0 ; extra == "build"
30
30
  Requires-Dist: ansys-sphinx-theme==1.5.2 ; extra == "doc"
31
31
  Requires-Dist: autodoc_pydantic==2.2.0 ; extra == "doc"
@@ -49,9 +49,9 @@ Requires-Dist: pytest-timeout==2.4.0 ; extra == "tests"
49
49
  Requires-Dist: pytest-mock-resources[redis]==2.12.2 ; extra == "tests"
50
50
  Requires-Dist: pytest-rerunfailures==15.1 ; extra == "tests"
51
51
  Requires-Dist: pytest-asyncio==1.1.0 ; extra == "tests"
52
- Requires-Dist: python-keycloak==5.7.0 ; extra == "tests"
52
+ Requires-Dist: python-keycloak==5.8.1 ; extra == "tests"
53
53
  Requires-Dist: python-slugify>=8.0.4 ; extra == "tests"
54
- Requires-Dist: tox==4.28.4 ; extra == "tests"
54
+ Requires-Dist: tox==4.29.0 ; extra == "tests"
55
55
  Project-URL: Documentation, https://data-transfer.hps.docs.pyansys.com
56
56
  Project-URL: Homepage, https://github.com/ansys/pyhps-data-transfer/
57
57
  Project-URL: Source, https://github.com/ansys/pyhps-data-transfer/
@@ -5,7 +5,7 @@ build-backend = "flit_core.buildapi"
5
5
  [project]
6
6
  # Check https://flit.readthedocs.io/en/latest/pyproject_toml.html for all available sections
7
7
  name = "ansys-hps-data-transfer-client"
8
- version = "0.3.0"
8
+ version = "0.4.dev0"
9
9
  description = "Python client library for hps data transfer service"
10
10
  readme = "README.rst"
11
11
  requires-python = ">=3.10,<4.0"
@@ -45,9 +45,9 @@ tests = [
45
45
  "pytest-mock-resources[redis]==2.12.2",
46
46
  "pytest-rerunfailures==15.1",
47
47
  "pytest-asyncio==1.1.0",
48
- "python-keycloak==5.7.0",
48
+ "python-keycloak==5.8.1",
49
49
  "python-slugify>=8.0.4",
50
- "tox==4.28.4",
50
+ "tox==4.29.0",
51
51
  ]
52
52
  doc = [
53
53
  "ansys-sphinx-theme==1.5.2",
@@ -72,8 +72,8 @@ build = [
72
72
  "build==1.2.2.post1",
73
73
  "twine==6.1.0",
74
74
  "wheel",
75
- "datamodel-code-generator==0.32.0",
76
- "pre-commit==4.2.0",
75
+ "datamodel-code-generator==0.33.0",
76
+ "pre-commit==4.3.0",
77
77
  "importlib_metadata>=7.0",
78
78
  ]
79
79
 
@@ -23,5 +23,6 @@
23
23
 
24
24
  from .__version__ import __version__
25
25
  from .api import AsyncDataTransferApi, DataTransferApi
26
+ from .binary import get_log_level
26
27
  from .client import AsyncClient, Client
27
28
  from .exceptions import APIError, ClientError, HPSError
@@ -24,3 +24,4 @@
24
24
 
25
25
  from .api import DataTransferApi
26
26
  from .async_api import AsyncDataTransferApi
27
+ from .handler import AsyncWaitHandler, WaitHandler
@@ -29,11 +29,10 @@ data transfer operations, managing resources, and handling client interactions.
29
29
  import builtins
30
30
  from collections.abc import Callable
31
31
  import logging
32
- import textwrap
33
32
  import time
33
+ import traceback
34
34
 
35
35
  import backoff
36
- import humanfriendly as hf
37
36
 
38
37
  from ..client import Client
39
38
  from ..exceptions import TimeoutError
@@ -52,6 +51,7 @@ from ..models.msg import (
52
51
  from ..models.ops import Operation, OperationState
53
52
  from ..models.permissions import RoleAssignment, RoleQuery
54
53
  from ..utils.jitter import get_expo_backoff
54
+ from .handler import WaitHandler
55
55
  from .retry import retry
56
56
 
57
57
  log = logging.getLogger(__name__)
@@ -70,6 +70,7 @@ class DataTransferApi:
70
70
  """Initializes the DataTransferApi class object."""
71
71
  self.dump_mode = "json"
72
72
  self.client = client
73
+ self.wait_handler_factory = WaitHandler
73
74
 
74
75
  @retry()
75
76
  def status(self, wait=False, sleep=5, jitter=True, timeout: float | None = 20.0):
@@ -95,7 +96,7 @@ class DataTransferApi:
95
96
  return s
96
97
 
97
98
  @retry()
98
- def operations(self, ids: list[str]):
99
+ def operations(self, ids: list[str], expand: bool = False):
99
100
  """Get a list of operations.
100
101
 
101
102
  Parameters
@@ -103,7 +104,7 @@ class DataTransferApi:
103
104
  ids: List[str]
104
105
  List of IDs.
105
106
  """
106
- return self._operations(ids)
107
+ return self._operations(ids, expand=expand)
107
108
 
108
109
  def storages(self):
109
110
  """Get types of storages available on the storage backend."""
@@ -186,9 +187,12 @@ class DataTransferApi:
186
187
  r = OpIdResponse(**json)
187
188
  return r
188
189
 
189
- def _operations(self, ids: builtins.list[str]):
190
+ def _operations(self, ids: builtins.list[str], expand: bool = False):
190
191
  url = "/operations"
191
- resp = self.client.session.get(url, params={"ids": ids})
192
+ params = {"ids": ids}
193
+ if expand:
194
+ params["expand"] = "true"
195
+ resp = self.client.session.get(url, params=params)
192
196
  json = resp.json()
193
197
  return OpsResponse(**json).operations
194
198
 
@@ -282,7 +286,7 @@ class DataTransferApi:
282
286
  interval: float = 0.1,
283
287
  cap: float = 2.0,
284
288
  raise_on_error: bool = False,
285
- progress_handler: Callable[[str, float], None] = None,
289
+ handler: Callable[[builtins.list[Operation]], None] = None,
286
290
  ):
287
291
  """Wait for operations to complete.
288
292
 
@@ -298,36 +302,29 @@ class DataTransferApi:
298
302
  The maximum backoff value used to calculate the next wait time. Default is 2.0.
299
303
  raise_on_error: bool
300
304
  Raise an exception if an error occurs. Default is False.
301
- progress_handler: Callable[[str, float], None]
302
- A function to handle progress updates. Default is None.
305
+ operation_handler: Callable[[builtins.list[Operation]], None]
306
+ A callable that will be called with the list of operations when they are fetched.
303
307
  """
308
+ if handler is None:
309
+ handler = self.wait_handler_factory()
310
+
304
311
  if not isinstance(operation_ids, list):
305
312
  operation_ids = [operation_ids]
306
313
  operation_ids = [op.id if isinstance(op, Operation | OpIdResponse) else op for op in operation_ids]
307
314
  start = time.time()
308
315
  attempt = 0
309
- op_str = textwrap.wrap(", ".join(operation_ids), width=60, placeholder="...")
310
- # log.debug(f"Waiting for operations to complete: {op_str}")
311
316
  while True:
312
317
  attempt += 1
313
318
  try:
314
- ops = self._operations(operation_ids)
315
- so_far = hf.format_timespan(time.time() - start)
316
- log.debug(f"Waiting for {len(operation_ids)} operations to complete, {so_far} so far")
317
- if self.client.binary_config.debug:
318
- for op in ops:
319
- fields = [
320
- f"id={op.id}",
321
- f"state={op.state}",
322
- f"start={op.started_at}",
323
- f"succeeded_on={op.succeeded_on}",
324
- ]
325
- if op.progress > 0:
326
- fields.append(f"progress={op.progress:.3f}")
327
- log.debug(f"- Operation '{op.description}' {' '.join(fields)}")
328
- if progress_handler is not None:
329
- for op in ops:
330
- progress_handler(op.id, op.progress)
319
+ expand = getattr(handler.Meta, "expand_group", False) if hasattr(handler, "Meta") else False
320
+ ops = self._operations(operation_ids, expand=expand)
321
+ if handler is not None:
322
+ try:
323
+ handler(ops)
324
+ except Exception as e:
325
+ log.warning(f"Handler error: {e}")
326
+ log.debug(traceback.format_exc())
327
+
331
328
  if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
332
329
  break
333
330
  except Exception as e:
@@ -340,10 +337,6 @@ class DataTransferApi:
340
337
 
341
338
  # TODO: Adjust based on transfer speed and file size
342
339
  duration = get_expo_backoff(interval, attempts=attempt, cap=cap, jitter=True)
343
- if self.client.binary_config.debug:
344
- log.debug(f"Next check in {hf.format_timespan(duration)} ...")
345
340
  time.sleep(duration)
346
341
 
347
- duration = hf.format_timespan(time.time() - start)
348
- log.debug(f"Operations completed after {duration}: {op_str}")
349
342
  return ops
@@ -32,6 +32,7 @@ from collections.abc import Awaitable, Callable
32
32
  import logging
33
33
  import textwrap
34
34
  import time
35
+ import traceback
35
36
 
36
37
  import backoff
37
38
  import humanfriendly as hf
@@ -53,6 +54,7 @@ from ..models.msg import (
53
54
  from ..models.ops import Operation, OperationState
54
55
  from ..models.permissions import RoleAssignment, RoleQuery
55
56
  from ..utils.jitter import get_expo_backoff
57
+ from .handler import AsyncWaitHandler
56
58
  from .retry import retry
57
59
 
58
60
  log = logging.getLogger(__name__)
@@ -65,6 +67,7 @@ class AsyncDataTransferApi:
65
67
  """Initialize the async data transfer API with the client object."""
66
68
  self.dump_mode = "json"
67
69
  self.client = client
70
+ self.wait_handler_factory = AsyncWaitHandler
68
71
 
69
72
  @retry()
70
73
  async def status(self, wait=False, sleep=5, jitter=True, timeout: float | None = 20.0):
@@ -91,9 +94,9 @@ class AsyncDataTransferApi:
91
94
  return s
92
95
 
93
96
  @retry()
94
- async def operations(self, ids: list[str]):
97
+ async def operations(self, ids: list[str], expand: bool = False):
95
98
  """Provides an async interface to get a list of operations by their IDs."""
96
- return await self._operations(ids)
99
+ return await self._operations(ids, expand=expand)
97
100
 
98
101
  async def storages(self):
99
102
  """Provides an async interface to get the list of storage configurations."""
@@ -140,9 +143,12 @@ class AsyncDataTransferApi:
140
143
  json = resp.json()
141
144
  return OpIdResponse(**json)
142
145
 
143
- async def _operations(self, ids: builtins.list[str]):
146
+ async def _operations(self, ids: builtins.list[str], expand: bool = False):
144
147
  url = "/operations"
145
- resp = await self.client.session.get(url, params={"ids": ids})
148
+ params = {"ids": ids}
149
+ if expand:
150
+ params["expand"] = "true"
151
+ resp = await self.client.session.get(url, params=params)
146
152
  json = resp.json()
147
153
  return OpsResponse(**json).operations
148
154
 
@@ -205,7 +211,7 @@ class AsyncDataTransferApi:
205
211
  interval: float = 0.1,
206
212
  cap: float = 2.0,
207
213
  raise_on_error: bool = False,
208
- progress_handler: Callable[[str, float], Awaitable[None]] = None,
214
+ handler: Callable[[builtins.list[Operation]], Awaitable[None]] = None,
209
215
  ):
210
216
  """Provides an async interface to wait for a list of operations to complete.
211
217
 
@@ -221,10 +227,12 @@ class AsyncDataTransferApi:
221
227
  The maximum backoff value used to calculate the next wait time. Default is 2.0.
222
228
  raise_on_error: bool
223
229
  Raise an exception if an error occurs. Default is False.
224
- progress_handler: Callable[[str, float], None]
225
- A async function to handle progress updates. Default is None.
226
-
230
+ operation_handler: Callable[[builtins.list[Operation]], None]
231
+ A callable that will be called with the list of operations when they are fetched.
227
232
  """
233
+ if handler is None:
234
+ handler = self.wait_handler_factory()
235
+
228
236
  if not isinstance(operation_ids, list):
229
237
  operation_ids = [operation_ids]
230
238
  operation_ids = [op.id if isinstance(op, Operation | OpIdResponse) else op for op in operation_ids]
@@ -235,23 +243,15 @@ class AsyncDataTransferApi:
235
243
  while True:
236
244
  attempt += 1
237
245
  try:
238
- ops = await self._operations(operation_ids)
239
- so_far = hf.format_timespan(time.time() - start)
240
- log.debug(f"Waiting for {len(operation_ids)} operations to complete, {so_far} so far")
241
- if self.client.binary_config.debug:
242
- for op in ops:
243
- fields = [
244
- f"id={op.id}",
245
- f"state={op.state}",
246
- f"start={op.started_at}",
247
- f"succeeded_on={op.succeeded_on}",
248
- ]
249
- if op.progress > 0:
250
- fields.append(f"progress={op.progress:.3f}")
251
- log.debug(f"- Operation '{op.description}' {' '.join(fields)}")
252
- if progress_handler is not None:
253
- for op in ops:
254
- await progress_handler(op.id, op.progress)
246
+ expand = getattr(handler.Meta, "expand_group", False) if hasattr(handler, "Meta") else False
247
+ ops = await self._operations(operation_ids, expand=expand)
248
+ if handler is not None:
249
+ try:
250
+ await handler(ops)
251
+ except Exception as e:
252
+ log.warning(f"Handler error: {e}")
253
+ log.debug(traceback.format_exc())
254
+
255
255
  if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
256
256
  break
257
257
  except Exception as e:
@@ -264,8 +264,8 @@ class AsyncDataTransferApi:
264
264
 
265
265
  # TODO: Adjust based on transfer speed and file size
266
266
  duration = get_expo_backoff(interval, attempts=attempt, cap=cap, jitter=True)
267
- if self.client.binary_config.debug:
268
- log.debug(f"Next check in {hf.format_timespan(duration)} ...")
267
+ # if self.client.binary_config.debug:
268
+ # log.debug(f"Next check in {hf.format_timespan(duration)} ...")
269
269
  await asyncio.sleep(duration)
270
270
 
271
271
  duration = hf.format_timespan(time.time() - start)
@@ -0,0 +1,123 @@
1
+ # Copyright (C) 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
+ """Provides functionality for monitoring of operations."""
24
+
25
+ import datetime
26
+ import logging
27
+ import time
28
+
29
+ from dateutil import parser
30
+ import humanfriendly as hf
31
+
32
+ from ..models.ops import Operation, OperationState
33
+
34
+ log = logging.getLogger(__name__)
35
+
36
+
37
+ class WaitHandler:
38
+ """Allows additional handling of operation status on wait."""
39
+
40
+ class Meta:
41
+ """Meta class for WaitHandler."""
42
+
43
+ expand_group = True
44
+
45
+ final = [OperationState.Succeeded, OperationState.Failed]
46
+
47
+ def __init__(self):
48
+ """Initializes the WaitHandler class object."""
49
+ self.start = time.time()
50
+ self.report_threshold = 2.0 # seconds
51
+ self.min_progress_interval = 3.0 # seconds
52
+ self.last_progress = self.start
53
+
54
+ def __call__(self, ops: list[Operation]):
55
+ """Handle operations after they are fetched."""
56
+ self._log_ops(ops)
57
+
58
+ def _log_ops(self, ops: list[Operation]) -> str:
59
+ # so_far = time.time() - self.start
60
+ num_running = 0
61
+ for op in ops:
62
+ for ch in op.children_detail or []:
63
+ if ch.state not in self.final:
64
+ num_running += 1
65
+ self._log_op(logging.DEBUG, ch)
66
+
67
+ if op.state not in self.final:
68
+ num_running += 1
69
+ self._log_op(logging.INFO, op)
70
+
71
+ def _log_op(self, lvl: int, op: Operation):
72
+ """Format the operation description."""
73
+ op_type = "operation" if len(op.children) == 0 else "operation group"
74
+
75
+ msg = f"Data transfer {op_type} '{op.description}'({op.id})"
76
+
77
+ op_done = op.state in self.final
78
+ try:
79
+ start = parser.parse(op.started_at)
80
+ if op_done:
81
+ end = parser.parse(op.ended_at)
82
+ else:
83
+ end = datetime.datetime.now(start.tzinfo)
84
+ duration = (end - start).seconds
85
+ duration_str = hf.format_timespan(end - start)
86
+ except Exception as ex:
87
+ log.debug(f"Failed to parse operation duration: {ex}")
88
+ duration = 0
89
+ duration_str = "unknown"
90
+
91
+ state = op.state.value
92
+ if op_done:
93
+ msg += f" has {state} after {duration_str}"
94
+ msg += self._info_str(op)
95
+ # if op.messages:
96
+ # msg += f', messages="{"; ".join(op.messages)}"'
97
+ log.log(lvl, msg)
98
+ elif duration > self.report_threshold and time.time() - self.last_progress > self.min_progress_interval:
99
+ self.last_progress = time.time()
100
+ msg += f" is {state}, {duration_str} so far"
101
+ if op.progress_current > 0:
102
+ msg += f", progress {op.progress * 100.0:.1f}%"
103
+ msg += self._info_str(op)
104
+ log.log(lvl, msg)
105
+
106
+ def _info_str(self, op: Operation) -> str:
107
+ """Format the operation info."""
108
+ if not op.info:
109
+ return ""
110
+ info = ", ".join([f"{k}={v}" for k, v in op.info.items()])
111
+ return f", {info}"
112
+
113
+
114
+ class AsyncWaitHandler(WaitHandler):
115
+ """Allows additional, asynchronous handling of operation status on wait."""
116
+
117
+ def __init__(self):
118
+ """Initializes the AsyncOperationHandler class object."""
119
+ super().__init__()
120
+
121
+ async def __call__(self, ops: list[Operation]):
122
+ """Handle operations after they are fetched."""
123
+ self._log_ops(ops)
@@ -51,6 +51,20 @@ level_map = {
51
51
  "panic": logging.CRITICAL,
52
52
  }
53
53
 
54
+ verbosity_map = {
55
+ 0: logging.WARNING,
56
+ 1: logging.INFO,
57
+ 2: logging.DEBUG,
58
+ 3: logging.DEBUG,
59
+ }
60
+
61
+
62
+ def get_log_level(verbosity: int, debug: bool = False) -> int:
63
+ """Get the log level based on verbosity and debug flag."""
64
+ if debug:
65
+ return logging.DEBUG
66
+ return verbosity_map.get(verbosity, logging.INFO)
67
+
54
68
 
55
69
  class PrepareSubprocess:
56
70
  """Provides for letting the context manager disable ``vfork`` and ``posix_spawn`` in the subprocess."""
@@ -75,6 +89,39 @@ class PrepareSubprocess:
75
89
  subprocess._USE_POSIX_SPAWN = self._orig_use_pspawn
76
90
 
77
91
 
92
+ def default_log_message(debug: bool, data: dict[str, any]):
93
+ """Default log message handler.
94
+
95
+ Parameters
96
+ ----------
97
+ data : dict
98
+ Data to log.
99
+ """
100
+ # log.warning(f"Worker: {d}")
101
+
102
+ level = data.pop("level", "info")
103
+ data.pop("time", None)
104
+ if not debug:
105
+ data.pop("caller", None)
106
+ data.pop("mode", None)
107
+ msg = data.pop("message", None)
108
+
109
+ if msg is None:
110
+ return
111
+
112
+ msg = msg.capitalize()
113
+ level_no = level_map.get(level, logging.INFO)
114
+ other = ""
115
+ for k, v in data.items():
116
+ formatted_value = f'"{v}"' if isinstance(v, str) and " " in v else v
117
+ other += f"{k}={formatted_value} "
118
+ other = other.strip()
119
+ if other:
120
+ msg += f" {other}"
121
+ msg = msg.encode("ascii", errors="ignore").decode().strip()
122
+ log.log(level_no, f"{msg}")
123
+
124
+
78
125
  class BinaryConfig:
79
126
  """Provides for configuring the worker binary connection to the HPS data transfer client.
80
127
 
@@ -107,8 +154,9 @@ class BinaryConfig:
107
154
  # Required
108
155
  data_transfer_url: str = "https://localhost:8443/hps/dt/api/v1",
109
156
  # Process related settings
110
- log: bool = True,
157
+ # log: bool = True,
111
158
  log_to_file: bool = False,
159
+ log_message: callable = default_log_message,
112
160
  monitor_interval: float = 0.5,
113
161
  # TODO: Remove path? not used anywhere
114
162
  path=None,
@@ -116,7 +164,7 @@ class BinaryConfig:
116
164
  token: str = None,
117
165
  host: str = "127.0.0.1",
118
166
  port: int = None,
119
- verbosity: int = 1,
167
+ verbosity: int = 3,
120
168
  insecure: bool = False,
121
169
  debug: bool = False,
122
170
  auth_type: str = None,
@@ -126,8 +174,9 @@ class BinaryConfig:
126
174
  self.data_transfer_url = data_transfer_url
127
175
 
128
176
  # Process related settings
129
- self.log = log
177
+ self.log = debug
130
178
  self.log_to_file = log_to_file
179
+ self._log_message = log_message
131
180
  self.monitor_interval = monitor_interval
132
181
  self.path = path
133
182
 
@@ -154,6 +203,8 @@ class BinaryConfig:
154
203
  setattr(self, key, value)
155
204
  else:
156
205
  raise AttributeError(f"Unknown attribute {key}")
206
+ if self.debug:
207
+ self.log = True
157
208
 
158
209
  @property
159
210
  def port(self):
@@ -199,6 +250,18 @@ class BinaryConfig:
199
250
  raise TypeError("Environment variables must be a dictionary.")
200
251
  self._env = value
201
252
 
253
+ @property
254
+ def log_message(self):
255
+ """Get the log message handler."""
256
+ return self._log_message
257
+
258
+ @log_message.setter
259
+ def log_message(self, value):
260
+ """Set the log message handler."""
261
+ if not callable(value):
262
+ raise TypeError("Log message handler must be a callable.")
263
+ self._log_message = value
264
+
202
265
 
203
266
  class Binary:
204
267
  """Provides for starting, stopping, and monitoring the worker binary.
@@ -263,7 +326,7 @@ class Binary:
263
326
 
264
327
  # Mark binary as executable
265
328
  if not os.access(bin_path, os.X_OK):
266
- log.debug(f"Marking binary as executable: {bin_path}")
329
+ # log.debug(f"Marking binary as executable: {bin_path}")
267
330
  st = os.stat(bin_path)
268
331
  os.chmod(bin_path, st.st_mode | stat.S_IEXEC)
269
332
 
@@ -280,20 +343,20 @@ class Binary:
280
343
  t.start()
281
344
 
282
345
  if not self._prepared.wait(timeout=5.0):
283
- log.warning("Worker did not prepare in time.")
346
+ log.warning("Worker preparation is taking longer than expected ...")
284
347
 
285
348
  def stop(self, wait=5.0):
286
349
  """Stop the worker binary."""
287
350
  if self._process is None:
288
351
  return
289
352
 
290
- log.debug("Stopping worker ...")
291
353
  self._stop.set()
292
354
  self._prepared.clear()
293
355
 
294
356
  start = time.time()
295
357
  while True:
296
358
  if self._process.poll() is not None:
359
+ log.debug("Worker stopped.")
297
360
  break
298
361
  if time.time() - start > wait:
299
362
  log.warning("Worker did not stop in time, killing ...")
@@ -302,6 +365,8 @@ class Binary:
302
365
  time.sleep(wait * 0.1)
303
366
 
304
367
  def _log_output(self):
368
+ log_message = self._config._log_message
369
+
305
370
  while not self._stop.is_set():
306
371
  if self._process is None or self._process.stdout is None:
307
372
  time.sleep(1)
@@ -311,41 +376,16 @@ class Binary:
311
376
  if not line:
312
377
  break
313
378
  line = line.decode(errors="strip").strip()
314
- # log.info("Worker: %s" % line)
315
- self._log_line(line)
379
+ if log_message is not None:
380
+ d = json.loads(line)
381
+ log_message(self._config.debug, d)
316
382
  except json.decoder.JSONDecodeError:
317
383
  pass
318
384
  except Exception as e:
319
385
  if self._config.debug:
320
386
  log.debug(f"Error reading worker output: {e}")
321
387
  time.sleep(1)
322
- log.debug("Worker log output stopped")
323
-
324
- def _log_line(self, line):
325
- d = json.loads(line)
326
- # log.warning(f"Worker: {d}")
327
-
328
- level = d.pop("level", "info")
329
- d.pop("time", None)
330
- if not self._config.debug:
331
- d.pop("caller", None)
332
- d.pop("mode", None)
333
- msg = d.pop("message", None)
334
-
335
- if msg is None:
336
- return
337
-
338
- msg = msg.capitalize()
339
- level_no = level_map.get(level, logging.INFO)
340
- other = ""
341
- for k, v in d.items():
342
- formatted_value = f'"{v}"' if isinstance(v, str) and " " in v else v
343
- other += f"{k}={formatted_value} "
344
- other = other.strip()
345
- if other:
346
- msg += f" {other}"
347
- msg = msg.encode("ascii", errors="ignore").decode().strip()
348
- log.log(level_no, f"{msg}")
388
+ # log.debug("Worker log output stopped")
349
389
 
350
390
  def _monitor(self):
351
391
  while not self._stop.is_set():
@@ -363,13 +403,13 @@ class Binary:
363
403
  env.update(self._config.env)
364
404
  env_str = ",".join([k for k in self._config.env.keys() if k != "PATH"])
365
405
 
366
- log.debug(f"Starting worker: {redacted}")
406
+ log.debug(f"Command: {redacted}")
367
407
  if self._config.debug:
368
- log.debug(f"Worker environment: {env_str}")
408
+ log.debug(f"Environment: {env_str}")
369
409
 
370
410
  with PrepareSubprocess():
371
411
  self._process = subprocess.Popen(
372
- args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env
412
+ args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
373
413
  )
374
414
  else:
375
415
  ret_code = self._process.poll()
@@ -385,7 +425,7 @@ class Binary:
385
425
  # log.debug(f"Worker running ...")
386
426
 
387
427
  time.sleep(self._config.monitor_interval)
388
- log.debug("Worker monitor stopped")
428
+ # log.debug("Worker monitor stopped")
389
429
 
390
430
  def _prepare(self):
391
431
  if self._config._selected_port is None:
@@ -423,17 +463,15 @@ class Binary:
423
463
  [
424
464
  "--dt-url",
425
465
  self._config.data_transfer_url,
426
- "--log-types",
427
- "console",
428
466
  ]
429
467
  )
430
468
 
431
- self._args.extend(
432
- [
433
- "-v",
434
- str(self._config.verbosity),
435
- ]
436
- )
469
+ # self._args.extend(
470
+ # [
471
+ # "-v",
472
+ # str(self._config.verbosity),
473
+ # ]
474
+ # )
437
475
 
438
476
  if self._config.insecure:
439
477
  self._args.append("--insecure")
@@ -38,6 +38,7 @@ import traceback
38
38
  import backoff
39
39
  import filelock
40
40
  import httpx
41
+ import humanfriendly as hf
41
42
  import psutil
42
43
  import urllib3
43
44
 
@@ -47,7 +48,7 @@ from ansys.hps.data_transfer.client.token import prepare_token
47
48
 
48
49
  urllib3.disable_warnings()
49
50
 
50
- for n in ["httpx", "httpcore", "requests", "urllib3"]:
51
+ for n in ["httpx", "httpcore", "requests", "urllib3", "filelock"]:
51
52
  logger = logging.getLogger(n)
52
53
  logger.setLevel(logging.CRITICAL)
53
54
 
@@ -227,6 +228,8 @@ class ClientBase:
227
228
  self._monitor_stop = None
228
229
  self._monitor_state = MonitorState()
229
230
 
231
+ self.progress_interval = 5.0 # seconds
232
+
230
233
  def __getstate__(self):
231
234
  """Return pickled state of the object."""
232
235
  state = self.__dict__.copy()
@@ -355,7 +358,9 @@ class ClientBase:
355
358
  return f"{plat}-{arch}"
356
359
 
357
360
  def _prepare_bin_path(self, build_info):
358
- log.debug(f"Server version: {build_info}")
361
+ log.debug("Server build info:")
362
+ for k, v in build_info.items():
363
+ log.debug(f" {k}: {v}")
359
364
  version_hash = build_info["version_hash"]
360
365
 
361
366
  # Figure out binary download path
@@ -434,17 +439,37 @@ class ClientBase:
434
439
  log.warning(f"Failed to create directory {bin_dir}: {ex}")
435
440
 
436
441
  platform_str = self._platform()
437
- log.debug(
438
- f"Downloading binary for platform '{platform_str}' from {dt_url} to {bin_path}, reason: {reason}"
442
+ log.info(
443
+ f"Downloading data transfer worker for platform '{platform_str}' from {dt_url}, reason: {reason}"
439
444
  )
445
+ log.debug(f"Binary download path: {bin_path}")
440
446
  url = f"/binaries/worker/{platform_str}/hpsdata{bin_ext}"
441
447
  try:
448
+ start = time.time()
449
+ last_progress = start
450
+ written = 0
442
451
  with open(bin_path, "wb") as f, session.stream("GET", url) as resp:
443
452
  resp.read()
444
453
  if resp.status_code != 200:
445
454
  raise BinaryError(f"Failed to download binary: {resp.text}")
455
+
446
456
  for chunk in resp.iter_bytes():
447
- f.write(chunk)
457
+ now = time.time()
458
+ written += f.write(chunk)
459
+
460
+ since_last_progress = now - last_progress
461
+ if since_last_progress > self.progress_interval:
462
+ msg = f"Downloading binary, {hf.format_timespan(now - start)} so far ..."
463
+ content_length = resp.headers.get("Content-Length", None)
464
+ if content_length is not None:
465
+ content_length = int(content_length)
466
+ prog = float(written) / float(content_length) * 100.0
467
+ msg += f" {prog:.1f}%, {hf.format_size(written)}/{hf.format_size(content_length)}"
468
+ else:
469
+ msg += f" {hf.format_size(written)} downloaded"
470
+ log.info(msg)
471
+ last_progress = now
472
+
448
473
  self._bin_config.path = bin_path
449
474
  except Exception as ex:
450
475
  if self._bin_config.debug:
@@ -453,16 +478,16 @@ class ClientBase:
453
478
  os.remove(bin_path)
454
479
 
455
480
  st = os.stat(bin_path)
456
- log.debug(f"Marking binary as executable: {bin_path}")
481
+ # log.debug(f"Marking binary as executable: {bin_path}")
457
482
  os.chmod(bin_path, st.st_mode | stat.S_IEXEC)
458
- if self._bin_config.debug:
459
- log.debug(f"Binary mode: {stat.filemode(os.stat(bin_path).st_mode)}")
483
+ # if self._bin_config.debug:
484
+ # log.debug(f"Binary mode: {stat.filemode(os.stat(bin_path).st_mode)}")
460
485
  except filelock.Timeout as ex:
461
486
  raise BinaryError(f"Failed to acquire lock for binary download: {lock_path}") from ex
462
487
 
463
488
  def _create_session(self, url: str, *, sync: bool = True):
464
489
  verify = not self._bin_config.insecure
465
- log.debug("Creating session for %s with verify=%s", url, verify)
490
+ # log.debug("Creating session for %s with verify=%s", url, verify)
466
491
 
467
492
  args = {
468
493
  "timeout": httpx.Timeout(self._timeout),
@@ -526,11 +551,24 @@ class AsyncClient(ClientBase):
526
551
  """Initializes the AsyncClient class object."""
527
552
  super().__init__(*args, **kwargs)
528
553
  self._bin_config._on_token_update = self._update_token
554
+ self._monitor_task = None
555
+
556
+ def __getstate__(self):
557
+ """Return pickled state of the object."""
558
+ state = super().__getstate__()
559
+ del state["_monitor_task"]
560
+ return state
561
+
562
+ def __setstate__(self, state):
563
+ """Restore state from pickled state."""
564
+ super().__setstate__(state)
565
+ self.__dict__.update(state)
566
+ self._monitor_task = None
529
567
 
530
568
  async def start(self):
531
569
  """Start the async binary worker."""
532
570
  super().start()
533
- asyncio.create_task(self._monitor())
571
+ self._monitor_task = asyncio.create_task(self._monitor())
534
572
 
535
573
  async def stop(self, wait=5.0):
536
574
  """Stop the async binary worker."""
@@ -538,6 +576,8 @@ class AsyncClient(ClientBase):
538
576
  try:
539
577
  await self._session.post(self.base_api_url + "/shutdown")
540
578
  await asyncio.sleep(0.1)
579
+ if self._monitor_task is not None:
580
+ self._monitor_task.cancel()
541
581
  except Exception as ex:
542
582
  log.warning(f"Failed to send shutdown request: {ex}")
543
583
  super().stop(wait=wait)
@@ -573,18 +613,21 @@ class AsyncClient(ClientBase):
573
613
  log.debug(f"Error updating token: {e}")
574
614
 
575
615
  async def _monitor(self):
576
- while not self._monitor_stop.is_set():
577
- await asyncio.sleep(self._monitor_state.sleep_for)
578
-
579
- if self._session is None or self.binary is None:
580
- continue
616
+ while True:
581
617
  try:
618
+ await asyncio.sleep(self._monitor_state.sleep_for)
619
+ if self._session is None or self.binary is None:
620
+ continue
621
+
582
622
  resp = await self._session.get(self.base_api_url)
583
623
 
584
624
  if resp.status_code == 200:
585
625
  ready = resp.json().get("ready", False)
586
626
  self._monitor_state.mark_ready(ready)
587
627
  continue
628
+ except asyncio.CancelledError:
629
+ log.debug("Monitor task cancelled")
630
+ return
588
631
  except Exception as ex:
589
632
  if self.binary_config.debug:
590
633
  log.debug("URL: %s", self.base_api_url)
@@ -593,7 +636,6 @@ class AsyncClient(ClientBase):
593
636
  continue
594
637
 
595
638
  self._monitor_state.report(self.binary)
596
- log.debug("Worker status monitor stopped")
597
639
 
598
640
 
599
641
  class Client(ClientBase):
@@ -40,10 +40,12 @@ class OperationState(Enum):
40
40
 
41
41
  class Operation(BaseModel):
42
42
  children: list[str] | None = None
43
+ children_detail: list[Operation] | None = Field(None, description="Used when expanding groups")
43
44
  description: str | None = None
44
45
  ended_at: str | None = None
45
46
  error: str | None = None
46
47
  id: str | None = None
48
+ info: dict[str, Any] | None = Field(None, description="Additional information about the operation")
47
49
  messages: list[str] | None = None
48
50
  progress: float | None = None
49
51
  progress_current: int | None = None
@@ -55,3 +57,6 @@ class Operation(BaseModel):
55
57
  state: OperationState | None = None
56
58
  succeeded_on: list[str] | None = Field(None, description="Remotes that the operation succeeded on")
57
59
  user_id: str | None = None
60
+
61
+
62
+ Operation.model_rebuild()