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,157 @@
|
|
|
1
|
+
"""Workflow Schedules 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_attempt, stop_after_delay
|
|
10
|
+
from tenacity.wait import wait_random
|
|
11
|
+
|
|
12
|
+
from workflow.http.client import Client
|
|
13
|
+
from workflow.utils.decorators import try_request
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Schedules(Client):
|
|
17
|
+
"""HTTP Client for interacting with the Schedules endpoints.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
Client (workflow.http.client): The base class for interacting with the backend.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
Schedules: A client for interacting with the Schedule endpoints.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
@retry(
|
|
27
|
+
reraise=True,
|
|
28
|
+
wait=wait_random(min=1.5, max=3.5),
|
|
29
|
+
stop=(stop_after_delay(5) | stop_after_attempt(1)),
|
|
30
|
+
)
|
|
31
|
+
def deploy(self, data: Dict[str, Any]):
|
|
32
|
+
"""Deploys a Schedule from payload data.
|
|
33
|
+
|
|
34
|
+
Parameters
|
|
35
|
+
----------
|
|
36
|
+
data : Dict[str, Any]
|
|
37
|
+
YAML data.
|
|
38
|
+
|
|
39
|
+
Returns
|
|
40
|
+
-------
|
|
41
|
+
List[str]
|
|
42
|
+
IDs of Schedule objects generated.
|
|
43
|
+
"""
|
|
44
|
+
with self.session as session:
|
|
45
|
+
url = f"{self.baseurl}/schedule"
|
|
46
|
+
response: Response = session.post(url, json=data)
|
|
47
|
+
response.raise_for_status()
|
|
48
|
+
return response.json()
|
|
49
|
+
|
|
50
|
+
@try_request
|
|
51
|
+
def get_schedule(self, query: Dict[str, Any]) -> Dict[str, Any]:
|
|
52
|
+
"""Gets details for one Schedule.
|
|
53
|
+
|
|
54
|
+
Parameters
|
|
55
|
+
----------
|
|
56
|
+
query : Dict[str, Any]
|
|
57
|
+
Dictionary with search parameters.
|
|
58
|
+
|
|
59
|
+
Returns
|
|
60
|
+
-------
|
|
61
|
+
Dict[str, Any]
|
|
62
|
+
Schedule payload.
|
|
63
|
+
"""
|
|
64
|
+
with self.session as session:
|
|
65
|
+
params = {"query": dumps(query)}
|
|
66
|
+
url = f"{self.baseurl}/schedule?{urlencode(params)}"
|
|
67
|
+
response: Response = session.get(url=url)
|
|
68
|
+
response.raise_for_status()
|
|
69
|
+
return response.json()[0]
|
|
70
|
+
|
|
71
|
+
@retry(
|
|
72
|
+
reraise=True,
|
|
73
|
+
wait=wait_random(min=1.5, max=3.5),
|
|
74
|
+
stop=(stop_after_delay(5) | stop_after_attempt(1)),
|
|
75
|
+
)
|
|
76
|
+
@try_request
|
|
77
|
+
def remove(self, id: str) -> Response:
|
|
78
|
+
"""Removes a schedule.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
id : str
|
|
83
|
+
Schedule ID.
|
|
84
|
+
|
|
85
|
+
Returns
|
|
86
|
+
-------
|
|
87
|
+
List[Dict[str, Any]]
|
|
88
|
+
Response payload.
|
|
89
|
+
"""
|
|
90
|
+
with self.session as session:
|
|
91
|
+
query = {"id": id}
|
|
92
|
+
params = {"query": dumps(query)}
|
|
93
|
+
url = f"{self.baseurl}/schedule?{urlencode(params)}"
|
|
94
|
+
response: Response = session.delete(url=url)
|
|
95
|
+
response.raise_for_status()
|
|
96
|
+
return response
|
|
97
|
+
|
|
98
|
+
@try_request
|
|
99
|
+
def list_schedules(self, name: Optional[str]) -> List[Dict[str, Any]]:
|
|
100
|
+
"""Gets the list of all schedules.
|
|
101
|
+
|
|
102
|
+
Parameters
|
|
103
|
+
----------
|
|
104
|
+
name : Optional[str]
|
|
105
|
+
Schedule name.
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
List[Dict[str, Any]]
|
|
110
|
+
List of schedule payloads.
|
|
111
|
+
"""
|
|
112
|
+
with self.session as session:
|
|
113
|
+
query = dumps({"config.name": name})
|
|
114
|
+
projection = dumps(
|
|
115
|
+
{
|
|
116
|
+
"id": True,
|
|
117
|
+
"status": True,
|
|
118
|
+
"lives": True,
|
|
119
|
+
"has_spawned": True,
|
|
120
|
+
"next_time": True,
|
|
121
|
+
"crontab": True,
|
|
122
|
+
"config.name": True,
|
|
123
|
+
}
|
|
124
|
+
)
|
|
125
|
+
url = (
|
|
126
|
+
f"{self.baseurl}/schedule?projection={projection}"
|
|
127
|
+
if name is None
|
|
128
|
+
else f"{self.baseurl}/schedule?query={query}&projection={projection}"
|
|
129
|
+
)
|
|
130
|
+
response: Response = session.get(url=url)
|
|
131
|
+
response.raise_for_status()
|
|
132
|
+
return response.json()
|
|
133
|
+
|
|
134
|
+
@try_request
|
|
135
|
+
def count_schedules(self, schedule_name: Optional[str] = None) -> Dict[str, Any]:
|
|
136
|
+
"""Count schedules per pipeline name.
|
|
137
|
+
|
|
138
|
+
Parameters
|
|
139
|
+
----------
|
|
140
|
+
schedule_name : Optional[str], optional
|
|
141
|
+
Schedule name, by default None
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
Dict[str, Any]
|
|
146
|
+
Count payload.
|
|
147
|
+
"""
|
|
148
|
+
with self.session as session:
|
|
149
|
+
query = dumps({"name": schedule_name})
|
|
150
|
+
url = (
|
|
151
|
+
f"{self.baseurl}/schedule/count"
|
|
152
|
+
if not schedule_name
|
|
153
|
+
else f"{self.baseurl}/schedule/count?query={query}"
|
|
154
|
+
)
|
|
155
|
+
response: Response = session.get(url=url)
|
|
156
|
+
response.raise_for_status()
|
|
157
|
+
return response.json()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Workflow Lifecycle Management
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Archive lifecycle module."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict
|
|
6
|
+
|
|
7
|
+
from workflow.definitions.work import Work
|
|
8
|
+
from workflow.lifecycle.archive import http, posix, s3
|
|
9
|
+
from workflow.utils import logger
|
|
10
|
+
|
|
11
|
+
log = logger.get_logger("workflow.lifecycle.archive")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run(work: Work, workspace: Dict[str, Any]) -> None:
|
|
15
|
+
"""Run the archive lifecycle for a work object.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
work (Work): The work object to run the archive lifecycle for.
|
|
19
|
+
workspace (Dict[str, Any]): The workspace configuration.
|
|
20
|
+
"""
|
|
21
|
+
try:
|
|
22
|
+
mounts: Dict[str, Any] = workspace.get("archive", {}).get("mounts", {})
|
|
23
|
+
archive_config: Dict[str, Any] = workspace.get("config", {}).get("archive", {})
|
|
24
|
+
changes: bool = False
|
|
25
|
+
actions = {
|
|
26
|
+
"s3": {
|
|
27
|
+
"bypass": s3.bypass,
|
|
28
|
+
"copy": s3.copy,
|
|
29
|
+
"delete": s3.delete,
|
|
30
|
+
"move": s3.move,
|
|
31
|
+
},
|
|
32
|
+
"posix": {
|
|
33
|
+
"bypass": posix.bypass,
|
|
34
|
+
"copy": posix.copy,
|
|
35
|
+
"delete": posix.delete,
|
|
36
|
+
"move": posix.move,
|
|
37
|
+
},
|
|
38
|
+
"http": {
|
|
39
|
+
"bypass": http.bypass,
|
|
40
|
+
"copy": http.copy,
|
|
41
|
+
"delete": http.delete,
|
|
42
|
+
"move": http.move,
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
if work.creation:
|
|
46
|
+
date: str = datetime.fromtimestamp(work.creation).strftime("%Y%m%d")
|
|
47
|
+
else:
|
|
48
|
+
raise NameError("Creation date not found in work object.")
|
|
49
|
+
basepath: Path = Path(f"{mounts.get(work.site)}")
|
|
50
|
+
path: Path = basepath / f"/workflow/{date}/{work.pipeline}/{work.id}"
|
|
51
|
+
|
|
52
|
+
if (
|
|
53
|
+
work.config.archive.products
|
|
54
|
+
in archive_config.get("products", {}).get("methods", [])
|
|
55
|
+
and work.products
|
|
56
|
+
):
|
|
57
|
+
storage: str = archive_config.get("products", {}).get("storage", "")
|
|
58
|
+
if storage in actions.keys():
|
|
59
|
+
actions[storage][work.config.archive.products](
|
|
60
|
+
path,
|
|
61
|
+
work.products,
|
|
62
|
+
)
|
|
63
|
+
changes = True
|
|
64
|
+
else:
|
|
65
|
+
log.warning(
|
|
66
|
+
f"Archive storage {storage} not supported, or storage has not been set for products in workspace." # noqa: E501
|
|
67
|
+
)
|
|
68
|
+
elif work.config.archive.products not in archive_config.get("products", {}).get(
|
|
69
|
+
"methods", []
|
|
70
|
+
):
|
|
71
|
+
log.warning(
|
|
72
|
+
f"Archive method {work.config.archive.products} not allowed for products by workspace." # noqa: E501
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
if (
|
|
76
|
+
work.config.archive.plots
|
|
77
|
+
in archive_config.get("plots", {}).get("methods", [])
|
|
78
|
+
and work.plots
|
|
79
|
+
):
|
|
80
|
+
storage = archive_config.get("plots", {}).get("storage", "")
|
|
81
|
+
if storage in actions.keys():
|
|
82
|
+
actions[storage][work.config.archive.plots](
|
|
83
|
+
path,
|
|
84
|
+
work.plots,
|
|
85
|
+
)
|
|
86
|
+
changes = True
|
|
87
|
+
else:
|
|
88
|
+
log.warning(
|
|
89
|
+
f"Archive storage {storage} not supported, or storage has not been set for plots in workspace." # noqa: E501
|
|
90
|
+
)
|
|
91
|
+
elif work.config.archive.plots not in archive_config.get("plots", {}).get(
|
|
92
|
+
"methods", []
|
|
93
|
+
):
|
|
94
|
+
log.warning(
|
|
95
|
+
f"Archive method {work.config.archive.plots} not allowed for plots by workspace." # noqa: E501
|
|
96
|
+
)
|
|
97
|
+
if changes and "posix" in archive_config.get("permissions", {}):
|
|
98
|
+
posix.permissions(
|
|
99
|
+
path, archive_config.get("permissions", {}).get("posix", {})
|
|
100
|
+
)
|
|
101
|
+
except Exception as error:
|
|
102
|
+
log.warning(error)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""HTTP archive functions."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import List, Optional
|
|
5
|
+
|
|
6
|
+
from workflow.utils import logger
|
|
7
|
+
|
|
8
|
+
log = logger.get_logger("workflow.lifecycle.archive.http")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def bypass(path: Path, payload: Optional[List[str]]) -> bool:
|
|
12
|
+
"""Bypass the archive.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
path (Path): Destination path.
|
|
16
|
+
payload (List[str]): List of files to copy.
|
|
17
|
+
"""
|
|
18
|
+
log.info("Bypassing archive.")
|
|
19
|
+
return True
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def copy(path: Path, payload: Optional[List[str]]) -> bool:
|
|
23
|
+
"""Copy the work products to the archive.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
path (Path): Destination path.
|
|
27
|
+
payload (List[str]): List of files to copy.
|
|
28
|
+
"""
|
|
29
|
+
log.warning("upload currently not implemented")
|
|
30
|
+
raise NotImplementedError
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def move(path: Path, payload: Optional[List[str]]) -> bool:
|
|
34
|
+
"""Move the work products to the archive.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
path (Path): Destination path.
|
|
38
|
+
payload (List[str]): List of products to move.
|
|
39
|
+
"""
|
|
40
|
+
log.warning("upload currently not implemented")
|
|
41
|
+
raise NotImplementedError
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def delete(path: Path, payload: Optional[List[str]]) -> bool:
|
|
45
|
+
"""Delete the work products from the archive.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
path (Path): Destination path.
|
|
49
|
+
payload (List[str]): List of products to delete.
|
|
50
|
+
"""
|
|
51
|
+
log.warning("delete currently not implemented")
|
|
52
|
+
raise NotImplementedError
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def permissions(path: Path, site: str) -> bool:
|
|
56
|
+
"""Set the permissions for the work products in the archive."""
|
|
57
|
+
log.warning("permissions currently not implemented")
|
|
58
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""POSIX archive functions."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from workflow.utils import logger
|
|
11
|
+
|
|
12
|
+
log = logger.get_logger("workflow.lifecycle.archive.posix")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def extract_basepath(path: Path):
|
|
16
|
+
"""Extract the base path from a given path.
|
|
17
|
+
|
|
18
|
+
Uses the fact that the path is build using the following format,
|
|
19
|
+
path = basepath / f"/workflow/{date}/{work.pipeline}/{work.id}"
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
path: Path to extract from.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Path: Base path.
|
|
26
|
+
"""
|
|
27
|
+
try:
|
|
28
|
+
split_path = re.split(r"/workflow/\d+", path.as_posix())
|
|
29
|
+
basepath = split_path[0]
|
|
30
|
+
return Path(basepath)
|
|
31
|
+
except Exception as e:
|
|
32
|
+
raise e
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def check_basepath(path: Path):
|
|
36
|
+
"""Validates if the basepath exists.
|
|
37
|
+
|
|
38
|
+
If the path given contains '/workflow' it is not the basepath and so the basepath
|
|
39
|
+
is extracted before the evaluation.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
path: Path to validate.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
FileNotFoundError: If the path doesn't exist.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
bool: True if the path exists.
|
|
49
|
+
"""
|
|
50
|
+
if "/workflow" in path.as_posix():
|
|
51
|
+
path = extract_basepath(path)
|
|
52
|
+
if not path.exists():
|
|
53
|
+
raise FileNotFoundError(f"Mount {path} does not exist.")
|
|
54
|
+
else:
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def bypass(path: Path, payload: Optional[List[str]]) -> bool:
|
|
59
|
+
"""Bypass the archive.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
path (Path): Destination path.
|
|
63
|
+
payload (List[str]): List of files to copy.
|
|
64
|
+
"""
|
|
65
|
+
log.info("Bypassing archive.")
|
|
66
|
+
return True
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def copy(path: Path, payload: Optional[List[str]]) -> bool:
|
|
70
|
+
"""Copy the work products to the archive.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
path (Path): Destination path.
|
|
74
|
+
payload (List[str]): List of files to copy.
|
|
75
|
+
"""
|
|
76
|
+
try:
|
|
77
|
+
check_basepath(path)
|
|
78
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
if not path.exists() or not path.is_dir() or not os.access(path, os.W_OK):
|
|
80
|
+
log.error("Destination path is invalid or not writable.")
|
|
81
|
+
return False
|
|
82
|
+
if not payload:
|
|
83
|
+
log.info("No files in payload.")
|
|
84
|
+
return True
|
|
85
|
+
for index, item in enumerate(payload):
|
|
86
|
+
if not os.path.exists(item):
|
|
87
|
+
log.warning(f"File {item} does not exist.")
|
|
88
|
+
continue
|
|
89
|
+
shutil.copy(item, path.as_posix())
|
|
90
|
+
payload[index] = (path / item.split("/")[-1]).as_posix()
|
|
91
|
+
return True
|
|
92
|
+
except Exception as error:
|
|
93
|
+
log.exception(error)
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def move(path: Path, payload: Optional[List[str]]) -> bool:
|
|
98
|
+
"""Move the work products to the archive.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
path (Path): Destination path.
|
|
102
|
+
payload (List[str]): List of products to move.
|
|
103
|
+
"""
|
|
104
|
+
status: bool = False
|
|
105
|
+
try:
|
|
106
|
+
check_basepath(path)
|
|
107
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
if path.exists() and path.is_dir() and os.access(path, os.W_OK) and payload:
|
|
109
|
+
for index, item in enumerate(payload):
|
|
110
|
+
shutil.move(item, path.as_posix())
|
|
111
|
+
payload[index] = (path / item.split("/")[-1]).as_posix()
|
|
112
|
+
elif not payload:
|
|
113
|
+
log.info("No files in payload.")
|
|
114
|
+
status = True
|
|
115
|
+
except Exception as error:
|
|
116
|
+
log.exception(error)
|
|
117
|
+
status = False
|
|
118
|
+
finally:
|
|
119
|
+
return status
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def delete(path: Path, payload: Optional[List[str]]) -> bool:
|
|
123
|
+
"""Delete the work products from the archive.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
path (Path): Destination path.
|
|
127
|
+
payload (List[str]): List of products to delete.
|
|
128
|
+
"""
|
|
129
|
+
status: bool = False
|
|
130
|
+
try:
|
|
131
|
+
check_basepath(path)
|
|
132
|
+
if payload:
|
|
133
|
+
for item in payload:
|
|
134
|
+
os.remove(item)
|
|
135
|
+
payload.remove(item)
|
|
136
|
+
else:
|
|
137
|
+
log.info("no files to delete.")
|
|
138
|
+
status = True
|
|
139
|
+
except Exception as error:
|
|
140
|
+
log.exception(error)
|
|
141
|
+
finally:
|
|
142
|
+
return status
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def permissions(path: Path, config: Dict[str, Any]) -> bool:
|
|
146
|
+
"""Set the permissions for the work products in the archive."""
|
|
147
|
+
status: bool = False
|
|
148
|
+
try:
|
|
149
|
+
check_basepath(path)
|
|
150
|
+
if not path.exists():
|
|
151
|
+
raise NotADirectoryError
|
|
152
|
+
|
|
153
|
+
user: Optional[str] = config.get("user")
|
|
154
|
+
group: Optional[str] = config.get("group")
|
|
155
|
+
if not user and not group:
|
|
156
|
+
raise ValueError("Either user or group must be specified.")
|
|
157
|
+
|
|
158
|
+
command: str = config.get(
|
|
159
|
+
"command",
|
|
160
|
+
"chgrop -R {group} {path}; chmod -R g+w {path}",
|
|
161
|
+
)
|
|
162
|
+
command = eval(f"f'{command}'")
|
|
163
|
+
subprocess.run(command)
|
|
164
|
+
status = True
|
|
165
|
+
|
|
166
|
+
except NotADirectoryError:
|
|
167
|
+
log.error(f"Path {path.as_posix()} does not exist.")
|
|
168
|
+
status = False
|
|
169
|
+
|
|
170
|
+
except ValueError as error:
|
|
171
|
+
log.error(error)
|
|
172
|
+
status = False
|
|
173
|
+
|
|
174
|
+
except FileNotFoundError as error:
|
|
175
|
+
log.warning(error)
|
|
176
|
+
try:
|
|
177
|
+
subprocess.run(f"chgrp -R chime-frb-rw {path.as_posix()}")
|
|
178
|
+
subprocess.run(f"chmod g+w {path.as_posix()}")
|
|
179
|
+
status = True
|
|
180
|
+
except Exception as error:
|
|
181
|
+
log.warning(error)
|
|
182
|
+
status = False
|
|
183
|
+
|
|
184
|
+
finally:
|
|
185
|
+
return status
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""S3 archive functions."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from minio import Minio
|
|
8
|
+
|
|
9
|
+
from workflow.utils import logger
|
|
10
|
+
|
|
11
|
+
log = logger.get_logger("workflow.lifecycle.archive.s3")
|
|
12
|
+
|
|
13
|
+
WORKFLOW_S3_ENDPOINT = os.getenv("WORKFLOW_S3_ENDPOINT")
|
|
14
|
+
WORKFLOW_S3_ACCESS_KEY = os.getenv("WORKFLOW_S3_ACCESS_KEY")
|
|
15
|
+
WORKFLOW_S3_SECRET_KEY = os.getenv("WORKFLOW_S3_SECRET_KEY")
|
|
16
|
+
WORKFLOW_S3_BUCKET = os.getenv("WORKFLOW_S3_BUCKET", "workflow")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def bypass(path: Path, payload: Optional[List[str]]) -> bool:
|
|
20
|
+
"""Bypass the archive.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
path (Path): Destination path.
|
|
24
|
+
payload (List[str]): List of files to copy.
|
|
25
|
+
"""
|
|
26
|
+
log.info("Bypassing archive.")
|
|
27
|
+
return True
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def copy(path: Path, payload: Optional[List[str]]) -> bool:
|
|
31
|
+
"""Copy the work products to the archive.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
path (Path): Destination path.
|
|
35
|
+
payload (List[str]): List of files to copy.
|
|
36
|
+
"""
|
|
37
|
+
try:
|
|
38
|
+
# Initialise minio client
|
|
39
|
+
log.info("Connecting to S3 storage to copy files")
|
|
40
|
+
log.debug(f"Endpoint: {WORKFLOW_S3_ENDPOINT}")
|
|
41
|
+
log.debug(f"Access Key: {WORKFLOW_S3_ACCESS_KEY}")
|
|
42
|
+
log.debug(f"Secret Key: {WORKFLOW_S3_SECRET_KEY}")
|
|
43
|
+
client = Minio(
|
|
44
|
+
endpoint=WORKFLOW_S3_ENDPOINT,
|
|
45
|
+
access_key=WORKFLOW_S3_ACCESS_KEY,
|
|
46
|
+
secret_key=WORKFLOW_S3_SECRET_KEY,
|
|
47
|
+
)
|
|
48
|
+
log.info("Connected ✅")
|
|
49
|
+
# Check bucket exists and if not, create it
|
|
50
|
+
if not client.bucket_exists(WORKFLOW_S3_BUCKET):
|
|
51
|
+
log.info(f"Bucket {WORKFLOW_S3_BUCKET} does not exist. Creating it.")
|
|
52
|
+
client.make_bucket(WORKFLOW_S3_BUCKET)
|
|
53
|
+
# Check there are files to copy
|
|
54
|
+
if not payload:
|
|
55
|
+
log.info("No files in payload.")
|
|
56
|
+
return True
|
|
57
|
+
split_path = path.as_posix().split("/")
|
|
58
|
+
object_paths = "/".join(split_path[split_path.index("workflow") + 1 :])
|
|
59
|
+
for index, item in enumerate(payload):
|
|
60
|
+
# Check file exists
|
|
61
|
+
if not os.path.exists(item):
|
|
62
|
+
log.warning(f"File {item} does not exist.")
|
|
63
|
+
continue
|
|
64
|
+
# Upload file to S3
|
|
65
|
+
client.fput_object(
|
|
66
|
+
bucket_name=WORKFLOW_S3_BUCKET,
|
|
67
|
+
object_name="/".join([object_paths, item.split("/")[-1]]),
|
|
68
|
+
file_path=item,
|
|
69
|
+
)
|
|
70
|
+
# Update payload with new path
|
|
71
|
+
payload[
|
|
72
|
+
index
|
|
73
|
+
] = f"s3://{os.getenv('WORKFLOW_S3_ENDPOINT')}/workflow/{'/'.join([object_paths, item.split('/')[-1]])}" # noqa: E501
|
|
74
|
+
log.info("Move complete ✅")
|
|
75
|
+
return True
|
|
76
|
+
except Exception as error:
|
|
77
|
+
log.error("Move failed ❌")
|
|
78
|
+
log.exception(error)
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def move(path: Path, payload: Optional[List[str]]) -> bool:
|
|
83
|
+
"""Move the work products to the archive.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
path (Path): Destination path.
|
|
87
|
+
payload (List[str]): List of products to move.
|
|
88
|
+
"""
|
|
89
|
+
try:
|
|
90
|
+
# Initialise minio client
|
|
91
|
+
log.info("Connecting to S3 storage to move files")
|
|
92
|
+
log.debug(f"Endpoint: {WORKFLOW_S3_ENDPOINT}")
|
|
93
|
+
log.debug(f"Access Key: {WORKFLOW_S3_ACCESS_KEY}")
|
|
94
|
+
log.debug(f"Secret Key: {WORKFLOW_S3_SECRET_KEY}")
|
|
95
|
+
client = Minio(
|
|
96
|
+
endpoint=WORKFLOW_S3_ENDPOINT,
|
|
97
|
+
access_key=WORKFLOW_S3_ACCESS_KEY,
|
|
98
|
+
secret_key=WORKFLOW_S3_SECRET_KEY,
|
|
99
|
+
)
|
|
100
|
+
log.info("Connected ✅")
|
|
101
|
+
# Check bucket exists and if not, create it
|
|
102
|
+
if not client.bucket_exists(WORKFLOW_S3_BUCKET):
|
|
103
|
+
log.info(f"Bucket {WORKFLOW_S3_BUCKET} does not exist. Creating it.")
|
|
104
|
+
client.make_bucket(WORKFLOW_S3_BUCKET)
|
|
105
|
+
# Check there are files to copy
|
|
106
|
+
if not payload:
|
|
107
|
+
log.info("No files in payload.")
|
|
108
|
+
return True
|
|
109
|
+
split_path = path.as_posix().split("/")
|
|
110
|
+
object_paths = "/".join(split_path[split_path.index("workflow") + 1 :])
|
|
111
|
+
for index, item in enumerate(payload):
|
|
112
|
+
# Check file exists
|
|
113
|
+
if not os.path.exists(item):
|
|
114
|
+
log.warning(f"File {item} does not exist.")
|
|
115
|
+
continue
|
|
116
|
+
# Upload file to S3
|
|
117
|
+
client.fput_object(
|
|
118
|
+
bucket_name=WORKFLOW_S3_BUCKET,
|
|
119
|
+
object_name="/".join([object_paths, item.split("/")[-1]]),
|
|
120
|
+
file_path=item,
|
|
121
|
+
)
|
|
122
|
+
# Update payload with new path
|
|
123
|
+
payload[
|
|
124
|
+
index
|
|
125
|
+
] = f"s3://{os.getenv('WORKFLOW_S3_ENDPOINT')}/workflow/{'/'.join([object_paths, item.split('/')[-1]])}" # noqa: E501 # noqa: E501
|
|
126
|
+
# Delete file
|
|
127
|
+
os.remove(item)
|
|
128
|
+
log.info("Move complete ✅")
|
|
129
|
+
return True
|
|
130
|
+
except Exception as error:
|
|
131
|
+
log.error("Move failed ❌")
|
|
132
|
+
log.exception(error)
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def delete(path: Path, payload: Optional[List[str]]) -> bool:
|
|
137
|
+
"""Delete the work products from the archive.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
path (Path): Destination path.
|
|
141
|
+
payload (List[str]): List of products to delete.
|
|
142
|
+
"""
|
|
143
|
+
# TODO: Implement delete for S3
|
|
144
|
+
# NOTE: Do we need a specific delete function for S3?
|
|
145
|
+
# Since Workflow always runs on a POSIX system, we can
|
|
146
|
+
# just use the POSIX delete function.
|
|
147
|
+
log.warning("delete currently not implemented")
|
|
148
|
+
raise NotImplementedError
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def permissions(path: Path, site: str) -> bool:
|
|
152
|
+
"""Set the permissions for the work products in the archive."""
|
|
153
|
+
# TODO: Implement permissions for S3
|
|
154
|
+
# NOTE: Permissions seems to be set on the bucket level, not the object level
|
|
155
|
+
# So, perhaps add this to a bucket creation function?
|
|
156
|
+
log.warning("permissions currently not implemented")
|
|
157
|
+
raise NotImplementedError
|