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,286 @@
1
+ """Workflow Buckets API."""
2
+
3
+ from typing import Any, Dict, List, Optional, Union
4
+ from urllib.parse import urlencode
5
+
6
+ from requests.models import Response
7
+ from tenacity import retry
8
+ from tenacity.stop import stop_after_delay
9
+ from tenacity.wait import wait_random
10
+
11
+ from workflow.http.client import Client
12
+ from workflow.utils.logger import get_logger
13
+ from workflow.utils.prompt import confirmation
14
+
15
+ logger = get_logger("workflow.http.buckets")
16
+
17
+
18
+ class Buckets(Client):
19
+ """HTTP Client for interacting with the Buckets backend.
20
+
21
+ Args:
22
+ Client (workflow.http.client): The base class for interacting with the backend.
23
+
24
+ Returns:
25
+ Buckets: A client for interacting with the Buckets backend.
26
+ """
27
+
28
+ @retry(wait=wait_random(min=0.1, max=2), stop=(stop_after_delay(30)))
29
+ def deposit(
30
+ self, works: List[Dict[str, Any]], return_ids: bool = False
31
+ ) -> Union[bool, List[str]]:
32
+ """Deposit works into the buckets backend.
33
+
34
+ Args:
35
+ works (List[Dict[str, Any]]): The payload from the Work Object.
36
+ return_ids (bool, optional): Whether to return the ids of the works.
37
+ Defaults to False.
38
+
39
+ Raises:
40
+ RequestException: If the request fails.
41
+
42
+ Returns:
43
+ Union[bool, List[str]]:
44
+ Whether the request was successful or the ids of the works.
45
+
46
+ Examples:
47
+ >>> from chime_frb_api.buckets import Buckets
48
+ >>> from chime_frb_api.tasks import Work
49
+ >>> work = Work(pipeline="sample")
50
+ >>> buckets.deposit([work.payload])
51
+ True
52
+ >>> buckets.deposit([work.payload], return_ids=True)
53
+ ["5f9b5e1b7e5c4b5eb1b""]
54
+ """
55
+ params: Dict[str, Any] = {"return_ids": return_ids}
56
+ with self.session as session:
57
+ response: Response = session.post(
58
+ url=f"{self.baseurl}/work?{urlencode(params)}",
59
+ json=works,
60
+ params=params,
61
+ timeout=self.timeout,
62
+ )
63
+ response.raise_for_status()
64
+ if return_ids:
65
+ return response.json()
66
+ return True
67
+
68
+ def withdraw(
69
+ self,
70
+ pipeline: Union[str, List[str]],
71
+ event: Optional[List[int]] = None,
72
+ site: Optional[str] = None,
73
+ priority: Optional[int] = None,
74
+ user: Optional[str] = None,
75
+ tags: Optional[List[str]] = None,
76
+ parent: Optional[List[str]] = None,
77
+ ) -> Dict[str, Any]:
78
+ """Withdraw `queued` work from the buckets backend.
79
+
80
+ Args:
81
+ pipeline (str | List[str]): The pipeline to withdraw work from.
82
+ event (Optional[List[int]], optional): The event to filter by.
83
+ site (Optional[str], optional): The site to filter by.
84
+ priority (Optional[int], optional): The priority to withdraw from.
85
+ user (Optional[str], optional): The user to filter by.
86
+ tags (Optional[List[str]], optional): The tags to filter by.
87
+ parent (Optional[str], optional): The parent to filter by.
88
+
89
+ Raises:
90
+ RequestException: If the request fails.
91
+
92
+ Returns:
93
+ Dict[str, Any]: The work withdrawn.
94
+ """
95
+ if isinstance(pipeline, str):
96
+ pipeline = [pipeline]
97
+ query: Dict[str, Any] = {"pipeline": {"$in": pipeline}}
98
+ query.update({"site": site} if site else {})
99
+ query.update({"priority": priority} if priority else {})
100
+ query.update({"user": user} if user else {})
101
+ query.update({"event": {"$in": event}} if event else {})
102
+ query.update({"tags": {"$in": tags}} if tags else {})
103
+ query.update({"config.parent": {"$in": parent}} if parent else {})
104
+ with self.session as session:
105
+ response: Response = session.post(
106
+ url=f"{self.baseurl}/work/withdraw", json=query
107
+ )
108
+ response.raise_for_status()
109
+ return response.json()
110
+
111
+ @retry(wait=wait_random(min=0.1, max=2), stop=(stop_after_delay(30)))
112
+ def update(self, works: List[Dict[str, Any]]) -> bool:
113
+ """Update works in the buckets backend.
114
+
115
+ Args:
116
+ works (List[Dict[str, Any]]): The payload from the Work Object.
117
+
118
+ Returns:
119
+ bool: Whether the works were updated successfully.
120
+ """
121
+ with self.session as session:
122
+ response: Response = session.put(url=f"{self.baseurl}/work", json=works)
123
+ response.raise_for_status()
124
+ return response.json()
125
+
126
+ @retry(wait=wait_random(min=0.1, max=2), stop=(stop_after_delay(30)))
127
+ def delete_ids(self, ids: List[str]) -> bool:
128
+ """Delete works from the buckets backend with the given ids.
129
+
130
+ Args:
131
+ ids (List[str]): The IDs of the works to delete.
132
+
133
+ Returns:
134
+ bool: Whether the works were deleted successfully.
135
+ """
136
+ with self.session as session:
137
+ response: Response = session.delete(
138
+ url=f"{self.baseurl}/work", params={"ids": ids}
139
+ )
140
+ response.raise_for_status()
141
+ return response.json()
142
+
143
+ def delete_many(
144
+ self,
145
+ pipeline: str,
146
+ status: Optional[str] = None,
147
+ events: Optional[List[int]] = None,
148
+ tags: Optional[List[str]] = None,
149
+ parent: Optional[str] = None,
150
+ force: bool = False,
151
+ ) -> bool:
152
+ """Delete works belonging to a pipeline from the buckets backend.
153
+
154
+ If a status is provided, only works with that status will be deleted.
155
+ If an event number is provided, only works with that event will be deleted.
156
+
157
+ Args:
158
+ pipeline (str): The pipeline to delete works from.
159
+ status (Optional[List[str]]): The status to delete works with.
160
+ e.g. ["queued"].
161
+ event (Optional[List[int]]): The event to delete works with.
162
+ force (bool, optional): Whether to force the deletion without requiring
163
+ user confirmation. Defaults to False.
164
+
165
+ Returns:
166
+ bool: Whether any works were deleted.
167
+ """
168
+ query: Dict[str, Any] = {"pipeline": pipeline}
169
+ query.update({"status": status} if status else {})
170
+ query.update({"event": {"$in": events}} if events else {})
171
+ query.update({"tags": {"$in": tags}} if tags else {})
172
+ query.update({"config.parent": parent} if parent else {})
173
+ projection = {"id": True}
174
+ result = self.view(query, projection)
175
+ ids: List[str] = []
176
+ if result:
177
+ ids = [work["id"] for work in result]
178
+ # Get user confirmation before deleting
179
+ if ids and not force:
180
+ msg = f"Are you sure you want to delete {len(ids)} works?"
181
+ # Display upto 5 ids only
182
+ msg += "\n\tids: " + ", ".join(ids[:5]) + ("..." if len(ids) > 5 else "")
183
+ msg += "\n\tstatus: " + status if status else ""
184
+ msg += "\n\tevents: " + ", ".join(map(str, events)) if events else ""
185
+ msg += "\n\ttags: " + ", ".join(tags) if tags else ""
186
+ msg += "\n\tparent: " + parent if parent else ""
187
+ force = confirmation(msg)
188
+ if ids and force:
189
+ return self.delete_ids(ids)
190
+ return False
191
+
192
+ def status(self, pipeline: Optional[str] = None) -> Dict[str, Any]:
193
+ """View the status of the buckets backend.
194
+
195
+ If overall is True, the status of all pipelines will be returned.
196
+
197
+ Args:
198
+ pipeline (Optional[str], optional): The pipeline to return the status of.
199
+
200
+ Returns:
201
+ List[Dict[str, Any]]: The status of the buckets backend.
202
+ """
203
+ url: str = f"{self.baseurl}/status"
204
+ if pipeline:
205
+ url = f"{url}/details/{pipeline}"
206
+ with self.session as session:
207
+ response: Response = session.get(url=url)
208
+ response.raise_for_status()
209
+ return response.json()
210
+
211
+ def pipelines(self) -> List[str]:
212
+ """View the current pipelines in the buckets backend.
213
+
214
+ Returns:
215
+ List[str]: The current pipelines.
216
+ """
217
+ with self.session as session:
218
+ response: Response = session.get(url=f"{self.baseurl}/status/pipelines")
219
+ response.raise_for_status()
220
+ return response.json()
221
+
222
+ def view(
223
+ self,
224
+ query: Dict[str, Any],
225
+ projection: Dict[str, bool] = {},
226
+ skip: int = 0,
227
+ limit: Optional[int] = 100,
228
+ ) -> List[Dict[str, Any]]:
229
+ """View works in the buckets backend.
230
+
231
+ Args:
232
+ query (Dict[str, Any]): The query to filter the works with.
233
+ projection (Dict[str, bool]): The projection to use to map the output.
234
+ skip (int, optional): The number of works to skip. Defaults to 0.
235
+ limit (Optional[int], optional): The number of works to limit to.
236
+ Defaults to 100.
237
+
238
+ Returns:
239
+ List[Dict[str, Any]]: The works matching the query.
240
+ """
241
+ projection.update({"_id": False})
242
+ payload = {
243
+ "query": query,
244
+ "projection": projection,
245
+ "skip": skip,
246
+ "limit": limit,
247
+ }
248
+ with self.session as session:
249
+ response: Response = session.post(url=f"{self.baseurl}/view", json=payload)
250
+ response.raise_for_status()
251
+ return response.json()
252
+
253
+ def audit(self) -> Dict[str, Any]:
254
+ """Audit work buckets backend.
255
+
256
+ The audit process retries failed work, expires any work past the
257
+ expiration time and checks for any stale work older than 7 days.
258
+
259
+ Returns:
260
+ Dict[str, Any]: The audit results.
261
+ """
262
+ reply: Dict[str, Any] = {}
263
+ urls: Dict[str, str] = {
264
+ "failed": "/audit/failed",
265
+ "expired": "/audit/expired",
266
+ "stale": "/audit/stale/7.0",
267
+ }
268
+ with self.session as session:
269
+ for process, url in urls.items():
270
+ response: Response = session.get(url=f"{self.baseurl}{url}")
271
+ response.raise_for_status()
272
+ reply[process] = response.json()
273
+ return reply
274
+
275
+ def info(self) -> Dict[str, Any]:
276
+ """Get the version of the buckets backend.
277
+
278
+ Returns:
279
+ Dict[str, Any]: The version of the buckets backend.
280
+ """
281
+ client_info = self.model_dump()
282
+ with self.session as session:
283
+ response: Response = session.get(url=f"{self.baseurl}/version")
284
+ response.raise_for_status()
285
+ server_info = response.json()
286
+ return {"client": client_info, "server": server_info}
@@ -0,0 +1,136 @@
1
+ """HTTP client for interacting with the Workflow Servers."""
2
+
3
+ from platform import machine, platform, python_version, release, system
4
+ from time import asctime, gmtime
5
+ from typing import List, Optional, Union
6
+ from warnings import warn
7
+
8
+ from pydantic import (
9
+ AliasChoices,
10
+ AnyHttpUrl,
11
+ Field,
12
+ SecretStr,
13
+ field_validator,
14
+ model_validator,
15
+ )
16
+ from pydantic_settings import BaseSettings, SettingsConfigDict
17
+ from requests import Session, head
18
+ from requests.exceptions import RequestException
19
+ from requests.models import Response
20
+
21
+ from workflow import __version__
22
+ from workflow.utils.logger import get_logger
23
+
24
+ logger = get_logger("workflow.http.client")
25
+
26
+
27
+ class Client(BaseSettings):
28
+ """A client for interacting with the Workflow Servers.
29
+
30
+ Args:
31
+ BaseModel (BaseModel): Pydantic base model.
32
+
33
+ Attributes:
34
+ baseurl (str): Base URLs for the server.
35
+ token (Optional[SecretStr]): Authentication token.
36
+ timeout (float): Request timeout in seconds.
37
+ session (requests.Session): HTTP request session.
38
+
39
+ Returns:
40
+ Client: A client for interacting with the Workflow Servers.
41
+ """
42
+
43
+ model_config = SettingsConfigDict(
44
+ title="Workflow HTTP Client",
45
+ arbitrary_types_allowed=True,
46
+ env_prefix="WORKFLOW_HTTP_",
47
+ secrets_dir="/run/secrets",
48
+ validate_assignment=True,
49
+ extra="ignore",
50
+ )
51
+ baseurl: Union[str, List[str]] = Field(
52
+ ..., description="Base URLs to for the server"
53
+ )
54
+ timeout: float = Field(default=15.0, description="Request timeout in seconds")
55
+ token: Optional[SecretStr] = Field(
56
+ default=None,
57
+ validation_alias=AliasChoices(
58
+ "WORKFLOW_HTTP_TOKEN",
59
+ "WORKFLOW_TOKEN",
60
+ "GITHUB_TOKEN",
61
+ "GITHUB_PAT",
62
+ ),
63
+ description="Authentication token",
64
+ )
65
+ session: Session = Field(
66
+ default=Session(), description="Requests Session", exclude=True
67
+ )
68
+
69
+ @model_validator(mode="after")
70
+ def configure_session(self) -> "Client":
71
+ """Validates the model after initialization.
72
+
73
+ Returns:
74
+ Client: The validated client instance.
75
+
76
+ """
77
+ if self.token:
78
+ self.session.headers.update(
79
+ {"x-access-token": self.token.get_secret_value()}
80
+ )
81
+ self.session.headers.update({"Content-Type": "application/json; charset=utf-8"})
82
+ self.session.headers.update({"Accept": "*/*"})
83
+ self.session.headers.update({"User-Agent": "workflow-client"})
84
+ self.session.headers.update({"Date": asctime(gmtime())})
85
+ self.session.headers.update({"X-Workflow-Core-Version": __version__})
86
+ self.session.headers.update(
87
+ {"X-Workflow-Client-Python-Version": python_version()}
88
+ )
89
+ self.session.headers.update({"X-Workflow-Client-Arch": machine()})
90
+ self.session.headers.update({"X-Workflow-Client-OS": system()})
91
+ self.session.headers.update({"X-Workflow-Client-OS-Version": release()})
92
+ self.session.headers.update({"X-Workflow-Client-Platform": platform()})
93
+ logger.debug(f"Configured Session: {self.session.headers}")
94
+ return self
95
+
96
+ @field_validator("baseurl")
97
+ def validate_baseurl(cls, baseurl: Union[str, List[str]]) -> str:
98
+ """Validate the baseurl.
99
+
100
+ Args:
101
+ baseurl(Union[str, List[str]]): Baseurls to validate.
102
+
103
+ Raises:
104
+ AttributeError: The baseurl is not a valid URL.
105
+ RequestException: The baseurl is not reachable.
106
+
107
+ Returns:
108
+ str: The validated baseurl.
109
+ """
110
+ if isinstance(baseurl, str):
111
+ baseurl = [baseurl]
112
+ for url in baseurl:
113
+ try:
114
+ AnyHttpUrl(url) # type: ignore
115
+ response: Response = head(f"{url}/version", timeout=5)
116
+ response.raise_for_status()
117
+ logger.debug(f"Validated baseurl: {url}")
118
+ return url
119
+ except RequestException as error:
120
+ logger.debug(error)
121
+ raise AttributeError(f"Unable to validate any baseurl: {baseurl}")
122
+
123
+ @field_validator("token", mode="after", check_fields=True)
124
+ def validate_token(cls, token: Optional[str]) -> Optional[str]:
125
+ """Validate the token.
126
+
127
+ Args:
128
+ token (Optional[str]): Token to use for authentication.
129
+
130
+ Returns:
131
+ Optional[str]: Token to use for authentication.
132
+ """
133
+ if not token:
134
+ msg = "WORKFLOW_TOKEN missing. Token auth will be required in the future."
135
+ warn(msg, FutureWarning, stacklevel=2)
136
+ return token
@@ -0,0 +1,165 @@
1
+ """Workflow Pipelines API."""
2
+
3
+ from json import dumps
4
+ from typing import Any, Dict, List, Optional
5
+ from urllib.parse import urlencode
6
+
7
+ from requests.models import Response
8
+ from tenacity import retry
9
+ from tenacity.stop import stop_after_delay
10
+ from tenacity.wait import wait_random
11
+
12
+ from workflow.http.client import Client
13
+
14
+
15
+ class Configs(Client):
16
+ """HTTP Client for interacting with the Configs endpoints on pipelines backend.
17
+
18
+ Args:
19
+ Client (workflow.http.client): The base class for interacting with the backend.
20
+
21
+ Returns:
22
+ Configs: A client for interacting with workflow-pipelines.
23
+ """
24
+
25
+ @retry(
26
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
27
+ )
28
+ def deploy(self, data: Dict[str, Any]):
29
+ """Deploys a Config from payload data.
30
+
31
+ Parameters
32
+ ----------
33
+ data : Dict[str, Any]
34
+ YAML data.
35
+
36
+ Returns
37
+ -------
38
+ List[str]
39
+ ID of Config object generated.
40
+ """
41
+ with self.session as session:
42
+ url = f"{self.baseurl}/configs"
43
+ response: Response = session.post(url, json=data)
44
+ response.raise_for_status()
45
+ return response.json()
46
+
47
+ def count(self) -> Dict[str, Any]:
48
+ """Count all documents in a collection.
49
+
50
+ Returns
51
+ -------
52
+ Dict[str, Any]
53
+ Dictionary with count.
54
+ """
55
+ with self.session as session:
56
+ response: Response = session.get(
57
+ url=f"{self.baseurl}/configs/count?database=configs"
58
+ )
59
+ response.raise_for_status()
60
+ return response.json()
61
+
62
+ def get_configs(
63
+ self,
64
+ name: Optional[str] = None,
65
+ query: Optional[str] = "{}",
66
+ projection: Optional[str] = "{}",
67
+ ) -> List[Dict[str, Any]]:
68
+ """View the current configurations on pipelines backend.
69
+
70
+ Parameters
71
+ ----------
72
+ name : str
73
+ Config name, by default None
74
+ query : str, optional
75
+ Query payload.
76
+ projection : str, optional
77
+ Query projection.
78
+
79
+ Returns
80
+ -------
81
+ List[Dict[str, Any]]
82
+ List of Config payloads.
83
+ """
84
+ with self.session as session:
85
+ # ? When using urlencode, internal dict object get single-quoted
86
+ # ? This can trigger error on workflow-pipelines backend
87
+ params = {"projection": projection, "query": query}
88
+ if name:
89
+ params.update({"name": name})
90
+ url = f"{self.baseurl}/configs?{urlencode(params)}"
91
+ response: Response = session.get(url=url)
92
+ response.raise_for_status()
93
+ return response.json()
94
+
95
+ @retry(
96
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
97
+ )
98
+ def remove(self, config: str, id: str) -> Response:
99
+ """Removes a cancelled pipeline configuration.
100
+
101
+ Parameters
102
+ ----------
103
+ config : str
104
+ Config name.
105
+ id : str
106
+ Config ID.
107
+
108
+ Returns
109
+ -------
110
+ List[Dict[str, Any]]
111
+ Response payload.
112
+ """
113
+ with self.session as session:
114
+ query = {"id": id}
115
+ params = {"query": dumps(query), "name": config}
116
+ url = f"{self.baseurl}/configs?{urlencode(params)}"
117
+ response: Response = session.delete(url=url)
118
+ response.raise_for_status()
119
+ return response
120
+
121
+ @retry(
122
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
123
+ )
124
+ def stop(self, config_name: str, id: str) -> List[Dict[str, Any]]:
125
+ """Stops the manager for a PipelineConfig.
126
+
127
+ Parameters
128
+ ----------
129
+ config_name : str
130
+ Config name.
131
+ id : str
132
+ Config ID.
133
+
134
+ Returns
135
+ -------
136
+ List[Dict[str, Any]]
137
+ List of stopped PipelineConfig objects.
138
+ """
139
+ with self.session as session:
140
+ query = {"id": id}
141
+ params = {"query": dumps(query), "name": config_name}
142
+ url = f"{self.baseurl}/configs/cancel?{urlencode(params)}"
143
+ response: Response = session.put(url)
144
+ response.raise_for_status()
145
+ if response.status_code == 304:
146
+ return []
147
+ return response.json()
148
+
149
+ @retry(
150
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
151
+ )
152
+ def info(self) -> Dict[str, Any]:
153
+ """Get the version of the pipelines backend.
154
+
155
+ Returns
156
+ -------
157
+ Dict[str, Any]
158
+ Pipelines backend info.
159
+ """
160
+ client_info = self.model_dump()
161
+ with self.session as session:
162
+ response: Response = session.get(url=f"{self.baseurl}/version")
163
+ response.raise_for_status()
164
+ server_info = response.json()
165
+ return {"client": client_info, "server": server_info}