workflow.core 1.4.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.
Files changed (58) hide show
  1. workflow/__init__.py +17 -0
  2. workflow/cli/__init__.py +0 -0
  3. workflow/cli/buckets.py +124 -0
  4. workflow/cli/configs.py +279 -0
  5. workflow/cli/main.py +48 -0
  6. workflow/cli/pipelines.py +146 -0
  7. workflow/cli/results.py +168 -0
  8. workflow/cli/run.py +283 -0
  9. workflow/cli/schedules.py +234 -0
  10. workflow/cli/workspace.py +149 -0
  11. workflow/daemons/__init__.py +0 -0
  12. workflow/daemons/audit.py +74 -0
  13. workflow/daemons/transfer.py +255 -0
  14. workflow/definitions/__init__.py +0 -0
  15. workflow/definitions/config.py +124 -0
  16. workflow/definitions/jsonschema.md +28 -0
  17. workflow/definitions/notify.py +91 -0
  18. workflow/definitions/work.py +520 -0
  19. workflow/definitions/workspace.py +252 -0
  20. workflow/examples/function.py +92 -0
  21. workflow/examples/sample.svg +12 -0
  22. workflow/examples/sample.workflow.yml +31 -0
  23. workflow/helpers/__init__.py +0 -0
  24. workflow/helpers/date.py +33 -0
  25. workflow/http/__init__.py +0 -0
  26. workflow/http/buckets.py +286 -0
  27. workflow/http/client.py +136 -0
  28. workflow/http/configs.py +165 -0
  29. workflow/http/context.py +170 -0
  30. workflow/http/pipelines.py +123 -0
  31. workflow/http/results.py +305 -0
  32. workflow/http/schedules.py +157 -0
  33. workflow/lifecycle/__init__.py +1 -0
  34. workflow/lifecycle/archive/__init__.py +102 -0
  35. workflow/lifecycle/archive/http.py +58 -0
  36. workflow/lifecycle/archive/posix.py +185 -0
  37. workflow/lifecycle/archive/s3.py +157 -0
  38. workflow/lifecycle/attempt.py +112 -0
  39. workflow/lifecycle/configure.py +152 -0
  40. workflow/lifecycle/execute.py +159 -0
  41. workflow/utils/__init__.py +0 -0
  42. workflow/utils/decorators.py +29 -0
  43. workflow/utils/logger.py +93 -0
  44. workflow/utils/prompt.py +26 -0
  45. workflow/utils/read.py +146 -0
  46. workflow/utils/renderers.py +113 -0
  47. workflow/utils/tmate.sh +17 -0
  48. workflow/utils/validate.py +198 -0
  49. workflow/utils/variables.py +24 -0
  50. workflow/utils/write.py +44 -0
  51. workflow/workspaces/__init__.py +0 -0
  52. workflow/workspaces/chimefrb.yml +48 -0
  53. workflow/workspaces/development.yml +48 -0
  54. workflow/workspaces/site-dev.yml +36 -0
  55. workflow_core-1.4.0.dist-info/METADATA +115 -0
  56. workflow_core-1.4.0.dist-info/RECORD +58 -0
  57. workflow_core-1.4.0.dist-info/WHEEL +4 -0
  58. workflow_core-1.4.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,170 @@
