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.
- workflow/__init__.py +17 -0
- workflow/cli/__init__.py +0 -0
- workflow/cli/buckets.py +124 -0
- workflow/cli/configs.py +279 -0
- workflow/cli/main.py +48 -0
- workflow/cli/pipelines.py +146 -0
- workflow/cli/results.py +168 -0
- workflow/cli/run.py +283 -0
- workflow/cli/schedules.py +234 -0
- workflow/cli/workspace.py +149 -0
- workflow/daemons/__init__.py +0 -0
- workflow/daemons/audit.py +74 -0
- workflow/daemons/transfer.py +255 -0
- workflow/definitions/__init__.py +0 -0
- workflow/definitions/config.py +124 -0
- workflow/definitions/jsonschema.md +28 -0
- workflow/definitions/notify.py +91 -0
- workflow/definitions/work.py +520 -0
- workflow/definitions/workspace.py +252 -0
- workflow/examples/function.py +92 -0
- workflow/examples/sample.svg +12 -0
- workflow/examples/sample.workflow.yml +31 -0
- workflow/helpers/__init__.py +0 -0
- workflow/helpers/date.py +33 -0
- workflow/http/__init__.py +0 -0
- workflow/http/buckets.py +286 -0
- workflow/http/client.py +136 -0
- workflow/http/configs.py +165 -0
- workflow/http/context.py +170 -0
- workflow/http/pipelines.py +123 -0
- workflow/http/results.py +305 -0
- workflow/http/schedules.py +157 -0
- workflow/lifecycle/__init__.py +1 -0
- workflow/lifecycle/archive/__init__.py +102 -0
- workflow/lifecycle/archive/http.py +58 -0
- workflow/lifecycle/archive/posix.py +185 -0
- workflow/lifecycle/archive/s3.py +157 -0
- workflow/lifecycle/attempt.py +112 -0
- workflow/lifecycle/configure.py +152 -0
- workflow/lifecycle/execute.py +159 -0
- workflow/utils/__init__.py +0 -0
- workflow/utils/decorators.py +29 -0
- workflow/utils/logger.py +93 -0
- workflow/utils/prompt.py +26 -0
- workflow/utils/read.py +146 -0
- workflow/utils/renderers.py +113 -0
- workflow/utils/tmate.sh +17 -0
- workflow/utils/validate.py +198 -0
- workflow/utils/variables.py +24 -0
- workflow/utils/write.py +44 -0
- workflow/workspaces/__init__.py +0 -0
- workflow/workspaces/chimefrb.yml +48 -0
- workflow/workspaces/development.yml +48 -0
- workflow/workspaces/site-dev.yml +36 -0
- workflow_core-1.4.0.dist-info/METADATA +115 -0
- workflow_core-1.4.0.dist-info/RECORD +58 -0
- workflow_core-1.4.0.dist-info/WHEEL +4 -0
- workflow_core-1.4.0.dist-info/entry_points.txt +3 -0
workflow/cli/results.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Results CLI Interface."""
|
|
2
|
+
|
|
3
|
+
from json import dumps
|
|
4
|
+
from typing import Any, Dict, Tuple
|
|
5
|
+
|
|
6
|
+
import click
|
|
7
|
+
from rich import pretty
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.json import JSON
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
|
|
12
|
+
from workflow.http.context import HTTPContext
|
|
13
|
+
|
|
14
|
+
pretty.install()
|
|
15
|
+
console = Console()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
table = Table(
|
|
19
|
+
title="\nWorkflow Results",
|
|
20
|
+
show_header=True,
|
|
21
|
+
header_style="magenta",
|
|
22
|
+
title_style="bold magenta",
|
|
23
|
+
)
|
|
24
|
+
status_colors = {
|
|
25
|
+
"success": "green",
|
|
26
|
+
"failure": "red",
|
|
27
|
+
}
|
|
28
|
+
yes_no_colors = {"yes": "green", "no": "red"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@click.group(name="results", help="Manage Workflow Results.")
|
|
32
|
+
def results():
|
|
33
|
+
"""Manage Workflow Results."""
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@results.command("version", help="Show the version.")
|
|
38
|
+
def version():
|
|
39
|
+
"""Show the version."""
|
|
40
|
+
http = HTTPContext(backends=["results"])
|
|
41
|
+
console.print(http.results.info())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@results.command("count", help="Count of results per pipeline.")
|
|
45
|
+
def count():
|
|
46
|
+
"""Count pipelines on results backend."""
|
|
47
|
+
http = HTTPContext(backends=["results"])
|
|
48
|
+
count_result = http.results.status()
|
|
49
|
+
table.add_column("Pipeline", max_width=50, justify="left", style="bright_blue")
|
|
50
|
+
table.add_column("Count", max_width=50, justify="left")
|
|
51
|
+
for pipeline, count in count_result.items():
|
|
52
|
+
table.add_row(pipeline, str(count))
|
|
53
|
+
console.print(table)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@results.command("view", help="View a set of filtered Results.")
|
|
57
|
+
@click.argument("pipeline", type=str, required=True)
|
|
58
|
+
@click.option(
|
|
59
|
+
"--status",
|
|
60
|
+
type=str,
|
|
61
|
+
multiple=True,
|
|
62
|
+
required=False,
|
|
63
|
+
default=None,
|
|
64
|
+
show_default=True,
|
|
65
|
+
help="Filter by status.",
|
|
66
|
+
)
|
|
67
|
+
@click.option(
|
|
68
|
+
"--event",
|
|
69
|
+
type=int,
|
|
70
|
+
multiple=True,
|
|
71
|
+
required=False,
|
|
72
|
+
default=None,
|
|
73
|
+
show_default=True,
|
|
74
|
+
help="Filter by event.",
|
|
75
|
+
)
|
|
76
|
+
@click.option(
|
|
77
|
+
"--tags",
|
|
78
|
+
type=str,
|
|
79
|
+
multiple=True,
|
|
80
|
+
required=False,
|
|
81
|
+
default=None,
|
|
82
|
+
show_default=True,
|
|
83
|
+
help="Filter by tags.",
|
|
84
|
+
)
|
|
85
|
+
@click.option(
|
|
86
|
+
"--limit",
|
|
87
|
+
type=int,
|
|
88
|
+
default=10,
|
|
89
|
+
show_default=True,
|
|
90
|
+
required=False,
|
|
91
|
+
help="Number of results to view.",
|
|
92
|
+
)
|
|
93
|
+
@click.option(
|
|
94
|
+
"--skip",
|
|
95
|
+
type=int,
|
|
96
|
+
default=0,
|
|
97
|
+
show_default=True,
|
|
98
|
+
required=False,
|
|
99
|
+
help="Number of results to skip.",
|
|
100
|
+
)
|
|
101
|
+
@click.option(
|
|
102
|
+
"--details",
|
|
103
|
+
is_flag=True,
|
|
104
|
+
default=False,
|
|
105
|
+
show_default=True,
|
|
106
|
+
required=False,
|
|
107
|
+
help="Show detailed information.",
|
|
108
|
+
)
|
|
109
|
+
@click.option(
|
|
110
|
+
"--json",
|
|
111
|
+
is_flag=True,
|
|
112
|
+
default=False,
|
|
113
|
+
show_default=True,
|
|
114
|
+
required=False,
|
|
115
|
+
help="Output as JSON.",
|
|
116
|
+
)
|
|
117
|
+
def view(
|
|
118
|
+
pipeline: str,
|
|
119
|
+
status: Tuple[str],
|
|
120
|
+
event: Tuple[int],
|
|
121
|
+
tags: Tuple[str],
|
|
122
|
+
skip: int = 0,
|
|
123
|
+
limit: int = 10,
|
|
124
|
+
details: bool = False,
|
|
125
|
+
json: bool = False,
|
|
126
|
+
):
|
|
127
|
+
"""View a set of filtered Results."""
|
|
128
|
+
http = HTTPContext()
|
|
129
|
+
if details:
|
|
130
|
+
projection = {}
|
|
131
|
+
else:
|
|
132
|
+
projection = {
|
|
133
|
+
"id": True,
|
|
134
|
+
"results": True,
|
|
135
|
+
"products": True,
|
|
136
|
+
"plots": True,
|
|
137
|
+
"status": True,
|
|
138
|
+
}
|
|
139
|
+
query: Dict[str, Any] = {}
|
|
140
|
+
if status:
|
|
141
|
+
query["status"] = {"$in": list(status)}
|
|
142
|
+
if event:
|
|
143
|
+
query["event"] = {"$in": list(event)}
|
|
144
|
+
if tags:
|
|
145
|
+
query["tags"] = {"$in": list(tags)}
|
|
146
|
+
|
|
147
|
+
results = http.results.view(
|
|
148
|
+
pipeline=pipeline, query=query, projection=projection, skip=skip, limit=limit
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
if json:
|
|
152
|
+
console.print(JSON(dumps(results), indent=2))
|
|
153
|
+
return
|
|
154
|
+
|
|
155
|
+
if not results:
|
|
156
|
+
console.print("No results found.")
|
|
157
|
+
return
|
|
158
|
+
from typing import List
|
|
159
|
+
|
|
160
|
+
values: List[JSON] = []
|
|
161
|
+
for name in results[0].keys():
|
|
162
|
+
table.add_column(name, justify="left", style="bright_blue")
|
|
163
|
+
for result in results:
|
|
164
|
+
for value in result.values():
|
|
165
|
+
values.append(JSON(dumps(value), indent=1))
|
|
166
|
+
table.add_row(*values)
|
|
167
|
+
console.print(table)
|
|
168
|
+
return
|
workflow/cli/run.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Fetch and process Work using any method compatible with Tasks API."""
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import signal
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from sys import stderr, stdout
|
|
7
|
+
from threading import Event
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
from click_params import JSON, URL, FirstOf
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
|
|
14
|
+
from workflow import DEFAULT_WORKSPACE_PATH
|
|
15
|
+
from workflow.http.context import HTTPContext
|
|
16
|
+
from workflow.lifecycle import attempt, configure
|
|
17
|
+
from workflow.utils import read
|
|
18
|
+
from workflow.utils.logger import get_logger
|
|
19
|
+
|
|
20
|
+
logger = get_logger("workflow.cli")
|
|
21
|
+
|
|
22
|
+
localspaces = Path(DEFAULT_WORKSPACE_PATH).parent
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@click.command("run", short_help="Fetch & Perform Work.")
|
|
26
|
+
@click.argument("bucket", type=str, nargs=-1, required=True)
|
|
27
|
+
@click.option(
|
|
28
|
+
"-s",
|
|
29
|
+
"--site",
|
|
30
|
+
type=click.STRING,
|
|
31
|
+
required=True,
|
|
32
|
+
show_default=True,
|
|
33
|
+
help="filter work by site.",
|
|
34
|
+
)
|
|
35
|
+
@click.option(
|
|
36
|
+
"-t",
|
|
37
|
+
"--tag",
|
|
38
|
+
type=click.STRING,
|
|
39
|
+
multiple=True,
|
|
40
|
+
required=False,
|
|
41
|
+
default=None,
|
|
42
|
+
show_default=True,
|
|
43
|
+
help="filter work by tag.(multiple allowed)",
|
|
44
|
+
)
|
|
45
|
+
@click.option(
|
|
46
|
+
"-p",
|
|
47
|
+
"--parent",
|
|
48
|
+
type=click.STRING,
|
|
49
|
+
multiple=True,
|
|
50
|
+
required=False,
|
|
51
|
+
default=None,
|
|
52
|
+
show_default=True,
|
|
53
|
+
help="filter work by parent.(multiple allowed)",
|
|
54
|
+
)
|
|
55
|
+
@click.option(
|
|
56
|
+
"-e",
|
|
57
|
+
"--event",
|
|
58
|
+
type=click.INT,
|
|
59
|
+
multiple=True,
|
|
60
|
+
required=False,
|
|
61
|
+
default=None,
|
|
62
|
+
show_default=True,
|
|
63
|
+
help="filter work by event.(multiple allowed)",
|
|
64
|
+
)
|
|
65
|
+
@click.option(
|
|
66
|
+
"-f",
|
|
67
|
+
"--function",
|
|
68
|
+
type=click.STRING,
|
|
69
|
+
required=False,
|
|
70
|
+
default=None,
|
|
71
|
+
show_default=True,
|
|
72
|
+
help="ignores work, runs this function instead",
|
|
73
|
+
)
|
|
74
|
+
@click.option(
|
|
75
|
+
"-c",
|
|
76
|
+
"--command",
|
|
77
|
+
type=click.STRING,
|
|
78
|
+
required=False,
|
|
79
|
+
default=None,
|
|
80
|
+
show_default=True,
|
|
81
|
+
help="ignores work, runs this command instead",
|
|
82
|
+
)
|
|
83
|
+
@click.option(
|
|
84
|
+
"--lives",
|
|
85
|
+
"-l",
|
|
86
|
+
type=click.IntRange(min=-1),
|
|
87
|
+
default=-1,
|
|
88
|
+
show_default=True,
|
|
89
|
+
help="count of work to perform.",
|
|
90
|
+
)
|
|
91
|
+
@click.option(
|
|
92
|
+
"--sleep",
|
|
93
|
+
type=click.IntRange(min=1, max=300),
|
|
94
|
+
default=30,
|
|
95
|
+
show_default=True,
|
|
96
|
+
help="seconds to sleep between work.",
|
|
97
|
+
)
|
|
98
|
+
@click.option(
|
|
99
|
+
"-w",
|
|
100
|
+
"--workspace",
|
|
101
|
+
type=FirstOf(
|
|
102
|
+
click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
|
|
103
|
+
URL,
|
|
104
|
+
JSON,
|
|
105
|
+
),
|
|
106
|
+
default=(DEFAULT_WORKSPACE_PATH.as_posix()),
|
|
107
|
+
show_default=True,
|
|
108
|
+
help="workspace config.",
|
|
109
|
+
)
|
|
110
|
+
@click.option(
|
|
111
|
+
"--log-level",
|
|
112
|
+
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
|
|
113
|
+
default="INFO",
|
|
114
|
+
show_default=True,
|
|
115
|
+
help="logging level.",
|
|
116
|
+
)
|
|
117
|
+
def run(
|
|
118
|
+
bucket: Tuple[str],
|
|
119
|
+
site: str,
|
|
120
|
+
tag: Tuple[str],
|
|
121
|
+
parent: Tuple[str],
|
|
122
|
+
event: Tuple[int],
|
|
123
|
+
function: str,
|
|
124
|
+
command: str,
|
|
125
|
+
lives: int,
|
|
126
|
+
sleep: int,
|
|
127
|
+
workspace: Union[str, Dict[Any, Any]],
|
|
128
|
+
log_level: str,
|
|
129
|
+
):
|
|
130
|
+
"""Fetch and perform work."""
|
|
131
|
+
tty: bool = stdout.isatty() or stderr.isatty()
|
|
132
|
+
# Set logging level
|
|
133
|
+
logger.root.setLevel(log_level)
|
|
134
|
+
logger.root.handlers[0].setLevel(log_level)
|
|
135
|
+
logger.info(f"Workspace: {workspace}")
|
|
136
|
+
logger.info(f"Log Level: {log_level}")
|
|
137
|
+
|
|
138
|
+
# Configure the runtime workspace
|
|
139
|
+
configure.workspace(workspace=workspace)
|
|
140
|
+
# At this point, the default workspace should exist
|
|
141
|
+
config: Dict[str, Any] = {}
|
|
142
|
+
config = read.workspace(DEFAULT_WORKSPACE_PATH)
|
|
143
|
+
# Collect baseurls from the workspace
|
|
144
|
+
baseurls: Dict[str, Any] = config.get("http", {}).get("baseurls", {})
|
|
145
|
+
# Reformat the tags, parent and buckets
|
|
146
|
+
tags: List[str] = list(tag)
|
|
147
|
+
parents: List[str] = list(parent)
|
|
148
|
+
buckets: List[str] = list(bucket)
|
|
149
|
+
events: List[int] = list(event)
|
|
150
|
+
# Setup and connect to the workflow backend
|
|
151
|
+
logger.info(
|
|
152
|
+
"[bold red]Workflow Run CLI[/bold red]", extra=dict(markup=True, color="green")
|
|
153
|
+
)
|
|
154
|
+
logger.info(f"Buckets : {buckets}")
|
|
155
|
+
logger.info(f"Function : {function}")
|
|
156
|
+
logger.info(f"Command : {command}")
|
|
157
|
+
logger.info(f"Mode : {'Static' if (function or command) else 'Dynamic'}")
|
|
158
|
+
logger.info(f"Lives : {'infinite' if lives == -1 else lives}")
|
|
159
|
+
logger.info(f"Sleep : {sleep}s")
|
|
160
|
+
logger.info(f"Log Level: {log_level}")
|
|
161
|
+
logger.info(
|
|
162
|
+
"[bold red]Work Filters [/bold red]",
|
|
163
|
+
extra=dict(markup=True, color="green"),
|
|
164
|
+
)
|
|
165
|
+
logger.info(f"Site : {site}")
|
|
166
|
+
logger.info(f"Tags : {tags}") if tags else None
|
|
167
|
+
logger.info(f"Parents: {parents}") if parents else None
|
|
168
|
+
logger.info(
|
|
169
|
+
"[bold red]Workspace Config[/bold red]",
|
|
170
|
+
extra=dict(markup=True, color="green"),
|
|
171
|
+
)
|
|
172
|
+
logger.info(f"Baseurls: {baseurls}")
|
|
173
|
+
|
|
174
|
+
logger.info(
|
|
175
|
+
"[bold red]Execution Environment [/bold red]",
|
|
176
|
+
extra=dict(markup=True, color="green"),
|
|
177
|
+
)
|
|
178
|
+
logger.info(f"Operating System: {platform.system()}")
|
|
179
|
+
logger.info(f"Python Version : {platform.python_version()}")
|
|
180
|
+
logger.info(f"Python Compiler : {platform.python_compiler()}")
|
|
181
|
+
logger.info(f"TTY Detected : {tty}")
|
|
182
|
+
# If both function and command are provided, raise an error
|
|
183
|
+
if function and command:
|
|
184
|
+
logger.error("Cannot provide both function and command. Exiting...")
|
|
185
|
+
exit(1)
|
|
186
|
+
logger.info(
|
|
187
|
+
"[bold red]Backend Checks [/bold red]",
|
|
188
|
+
extra=dict(markup=True, color="green"),
|
|
189
|
+
)
|
|
190
|
+
loki_status: bool = configure.loki(logger=logger, config=config)
|
|
191
|
+
logger.info(f"Loki Logs: {'✅' if loki_status else '❌'}")
|
|
192
|
+
http: HTTPContext = HTTPContext(backends=["buckets"])
|
|
193
|
+
try:
|
|
194
|
+
version: Dict[str, Any] = http.buckets.info()
|
|
195
|
+
logger.debug(f"Buckets Version: {version.get('version')}")
|
|
196
|
+
logger.info("Buckets : ✅")
|
|
197
|
+
except Exception:
|
|
198
|
+
logger.error("unable to connect to buckets.")
|
|
199
|
+
exit(1)
|
|
200
|
+
logger.info("System Checks Complete")
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
logger.info(
|
|
204
|
+
"[bold]Starting Workflow Lifecycle[/bold]",
|
|
205
|
+
extra=dict(markup=True, color="green"),
|
|
206
|
+
)
|
|
207
|
+
console = Console(force_terminal=True, tab_size=4)
|
|
208
|
+
with console.status(
|
|
209
|
+
status="",
|
|
210
|
+
spinner="aesthetic" if tty else "dots",
|
|
211
|
+
spinner_style="bold green",
|
|
212
|
+
refresh_per_second=10 if tty else 1,
|
|
213
|
+
):
|
|
214
|
+
lifecycle(
|
|
215
|
+
buckets,
|
|
216
|
+
function,
|
|
217
|
+
command,
|
|
218
|
+
lives,
|
|
219
|
+
sleep,
|
|
220
|
+
site,
|
|
221
|
+
tags,
|
|
222
|
+
parents,
|
|
223
|
+
events,
|
|
224
|
+
config,
|
|
225
|
+
http,
|
|
226
|
+
)
|
|
227
|
+
except Exception as error:
|
|
228
|
+
logger.exception(error)
|
|
229
|
+
finally:
|
|
230
|
+
logger.info(
|
|
231
|
+
"[bold]Workflow Lifecycle Complete[/bold]",
|
|
232
|
+
extra=dict(markup=True, color="green"),
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def lifecycle(
|
|
237
|
+
buckets: List[str],
|
|
238
|
+
function: Optional[str],
|
|
239
|
+
command: Optional[str],
|
|
240
|
+
lives: int,
|
|
241
|
+
sleep: int,
|
|
242
|
+
site: str,
|
|
243
|
+
tags: List[str],
|
|
244
|
+
parents: List[str],
|
|
245
|
+
events: List[int],
|
|
246
|
+
config: Dict[str, Any],
|
|
247
|
+
http: HTTPContext,
|
|
248
|
+
):
|
|
249
|
+
"""Run the workflow lifecycle."""
|
|
250
|
+
# Start the exit event
|
|
251
|
+
exit = Event()
|
|
252
|
+
|
|
253
|
+
# Get any stop, kill, or terminate signals and set the exit event
|
|
254
|
+
def quit(signo: int, _: Any):
|
|
255
|
+
"""Handle terminal signals."""
|
|
256
|
+
logger.critical(f"Received terminal signal {signo}. Exiting...")
|
|
257
|
+
exit.set()
|
|
258
|
+
|
|
259
|
+
# Register the quit function to handle the signals
|
|
260
|
+
for sig in ("TERM", "HUP", "INT"):
|
|
261
|
+
signal.signal(getattr(signal, "SIG" + sig), quit)
|
|
262
|
+
|
|
263
|
+
# Run the lifecycle until the exit event is set or the lifetime is reached
|
|
264
|
+
while lives != 0 and not exit.is_set():
|
|
265
|
+
attempt.work(
|
|
266
|
+
buckets=buckets,
|
|
267
|
+
function=function,
|
|
268
|
+
command=command,
|
|
269
|
+
site=site,
|
|
270
|
+
tags=tags,
|
|
271
|
+
parents=parents,
|
|
272
|
+
events=events,
|
|
273
|
+
config=config,
|
|
274
|
+
http=http,
|
|
275
|
+
)
|
|
276
|
+
lives -= 1
|
|
277
|
+
logger.debug(f"sleeping: {sleep}s")
|
|
278
|
+
exit.wait(sleep)
|
|
279
|
+
logger.debug(f"awake: {sleep}s")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
if __name__ == "__main__":
|
|
283
|
+
run()
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Manage workflow pipelines schedules."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any, Dict, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
import click
|
|
7
|
+
import requests
|
|
8
|
+
import yaml
|
|
9
|
+
from rich import pretty
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.json import JSON
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
from rich.text import Text
|
|
14
|
+
from yaml.loader import SafeLoader
|
|
15
|
+
|
|
16
|
+
from workflow.http.context import HTTPContext
|
|
17
|
+
from workflow.utils.variables import status_colors
|
|
18
|
+
|
|
19
|
+
pretty.install()
|
|
20
|
+
console = Console()
|
|
21
|
+
|
|
22
|
+
table = Table(
|
|
23
|
+
title="\nWorkflow Pipelines - Schedules",
|
|
24
|
+
show_header=True,
|
|
25
|
+
header_style="magenta",
|
|
26
|
+
title_style="bold green",
|
|
27
|
+
min_width=50,
|
|
28
|
+
)
|
|
29
|
+
BASE_URL = "https://frb.chimenet.ca/schedule"
|
|
30
|
+
STATUS = ["active", "running", "expired"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@click.group(name="schedules", help="Manage Workflow Schedules.")
|
|
34
|
+
def schedules():
|
|
35
|
+
"""Manage Workflow Schedules."""
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@schedules.command("version", help="Backend version.")
|
|
40
|
+
def version():
|
|
41
|
+
"""Get version of the pipelines service."""
|
|
42
|
+
http = HTTPContext()
|
|
43
|
+
console.print(http.pipelines.info())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@schedules.command("ls", help="List schedules.")
|
|
47
|
+
@click.option(
|
|
48
|
+
"name",
|
|
49
|
+
"--name",
|
|
50
|
+
"-n",
|
|
51
|
+
type=str,
|
|
52
|
+
required=False,
|
|
53
|
+
help="List only Schedules with provided name.",
|
|
54
|
+
)
|
|
55
|
+
@click.option(
|
|
56
|
+
"quiet",
|
|
57
|
+
"--quiet",
|
|
58
|
+
"-q",
|
|
59
|
+
is_flag=True,
|
|
60
|
+
required=False,
|
|
61
|
+
help="Only show IDs.",
|
|
62
|
+
)
|
|
63
|
+
def ls(name: Optional[str] = None, quiet: Optional[bool] = False):
|
|
64
|
+
"""List schedules.
|
|
65
|
+
|
|
66
|
+
Parameters
|
|
67
|
+
----------
|
|
68
|
+
name : Optional[str], optional
|
|
69
|
+
Name of specific schedule, by default None
|
|
70
|
+
quiet : Optional[bool], optional
|
|
71
|
+
Whether to show only IDs.
|
|
72
|
+
"""
|
|
73
|
+
http = HTTPContext()
|
|
74
|
+
objects = http.schedules.list_schedules(name)
|
|
75
|
+
table.title = "Workflow Scheduled Pipelines"
|
|
76
|
+
table.add_column("ID", max_width=50, justify="left", style="blue")
|
|
77
|
+
if not quiet:
|
|
78
|
+
table.add_column("Name", max_width=50, justify="left", style="bright_green")
|
|
79
|
+
table.add_column("Status", max_width=50, justify="left")
|
|
80
|
+
table.add_column("Lives", max_width=50, justify="left")
|
|
81
|
+
table.add_column("Has Spawned", max_width=50, justify="left")
|
|
82
|
+
table.add_column("Next Time", max_width=50, justify="left")
|
|
83
|
+
for schedule_obj in objects:
|
|
84
|
+
if not quiet:
|
|
85
|
+
status = Text(
|
|
86
|
+
schedule_obj["status"], style=status_colors[schedule_obj["status"]]
|
|
87
|
+
)
|
|
88
|
+
lives = schedule_obj["lives"]
|
|
89
|
+
lives_text = Text(str(lives) if lives > -1 else "\u221e")
|
|
90
|
+
table.add_row(
|
|
91
|
+
schedule_obj["id"],
|
|
92
|
+
schedule_obj["config"]["name"],
|
|
93
|
+
status,
|
|
94
|
+
lives_text,
|
|
95
|
+
str(schedule_obj["has_spawned"]),
|
|
96
|
+
str(schedule_obj["next_time"]),
|
|
97
|
+
)
|
|
98
|
+
continue
|
|
99
|
+
table.add_row(schedule_obj["id"])
|
|
100
|
+
console.print(table)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@schedules.command("count", help="Count schedules per collection.")
|
|
104
|
+
def count():
|
|
105
|
+
"""Count schedules."""
|
|
106
|
+
http = HTTPContext()
|
|
107
|
+
counts = http.schedules.count_schedules()
|
|
108
|
+
table.title = "Workflow Schedules"
|
|
109
|
+
table.add_column("Name", max_width=50, justify="left", style="blue")
|
|
110
|
+
table.add_column("Count", max_width=50, justify="left")
|
|
111
|
+
total = int()
|
|
112
|
+
for k, v in counts.items():
|
|
113
|
+
table.add_row(k, str(v))
|
|
114
|
+
total += v
|
|
115
|
+
table.add_section()
|
|
116
|
+
table.add_row("Total", str(total))
|
|
117
|
+
console.print(table)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@schedules.command("deploy", help="Deploy a scheduled pipeline.")
|
|
121
|
+
@click.argument(
|
|
122
|
+
"filename",
|
|
123
|
+
type=click.Path(exists=True, dir_okay=False, readable=True),
|
|
124
|
+
required=True,
|
|
125
|
+
)
|
|
126
|
+
def deploy(filename: click.Path):
|
|
127
|
+
"""Deploy a scheduled pipeline."""
|
|
128
|
+
http = HTTPContext()
|
|
129
|
+
filepath: str = str(filename)
|
|
130
|
+
data: Dict[str, Any] = {}
|
|
131
|
+
with open(filepath) as reader:
|
|
132
|
+
data = yaml.load(reader, Loader=SafeLoader) # type: ignore
|
|
133
|
+
try:
|
|
134
|
+
deploy_result = http.schedules.deploy(data)
|
|
135
|
+
except requests.HTTPError as deploy_error:
|
|
136
|
+
console.print(deploy_error.response.json()["message"])
|
|
137
|
+
return
|
|
138
|
+
table.add_column("IDs", max_width=50, justify="left", style="bright_green")
|
|
139
|
+
if isinstance(deploy_result, list):
|
|
140
|
+
for _id in deploy_result:
|
|
141
|
+
table.add_row(_id)
|
|
142
|
+
if isinstance(deploy_result, dict):
|
|
143
|
+
for v in deploy_result.values():
|
|
144
|
+
table.add_row(v)
|
|
145
|
+
console.print(table)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@schedules.command("ps", help="Get schedule details.")
|
|
149
|
+
@click.argument("id", type=str, required=True)
|
|
150
|
+
@click.option(
|
|
151
|
+
"--details",
|
|
152
|
+
is_flag=True,
|
|
153
|
+
show_default=True,
|
|
154
|
+
help="Returns the Schedule Payload.",
|
|
155
|
+
)
|
|
156
|
+
def ps(id: str, details: Optional[bool] = False):
|
|
157
|
+
"""Gets schedules details."""
|
|
158
|
+
http = HTTPContext()
|
|
159
|
+
query: Dict[str, Any] = {"id": id}
|
|
160
|
+
console_content = None
|
|
161
|
+
key_nicknames = {
|
|
162
|
+
"id": "ID",
|
|
163
|
+
"crontab": "Crontab",
|
|
164
|
+
"lives": "To Spawn",
|
|
165
|
+
"has_spawned": "Has Spawned",
|
|
166
|
+
"status": "Status",
|
|
167
|
+
"next_time": "Next Execution",
|
|
168
|
+
"history": "History",
|
|
169
|
+
}
|
|
170
|
+
try:
|
|
171
|
+
payload = http.schedules.get_schedule(query)
|
|
172
|
+
except IndexError:
|
|
173
|
+
error_text = Text("No Schedule was found", style="red")
|
|
174
|
+
console_content = error_text
|
|
175
|
+
else:
|
|
176
|
+
table.add_column(
|
|
177
|
+
f"Scheduled Pipeline: {payload['config']['name']}",
|
|
178
|
+
max_width=120,
|
|
179
|
+
min_width=50,
|
|
180
|
+
justify="left",
|
|
181
|
+
)
|
|
182
|
+
text = Text("")
|
|
183
|
+
for k, v in payload.items():
|
|
184
|
+
if k == "config":
|
|
185
|
+
continue
|
|
186
|
+
if k == "history":
|
|
187
|
+
key_value_text = Text(
|
|
188
|
+
f"{key_nicknames.get(k, k)}: \n", style="bright_green"
|
|
189
|
+
)
|
|
190
|
+
for history in v:
|
|
191
|
+
history_dt = datetime.fromisoformat(history[0])
|
|
192
|
+
legible_dt = history_dt.strftime("%B %d, %Y at %I:%M:%S %p")
|
|
193
|
+
id = history[1]
|
|
194
|
+
key_value_text.append(f"-- {legible_dt}:", style="bright_blue")
|
|
195
|
+
key_value_text.append(f"\n\t{id}\n\n", style="white")
|
|
196
|
+
text.append_text(key_value_text)
|
|
197
|
+
continue
|
|
198
|
+
key_value_text = Text(f"{key_nicknames.get(k, k)}: ", style="bright_green")
|
|
199
|
+
key_value_text.append(
|
|
200
|
+
f"{v}\n", style="white" if k != "status" else status_colors[v]
|
|
201
|
+
)
|
|
202
|
+
text.append_text(key_value_text)
|
|
203
|
+
if details:
|
|
204
|
+
table.add_column("Details", style="magenta")
|
|
205
|
+
this_payload = JSON.from_data(payload["config"], indent=2)
|
|
206
|
+
table.add_row(text, this_payload)
|
|
207
|
+
else:
|
|
208
|
+
table.add_row(text)
|
|
209
|
+
console_content = table
|
|
210
|
+
finally:
|
|
211
|
+
console.print(console_content)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@schedules.command("rm", help="Remove a schedule.")
|
|
215
|
+
@click.argument("id", type=str, required=True)
|
|
216
|
+
def rm(id: Tuple[str]):
|
|
217
|
+
"""Remove a schedule."""
|
|
218
|
+
http = HTTPContext()
|
|
219
|
+
content = None
|
|
220
|
+
try:
|
|
221
|
+
delete_result = http.schedules.remove(id)
|
|
222
|
+
if delete_result.status_code == 204:
|
|
223
|
+
text = Text("No pipeline configurations were deleted.", style="red")
|
|
224
|
+
content = text
|
|
225
|
+
except Exception as e:
|
|
226
|
+
text = Text(
|
|
227
|
+
f"No pipeline configurations were deleted.\nError: {e}", style="red"
|
|
228
|
+
)
|
|
229
|
+
content = text
|
|
230
|
+
else:
|
|
231
|
+
table.add_column("Deleted IDs", max_width=50, justify="left", style="red")
|
|
232
|
+
table.add_row(id)
|
|
233
|
+
content = table
|
|
234
|
+
console.print(content)
|