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,112 @@
1
+ """Workflow lifecycle module."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ from requests import exceptions
6
+
7
+ from workflow.definitions.work import Work
8
+ from workflow.http.context import HTTPContext
9
+ from workflow.lifecycle import archive, execute
10
+ from workflow.utils.logger import get_logger, set_tag, unset_tag
11
+
12
+ logger = get_logger("workflow.lifecycle.attempt")
13
+
14
+
15
+ def work(
16
+ buckets: List[str],
17
+ function: Optional[str],
18
+ command: Optional[str],
19
+ site: str,
20
+ tags: List[str],
21
+ parents: List[str],
22
+ events: List[int],
23
+ config: Dict[str, Any],
24
+ http: Optional[HTTPContext] = None,
25
+ ) -> bool:
26
+ """Attempt to perform work.
27
+
28
+ Args:
29
+ buckets (List[str]): Name of the buckets to perform work from.
30
+ function (Optional[str]): Static function to perform work.
31
+ site (str): Site to filter work by.
32
+ tags (List[str]): Tags to filter work by.
33
+ parents (List[str]): Parent pipeline to filter work by.
34
+ config (Dict[str, Any]): Workspace configuration.
35
+
36
+ Raises:
37
+ TimeoutError: _description_
38
+
39
+ Returns:
40
+ bool: _description_
41
+ """
42
+ work: Optional[Work] = None
43
+ status: bool = False
44
+
45
+ try:
46
+ # Attempt to get work from the workflow queue
47
+ try:
48
+ work = Work.withdraw(
49
+ pipeline=buckets,
50
+ site=site,
51
+ tags=tags,
52
+ parent=parents,
53
+ event=events,
54
+ http=http,
55
+ )
56
+ except exceptions.ConnectTimeout as error:
57
+ logger.error("connection timeout getting work")
58
+ raise error
59
+ except exceptions.RequestException as error:
60
+ logger.error("request exception getting work")
61
+ raise error
62
+ except Exception as error:
63
+ logger.error("error getting work")
64
+ raise error
65
+
66
+ if work:
67
+ # Set the work id for the logger
68
+ set_tag(work.id) # type: ignore
69
+ logger.info("got work: ✅")
70
+ logger.debug(f"{work.payload}")
71
+
72
+ # When overloading, work cannot have both a function and a command
73
+ if function:
74
+ logger.debug(f"overloading work with static function: {function}")
75
+ work.command = None
76
+ work.function = function
77
+ if command:
78
+ logger.debug(f"overloading work with static command: {command}")
79
+ work.function = None
80
+ work.command = command.split(" ")
81
+
82
+ assert work.command or work.function, "neither function or command provided"
83
+
84
+ # Get the user function from the work object dynamically
85
+ if work.function:
86
+ logger.debug(f"executing function: {work.function}")
87
+ work = execute.function(work)
88
+
89
+ # If we have a valid command, execute it
90
+ if work.command:
91
+ logger.debug(f"executing command: {work.command}")
92
+ work = execute.command(work)
93
+
94
+ # * Note: work.status is already set to either "success" or "failure"
95
+ # * in the execute module. We don't need to set it here.
96
+
97
+ archive.run(work, config)
98
+ work.update()
99
+ status = True
100
+ except Exception as error:
101
+ logger.error(error)
102
+ if work:
103
+ work.results = {"error": str(error)}
104
+ work.products = None
105
+ work.plots = None
106
+ work.status = "failure"
107
+ finally:
108
+ if work:
109
+ work.update()
110
+ logger.info("work completed: ✅")
111
+ unset_tag()
112
+ return status
@@ -0,0 +1,152 @@
1
+ """Configure workflow during the lifecycle."""
2
+
3
+ from logging import Formatter, Logger
4
+ from pathlib import Path
5
+ from typing import Any, Callable, Dict, List, Optional, Union
6
+
7
+ import click
8
+ import requests
9
+ from logging_loki import LokiHandler
10
+
11
+ from workflow import DEFAULT_WORKSPACE_PATH
12
+ from workflow.definitions.work import Work
13
+ from workflow.utils import read, validate, write
14
+ from workflow.utils.logger import get_logger
15
+
16
+ logger = get_logger("workflow.lifecycle.process")
17
+
18
+
19
+ def workspace(workspace: Union[str, Dict[Any, Any]]):
20
+ """Configure the workspace during the lifecycle.
21
+
22
+ Args:
23
+ workspace (Union[str, Dict[Any, Any]]): Workspace configuration src.
24
+ """
25
+ # workspace passed as a string for Path or URL
26
+ if isinstance(workspace, str):
27
+ if Path(workspace).absolute().exists():
28
+ if workspace == DEFAULT_WORKSPACE_PATH.as_posix():
29
+ logger.info("Running with active workspace.")
30
+ else:
31
+ logger.info(f"Saving {workspace} as active workspace.")
32
+ # Save the workspace path to the default location
33
+ write.workspace(Path(workspace))
34
+ # Check if the workspace is a URL
35
+ elif validate.url(workspace):
36
+ logger.info(f"Running with workspace from URL {workspace}")
37
+ # Fetch the workspace from the URL
38
+ payload = read.url(workspace)
39
+ logger.info(f"URL Workspace: {payload}")
40
+ # Save the workspace to the default location
41
+ write.workspace(payload)
42
+
43
+ if isinstance(workspace, dict):
44
+ name: Optional[str] = workspace.get("workspace")
45
+ logger.info(f"Running with dict workspace: {name}")
46
+ # Save the workspace to the default location
47
+ write.workspace(workspace)
48
+
49
+
50
+ def loki(logger: Logger, config: Dict[str, Any]) -> bool:
51
+ """Add a Loki handler to the logger.
52
+
53
+ Args:
54
+ logger (Logger): Python logger
55
+ config (Dict[str, Any]): Workspace configuration
56
+
57
+ Returns:
58
+ bool: Loki handler status
59
+ """
60
+ status: bool = False
61
+ urls: List[str] = []
62
+ loki_urls: Optional[Any] = config.get("http", {}).get("baseurls", {}).get("loki")
63
+ loki_tags: Optional[Any] = config.get("logging", {}).get("loki", {}).get("tags", {})
64
+ if not loki_urls:
65
+ return status
66
+ elif isinstance(loki_urls, str):
67
+ urls = [loki_urls]
68
+ elif isinstance(loki_urls, list):
69
+ urls = loki_urls
70
+ else:
71
+ logger.error(f"Invalid Loki URL: {loki_urls}")
72
+ return status
73
+
74
+ for url in urls:
75
+ try:
76
+ status_code: int = requests.get(
77
+ url.replace("loki/api/v1/push", "ready"), timeout=1
78
+ ).status_code
79
+ if status_code == 200:
80
+ loki_handler = LokiHandler(url=url, tags=loki_tags, version="1")
81
+ loki_handler.setFormatter(
82
+ Formatter("%(levelname)s %(tag)s %(name)s %(message)s")
83
+ )
84
+ loki_handler.setLevel(logger.root.level)
85
+ logger.root.addHandler(loki_handler)
86
+ logger.debug(f"Loki URL: {url}")
87
+ status = True
88
+ return status
89
+ except Exception as error:
90
+ logger.debug(error)
91
+ return status
92
+
93
+
94
+ def arguments(arguments: Optional[Dict[str, Any]]) -> List[str]:
95
+ """Return a list of CLI arguments.
96
+
97
+ Args:
98
+ arguments (Dict[str, Any]): CLI arguments
99
+
100
+ Returns:
101
+ List[str]: List of CLI arguments
102
+ """
103
+ args: List[str] = []
104
+ if arguments:
105
+ for key, value in arguments.items():
106
+ if not value:
107
+ args.append(f"{key}")
108
+ elif value and len(key) == 2:
109
+ args.append(f"{key} {value}")
110
+ elif value and len(key) > 2:
111
+ args.append(f"{key}={value}")
112
+ return args
113
+
114
+
115
+ def defaults(func: Callable[..., Any], work: Work) -> Work:
116
+ """Gather the parameters for the user function.
117
+
118
+ Args:
119
+ func (Callable[..., Any]): User function
120
+ work (Work): Work object
121
+
122
+ Returns:
123
+ Tuple[Callable[..., Any], Dict[str, Any]]:
124
+ Tuple of user function and parameters
125
+ """
126
+ # Options calculated from the click command and work parameters
127
+ options: Dict[str, Any] = {}
128
+ # Parameters passed to work object
129
+ parameters: Dict[str, Any] = work.parameters or {}
130
+ # Known work parameters keys
131
+ known: List[Any] = list(work.parameters.keys()) if work.parameters else []
132
+ if isinstance(func, click.Command):
133
+ logger.info(f"click cli detected for func {work.function}")
134
+ # Get default options from the click command
135
+ for parameter in func.params:
136
+ if (parameter.name not in known) and parameter.default:
137
+ if parameter.is_flag: # type: ignore
138
+ options[parameter.opts[-1]] = None
139
+ else:
140
+ options[parameter.opts[-1]] = parameter.default
141
+ elif parameter.name in known:
142
+ if parameter.is_flag:
143
+ if parameter.default == parameters.get(parameter.name):
144
+ options[parameter.opts[-1]] = None
145
+ else:
146
+ options[parameter.opts[-1]] = parameters.get(
147
+ parameter.name # type: ignore
148
+ )
149
+ logger.info(f"click cli options: {options}")
150
+ work.parameters = options
151
+ logger.debug(f"work parameters: {work.parameters}")
152
+ return work
@@ -0,0 +1,159 @@
1
+ """Execute the work function or command."""
2
+
3
+ import subprocess
4
+ import time
5
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union, get_type_hints
6
+
7
+ import click
8
+
9
+ from workflow.definitions.work import Work
10
+ from workflow.lifecycle import configure
11
+ from workflow.utils import validate
12
+ from workflow.utils.logger import get_logger
13
+
14
+ logger = get_logger("workflow.lifecycle.execute")
15
+
16
+ Outcome = Union[Dict[str, Any], Tuple[Dict[str, Any], List[str], List[str]], Any, None]
17
+
18
+
19
+ def function(work: Work) -> Work:
20
+ """Execute a Python function.
21
+
22
+ Args:
23
+ func (Callable[..., Any]): Python function
24
+ work (Work): The work object
25
+
26
+ Returns:
27
+ Work: The work object
28
+ """
29
+ logger.debug(f"executing func: {work.function}")
30
+ start = time.time()
31
+ outcome: Outcome = None
32
+ results: Optional[Dict[str, Any]] = None
33
+ products: Optional[List[str]] = None
34
+ plots: Optional[List[str]] = None
35
+ try:
36
+ assert isinstance(work.function, str), "missing function to execute"
37
+ func: Callable[..., Any] = validate.function(work.function)
38
+ arguments: List[str] = []
39
+ # Configure default values for the function
40
+ work = configure.defaults(func, work)
41
+ # Paramters to execute the function with
42
+ parameters: Dict[str, Any] = work.parameters or {}
43
+
44
+ if isinstance(func, click.Command):
45
+ arguments = configure.arguments(parameters)
46
+ logger.info(
47
+ f"executing: {func.name}.main(args={arguments}, standalone_mode=False)"
48
+ )
49
+ outcome = func.main(args=arguments, standalone_mode=False)
50
+ else:
51
+ logger.info(
52
+ f"executing as python function: {func.__name__}(**{work.parameters})"
53
+ )
54
+ outcome = func(**parameters)
55
+ logger.info(f"func call outcome: {outcome}")
56
+ results, products, plots = validate.outcome(outcome)
57
+ logger.debug(f"results: {results}")
58
+ logger.debug(f"products: {products}")
59
+ logger.debug(f"plots: {plots}")
60
+ # * Merge work object with results, products, and plots
61
+ if results and not work.results:
62
+ work.results = results
63
+ if results and work.results:
64
+ work.results = {**work.results, **results}
65
+ if products:
66
+ work.products = (work.products or []) + products
67
+ if plots:
68
+ work.plots = (work.plots or []) + plots
69
+ work = validate.size(work)
70
+ work.status = "success"
71
+ except Exception as error:
72
+ work.status = "failure"
73
+ logger.error(error)
74
+ finally:
75
+ end = time.time()
76
+ work.stop = end
77
+ logger.info(f"execution time: {end - start:.2f}s")
78
+ return work
79
+
80
+
81
+ def command(work: Work) -> Work:
82
+ """Execute a command.
83
+
84
+ Args:
85
+ command (List[str]): Command to execute
86
+ work (Work): Work object
87
+
88
+ Returns:
89
+ Work: Work object
90
+ """
91
+ # Execute command in a subprocess with stdout and stderr redirected to PIPE
92
+ # and timeout of work.timeout
93
+ logger.debug(f"executing command: {work.command}")
94
+ start = time.time()
95
+ try:
96
+ assert isinstance(work.command, list), "missing command to execute"
97
+ validate.command(work.command[0])
98
+ process = subprocess.run(
99
+ work.command,
100
+ stdout=subprocess.PIPE,
101
+ stderr=subprocess.PIPE,
102
+ timeout=work.timeout,
103
+ )
104
+ # Check return code
105
+ process.check_returncode()
106
+ # Convert stdout and stderr to strings
107
+ stdout = process.stdout.decode("utf-8").splitlines()
108
+ stderr = process.stderr.decode("utf-8").splitlines()
109
+ # Convert last line of stdout to a Tuple
110
+ if not (work.results or work.products or work.plots):
111
+ work.results = {
112
+ "args": process.args,
113
+ "stdout": stdout,
114
+ "stderr": stderr,
115
+ "returncode": process.returncode,
116
+ }
117
+ # * Check if results are less than 4MB
118
+ validate.size(work)
119
+ work.status = "success"
120
+ except Exception as error:
121
+ work.status = "failure"
122
+ logger.exception(error)
123
+ finally:
124
+ end = time.time()
125
+ work.stop = end
126
+ logger.info(f"execution time: {end - start:.2f}s")
127
+ return work
128
+
129
+
130
+ def with_work(work: Work) -> Work:
131
+ """Execute a work function with work object.
132
+
133
+ Args:
134
+ work (Work): Work object
135
+
136
+ Returns:
137
+ Work: Work object
138
+ """
139
+ logger.debug(f"executing with work: {work.function}")
140
+ start = time.time()
141
+ try:
142
+ assert isinstance(work.function, str), "missing function to execute"
143
+ func: Callable[..., Any] = validate.function(work.function)
144
+ # Check the type hints of the function,
145
+ # check if the input/output is a Work object
146
+ hints = get_type_hints(func)
147
+ logger.info(f"function hints: {hints}")
148
+ assert hints.get("work") == Work, "function must have a Work object as input"
149
+ assert hints.get("return") == Work, "function must return a Work object"
150
+ work = func(work)
151
+ work.status = "success"
152
+ except Exception as error:
153
+ work.status = "failure"
154
+ logger.error(error)
155
+ finally:
156
+ end = time.time()
157
+ work.stop = end
158
+ logger.info(f"execution time: {end - start:.2f}s")
159
+ return work
File without changes
@@ -0,0 +1,29 @@
1
+ """Workflow decorators."""
2
+
3
+ import functools
4
+ from typing import Any, Callable
5
+
6
+ from workflow.utils.logger import get_logger
7
+
8
+ logger = get_logger("workflow.utils.decorators")
9
+
10
+
11
+ def try_request(func: Callable[..., Any]) -> Callable[..., Any]:
12
+ """Try / Except wrapper for requests.
13
+
14
+ Args:
15
+ func (Callable[..., Any]): The function to wrap.
16
+
17
+ Returns:
18
+ Callable[..., Any]: The wrapped function.
19
+ """
20
+
21
+ @functools.wraps(func)
22
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
23
+ try:
24
+ return func(*args, **kwargs)
25
+ except Exception as error:
26
+ logger.exception(error)
27
+ raise error
28
+
29
+ return wrapper
@@ -0,0 +1,93 @@
1
+ """Workflow Python Logging Module."""
2
+
3
+ import logging
4
+ from datetime import datetime
5
+ from typing import Optional
6
+
7
+ import click
8
+ from rich.logging import RichHandler
9
+
10
+
11
+ def get_logger(name: Optional[str] = None, level: int = logging.INFO) -> logging.Logger:
12
+ """Create a python logger with rich logging handler.
13
+
14
+ Args:
15
+ name (Optional[str], optional): Name of the module. Defaults to None.
16
+ level (int, optional): . Defaults to logging.INFO.
17
+
18
+ Returns:
19
+ logging.Logger: Python logger object.
20
+ """
21
+ name = f"chimefrb.{name}" if name else "chimefrb"
22
+ log = logging.getLogger(name=name)
23
+ # Create timezone string
24
+ tz = datetime.now().astimezone().tzinfo
25
+ # # Detailed message format with level, module, line number, and and message
26
+ format = "%(tag)s %(name)s %(message)s"
27
+ logging.basicConfig(
28
+ level=level,
29
+ format=format,
30
+ datefmt=f"%d %b %Y %H:%M:%S {tz}",
31
+ handlers=[
32
+ RichHandler(
33
+ level=level,
34
+ show_path=False,
35
+ show_time=True,
36
+ omit_repeated_times=False,
37
+ markup=True,
38
+ log_time_format=f"%d %b %Y %H:%M:%S {tz}",
39
+ show_level=True,
40
+ rich_tracebacks=True,
41
+ tracebacks_suppress=[click],
42
+ tracebacks_show_locals=True,
43
+ )
44
+ ],
45
+ force=True,
46
+ )
47
+ for handler in logging.root.handlers:
48
+ handler.addFilter(TagFilter(tag=""))
49
+ return log
50
+
51
+
52
+ class TagFilter(logging.Filter):
53
+ """Filter log messages by tag."""
54
+
55
+ def __init__(self, tag: str) -> None:
56
+ """Initialize the tag.
57
+
58
+ Args:
59
+ tag (str): tag.
60
+ """
61
+ self.tag = tag
62
+
63
+ def filter(self, record: logging.LogRecord) -> bool:
64
+ """Filter log messages by tag.
65
+
66
+ Args:
67
+ record (logging.LogRecord): Log record.
68
+
69
+ Returns:
70
+ bool: True if the tag matches the log record.
71
+ """
72
+ record.tag = self.tag
73
+ return True
74
+
75
+
76
+ def set_tag(tag: str) -> None:
77
+ """Set the tag for the logger.
78
+
79
+ Args:
80
+ tag (str): tag.
81
+ """
82
+ for handler in logging.root.handlers:
83
+ for filter in handler.filters:
84
+ if isinstance(filter, TagFilter):
85
+ filter.tag = tag
86
+
87
+
88
+ def unset_tag() -> None:
89
+ """Unset the tag for the logger."""
90
+ for handler in logging.root.handlers:
91
+ for filter in handler.filters:
92
+ if isinstance(filter, TagFilter):
93
+ filter.tag = ""
@@ -0,0 +1,26 @@
1
+ """Utility functions for prompting the user for input."""
2
+
3
+ import click
4
+ from rich.console import Console
5
+
6
+ console = Console()
7
+
8
+
9
+ def confirmation(msg: str) -> bool:
10
+ """Get confirmation from the user.
11
+
12
+ Args:
13
+ msg (str): Message to display to the user.
14
+
15
+ Returns:
16
+ bool: True if the user confirms, False otherwise.
17
+ """
18
+ console.print(
19
+ "Please confirm the following action:",
20
+ style="bold red",
21
+ justify="center",
22
+ )
23
+ console.print(msg, style="magenta italic")
24
+ # Get confirmation from the user
25
+ confirmation = click.prompt('Type "yes" to confirm', default="no")
26
+ return confirmation.lower() == "yes"