1
+ """HTTP client for interacting with the Workflow Servers."""
2
+
3
+ import os
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from pydantic import (
7
+ AliasChoices,
8
+ Field,
9
+ FilePath,
10
+ SecretStr,
11
+ field_validator,
12
+ model_validator,
13
+ )
14
+ from pydantic_settings import BaseSettings, SettingsConfigDict
15
+ from typing_extensions import Self
16
+
17
+ from workflow import DEFAULT_WORKSPACE_PATH
18
+ from workflow.http.buckets import Buckets
19
+ from workflow.http.configs import Configs
20
+ from workflow.http.pipelines import Pipelines
21
+ from workflow.http.results import Results
22
+ from workflow.http.schedules import Schedules
23
+ from workflow.utils import read
24
+ from workflow.utils.logger import get_logger
25
+
26
+ logger = get_logger("workflow.http.context")
27
+
28
+
29
+ class HTTPContext(BaseSettings):
30
+ """HTTP Context for the Workflow Servers.
31
+
32
+ Args:
33
+ BaseSettings (BaseSettings): Pydantic BaseModel with settings.
34
+
35
+ Attributes:
36
+ baseurl (str): HTTP baseurl of the buckets backend.
37
+ timeout (float): HTTP Request timeout in seconds.
38
+ token (Optional[SecretStr]): Workflow Access Token.
39
+
40
+ Returns:
41
+ HTTPContext: The current HTTPContext object.
42
+ """
43
+
44
+ model_config = SettingsConfigDict(
45
+ title="Workflow Local Context",
46
+ arbitrary_types_allowed=True,
47
+ env_prefix="WORKFLOW_HTTP_",
48
+ secrets_dir="/run/secrets",
49
+ validate_assignment=True,
50
+ extra="ignore",
51
+ )
52
+ workspace: FilePath = Field(
53
+ default=DEFAULT_WORKSPACE_PATH,
54
+ frozen=True,
55
+ description="Path to the workspace configuration.",
56
+ examples=[DEFAULT_WORKSPACE_PATH.as_posix()],
57
+ )
58
+ timeout: float = Field(
59
+ default=15.0,
60
+ ge=0.5,
61
+ le=60.0,
62
+ description="HTTP Request timeout in seconds",
63
+ examples=[15.0],
64
+ )
65
+ token: Optional[SecretStr] = Field(
66
+ default=None,
67
+ validation_alias=AliasChoices(
68
+ "WORKFLOW_HTTP_TOKEN",
69
+ "WORKFLOW_TOKEN",
70
+ "GITHUB_TOKEN",
71
+ "GITHUB_PAT",
72
+ ),
73
+ description="Workflow Access Token.",
74
+ examples=["ghp_1234567890abcdefg"],
75
+ )
76
+ backends: List[str] = Field(
77
+ default=["buckets", "results", "pipelines", "schedules", "configs"],
78
+ description="List of backend services to create clients for.",
79
+ examples=[["buckets", "results", "pipelines", "schedules", "configs"]],
80
+ )
81
+ buckets: Buckets = Field(
82
+ default=None,
83
+ validate_default=False,
84
+ description="Buckets API Client.",
85
+ exclude=True,
86
+ )
87
+
88
+ results: Results = Field(
89
+ default=None,
90
+ validate_default=False,
91
+ description="Results API Client.",
92
+ exclude=True,
93
+ )
94
+
95
+ configs: Configs = Field(
96
+ default=None,
97
+ validate_default=False,
98
+ description="Configs API Client.",
99
+ exclude=True,
100
+ )
101
+
102
+ pipelines: Pipelines = Field(
103
+ default=None,
104
+ validate_default=False,
105
+ description="Pipelines API Client.",
106
+ exclude=True,
107
+ )
108
+
109
+ schedules: Schedules = Field(
110
+ default=None,
111
+ validate_default=False,
112
+ description="Schedules API Client.",
113
+ exclude=True,
114
+ )
115
+
116
+ @field_validator("workspace", mode="before")
117
+ @classmethod
118
+ def check_workspace_is_set(cls, value: str) -> str:
119
+ """Check that workspace field has a valid filepath.
120
+
121
+ Args:
122
+ value (str): FilePath str value.
123
+
124
+ Raises:
125
+ ValueError: If path is not a valid file.
126
+
127
+ Returns:
128
+ str: FilePath str value.
129
+ """
130
+ if not os.path.isfile(value):
131
+ logger.error("No workspace set.")
132
+ raise ValueError("No workspace set.")
133
+ return value
134
+
135
+ @model_validator(mode="after")
136
+ def create_clients(self) -> Self:
137
+ """Create the HTTP Clients for the Workflow Servers.
138
+
139
+ Returns:
140
+ Self: The current HTTPContext object.
141
+ """
142
+ clients: Dict[str, Any] = {
143
+ "buckets": Buckets,
144
+ "results": Results,
145
+ "pipelines": Pipelines,
146
+ "schedules": Schedules,
147
+ "configs": Configs,
148
+ }
149
+ logger.debug(f"creating http clients for {self.backends}.")
150
+ config: Dict[str, Any] = read.workspace(self.workspace)
151
+ baseurls = config.get("http", {}).get("baseurls", {})
152
+ logger.debug(f"baseurls: {baseurls}")
153
+ for backend in self.backends:
154
+ baseurl = baseurls.get(backend, None)
155
+ client = getattr(self, backend)
156
+ logger.debug(f"creating {backend} client @ {baseurl}.")
157
+ if baseurl and not client:
158
+ try:
159
+ setattr(
160
+ self,
161
+ backend,
162
+ clients[backend](
163
+ baseurl=baseurl, token=self.token, timeout=self.timeout
164
+ ),
165
+ )
166
+ logger.debug(f"created {backend} client @ {baseurl}.")
167
+ except Exception as error:
168
+ logger.error(f"failed to create {backend} client @ {baseurl}.")
169
+ logger.error(error)
170
+ return self
@@ -0,0 +1,123 @@
1
+ """Workflow Pipelines API."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+ from urllib.parse import urlencode
5
+
6
+ from requests.models import Response
7
+
8
+ from workflow.http.client import Client
9
+ from workflow.utils.decorators import try_request
10
+
11
+
12
+ class Pipelines(Client):
13
+ """HTTP Client for interacting with the Pipelines backend.
14
+
15
+ Args:
16
+ Client (workflow.http.client): The base class for interacting with the backend.
17
+
18
+ Returns:
19
+ Pipelines: A client for interacting with the Pipelines backend.
20
+ """
21
+
22
+ @try_request
23
+ def count(self) -> Dict[str, Any]:
24
+ """Count all documents in a collection.
25
+
26
+ Returns
27
+ -------
28
+ Dict[str, Any]
29
+ Dictionary with count.
30
+ """
31
+ with self.session as session:
32
+ params = {"database": "pipelines"}
33
+ response: Response = session.get(
34
+ url=f"{self.baseurl}/configs/count?{urlencode(params)}"
35
+ )
36
+ response.raise_for_status()
37
+ return response.json()
38
+
39
+ def list_pipelines(self, name: Optional[str] = None) -> List[Dict[str, Any]]:
40
+ """View the current pipeline configurations in the pipelines backend.
41
+
42
+ Parameters
43
+ ----------
44
+ name : Optional[str], optional
45
+ Config name, by default None
46
+
47
+ Returns
48
+ -------
49
+ List[Dict[str, Any]]
50
+ List of PipelineConfig payloads.
51
+ """
52
+ with self.session as session:
53
+ params = {"database": "pipelines"}
54
+ if name:
55
+ params.update({"name": name})
56
+ url = f"{self.baseurl}/configs?{urlencode(params)}"
57
+ response: Response = session.get(url=url)
58
+ response.raise_for_status()
59
+ return response.json()
60
+
61
+ def get_pipelines(self, name: str, query: str, projection: str) -> Dict[str, Any]:
62
+ """Gets details for one pipeline configuration.
63
+
64
+ Parameters
65
+ ----------
66
+ name : str
67
+ Config name.
68
+ query : Dict[str, Any]
69
+ Dictionary with search parameters.
70
+ projection : Dict[str, Any]
71
+ Dictionary with projection parameters.
72
+
73
+ Returns
74
+ -------
75
+ Dict[str, Any]
76
+ Pipeline configuration payload.
77
+ """
78
+ with self.session as session:
79
+ params = {
80
+ "query": query,
81
+ "name": name,
82
+ "projection": projection,
83
+ "database": "pipelines",
84
+ }
85
+ url = f"{self.baseurl}/configs?{urlencode(params)}"
86
+ response: Response = session.get(url=url)
87
+ response.raise_for_status()
88
+ return response.json()
89
+
90
+ def info(self) -> Dict[str, Any]:
91
+ """Get the version of the pipelines backend.
92
+
93
+ Returns
94
+ -------
95
+ Dict[str, Any]
96
+ Pipelines backend info.
97
+ """
98
+ client_info = self.model_dump()
99
+ with self.session as session:
100
+ response: Response = session.get(url=f"{self.baseurl}/version")
101
+ response.raise_for_status()
102
+ server_info = response.json()
103
+ return {"client": client_info, "server": server_info}
104
+
105
+ def status(self, params: Dict[str, Any]) -> Dict[str, Any]:
106
+ """Get the status of all pipelines.
107
+
108
+ Parameters
109
+ ----------
110
+ params : Dict[str, Any]
111
+ Dictionary with query parameters.
112
+
113
+ Returns
114
+ -------
115
+ Dict[str, Any]
116
+ Dictionary with pipeline status.
117
+ """
118
+ with self.session as session:
119
+ response: Response = session.get(
120
+ url=f"{self.baseurl}/status", params=params
121
+ )
122
+ response.raise_for_status()
123
+ return response.json()
@@ -0,0 +1,305 @@
1
+ """Workflow Results API."""
2
+
3
+ from typing import Any, Dict, List
4
+
5
+ from requests.models import Response
6
+
7
+ from workflow.http.client import Client
8
+ from workflow.utils.decorators import try_request
9
+ from workflow.utils.prompt import confirmation
10
+
11
+
12
+ class Results(Client):
13
+ """HTTP Client for interacting with the Results backend.
14
+
15
+ Args:
16
+ Client (workflow.http.client): The base class for interacting with the backend.
17
+
18
+ Returns:
19
+ Results: A client for interacting with the Buckets backend.
20
+ """
21
+
22
+ @try_request
23
+ def info(self) -> Dict[str, Any]:
24
+ """Get the version of the results backend.
25
+
26
+ Returns:
27
+ Dict[str, Any]: The version of the results backend.
28
+ """
29
+ client_info = self.model_dump()
30
+ with self.session as session:
31
+ response: Response = session.get(url=f"{self.baseurl}/version")
32
+ response.raise_for_status()
33
+ server_info = response.json()
34
+ return {"client": client_info, "server": server_info}
35
+
36
+ def deposit(self, works: List[Dict[str, Any]]) -> Dict[str, bool]:
37
+ """Deposit works into the results backend.
38
+
39
+ Args:
40
+ works (List[Dict[str, Any]]): A list of payloads from Work Objects.
41
+
42
+ Note:
43
+ This method is not intended for direct use by the user.
44
+ Work status must be 'success' or 'failure'.
45
+
46
+ Raises:
47
+ AssertionError: If work status is not 'success' or 'failure'.
48
+
49
+ Returns:
50
+ Dict[str, bool]: Dictionary of deposit results for each pipeline.
51
+
52
+ Examples:
53
+ >>> from workflow.http.results import Results
54
+ >>> from workflow.definitions.work import Work
55
+ >>> results = Results()
56
+ >>> work = Work.withdraw(pipeline="test)
57
+ >>> work.status = "success"
58
+ >>> status = results.deposit([work.payload])
59
+ """
60
+ for work in works:
61
+ assert work["status"] in [
62
+ "success",
63
+ "failure",
64
+ ], "work.status must be 'success' or 'failure'"
65
+ with self.session as session:
66
+ response: Response = session.post(url=f"{self.baseurl}/results", json=works)
67
+ response.raise_for_status()
68
+ return response.json()
69
+
70
+ def update(self, works: List[Dict[str, Any]]) -> bool:
71
+ """Update works in the results backend.
72
+
73
+ Args:
74
+ works (List[Dict[str, Any]]): A list of payloads from Work Objects.
75
+
76
+ Note:
77
+ This method is not intended for direct use by the user.
78
+ Work status must be 'success' or 'failure'.
79
+
80
+ Returns:
81
+ bool: Whether the works were updated successfully.
82
+ """
83
+ with self.session as session:
84
+ response: Response = session.put(url=f"{self.baseurl}/results", json=works)
85
+ response.raise_for_status()
86
+ return response.json()
87
+
88
+ def delete_ids(self, pipeline: str, ids: List[str]) -> bool:
89
+ """Delete results from the results backend.
90
+
91
+ Args:
92
+ pipeline (str): Name of pipeline.
93
+ ids (List[str]): The IDs of the works to delete.
94
+
95
+ Returns:
96
+ bool: Whether the results were deleted successfully.
97
+ """
98
+ with self.session as session:
99
+ response: Response = session.delete(
100
+ url=f"{self.baseurl}/results", params={pipeline: ids}
101
+ )
102
+ response.raise_for_status()
103
+ return response.json()
104
+
105
+ def view(
106
+ self,
107
+ pipeline: str,
108
+ query: Dict[str, Any],
109
+ projection: Dict[str, bool] = {},
110
+ skip: int = 0,
111
+ limit: int = 100,
112
+ ) -> List[Dict[str, Any]]:
113
+ """View works in the results backend.
114
+
115
+ Args:
116
+ pipeline (str): Name of pipeline.
117
+ query (Dict[str, Any]): MongoDB query.
118
+ projection (Dict[str, bool], optional): MongoDB projection.
119
+ Defaults to {}.
120
+ skip (int, optional): Number of works to skip.
121
+ Defaults to 0.
122
+ limit (int, optional): Number of works to limit to. -1 for no limit.
123
+ Defaults to 100.
124
+
125
+ Returns:
126
+ List[Dict[str, Any]]: List of work payloads.
127
+ """
128
+ query["pipeline"] = pipeline
129
+ if limit == -1:
130
+ limit = 0
131
+ payload = {
132
+ "query": query,
133
+ "projection": projection,
134
+ "skip": skip,
135
+ "limit": limit,
136
+ }
137
+ with self.session as session:
138
+ response: Response = session.post(url=f"{self.baseurl}/view", json=payload)
139
+ response.raise_for_status()
140
+ return response.json()
141
+
142
+ def count(
143
+ self,
144
+ pipeline: str,
145
+ query: Dict[str, Any],
146
+ ) -> int:
147
+ """Get count of results filtered by the query.
148
+
149
+ Args:
150
+ pipeline (str): Name of pipeline.
151
+ query (Dict[str, Any]): MongoDB query.
152
+
153
+ Returns:
154
+ int: The number of results that match the query.
155
+ """
156
+ query["pipeline"] = pipeline
157
+ payload = {
158
+ "query": query,
159
+ }
160
+ with self.session as session:
161
+ response: Response = session.post(
162
+ url=f"{self.baseurl}/view/count", json=payload
163
+ )
164
+ response.raise_for_status()
165
+ return response.json()
166
+
167
+ def status(self) -> Dict[str, int]:
168
+ """Get the status of the results backend.
169
+
170
+ Returns:
171
+ Dict[str, int]: The status of the results backend.
172
+ """
173
+ with self.session as session:
174
+ response: Response = session.get(url=f"{self.baseurl}/status")
175
+ response.raise_for_status()
176
+ return response.json()
177
+
178
+ def get_by_count(self, pipeline: str, count: int = 10) -> List[Dict[str, Any]]:
179
+ """Get results by count from the specified pipeline.
180
+
181
+ Args:
182
+ pipeline (str): The name of the pipeline.
183
+ count (int): The number of results to get. Defaults to 10.
184
+
185
+ Returns:
186
+ List[Dict[str, Any]]: Retrieved results.
187
+ """
188
+ response = self.view(
189
+ pipeline=pipeline, query={}, projection={}, skip=0, limit=count
190
+ )
191
+ return response
192
+
193
+ def get_by_id(self, pipeline: str, ids: List[str]) -> List[Dict[str, Any]]:
194
+ """Get results by ID from the specified pipeline.
195
+
196
+ Args:
197
+ pipeline (str): The name of the pipeline.
198
+ ids (List[str]): The IDs of the results to get.
199
+
200
+ Returns:
201
+ List[Dict[str, Any]]: Retrieved results.
202
+ """
203
+ response = self.view(
204
+ pipeline=pipeline, query={"id": {"$in": ids}}, projection={}, limit=-1
205
+ )
206
+ return response
207
+
208
+ def get_by_event(self, pipeline: str, event_number: int) -> List[Dict[str, Any]]:
209
+ """Get work filtered by event number from the results backend.
210
+
211
+ Args:
212
+ pipeline (str): The name of the pipeline.
213
+ event_number (int): The event number of the event.
214
+
215
+ Returns:
216
+ List[Dict[str, Any]]: Retrieved results.
217
+ """
218
+ return self.view(
219
+ pipeline=pipeline,
220
+ query={"event": [event_number]},
221
+ projection={},
222
+ limit=-1,
223
+ )
224
+
225
+ def get_locked(
226
+ self, pipeline: str, skip: int = 0, count: int = 10
227
+ ) -> List[Dict[str, Any]]:
228
+ """Get work that is locked from the results backend.
229
+
230
+ Args:
231
+ pipeline (str): The name of the pipeline.
232
+ skip (int, optional): The number of results to skip. Defaults to 0.
233
+ count (int, optional): The maximum number of results. Defaults to 10.
234
+
235
+ Note:
236
+ Only results with valid results, plots and products are returned.
237
+
238
+ Returns:
239
+ List[Dict[str, Any]]: A list of the locked results.
240
+ """
241
+ return self.view(
242
+ pipeline=pipeline,
243
+ query={"results.locked": True},
244
+ projection={
245
+ "event": True,
246
+ "plots": True,
247
+ "products": True,
248
+ "results": True,
249
+ },
250
+ skip=skip,
251
+ limit=count,
252
+ )
253
+
254
+ def get_locked_count(self, pipeline: str) -> int:
255
+ """Retrieves the count of locked results.
256
+
257
+ Args:
258
+ pipeline (str): The name of the pipeline.
259
+
260
+ Returns:
261
+ int: The count of locked results.
262
+ """
263
+ return self.count(
264
+ pipeline=pipeline,
265
+ query={"results.locked": True},
266
+ )
267
+
268
+ def lock(self, pipeline: str, ids: List[str]) -> bool:
269
+ """Lock results.
270
+
271
+ Note:
272
+ A locked result cannot be deleted or updated.
273
+
274
+ Args:
275
+ pipeline (str): The name of the pipeline.
276
+ ids (List[str]): The IDs of the results to lock.
277
+
278
+ Returns:
279
+ Boolean: True if successful, False if not.
280
+ """
281
+ payload: List[Dict[str, Any]] = self.get_by_id(pipeline, ids)
282
+ for work in payload:
283
+ work["results"]["locked"] = True
284
+ response = self.update(payload)
285
+ return True if response else False
286
+
287
+ def unlock(self, pipeline: str, ids: List[str], force: bool = False) -> bool:
288
+ """Unlock results.
289
+
290
+ Args:
291
+ pipeline (str): The pipeline name.
292
+ ids (List[str]): The IDs of the results to unlock.
293
+ force (bool): Force the unlock. Defaults to False.
294
+
295
+ Returns:
296
+ Bool: True if successful, False if not.
297
+ """
298
+ msg = "Unlocking results will allow them to be deleted or updated."
299
+ if force or confirmation(msg):
300
+ works = self.get_by_id(pipeline, ids)
301
+ for work in works:
302
+ work["results"]["locked"] = False
303
+ response = self.update(works)
304
+ return True if response else False
305
+ return False