workflow.core 1.5.0__tar.gz → 1.7.0__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 (59) hide show
  1. {workflow_core-1.5.0 → workflow_core-1.7.0}/PKG-INFO +1 -1
  2. {workflow_core-1.5.0 → workflow_core-1.7.0}/pyproject.toml +1 -1
  3. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/main.py +2 -0
  4. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/run.py +23 -11
  5. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/daemons/audit.py +2 -11
  6. workflow_core-1.7.0/workflow/daemons/transfer.py +228 -0
  7. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/examples/function.py +24 -1
  8. workflow_core-1.7.0/workflow/exceptions.py +24 -0
  9. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/client.py +1 -1
  10. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/attempt.py +7 -1
  11. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/execute.py +3 -2
  12. workflow_core-1.5.0/workflow/daemons/transfer.py +0 -210
  13. {workflow_core-1.5.0 → workflow_core-1.7.0}/README.md +0 -0
  14. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/__init__.py +0 -0
  15. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/__init__.py +0 -0
  16. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/buckets.py +0 -0
  17. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/configs.py +0 -0
  18. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/pipelines.py +0 -0
  19. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/results.py +0 -0
  20. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/schedules.py +0 -0
  21. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/cli/workspace.py +0 -0
  22. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/daemons/__init__.py +0 -0
  23. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/__init__.py +0 -0
  24. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/config.py +0 -0
  25. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/jsonschema.md +0 -0
  26. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/notify.py +0 -0
  27. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/work.py +0 -0
  28. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/definitions/workspace.py +0 -0
  29. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/examples/sample.svg +0 -0
  30. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/examples/sample.workflow.yml +0 -0
  31. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/helpers/__init__.py +0 -0
  32. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/helpers/date.py +0 -0
  33. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/__init__.py +0 -0
  34. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/buckets.py +0 -0
  35. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/configs.py +0 -0
  36. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/context.py +0 -0
  37. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/pipelines.py +0 -0
  38. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/results.py +0 -0
  39. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/http/schedules.py +0 -0
  40. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/__init__.py +0 -0
  41. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/archive/__init__.py +0 -0
  42. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/archive/http.py +0 -0
  43. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/archive/posix.py +0 -0
  44. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/archive/s3.py +0 -0
  45. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/lifecycle/configure.py +0 -0
  46. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/__init__.py +0 -0
  47. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/decorators.py +0 -0
  48. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/logger.py +0 -0
  49. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/prompt.py +0 -0
  50. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/read.py +0 -0
  51. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/renderers.py +0 -0
  52. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/tmate.sh +0 -0
  53. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/validate.py +0 -0
  54. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/variables.py +0 -0
  55. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/utils/write.py +0 -0
  56. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/workspaces/__init__.py +0 -0
  57. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/workspaces/chimefrb.yml +0 -0
  58. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/workspaces/development.yml +0 -0
  59. {workflow_core-1.5.0 → workflow_core-1.7.0}/workflow/workspaces/site-dev.yml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: workflow.core
3
- Version: 1.5.0
3
+ Version: 1.7.0
4
4
  Summary: Workflow Core
5
5
  Home-page: https://github.com/chimefrb/workflow
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "workflow.core"
3
- version = "1.5.0"
3
+ version = "1.7.0"
4
4
  description = "Workflow Core"
5
5
  authors = ["Shiny Brar <charanjotbrar@gmail.com>"]
6
6
  license = "MIT"
@@ -13,6 +13,7 @@ from workflow.cli.run import run
13
13
  from workflow.cli.schedules import schedules
14
14
  from workflow.cli.workspace import workspace
15
15
  from workflow.daemons.audit import audit
16
+ from workflow.daemons.transfer import transfer
16
17
  from workflow.utils.read import get_active_workspace
17
18
 
18
19
  console = Console()
@@ -43,6 +44,7 @@ cli.add_command(pipelines)
43
44
  cli.add_command(schedules)
44
45
  cli.add_command(workspace)
45
46
  cli.add_command(audit)
47
+ cli.add_command(transfer)
46
48
 
47
49
  if __name__ == "__main__":
48
50
  cli()
@@ -107,6 +107,13 @@ localspaces = Path(DEFAULT_WORKSPACE_PATH).parent
107
107
  show_default=True,
108
108
  help="workspace config.",
109
109
  )
