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
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Workflow Workspace CLI."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Dict
|
|
5
|
+
|
|
6
|
+
import click
|
|
7
|
+
from rich import pretty
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
from yaml import dump
|
|
11
|
+
|
|
12
|
+
from workflow import DEFAULT_WORKSPACE_PATH, MODULE_PATH
|
|
13
|
+
from workflow.utils import read as reader
|
|
14
|
+
from workflow.utils.logger import get_logger
|
|
15
|
+
|
|
16
|
+
logger = get_logger("workflow.cli.workspace")
|
|
17
|
+
|
|
18
|
+
pretty.install()
|
|
19
|
+
console = Console()
|
|
20
|
+
|
|
21
|
+
localspaces = Path(DEFAULT_WORKSPACE_PATH).parent
|
|
22
|
+
localstems = [space.stem for space in localspaces.glob("*.y*ml")]
|
|
23
|
+
modulespaces = Path(MODULE_PATH, "workflow", "workspaces")
|
|
24
|
+
modulestems = [space.stem for space in modulespaces.glob("*.y*ml")]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@click.group(name="workspace", help="Manage Workflow Workspaces.")
|
|
28
|
+
def workspace():
|
|
29
|
+
"""Manage Workflow Workspaces."""
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@workspace.command("ls", help="List workspaces.")
|
|
34
|
+
def ls():
|
|
35
|
+
"""List all workspaces."""
|
|
36
|
+
table = Table(
|
|
37
|
+
title="\nWorkflow Workspaces",
|
|
38
|
+
header_style="magenta",
|
|
39
|
+
title_style="bold magenta",
|
|
40
|
+
)
|
|
41
|
+
table.add_column("Workspace", style="cyan", justify="right")
|
|
42
|
+
table.add_column("Source", style="green", justify="left")
|
|
43
|
+
table.add_row("", "From Workflow Python Module", style="red italic")
|
|
44
|
+
for workspace in modulespaces.glob("*.y*ml"):
|
|
45
|
+
table.add_row(workspace.stem, workspace.as_posix())
|
|
46
|
+
table.add_row("", "From Local Configuration Folder", style="red italic")
|
|
47
|
+
for workspace in localspaces.glob("*.y*ml"):
|
|
48
|
+
if workspace.stem == "workspace":
|
|
49
|
+
table.add_row(
|
|
50
|
+
f"{workspace.stem} (active)", workspace.as_posix(), style="italic"
|
|
51
|
+
)
|
|
52
|
+
else:
|
|
53
|
+
table.add_row(workspace.stem, workspace.as_posix())
|
|
54
|
+
console.print(table)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@workspace.command("set", help="Set the active workspace.")
|
|
58
|
+
@click.argument(
|
|
59
|
+
"workspace",
|
|
60
|
+
type=str,
|
|
61
|
+
required=True,
|
|
62
|
+
nargs=1,
|
|
63
|
+
)
|
|
64
|
+
def set(workspace: str):
|
|
65
|
+
"""Set the active workspace.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
workspace (str): The workspace to set. The workspace
|
|
69
|
+
argument can be a url, a local path, or a name of
|
|
70
|
+
a local workspace.
|
|
71
|
+
debug (bool, optional): Debug Logs. Defaults to False.
|
|
72
|
+
"""
|
|
73
|
+
config: Dict[str, Any] = {}
|
|
74
|
+
console.print(f"Locating workspace {workspace}", style="italic blue")
|
|
75
|
+
if Path(workspace).absolute().exists():
|
|
76
|
+
console.print(f"Reading {workspace}", style="italic blue")
|
|
77
|
+
config = reader.workspace(Path(workspace).absolute())
|
|
78
|
+
elif workspace in localstems:
|
|
79
|
+
for possibility in localspaces.glob(f"{workspace}.y*ml"):
|
|
80
|
+
console.print(f"Reading {possibility}", style="italic blue")
|
|
81
|
+
config = reader.workspace(possibility)
|
|
82
|
+
break
|
|
83
|
+
elif workspace in [space.stem for space in modulespaces.glob("*.y*ml")]:
|
|
84
|
+
for possibility in modulespaces.glob(f"{workspace}.y*ml"):
|
|
85
|
+
console.print(f"Reading {possibility}", style="italic blue")
|
|
86
|
+
config = reader.workspace(possibility)
|
|
87
|
+
break
|
|
88
|
+
else:
|
|
89
|
+
console.print(f"Workspace {workspace} not found.", style="bold red")
|
|
90
|
+
return
|
|
91
|
+
|
|
92
|
+
name: str = config["workspace"]
|
|
93
|
+
localspaces.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
activepath = localspaces / "workspace.yml"
|
|
95
|
+
# Write config to activepath, even if it already exists.
|
|
96
|
+
with open(activepath, "w") as filename:
|
|
97
|
+
dump(config, filename)
|
|
98
|
+
console.print(f"Workspace {name} set to active.", style="bold green")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@workspace.command("read", help="Read workspace config.")
|
|
102
|
+
@click.argument("workspace", type=str, required=True, nargs=1, default="workspace")
|
|
103
|
+
def read(workspace: str):
|
|
104
|
+
"""Read the active workspace.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
workspace (str): The workspace to read.
|
|
108
|
+
"""
|
|
109
|
+
if workspace in localstems:
|
|
110
|
+
for possibility in localspaces.glob(f"{workspace}.y*ml"):
|
|
111
|
+
console.print(f"Reading {possibility}", style="italic blue")
|
|
112
|
+
config = reader.workspace(possibility)
|
|
113
|
+
console.print(config, style="green")
|
|
114
|
+
return
|
|
115
|
+
elif workspace in modulestems:
|
|
116
|
+
for possibility in modulespaces.glob(f"{workspace}.y*ml"):
|
|
117
|
+
console.print(f"Reading {possibility}", style="italic blue")
|
|
118
|
+
config = reader.workspace(possibility)
|
|
119
|
+
console.print(config, style="green")
|
|
120
|
+
return
|
|
121
|
+
else:
|
|
122
|
+
console.print("No local workspace found.", style="italic bold red")
|
|
123
|
+
# Check if workspace is a url.
|
|
124
|
+
if "://" in workspace:
|
|
125
|
+
console.print("Reading from URL.", style="italic blue")
|
|
126
|
+
config = reader.workspace(workspace)
|
|
127
|
+
console.print(config, style="green")
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@workspace.command("unset", help="Unset active workspace.")
|
|
132
|
+
def unset():
|
|
133
|
+
"""Unset the active workspace."""
|
|
134
|
+
# Set the default console style.
|
|
135
|
+
console.print("Removing the active workspace.", style="italic red")
|
|
136
|
+
# If the workspace already exists, warn the user.
|
|
137
|
+
(localspaces / "workspace.yml").unlink(missing_ok=True)
|
|
138
|
+
console.print("Workspace Removed.", style="bold red")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@workspace.command("purge", help="Purge all local workspaces.")
|
|
142
|
+
def purge():
|
|
143
|
+
"""Purge all local workspaces."""
|
|
144
|
+
# Remove all files from ~/.config/workflow/
|
|
145
|
+
console.print("Purging all local workspaces", style="italic red")
|
|
146
|
+
for workspace in localspaces.glob("*.y*ml"):
|
|
147
|
+
console.print(f"Removing {workspace}", style="italic red")
|
|
148
|
+
workspace.unlink()
|
|
149
|
+
console.print("Done.", style="bold red")
|
|
File without changes
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Audit Daemon."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any, Dict, 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.logger import get_logger
|
|
13
|
+
|
|
14
|
+
logger = get_logger("workflow.daemons.audit")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@click.command()
|
|
18
|
+
@click.option(
|
|
19
|
+
"--sleep",
|
|
20
|
+
"-s",
|
|
21
|
+
default=5,
|
|
22
|
+
type=click.INT,
|
|
23
|
+
help="Number of seconds to sleep between audits.",
|
|
24
|
+
)
|
|
25
|
+
@click.option(
|
|
26
|
+
"-w",
|
|
27
|
+
"--workspace",
|
|
28
|
+
type=FirstOf(
|
|
29
|
+
click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
|
|
30
|
+
URL,
|
|
31
|
+
JSON,
|
|
32
|
+
),
|
|
33
|
+
default=(DEFAULT_WORKSPACE_PATH.as_posix()),
|
|
34
|
+
show_default=True,
|
|
35
|
+
help="workspace config.",
|
|
36
|
+
)
|
|
37
|
+
@click.option(
|
|
38
|
+
"--test-mode",
|
|
39
|
+
default=False,
|
|
40
|
+
is_flag=True,
|
|
41
|
+
type=click.BOOL,
|
|
42
|
+
help="Enable test mode to avoid while True loop",
|
|
43
|
+
)
|
|
44
|
+
def audit(
|
|
45
|
+
sleep: int,
|
|
46
|
+
workspace: Union[str, Dict[Any, Any]],
|
|
47
|
+
test_mode: bool,
|
|
48
|
+
) -> Dict[str, Any]:
|
|
49
|
+
"""Audit Buckets Backend.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
sleep (int): number of seconds to sleep between audits
|
|
53
|
+
workspace (Union[str, Dict[Any, Any]]): workspace config
|
|
54
|
+
token (Optional[str]): authentication token
|
|
55
|
+
test_mode (bool): enable test mode to avoid while True loop
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Dict[str, Any]: Audit results.
|
|
59
|
+
"""
|
|
60
|
+
logger.info("Starting Audit Daemon")
|
|
61
|
+
logger.info(f"Sleep Time: {sleep}")
|
|
62
|
+
logger.info(f"Workspace : {workspace}")
|
|
63
|
+
logger.info(f"Test Mode : {test_mode}")
|
|
64
|
+
configure.workspace(workspace=workspace)
|
|
65
|
+
|
|
66
|
+
http: HTTPContext = HTTPContext(backends=["buckets"])
|
|
67
|
+
logger.info("HTTP Context Initialized")
|
|
68
|
+
logger.info(f"HTTP Context: Buckets Backend @ {http.buckets.baseurl}")
|
|
69
|
+
if test_mode:
|
|
70
|
+
return http.buckets.audit()
|
|
71
|
+
while True:
|
|
72
|
+
response = http.buckets.audit()
|
|
73
|
+
logger.info(response)
|
|
74
|
+
time.sleep(sleep)
|
|
@@ -0,0 +1,255 @@
|
|
|
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
|
+
from workflow import DEFAULT_WORKSPACE_PATH
|
|
9
|
+
from workflow.http.buckets import Buckets
|
|
10
|
+
from workflow.http.results import Results
|
|
11
|
+
from workflow.utils.logger import get_logger
|
|
12
|
+
from workflow.utils import read
|
|
13
|
+
from workflow.lifecycle import configure
|
|
14
|
+
from workflow.http.context import HTTPContext
|
|
15
|
+
|
|
16
|
+
logger = get_logger("workflow.daemons.transfer")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def deposit_work_to_results(
|
|
20
|
+
buckets: Buckets, results: Results, works: List[Dict[str, Any]]
|
|
21
|
+
) -> int:
|
|
22
|
+
"""Deposit work to results, and remove them from buckets.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
buckets (Buckets): Buckets module.
|
|
26
|
+
results (Results): Results module.
|
|
27
|
+
works (List[Dict[str, Any]]): Work to deposit.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
transfer_status (bool): Number of works deposited to results.
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
transfer_status = False
|
|
34
|
+
results_deposit_status = results.deposit(works)
|
|
35
|
+
if all([val > 0 for val in results_deposit_status.values()]):
|
|
36
|
+
buckets.delete_ids([work["id"] for work in works])
|
|
37
|
+
transfer_status = True
|
|
38
|
+
return transfer_status
|
|
39
|
+
except Exception as error:
|
|
40
|
+
print(f"Exception occurred: {error}")
|
|
41
|
+
transfer_status = False
|
|
42
|
+
work_to_deposit = [
|
|
43
|
+
work for work in works if is_work_already_deposited(results, work) is False
|
|
44
|
+
]
|
|
45
|
+
results_deposit_status = results.deposit(work_to_deposit)
|
|
46
|
+
if (
|
|
47
|
+
all([val > 0 for val in results_deposit_status.values()])
|
|
48
|
+
or results_deposit_status == {}
|
|
49
|
+
):
|
|
50
|
+
buckets.delete_ids([work["id"] for work in works])
|
|
51
|
+
transfer_status = True
|
|
52
|
+
return transfer_status
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def is_work_already_deposited(results: Results, work: Dict[str, Any]) -> bool:
|
|
56
|
+
"""Check if a work has already been deposited to results.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
results (Results): Results module.
|
|
60
|
+
work (Dict[str, Any]): work to check
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
bool: _description_
|
|
64
|
+
"""
|
|
65
|
+
return results.count(pipeline=work["pipeline"], query={"id": work["id"]}) == 1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@click.command()
|
|
69
|
+
@click.option("--sleep", "-s", default=5, help="seconds to sleep between transfers.")
|
|
70
|
+
@click.option(
|
|
71
|
+
"-w",
|
|
72
|
+
"--workspace",
|
|
73
|
+
type=FirstOf(
|
|
74
|
+
click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
|
|
75
|
+
URL,
|
|
76
|
+
JSON,
|
|
77
|
+
),
|
|
78
|
+
default=(DEFAULT_WORKSPACE_PATH.as_posix()),
|
|
79
|
+
show_default=True,
|
|
80
|
+
help="workspace config.",
|
|
81
|
+
)
|
|
82
|
+
@click.option("--limit", default=50, help="works to transfer per run.")
|
|
83
|
+
@click.option(
|
|
84
|
+
"--cutoff", default=60 * 60 * 24 * 7, help="cutoff time in seconds for stale work."
|
|
85
|
+
)
|
|
86
|
+
@click.option(
|
|
87
|
+
"--test-mode", default=False, help="Enable test mode to avoid while True loop"
|
|
88
|
+
)
|
|
89
|
+
def transfer(
|
|
90
|
+
sleep: int,
|
|
91
|
+
workspace: Union[str, Dict[Any, Any]],
|
|
92
|
+
test_mode: bool,
|
|
93
|
+
limit: int,
|
|
94
|
+
cutoff: int,
|
|
95
|
+
) -> Dict[str, Any]:
|
|
96
|
+
"""Transfer work from Buckets to Results.
|
|
97
|
+
Args:
|
|
98
|
+
sleep (int): seconds to sleep between transfers.
|
|
99
|
+
workspace (Union[str, Dict[Any, Any]]): workspace config.
|
|
100
|
+
test_mode (bool): Enable test mode to avoid while True loop.
|
|
101
|
+
limit (int): works to transfer per run.
|
|
102
|
+
cutoff (int): cutoff time in seconds for stale work.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
Dict[str, Any]: _description_
|
|
106
|
+
"""
|
|
107
|
+
logger.info("Starting Transfer Daemon")
|
|
108
|
+
logger.info(f"Sleep Time: {sleep}")
|
|
109
|
+
logger.info(f"Workspace : {workspace}")
|
|
110
|
+
logger.info(f"Test Mode : {test_mode}")
|
|
111
|
+
logger.info(f"Limit/Tx : {limit}")
|
|
112
|
+
logger.info(f"Cutoff : {cutoff} days")
|
|
113
|
+
configure.workspace(workspace=workspace)
|
|
114
|
+
archive: bool = (
|
|
115
|
+
read.workspace(DEFAULT_WORKSPACE_PATH.as_posix())
|
|
116
|
+
.get("config", {})
|
|
117
|
+
.get("archive", {})
|
|
118
|
+
.get("results", True)
|
|
119
|
+
)
|
|
120
|
+
logger.info(f"Archive : {'Enabled' if archive else 'Disabled'}")
|
|
121
|
+
http: HTTPContext = HTTPContext(backends=["buckets", "results"])
|
|
122
|
+
logger.info("HTTP Context Initialized")
|
|
123
|
+
logger.info(f"HTTP Context: Buckets Backend @ {http.buckets.baseurl}")
|
|
124
|
+
logger.info(f"HTTP Context: Results Backend @ {http.results.baseurl}")
|
|
125
|
+
|
|
126
|
+
delete: List[str] = []
|
|
127
|
+
successful: List[Dict[str, Any]] = []
|
|
128
|
+
failed: List[Dict[str, Any]] = []
|
|
129
|
+
|
|
130
|
+
for work in http.buckets.view(
|
|
131
|
+
query={"status": "success"}, projection={}, skip=0, limit=limit
|
|
132
|
+
):
|
|
133
|
+
if work["config"]["archive"]["results"] is False:
|
|
134
|
+
delete.append(work["id"])
|
|
135
|
+
elif work["config"]["archive"]["results"] is True and archive:
|
|
136
|
+
successful.append(work)
|
|
137
|
+
else:
|
|
138
|
+
delete.append(work["id"])
|
|
139
|
+
|
|
140
|
+
# Transfer successful work to results
|
|
141
|
+
response: Dict[str, Any] = {}
|
|
142
|
+
response = http.results.deposit(successful)
|
|
143
|
+
for key, value in response.items():
|
|
144
|
+
if value:
|
|
145
|
+
delete.append(key)
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
logger.info(f"Transferring {len(successful)} successful works to results")
|
|
149
|
+
response = http.results.deposit(successful)
|
|
150
|
+
for key, value in response.items():
|
|
151
|
+
if value:
|
|
152
|
+
delete.append(key)
|
|
153
|
+
except Exception as error:
|
|
154
|
+
logger.error("Failed to deposit successful works to results")
|
|
155
|
+
logger.error(f"Exception: {error}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def transfer(test_flag: bool, buckets: Buckets, results: Results) -> Dict[str, Any]:
|
|
159
|
+
"""Transfer Work from Buckets to Results.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
test_flag (bool): If True, run once and exit.
|
|
163
|
+
buckets (Buckets): Buckets module.
|
|
164
|
+
results (Results): Results module.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
Dict[str, Any]: Transfer status.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
transfer_status: Dict[str, Any] = {}
|
|
171
|
+
# 1. Transfer successful Work
|
|
172
|
+
# TODO: decide projection fields
|
|
173
|
+
successful_work = buckets.view(
|
|
174
|
+
query={"status": "success"},
|
|
175
|
+
projection={},
|
|
176
|
+
skip=0,
|
|
177
|
+
limit=limit,
|
|
178
|
+
)
|
|
179
|
+
successful_work_to_delete = [
|
|
180
|
+
work
|
|
181
|
+
for work in successful_work
|
|
182
|
+
if work["config"]["archive"]["results"] is False
|
|
183
|
+
and not results_workspace_config
|
|
184
|
+
]
|
|
185
|
+
successful_work_to_transfer = [
|
|
186
|
+
work
|
|
187
|
+
for work in successful_work
|
|
188
|
+
if work["config"]["archive"]["results"] is True and results_workspace_config
|
|
189
|
+
]
|
|
190
|
+
|
|
191
|
+
if successful_work_to_transfer:
|
|
192
|
+
transfer_status["successful_work_transferred"] = deposit_work_to_results(
|
|
193
|
+
buckets, results, successful_work_to_transfer
|
|
194
|
+
)
|
|
195
|
+
if successful_work_to_delete:
|
|
196
|
+
buckets.delete_ids([work["id"] for work in successful_work_to_delete])
|
|
197
|
+
transfer_status["successful_work_deleted"] = True
|
|
198
|
+
|
|
199
|
+
cutoff_creation_time = time.time() - (60 * 60 * 24 * 7)
|
|
200
|
+
# 2. Transfer failed Work which is not stale
|
|
201
|
+
failed_work = buckets.view(
|
|
202
|
+
query={
|
|
203
|
+
"status": "failure",
|
|
204
|
+
"$expr": {"$gte": ["$attempt", "$retries"]},
|
|
205
|
+
"creation": {"$gt": cutoff_creation_time},
|
|
206
|
+
},
|
|
207
|
+
projection={},
|
|
208
|
+
skip=0,
|
|
209
|
+
limit=limit,
|
|
210
|
+
)
|
|
211
|
+
failed_work_to_delete = [
|
|
212
|
+
work
|
|
213
|
+
for work in failed_work
|
|
214
|
+
if work["config"]["archive"]["results"] is False
|
|
215
|
+
and not results_workspace_config
|
|
216
|
+
]
|
|
217
|
+
failed_work_to_transfer = [
|
|
218
|
+
work
|
|
219
|
+
for work in failed_work
|
|
220
|
+
if work["config"]["archive"]["results"] is True and results_workspace_config
|
|
221
|
+
]
|
|
222
|
+
|
|
223
|
+
if failed_work_to_transfer:
|
|
224
|
+
transfer_status["failed_work_transferred"] = deposit_work_to_results(
|
|
225
|
+
buckets, results, failed_work_to_transfer
|
|
226
|
+
)
|
|
227
|
+
if failed_work_to_delete:
|
|
228
|
+
buckets.delete_ids([work["id"] for work in failed_work_to_delete])
|
|
229
|
+
transfer_status["failed_work_deleted"] = True
|
|
230
|
+
|
|
231
|
+
# 3. Delete stale Work (cut off time: 7 days)
|
|
232
|
+
stale_work = buckets.view(
|
|
233
|
+
query={
|
|
234
|
+
"status": "failure",
|
|
235
|
+
"creation": {"$lt": cutoff_creation_time},
|
|
236
|
+
},
|
|
237
|
+
projection={},
|
|
238
|
+
skip=0,
|
|
239
|
+
limit=limit,
|
|
240
|
+
)
|
|
241
|
+
if stale_work:
|
|
242
|
+
buckets.delete_ids([work["id"] for work in stale_work])
|
|
243
|
+
transfer_status["stale_work_deleted"] = True
|
|
244
|
+
log.info(f"Transfer Status: {transfer_status}")
|
|
245
|
+
return transfer_status
|
|
246
|
+
|
|
247
|
+
if test_mode:
|
|
248
|
+
return transfer(test_flag=True, buckets=buckets, results=results)
|
|
249
|
+
while True:
|
|
250
|
+
transfer(test_flag=False, buckets=buckets, results=results)
|
|
251
|
+
time.sleep(sleep)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
if __name__ == "__main__":
|
|
255
|
+
transfer()
|
|
File without changes
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Work Object Configuration."""
|
|
2
|
+
|
|
3
|
+
from typing import List, Optional
|
|
4
|
+
|
|
5
|
+
from pydantic import Field, field_validator
|
|
6
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Archive(BaseSettings):
|
|
10
|
+
"""Archive Configuration.
|
|
11
|
+
|
|
12
|
+
This class is used to configure the archive strategy for the work.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
BaseModel (BaseModel): Pydantic BaseModel.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
results (bool): Archive results for the work.
|
|
19
|
+
products (str): Archive strategy for the products.
|
|
20
|
+
plots (str): Archive strategy for the plots.
|
|
21
|
+
logs (str): Archive strategy for the logs.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
model_config = SettingsConfigDict(
|
|
25
|
+
title="Workflow Archive Object",
|
|
26
|
+
validate_default=True,
|
|
27
|
+
validate_assignment=True,
|
|
28
|
+
validate_return=True,
|
|
29
|
+
revalidate_instances="always",
|
|
30
|
+
env_prefix="WORKFLOW_CONFIG_ARCHIVE_",
|
|
31
|
+
secrets_dir="/run/secrets",
|
|
32
|
+
extra="ignore",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
results: bool = Field(
|
|
36
|
+
default=True,
|
|
37
|
+
description="Whether to archive the results of the work.",
|
|
38
|
+
examples=[True],
|
|
39
|
+
)
|
|
40
|
+
products: str = Field(
|
|
41
|
+
default="copy",
|
|
42
|
+
description="Archive strategy for the products.",
|
|
43
|
+
examples=["copy"],
|
|
44
|
+
)
|
|
45
|
+
plots: str = Field(
|
|
46
|
+
default="copy",
|
|
47
|
+
description="Archive strategy for the plots.",
|
|
48
|
+
examples=["move"],
|
|
49
|
+
)
|
|
50
|
+
logs: str = Field(
|
|
51
|
+
default="move",
|
|
52
|
+
description="Archive strategy for the logs.",
|
|
53
|
+
examples=["delete"],
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
@field_validator("products", "plots", "logs")
|
|
57
|
+
def validate_archive(cls, value: str) -> str:
|
|
58
|
+
"""Validate the archive strategy.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
value (str): Archive strategy.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
ValueError: If the archive strategy is not valid.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
str: The archive strategy.
|
|
68
|
+
"""
|
|
69
|
+
strategy = ["bypass", "copy", "delete", "move"]
|
|
70
|
+
if value not in strategy:
|
|
71
|
+
raise ValueError(f"archive strategy must be one of {strategy}")
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Config(BaseSettings):
|
|
76
|
+
"""Workflow Configuration Object.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
BaseSettings (BaseSettings): Pydantic BaseModel with settings.
|
|
80
|
+
|
|
81
|
+
Attributes:
|
|
82
|
+
archive (Archive): Archive Configuration.
|
|
83
|
+
metrics (bool): Generate metrics from work lifecycle.
|
|
84
|
+
parent (Optional[str]): Parent Pipeline ID. None implies no parent.
|
|
85
|
+
orgs (List[str]): GitHub organization[s] the work belongs to.
|
|
86
|
+
teams (Optional[List[str]]): GitHub Team[s] with access to the work.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
model_config = SettingsConfigDict(
|
|
90
|
+
title="Workflow Config Object",
|
|
91
|
+
validate_default=True,
|
|
92
|
+
validate_assignment=True,
|
|
93
|
+
validate_return=True,
|
|
94
|
+
revalidate_instances="always",
|
|
95
|
+
env_prefix="WORKFLOW_CONFIG_",
|
|
96
|
+
secrets_dir="/run/secrets",
|
|
97
|
+
extra="ignore",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
archive: Archive = Archive()
|
|
101
|
+
metrics: bool = Field(
|
|
102
|
+
default=False,
|
|
103
|
+
description="Metrics for the workflow lifecycle.",
|
|
104
|
+
)
|
|
105
|
+
parent: Optional[str] = Field(
|
|
106
|
+
default=None,
|
|
107
|
+
description="Parent Pipeline ID. None implies no parent.",
|
|
108
|
+
examples=["5f9b5c5d7b54b5a9c5e5b5c5"],
|
|
109
|
+
)
|
|
110
|
+
orgs: List[str] = Field(
|
|
111
|
+
default=["chimefrb"],
|
|
112
|
+
description="""
|
|
113
|
+
GitHub organization[s] the work belongs to. If authentication is enabled,
|
|
114
|
+
this must be a subset of the authenticated user's organizations.""",
|
|
115
|
+
examples=[["octocat", "chimefrb"]],
|
|
116
|
+
)
|
|
117
|
+
teams: Optional[List[str]] = Field(
|
|
118
|
+
default=None,
|
|
119
|
+
description="""
|
|
120
|
+
GitHub Team[s] with access to the work. If authentication is enabled,
|
|
121
|
+
this must be a subset of the authenticated user's teams.
|
|
122
|
+
""",
|
|
123
|
+
examples=[["developers", "admins"]],
|
|
124
|
+
)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# JSON Schema
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
JSON schema is the standard for defining the structure of JSON data. It is used to validate the structure of JSON data or by extension any system that accepts JSON Schema. For our usecase, we use JSON Schema derived from Pydantic Models in Python to generate a JSON Schema file. This, schema is then used by IDE's to provide autocompletion and validation for YAML files that are used to define the workflow workspaces and pipelines.
|
|
6
|
+
|
|
7
|
+
## Translate Pydanitc Models to JSON Schema
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from workflow.definitions.work import Work
|
|
11
|
+
|
|
12
|
+
schema = Work.model_json_schema(mode="serialization")
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Translate JSON Schema to Python Dataclasses
|
|
16
|
+
|
|
17
|
+
- Go to [JSON Schema Store](https://www.schemastore.org/json/) and download a JSON schema file, using
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
curl -O https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- Follow the Code Generation instructions in the Pydantic documentation to create Python Code from the JSON schema file.
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install datamodel-code-generator
|
|
27
|
+
datamodel-codegen --input compose-spec.json --input-file-type jsonschema --output compose.py
|
|
28
|
+
```
|