110
+ @click.option(
111
+ "--argsource",
112
+ type=click.Choice(["parameters", "work"]),
113
+ default="parameters",
114
+ show_default=True,
115
+ help="run function with parameters or work object.",
116
+ )
110
117
  @click.option(
111
118
  "--log-level",
112
119
  type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
@@ -125,6 +132,7 @@ def run(
125
132
  lives: int,
126
133
  sleep: int,
127
134
  workspace: Union[str, Dict[Any, Any]],
135
+ argsource: str,
128
136
  log_level: str,
129
137
  ):
130
138
  """Fetch and perform work."""
@@ -153,6 +161,7 @@ def run(
153
161
  )
154
162
  logger.info(f"Buckets : {buckets}")
155
163
  logger.info(f"Function : {function}")
164
+ logger.info(f"Argsource: {argsource}")
156
165
  logger.info(f"Command : {command}")
157
166
  logger.info(f"Mode : {'Static' if (function or command) else 'Dynamic'}")
158
167
  logger.info(f"Lives : {'infinite' if lives == -1 else lives}")
@@ -212,17 +221,18 @@ def run(
212
221
  refresh_per_second=10 if tty else 1,
213
222
  ):
214
223
  lifecycle(
215
- buckets,
216
- function,
217
- command,
218
- lives,
219
- sleep,
220
- site,
221
- tags,
222
- parents,
223
- events,
224
- config,
225
- http,
224
+ buckets=buckets,
225
+ function=function,
226
+ command=command,
227
+ argsource=argsource,
228
+ lives=lives,
229
+ sleep=sleep,
230
+ site=site,
231
+ tags=tags,
232
+ parents=parents,
233
+ events=events,
234
+ config=config,
235
+ http=http,
226
236
  )
227
237
  except Exception as error:
228
238
  logger.exception(error)
@@ -237,6 +247,7 @@ def lifecycle(
237
247
  buckets: List[str],
238
248
  function: Optional[str],
239
249
  command: Optional[str],
250
+ argsource: str,
240
251
  lives: int,
241
252
  sleep: int,
242
253
  site: str,
@@ -266,6 +277,7 @@ def lifecycle(
266
277
  buckets=buckets,
267
278
  function=function,
268
279
  command=command,
280
+ argsource=argsource,
269
281
  site=site,
270
282
  tags=tags,
271
283
  parents=parents,
@@ -1,7 +1,7 @@
1
1
  """Audit Daemon."""
2
2
 
3
3
  import time
4
- from typing import Any, Dict, Optional, Union
4
+ from typing import Any, Dict, Union
5
5
 
6
6
  import click
7
7
  from click_params import JSON, URL, FirstOf
@@ -34,13 +34,6 @@ logger = get_logger("workflow.daemons.audit")
34
34
  show_default=True,
35
35
  help="workspace config.",
36
36
  )
37
- @click.option(
38
- "--token",
39
- "-t",
40
- default=None,
41
- type=click.STRING,
42
- help="Authentication Token.",
43
- )
44
37
  @click.option(
45
38
  "--test-mode",
46
39
  default=False,
@@ -51,10 +44,9 @@ logger = get_logger("workflow.daemons.audit")
51
44
  def audit(
52
45
  sleep: int,
53
46
  workspace: Union[str, Dict[Any, Any]],
54
- token: Optional[str],
55
47
  test_mode: bool,
56
48
  ) -> Dict[str, Any]:
57
- """Audit Buckets Backend.
49
+ """Audit Buckets.
58
50
 
59
51
  Args:
60
52
  sleep (int): number of seconds to sleep between audits
@@ -68,7 +60,6 @@ def audit(
68
60
  logger.info("Starting Audit Daemon")
69
61
  logger.info(f"Sleep Time: {sleep}")
70
62
  logger.info(f"Workspace : {workspace}")
71
- logger.info(f"Token : {token}")
72
63
  logger.info(f"Test Mode : {test_mode}")
73
64
  configure.workspace(workspace=workspace)
74
65
 
@@ -0,0 +1,228 @@
1
+ """Workflow Transfer Daemon."""
2
+
3
+ import time
4
+ from typing import Any, Dict, List, Union
5
+
6
+ import click
7
+ from click_params import JSON, URL, FirstOf
8
+
9
+ from workflow import DEFAULT_WORKSPACE_PATH
10
+ from workflow.http.context import HTTPContext
11
+ from workflow.lifecycle import configure
12
+ from workflow.utils import read
13
+ from workflow.utils.logger import get_logger
14
+
15
+ logger = get_logger("workflow.daemons.transfer")
16
+
17
+
18
+ @click.command()
19
+ @click.option("--sleep", "-s", default=5, help="seconds between transfers.")
20
+ @click.option(
21
+ "-w",
22
+ "--workspace",
23
+ type=FirstOf(
24
+ click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
25
+ URL,
26
+ JSON,
27
+ ),
28
+ default=(DEFAULT_WORKSPACE_PATH.as_posix()),
29
+ show_default=True,
30
+ help="workspace config.",
31
+ )
32
+ @click.option("--limit", default=50, help="works per transfer.")
33
+ @click.option(
34
+ "--cutoff", default=60 * 60 * 24 * 7, help="cutoff time in seconds for stale work."
35
+ )
36
+ @click.option(
37
+ "--test-mode",
38
+ is_flag=True,
39
+ default=False,
40
+ help="Enable test mode to avoid while True loop",
41
+ )
42
+ @click.option("--log-level", default="INFO", help="logging level.")
43
+ def transfer(
44
+ workspace: Union[str, Dict[Any, Any]],
45
+ limit: int,
46
+ cutoff: int,
47
+ sleep: int,
48
+ test_mode: bool,
49
+ log_level: str,
50
+ ) -> Dict[str, int]:
51
+ """Transfer Work.
52
+
53
+ Args:
54
+ sleep (int): seconds to sleep between transfers.
55
+ workspace (Union[str, Dict[Any, Any]]): workspace config.
56
+ test_mode (bool): Enable test mode to avoid while True loop.
57
+ limit (int): works to transfer per run.
58
+ cutoff (int): cutoff time in seconds for stale work.
59
+
60
+ Returns:
61
+ Dict[str, Any]: _description_
62
+ """
63
+ if test_mode:
64
+ log_level = "DEBUG"
65
+ logger.setLevel(log_level)
66
+ logger.info("Starting Transfer Daemon")
67
+ logger.info(f"Test Mode : {test_mode}")
68
+ logger.info(f"Sleep Time: {sleep}")
69
+ logger.info(f"Workspace : {workspace}")
70
+ logger.info(f"Limit/Tx : {limit}")
71
+ logger.info(f"Cutoff : {cutoff} days")
72
+ try:
73
+ configure.workspace(workspace=workspace)
74
+ archive: bool = (
75
+ read.workspace(DEFAULT_WORKSPACE_PATH)
76
+ .get("config", {})
77
+ .get("archive", {})
78
+ .get("results", True)
79
+ )
80
+ logger.info(f"Archive : {'Enabled' if archive else 'Disabled'}")
81
+ http: HTTPContext = HTTPContext(backends=["buckets", "results"])
82
+ logger.info("HTTP Context Initialized")
83
+ logger.info(f"HTTP Context: Buckets Backend @ {http.buckets.baseurl}")
84
+ logger.info(f"HTTP Context: Results Backend @ {http.results.baseurl}")
85
+
86
+ # Check if Buckets and Results backends are available
87
+ assert http.buckets.info(), "Buckets backend not available, exiting."
88
+ assert http.results.info(), "Results backend not available, exiting."
89
+ except Exception as error:
90
+ logger.error(f"Transfer Initialization Error: {error}")
91
+ exit(1)
92
+
93
+ if test_mode:
94
+ logger.debug("Running in Test Mode")
95
+ outcome = perform(archive, limit, cutoff, http)
96
+ logger.info(f"Transfer Outcome: {outcome}")
97
+ return outcome
98
+ else:
99
+ iteration: int = 0
100
+ while True:
101
+ try:
102
+ iteration += 1
103
+ logger.debug(f"Transfer Iteration: {iteration}")
104
+ outcome = perform(archive, limit, cutoff, http)
105
+ logger.info(f"Transfer Outcome: {outcome}")
106
+ except Exception as error:
107
+ logger.error(f"Transfer Error: {error}")
108
+ finally:
109
+ time.sleep(sleep)
110
+
111
+
112
+ def perform(
113
+ archive: bool,
114
+ limit: int,
115
+ cutoff: int,
116
+ http: HTTPContext,
117
+ ) -> Dict[str, int]:
118
+ """Perform transfer of work from Buckets to Results backend.
119
+
120
+ Args:
121
+ workspace (Union[str, Dict[Any, Any]]): workspace config.
122
+ limit (int): works to transfer per run.
123
+ cutoff (int): cutoff time in seconds for stale work.
124
+
125
+ Returns:
126
+ Dict[str, int]: transfer outcome.
127
+ """
128
+ delete: List[str] = []
129
+ transfer: List[str] = []
130
+ payload: List[Dict[str, Any]] = []
131
+ response: Dict[str, Any] = {}
132
+ transfered: int = 0
133
+
134
+ # Find successful work in buckets
135
+ logger.debug("checking successful work in buckets")
136
+ for work in http.buckets.view(
137
+ query={"status": "success"},
138
+ projection={"id": True, "config": True},
139
+ skip=0,
140
+ limit=limit,
141
+ ):
142
+ if work["config"]["archive"]["results"] is False:
143
+ delete.append(work["id"])
144
+ elif work["config"]["archive"]["results"] is True and archive:
145
+ transfer.append(work["id"])
146
+ else:
147
+ delete.append(work["id"])
148
+ logger.debug(
149
+ f"discovered {len(transfer)} transfer and {len(delete)} works to delete"
150
+ )
151
+
152
+ # Find failed work in buckets that is not retryable
153
+ logger.debug("checking failed work in buckets")
154
+ for work in http.buckets.view(
155
+ query={
156
+ "status": "failure",
157
+ "$expr": {"$gte": ["$attempt", "$retries"]},
158
+ "creation": {"$gt": time.time() - cutoff},
159
+ },
160
+ projection={"id": True, "config": True},
161
+ skip=0,
162
+ limit=limit,
163
+ ):
164
+ if work["config"]["archive"]["results"] is False:
165
+ delete.append(work["id"])
166
+ elif work["config"]["archive"]["results"] is True and archive:
167
+ transfer.append(work["id"])
168
+ else:
169
+ delete.append(work["id"])
170
+ logger.debug(
171
+ f"discovered {len(transfer)} transfer and {len(delete)} works to delete"
172
+ )
173
+
174
+ # Find work in buckets that is too old and stale
175
+ logger.debug("checking stale work in buckets")
176
+ for work in http.buckets.view(
177
+ query={
178
+ "creation": {"$lt": time.time() - cutoff},
179
+ },
180
+ projection={"id": True},
181
+ skip=0,
182
+ limit=limit,
183
+ ):
184
+ delete.append(work["id"])
185
+ logger.debug(
186
+ f"discovered {len(transfer)} transfer and {len(delete)} works to delete"
187
+ )
188
+
189
+ # Transfer work to results
190
+ payload = http.buckets.view(
191
+ query={"id": {"$in": transfer}}, projection={}, skip=0, limit=limit * 3
192
+ )
193
+ try:
194
+ logger.debug(f"tx {len(payload)} works to results")
195
+ response = http.results.deposit(payload)
196
+ logger.debug(f"tx {len(payload)} works to results successfully")
197
+ logger.debug(f"tx response: {response}")
198
+ delete = delete + transfer
199
+ transfered = len(payload)
200
+ except Exception as error:
201
+ logger.warning(f"bulk transfer to results failed: {error}")
202
+ logger.warning("checking for existing works in results")
203
+ for index, work in enumerate(payload):
204
+ if http.results.count(pipeline=work["pipeline"], query={"id": work["id"]}):
205
+ delete.append(work["id"])
206
+ logger.debug(f"work {work['id']} already exists in results")
207
+ payload.pop(index)
208
+ logger.debug(f"retrying transfer of {len(payload)} works to results")
209
+ response = http.results.deposit(payload)
210
+ logger.info(
211
+ f"transferred {len(payload)} works to results after duplicate check"
212
+ )
213
+ logger.debug(f"response: {response}")
214
+ delete = delete + [work["id"] for work in payload]
215
+ transfered = len(payload)
216
+
217
+ if delete:
218
+ logger.info(f"deleting {len(delete)} works from buckets")
219
+ http.buckets.delete_ids(delete)
220
+ logger.info(f"transferred {transfered}, deleted {len(delete)} works")
221
+ return {
222
+ "transfered": transfered,
223
+ "deleted": len(delete),
224
+ }
225
+
226
+
227
+ if __name__ == "__main__":
228
+ transfer.main(args=["--test-mode=True", "--log-level=DEBUG"], standalone_mode=False)
@@ -1,11 +1,16 @@
1
1
  """Sample CHIME/FRB Workflow Compatible Function."""
2
2
 
3
3
  from pathlib import Path
4
- from typing import Dict, List, Tuple, Union
4
+ from typing import Any, Dict, List, Tuple, Union
5
5
 
6
6
  import click
7
7
  from click_params import FirstOf
8
8
 
9
+ from workflow.definitions.work import Work
10
+ from workflow.utils.logger import get_logger
11
+
12
+ logger = get_logger("workflow.examples.function")
13
+
9
14
 
10
15
  def math(
11
16
  alpha: Union[float, int], beta: Union[float, int] = 1.0
@@ -24,6 +29,7 @@ def math(
24
29
  The results, products, and plots
25
30
  """
26
31
  try:
32
+ logger.info(f"Running math with alpha:{alpha}, beta:{beta}")
27
33
  assert isinstance(alpha, (float, int)), "alpha must be a number"
28
34
  assert isinstance(beta, (float, int)), "beta must be a number"
29
35
  results: Dict[str, float] = {
@@ -52,6 +58,23 @@ def math(
52
58
  raise error
53
59
 
54
60
 
61
+ def worker(work: Work) -> Work:
62
+ """Sample CHIME/FRB Workflow Compatible Function.
63
+
64
+ Args:
65
+ work (Work): A work object
66
+
67
+ Returns:
68
+ Work: The work object
69
+ """
70
+ logger.info("Processing math with work object...")
71
+ parameters: Dict[str, Any] = work.parameters or {}
72
+ alpha: float = float(parameters.get("alpha", 1.14))
73
+ beta: float = float(parameters.get("beta", 3.14))
74
+ work.results, work.products, work.plots = math(alpha, beta)
75
+ return work
76
+
77
+
55
78
  @click.command("math", help="Sample CHIME/FRB Workflow Compatible Function.")
56
79
  @click.option(
57
80
  "--alpha",
@@ -0,0 +1,24 @@
1
+ """Exceptions and warnings for workflow."""
2
+
3
+
4
+ class WorkflowException(Exception):
5
+ """Ambigous workflow exception."""
6
+
7
+
8
+ class WorkspaceError(WorkflowException):
9
+ """Invalid workflow workspace."""
10
+
11
+
12
+ class HTTPContextError(WorkflowException):
13
+ """Invalid HTTP context."""
14
+
15
+
16
+ # Workflow Warnings
17
+
18
+
19
+ class WorkflowWarning(Warning):
20
+ """Base warning for workflow."""
21
+
22
+
23
+ class WorkWarning(WorkflowWarning):
24
+ """Base warning for work."""
@@ -31,7 +31,7 @@ class Client(BaseSettings):
31
31
  BaseModel (BaseModel): Pydantic base model.
32
32
 
33
33
  Attributes:
34
- baseurl (str): Base URLs for the server.
34
+ baseurl (Union[str, List[str]): Base URLs to for the server.
35
35
  token (Optional[SecretStr]): Authentication token.
36
36
  timeout (float): Request timeout in seconds.
37
37
  session (requests.Session): HTTP request session.
@@ -16,6 +16,7 @@ def work(
16
16
  buckets: List[str],
17
17
  function: Optional[str],
18
18
  command: Optional[str],
19
+ argsource: str,
19
20
  site: str,
20
21
  tags: List[str],
21
22
  parents: List[str],
@@ -28,6 +29,8 @@ def work(
28
29
  Args:
29
30
  buckets (List[str]): Name of the buckets to perform work from.
30
31
  function (Optional[str]): Static function to perform work.
32
+ command (Optional[str]): Static command to perform work.
33
+ argsource (str): Source of arguments for the function.
31
34
  site (str): Site to filter work by.
32
35
  tags (List[str]): Tags to filter work by.
33
36
  parents (List[str]): Parent pipeline to filter work by.
@@ -82,9 +85,12 @@ def work(
82
85
  assert work.command or work.function, "neither function or command provided"
83
86
 
84
87
  # Get the user function from the work object dynamically
85
- if work.function:
88
+ if work.function and argsource == "parameters":
86
89
  logger.debug(f"executing function: {work.function}")
87
90
  work = execute.function(work)
91
+ elif work.function and argsource == "work":
92
+ logger.debug(f"executing function with work object: {work.function}")
93
+ work = execute.function_with_work(work)
88
94
 
89
95
  # If we have a valid command, execute it
90
96
  if work.command:
@@ -127,7 +127,7 @@ def command(work: Work) -> Work:
127
127
  return work
128
128
 
129
129
 
130
- def with_work(work: Work) -> Work:
130
+ def function_with_work(work: Work) -> Work:
131
131
  """Execute a work function with work object.
132
132
 
133
133
  Args:
@@ -144,10 +144,11 @@ def with_work(work: Work) -> Work:
144
144
  # Check the type hints of the function,
145
145
  # check if the input/output is a Work object
146
146
  hints = get_type_hints(func)
147
- logger.info(f"function hints: {hints}")
147
+ logger.info(f"executing function with work object: {func.__name__}({work})")
148
148
  assert hints.get("work") == Work, "function must have a Work object as input"
149
149
  assert hints.get("return") == Work, "function must return a Work object"
150
150
  work = func(work)
151
+ validate.size(work)
151
152
  work.status = "success"
152
153
  except Exception as error:
153
154
  work.status = "failure"
@@ -1,210 +0,0 @@
1
- """Workflow Transfer Daemon."""
2
-
3
- import time
4
- from typing import Any, Dict, List
5
-
6
- import click
7
-
8
- from workflow import DEFAULT_WORKSPACE_PATH
9
- from workflow.http.buckets import Buckets
10
- from workflow.http.results import Results
11
- from workflow.utils import logger, read
12
-
13
- log = logger.get_logger("workflow.daemons.transfer")
14
-
15
-
16
- def deposit_work_to_results(
17
- buckets: Buckets, results: Results, works: List[Dict[str, Any]]
18
- ) -> int:
19
- """Deposit work to results, and remove them from buckets.
20
-
21
- Args:
22
- buckets (Buckets): Buckets module.
23
- results (Results): Results module.
24
- works (List[Dict[str, Any]]): Work to deposit.
25
-
26
- Returns:
27
- transfer_status (bool): Number of works deposited to results.
28
- """
29
- try:
30
- transfer_status = False
31
- results_deposit_status = results.deposit(works)
32
- if all([val > 0 for val in results_deposit_status.values()]):
33
- buckets.delete_ids([work["id"] for work in works])
34
- transfer_status = True
35
- return transfer_status
36
- except Exception as error:
37
- print(f"Exception occurred: {error}")
38
- transfer_status = False
39
- work_to_deposit = [
40
- work for work in works if is_work_already_deposited(results, work) is False
41
- ]
42
- results_deposit_status = results.deposit(work_to_deposit)
43
- if (
44
- all([val > 0 for val in results_deposit_status.values()])
45
- or results_deposit_status == {}
46
- ):
47
- buckets.delete_ids([work["id"] for work in works])
48
- transfer_status = True
49
- return transfer_status
50
-
51
-
52
- def is_work_already_deposited(results: Results, work: Dict[str, Any]) -> bool:
53
- """Check if a work has already been deposited to results.
54
-
55
- Args:
56
- results (Results): Results module.
57
- work (Dict[str, Any]): work to check
58
-
59
- Returns:
60
- bool: _description_
61
- """
62
- return results.count(pipeline=work["pipeline"], query={"id": work["id"]}) == 1
63
-
64
-
65
- @click.command()
66
- @click.option("--sleep", "-s", default=5, help="Time to sleep between transfers")
67
- @click.option(
68
- "--buckets-base-url",
69
- "-b",
70
- default="http://frb-vsop.chime:8004",
71
- help="Location of the Buckets backend.",
72
- )
73
- @click.option(
74
- "--results-base-url",
75
- "-r",
76
- default="http://frb-vsop.chime:8005",
77
- help="Location of the Results backend.",
78
- )
79
- @click.option(
80
- "--test-mode", default=False, help="Enable test mode to avoid while True loop"
81
- )
82
- def transfer_work(
83
- sleep: int,
84
- buckets_base_url: str,
85
- results_base_url: str,
86
- test_mode: bool,
87
- limit_per_run: int = 50,
88
- ) -> Dict[str, Any]:
89
- """Transfer successful Work from Buckets DB to Results DB.
90
-
91
- Args:
92
- sleep (int): number of seconds to sleep between transfers
93
- buckets_base_url (str): location of the Buckets backend
94
- results_base_url (str): location of the Results backend
95
- test_mode (bool): Enable test mode to avoid while True loop
96
- limit_per_run (int): Max number of failed Work entires to transfer per
97
- run of daemon.
98
- """
99
- buckets = Buckets(base_url=buckets_base_url, debug=test_mode)
100
- results = Results(base_url=results_base_url, debug=test_mode)
101
-
102
- log.info("Starting Transfer Daemon")
103
- log.info(f"Sleeptime: {sleep}")
104
- log.info(f"Buckets@ : {buckets_base_url}")
105
- log.info(f"Results@ : {results_base_url}")
106
- log.info(f"Test Mode: {test_mode}")
107
- log.info(f"Limit/Tx : {limit_per_run}")
108
-
109
- def transfer(test_flag: bool, buckets: Buckets, results: Results) -> Dict[str, Any]:
110
- """Transfer Work from Buckets to Results.
111
-
112
- Args:
113
- test_flag (bool): If True, run once and exit.
114
- buckets (Buckets): Buckets module.
115
- results (Results): Results module.
116
-
117
- Returns:
118
- Dict[str, Any]: Transfer status.
119
- """
120
- results_workspace_config = (
121
- read.workspace(DEFAULT_WORKSPACE_PATH.as_posix())
122
- .get("config", {})
123
- .get("archive", {})
124
- .get("results", None)
125
- )
126
- transfer_status: Dict[str, Any] = {}
127
- # 1. Transfer successful Work
128
- # TODO: decide projection fields
129
- successful_work = buckets.view(
130
- query={"status": "success"},
131
- projection={},
132
- skip=0,
133
- limit=limit_per_run,
134
- )
135
- successful_work_to_delete = [
136
- work
137
- for work in successful_work
138
- if work["config"]["archive"]["results"] is False
139
- and not results_workspace_config
140
- ]
141
- successful_work_to_transfer = [
142
- work
143
- for work in successful_work
144
- if work["config"]["archive"]["results"] is True and results_workspace_config
145
- ]
146
- if successful_work_to_transfer:
147
- transfer_status["successful_work_transferred"] = deposit_work_to_results(
148
- buckets, results, successful_work_to_transfer
149
- )
150
- if successful_work_to_delete:
151
- buckets.delete_ids([work["id"] for work in successful_work_to_delete])
152
- transfer_status["successful_work_deleted"] = True
153
-
154
- cutoff_creation_time = time.time() - (60 * 60 * 24 * 7)
155
- # 2. Transfer failed Work which is not stale
156
- failed_work = buckets.view(
157
- query={
158
- "status": "failure",
159
- "$expr": {"$gte": ["$attempt", "$retries"]},
160
- "creation": {"$gt": cutoff_creation_time},
161
- },
162
- projection={},
163
- skip=0,
164
- limit=limit_per_run,
165
- )
166
- failed_work_to_delete = [
167
- work
168
- for work in failed_work
169
- if work["config"]["archive"]["results"] is False
170
- and not results_workspace_config
171
- ]
172
- failed_work_to_transfer = [
173
- work
174
- for work in failed_work
175
- if work["config"]["archive"]["results"] is True and results_workspace_config
176
- ]
177
-
178
- if failed_work_to_transfer:
179
- transfer_status["failed_work_transferred"] = deposit_work_to_results(
180
- buckets, results, failed_work_to_transfer
181
- )
182
- if failed_work_to_delete:
183
- buckets.delete_ids([work["id"] for work in failed_work_to_delete])
184
- transfer_status["failed_work_deleted"] = True
185
-
186
- # 3. Delete stale Work (cut off time: 7 days)
187
- stale_work = buckets.view(
188
- query={
189
- "status": "failure",
190
- "creation": {"$lt": cutoff_creation_time},
191
- },
192
- projection={},
193
- skip=0,
194
- limit=limit_per_run,
195
- )
196
- if stale_work:
197
- buckets.delete_ids([work["id"] for work in stale_work])
198
- transfer_status["stale_work_deleted"] = True
199
- log.info(f"Transfer Status: {transfer_status}")
200
- return transfer_status
201
-
202
- if test_mode:
203
- return transfer(test_flag=True, buckets=buckets, results=results)
204
- while True:
205
- transfer(test_flag=False, buckets=buckets, results=results)
206
- time.sleep(sleep)
207
-
208
-
209
- if __name__ == "__main__":
210
- transfer_work()
File without changes