runnable 0.25.0__py3-none-any.whl → 0.27.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,201 @@
1
+ import logging
2
+ import os
3
+ import shutil
4
+ from abc import abstractmethod
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from cloudpathlib import CloudPath
9
+
10
+ from runnable import defaults, utils
11
+ from runnable.catalog import BaseCatalog
12
+ from runnable.datastore import DataCatalog
13
+
14
+ logger = logging.getLogger(defaults.LOGGER_NAME)
15
+
16
+
17
+ class AnyPathCatalog(BaseCatalog):
18
+ """
19
+ A Catalog handler that uses the local file system for cataloging.
20
+
21
+ Note: Do not use this if the steps of the pipeline run on different compute environments.
22
+
23
+ Example config:
24
+
25
+ catalog:
26
+ type: file-system
27
+ config:
28
+ catalog_location: The location to store the catalog.
29
+ compute_data_folder: The folder to source the data from.
30
+
31
+ """
32
+
33
+ @abstractmethod
34
+ def get_summary(self) -> Dict[str, Any]: ...
35
+
36
+ @abstractmethod
37
+ def upload_to_catalog(self, file: Path) -> None: ...
38
+
39
+ @abstractmethod
40
+ def download_from_catalog(self, file: Path | CloudPath) -> None: ...
41
+
42
+ @abstractmethod
43
+ def get_catalog_location(self) -> Path | CloudPath:
44
+ """
45
+ For local file systems, this is the .catalog/run_id/compute_data_folder
46
+ For cloud systems, this is s3://bucket/run_id/compute_data_folder
47
+ """
48
+ ...
49
+
50
+ def get(self, name: str) -> List[DataCatalog]:
51
+ """
52
+ Get the file by matching glob pattern to the name
53
+
54
+ Args:
55
+ name ([str]): A glob matching the file name
56
+ run_id ([str]): The run id
57
+
58
+ Raises:
59
+ Exception: If the catalog location does not exist
60
+
61
+ Returns:
62
+ List(object) : A list of catalog objects
63
+ """
64
+ run_catalog = self.get_catalog_location()
65
+
66
+ # Iterate through the contents of the run_catalog and copy the files that fit the name pattern
67
+ # We should also return a list of data hashes
68
+ glob_files = run_catalog.glob(name)
69
+ logger.debug(
70
+ f"Glob identified {glob_files} as matches to from the catalog location: {run_catalog}"
71
+ )
72
+
73
+ data_catalogs = []
74
+ run_log_store = self._context.run_log_store
75
+ for file in glob_files:
76
+ if file.is_dir():
77
+ # Need not add a data catalog for the folder
78
+ continue
79
+
80
+ if str(file).endswith(".execution.log"):
81
+ continue
82
+
83
+ self.download_from_catalog(file)
84
+ relative_file_path = file.relative_to(run_catalog) # type: ignore
85
+
86
+ data_catalog = run_log_store.create_data_catalog(str(relative_file_path))
87
+ data_catalog.catalog_relative_path = str(relative_file_path)
88
+ data_catalog.data_hash = utils.get_data_hash(str(relative_file_path))
89
+ data_catalog.stage = "get"
90
+ data_catalogs.append(data_catalog)
91
+
92
+ if not data_catalogs:
93
+ raise Exception(f"Did not find any files matching {name} in {run_catalog}")
94
+
95
+ return data_catalogs
96
+
97
+ def put(self, name: str) -> List[DataCatalog]:
98
+ """
99
+ Put the files matching the glob pattern into the catalog.
100
+
101
+ If previously synced catalogs are provided, and no changes were observed, we do not sync them.
102
+
103
+ Args:
104
+ name (str): The glob pattern of the files to catalog
105
+ run_id (str): The run id of the run
106
+ compute_data_folder (str, optional): The compute data folder to sync from. Defaults to settings default.
107
+ synced_catalogs (dict, optional): dictionary of previously synced catalogs. Defaults to None.
108
+
109
+ Raises:
110
+ Exception: If the compute data folder does not exist.
111
+
112
+ Returns:
113
+ List(object) : A list of catalog objects
114
+ """
115
+ run_id = self._context.run_id
116
+ logger.info(
117
+ f"Using the {self.service_name} catalog and trying to put {name} for run_id: {run_id}"
118
+ )
119
+
120
+ copy_from = Path(self.compute_data_folder)
121
+
122
+ if not copy_from.is_dir():
123
+ msg = (
124
+ f"Expected compute data folder to be present at: {copy_from} but not found. \n"
125
+ "Note: runnable does not create the compute data folder for you. Please ensure that the "
126
+ "folder exists.\n"
127
+ )
128
+ raise Exception(msg)
129
+
130
+ # Iterate through the contents of copy_from and if the name matches, we move them to the run_catalog
131
+ # We should also return a list of datastore.DataCatalog items
132
+ glob_files = copy_from.glob(name)
133
+ logger.debug(
134
+ f"Glob identified {glob_files} as matches to from the compute data folder: {copy_from}"
135
+ )
136
+
137
+ data_catalogs = []
138
+ run_log_store = self._context.run_log_store
139
+ for file in glob_files:
140
+ if file.is_dir():
141
+ # Need not add a data catalog for the folder
142
+ continue
143
+
144
+ relative_file_path = file.relative_to(copy_from)
145
+
146
+ data_catalog = run_log_store.create_data_catalog(str(relative_file_path))
147
+ data_catalog.catalog_relative_path = (
148
+ run_id + os.sep + str(relative_file_path)
149
+ )
150
+ data_catalog.data_hash = utils.get_data_hash(str(file))
151
+ data_catalog.stage = "put"
152
+ data_catalogs.append(data_catalog)
153
+
154
+ # TODO: Think about syncing only if the file is changed
155
+ self.upload_to_catalog(file)
156
+
157
+ if not data_catalogs:
158
+ raise Exception(f"Did not find any files matching {name} in {copy_from}")
159
+
160
+ return data_catalogs
161
+
162
+ def sync_between_runs(self, previous_run_id: str, run_id: str):
163
+ """
164
+ Given the previous run id, sync the catalogs between the current one and previous
165
+
166
+ Args:
167
+ previous_run_id (str): The previous run id to sync the catalogs from
168
+ run_id (str): The run_id to which the data catalogs should be synced to.
169
+
170
+ Raises:
171
+ Exception: If the previous run log does not exist in the catalog
172
+
173
+ """
174
+ logger.info(
175
+ f"Using the {self.service_name} catalog and syncing catalogs"
176
+ "between old: {previous_run_id} to new: {run_id}"
177
+ )
178
+
179
+ catalog_location = Path(self.get_catalog_location())
180
+ run_catalog = catalog_location / run_id
181
+ utils.safe_make_dir(run_catalog)
182
+
183
+ if not utils.does_dir_exist(catalog_location / previous_run_id):
184
+ msg = (
185
+ f"Catalogs from previous run : {previous_run_id} are not found.\n"
186
+ "Note: Please provision the catalog objects generated by previous run in the same catalog location"
187
+ " as the current run, even if the catalog handler for the previous run was different"
188
+ )
189
+ raise Exception(msg)
190
+
191
+ cataloged_files = list((catalog_location / previous_run_id).glob("*"))
192
+
193
+ for cataloged_file in cataloged_files:
194
+ if str(cataloged_file).endswith("execution.log"):
195
+ continue
196
+
197
+ if cataloged_file.is_file():
198
+ shutil.copy(cataloged_file, run_catalog / cataloged_file.name)
199
+ else:
200
+ shutil.copytree(cataloged_file, run_catalog / cataloged_file.name)
201
+ logger.info(f"Copied file from: {cataloged_file} to {run_catalog}")
@@ -1,253 +1,52 @@
1
1
  import logging
2
- import os
3
2
  import shutil
4
3
  from pathlib import Path
5
- from typing import Any, Dict, List, Optional
4
+ from typing import Any
6
5
 
7
- from runnable import defaults, utils
8
- from runnable.catalog import BaseCatalog, is_catalog_out_of_sync
9
- from runnable.datastore import DataCatalog
6
+ from cloudpathlib import CloudPath
7
+ from pydantic import Field
10
8
 
11
- logger = logging.getLogger(defaults.LOGGER_NAME)
12
-
13
-
14
- class FileSystemCatalog(BaseCatalog):
15
- """
16
- A Catalog handler that uses the local file system for cataloging.
17
-
18
- Note: Do not use this if the steps of the pipeline run on different compute environments.
9
+ from extensions.catalog.any_path import AnyPathCatalog
10
+ from runnable import defaults
19
11
 
20
- Example config:
21
-
22
- catalog:
23
- type: file-system
24
- config:
25
- catalog_location: The location to store the catalog.
26
- compute_data_folder: The folder to source the data from.
12
+ logger = logging.getLogger(defaults.LOGGER_NAME)
27
13
 
28
- """
29
14
 
15
+ class FileSystemCatalog(AnyPathCatalog):
30
16
  service_name: str = "file-system"
31
- catalog_location: str = defaults.CATALOG_LOCATION_FOLDER
32
17
 
33
- def get_catalog_location(self):
34
- return self.catalog_location
18
+ catalog_location: str = Field(default=defaults.CATALOG_LOCATION_FOLDER)
35
19
 
36
- def get_summary(self) -> Dict[str, Any]:
37
- summary = {
38
- "Catalog Location": self.get_catalog_location(),
20
+ def get_summary(self) -> dict[str, Any]:
21
+ return {
22
+ "compute_data_folder": self.compute_data_folder,
23
+ "catalog_location": self.catalog_location,
39
24
  }
40
25
 
41
- return summary
42
-
43
- def get(
44
- self, name: str, run_id: str, compute_data_folder: str = "", **kwargs
45
- ) -> List[DataCatalog]:
46
- """
47
- Get the file by matching glob pattern to the name
26
+ def get_catalog_location(self) -> Path:
27
+ run_id = self._context.run_id
28
+ return Path(self.catalog_location) / run_id / self.compute_data_folder
48
29
 
49
- Args:
50
- name ([str]): A glob matching the file name
51
- run_id ([str]): The run id
30
+ def download_from_catalog(self, file: Path | CloudPath) -> None:
31
+ assert isinstance(file, Path)
52
32
 
53
- Raises:
54
- Exception: If the catalog location does not exist
55
-
56
- Returns:
57
- List(object) : A list of catalog objects
58
- """
59
- logger.info(
60
- f"Using the {self.service_name} catalog and trying to get {name} for run_id: {run_id}"
61
- )
33
+ run_catalog = self.get_catalog_location()
34
+ relative_file_path = file.relative_to(run_catalog)
62
35
 
63
36
  copy_to = self.compute_data_folder
64
- if compute_data_folder:
65
- copy_to = compute_data_folder
66
-
67
- copy_to = Path(copy_to) # type: ignore
68
-
69
- catalog_location = self.get_catalog_location()
70
- run_catalog = Path(catalog_location) / run_id / copy_to
71
-
72
- logger.debug(
73
- f"Copying objects to {copy_to} from the run catalog location of {run_catalog}"
74
- )
37
+ # Make the directory in the data folder if required
38
+ Path(copy_to / relative_file_path.parent).mkdir(parents=True, exist_ok=True)
39
+ shutil.copy(file, copy_to / relative_file_path)
75
40
 
76
- if not utils.does_dir_exist(run_catalog):
77
- msg = (
78
- f"Expected Catalog to be present at: {run_catalog} but not found.\n"
79
- "Note: Please make sure that some data was put in the catalog before trying to get from it.\n"
80
- )
81
- raise Exception(msg)
41
+ def upload_to_catalog(self, file: Path) -> None:
42
+ run_catalog = self.get_catalog_location()
43
+ run_catalog.mkdir(parents=True, exist_ok=True)
82
44
 
83
- # Iterate through the contents of the run_catalog and copy the files that fit the name pattern
84
- # We should also return a list of data hashes
85
- glob_files = run_catalog.glob(name)
86
45
  logger.debug(
87
- f"Glob identified {glob_files} as matches to from the catalog location: {run_catalog}"
46
+ f"Copying objects from {self.compute_data_folder} to the run catalog location of {run_catalog}"
88
47
  )
89
48
 
90
- data_catalogs = []
91
- run_log_store = self._context.run_log_store
92
- for file in glob_files:
93
- if file.is_dir():
94
- # Need not add a data catalog for the folder
95
- continue
96
-
97
- if str(file).endswith(".execution.log"):
98
- continue
99
-
100
- relative_file_path = file.relative_to(run_catalog)
101
-
102
- data_catalog = run_log_store.create_data_catalog(str(relative_file_path))
103
- data_catalog.catalog_handler_location = catalog_location
104
- data_catalog.catalog_relative_path = str(relative_file_path)
105
- data_catalog.data_hash = utils.get_data_hash(str(file))
106
- data_catalog.stage = "get"
107
- data_catalogs.append(data_catalog)
108
-
109
- # Make the directory in the data folder if required
110
- Path(copy_to / relative_file_path.parent).mkdir(parents=True, exist_ok=True)
111
- shutil.copy(file, copy_to / relative_file_path)
112
-
113
- logger.info(f"Copied {file} from {run_catalog} to {copy_to}")
114
-
115
- if not data_catalogs:
116
- raise Exception(f"Did not find any files matching {name} in {run_catalog}")
117
-
118
- return data_catalogs
119
-
120
- def put(
121
- self,
122
- name: str,
123
- run_id: str,
124
- compute_data_folder: str = "",
125
- synced_catalogs: Optional[List[DataCatalog]] = None,
126
- **kwargs,
127
- ) -> List[DataCatalog]:
128
- """
129
- Put the files matching the glob pattern into the catalog.
130
-
131
- If previously synced catalogs are provided, and no changes were observed, we do not sync them.
132
-
133
- Args:
134
- name (str): The glob pattern of the files to catalog
135
- run_id (str): The run id of the run
136
- compute_data_folder (str, optional): The compute data folder to sync from. Defaults to settings default.
137
- synced_catalogs (dict, optional): dictionary of previously synced catalogs. Defaults to None.
138
-
139
- Raises:
140
- Exception: If the compute data folder does not exist.
141
-
142
- Returns:
143
- List(object) : A list of catalog objects
144
- """
145
- logger.info(
146
- f"Using the {self.service_name} catalog and trying to put {name} for run_id: {run_id}"
147
- )
148
-
149
- copy_from = self.compute_data_folder
150
- if compute_data_folder:
151
- copy_from = compute_data_folder
152
- copy_from = Path(copy_from) # type: ignore
153
-
154
- catalog_location = self.get_catalog_location()
155
- run_catalog = Path(catalog_location) / run_id
156
- utils.safe_make_dir(run_catalog)
157
-
158
- logger.debug(
159
- f"Copying objects from {copy_from} to the run catalog location of {run_catalog}"
160
- )
161
-
162
- if not utils.does_dir_exist(copy_from):
163
- msg = (
164
- f"Expected compute data folder to be present at: {compute_data_folder} but not found. \n"
165
- "Note: runnable does not create the compute data folder for you. Please ensure that the "
166
- "folder exists.\n"
167
- )
168
- raise Exception(msg)
169
-
170
- # Iterate through the contents of copy_from and if the name matches, we move them to the run_catalog
171
- # We should also return a list of datastore.DataCatalog items
172
-
173
- glob_files = copy_from.glob(name) # type: ignore
174
- logger.debug(
175
- f"Glob identified {glob_files} as matches to from the compute data folder: {copy_from}"
176
- )
177
-
178
- data_catalogs = []
179
- run_log_store = self._context.run_log_store
180
- for file in glob_files:
181
- if file.is_dir():
182
- # Need not add a data catalog for the folder
183
- continue
184
-
185
- relative_file_path = file.relative_to(".")
186
-
187
- data_catalog = run_log_store.create_data_catalog(str(relative_file_path))
188
- data_catalog.catalog_handler_location = catalog_location
189
- data_catalog.catalog_relative_path = (
190
- run_id + os.sep + str(relative_file_path)
191
- )
192
- data_catalog.data_hash = utils.get_data_hash(str(file))
193
- data_catalog.stage = "put"
194
- data_catalogs.append(data_catalog)
195
-
196
- if is_catalog_out_of_sync(data_catalog, synced_catalogs):
197
- logger.info(f"{data_catalog.name} was found to be changed, syncing")
198
-
199
- # Make the directory in the catalog if required
200
- Path(run_catalog / relative_file_path.parent).mkdir(
201
- parents=True, exist_ok=True
202
- )
203
- shutil.copy(file, run_catalog / relative_file_path)
204
- else:
205
- logger.info(
206
- f"{data_catalog.name} was found to be unchanged, ignoring syncing"
207
- )
208
-
209
- if not data_catalogs:
210
- raise Exception(f"Did not find any files matching {name} in {copy_from}")
211
-
212
- return data_catalogs
213
-
214
- def sync_between_runs(self, previous_run_id: str, run_id: str):
215
- """
216
- Given the previous run id, sync the catalogs between the current one and previous
217
-
218
- Args:
219
- previous_run_id (str): The previous run id to sync the catalogs from
220
- run_id (str): The run_id to which the data catalogs should be synced to.
221
-
222
- Raises:
223
- Exception: If the previous run log does not exist in the catalog
224
-
225
- """
226
- logger.info(
227
- f"Using the {self.service_name} catalog and syncing catalogs"
228
- "between old: {previous_run_id} to new: {run_id}"
229
- )
230
-
231
- catalog_location = Path(self.get_catalog_location())
232
- run_catalog = catalog_location / run_id
233
- utils.safe_make_dir(run_catalog)
234
-
235
- if not utils.does_dir_exist(catalog_location / previous_run_id):
236
- msg = (
237
- f"Catalogs from previous run : {previous_run_id} are not found.\n"
238
- "Note: Please provision the catalog objects generated by previous run in the same catalog location"
239
- " as the current run, even if the catalog handler for the previous run was different"
240
- )
241
- raise Exception(msg)
242
-
243
- cataloged_files = list((catalog_location / previous_run_id).glob("*"))
244
-
245
- for cataloged_file in cataloged_files:
246
- if str(cataloged_file).endswith("execution.log"):
247
- continue
49
+ relative_file_path = file.relative_to(self.compute_data_folder)
248
50
 
249
- if cataloged_file.is_file():
250
- shutil.copy(cataloged_file, run_catalog / cataloged_file.name)
251
- else:
252
- shutil.copytree(cataloged_file, run_catalog / cataloged_file.name)
253
- logger.info(f"Copied file from: {cataloged_file} to {run_catalog}")
51
+ (run_catalog / relative_file_path.parent).mkdir(parents=True, exist_ok=True)
52
+ shutil.copy(file, run_catalog / relative_file_path)
@@ -0,0 +1,72 @@
1
+ import logging
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from cloudpathlib import CloudPath, S3Client, S3Path
7
+ from pydantic import Field, SecretStr
8
+
9
+ from extensions.catalog.any_path import AnyPathCatalog
10
+ from runnable import defaults
11
+
12
+ logger = logging.getLogger(defaults.LOGGER_NAME)
13
+
14
+
15
+ @lru_cache
16
+ def get_minio_client(
17
+ endpoint_url: str, aws_access_key_id: str, aws_secret_access_key: str
18
+ ) -> S3Client:
19
+ return S3Client(
20
+ endpoint_url=endpoint_url,
21
+ aws_access_key_id=aws_access_key_id,
22
+ aws_secret_access_key=aws_secret_access_key,
23
+ )
24
+
25
+
26
+ class MinioCatalog(AnyPathCatalog):
27
+ service_name: str = "minio"
28
+
29
+ endpoint_url: str = Field(default="http://localhost:9002")
30
+ aws_access_key_id: SecretStr = SecretStr(secret_value="minioadmin")
31
+ aws_secret_access_key: SecretStr = SecretStr(secret_value="minioadmin")
32
+ bucket: str = "runnable"
33
+
34
+ def get_summary(self) -> dict[str, Any]:
35
+ return {
36
+ "service_name": self.service_name,
37
+ "compute_data_folder": self.compute_data_folder,
38
+ "endpoint_url": self.endpoint_url,
39
+ "bucket": self.bucket,
40
+ }
41
+
42
+ def get_catalog_location(self) -> S3Path:
43
+ run_id = self._context.run_id
44
+
45
+ return S3Path(
46
+ f"s3://{self.bucket}/{run_id}/{self.compute_data_folder}".strip("."),
47
+ client=get_minio_client(
48
+ self.endpoint_url,
49
+ self.aws_access_key_id.get_secret_value(),
50
+ self.aws_secret_access_key.get_secret_value(),
51
+ ),
52
+ )
53
+
54
+ def download_from_catalog(self, file: Path | CloudPath) -> None:
55
+ assert isinstance(file, S3Path)
56
+
57
+ relative_file_path = file.relative_to(self.get_catalog_location())
58
+
59
+ file_to_download = Path(self.compute_data_folder) / relative_file_path
60
+ file_to_download.parent.mkdir(parents=True, exist_ok=True)
61
+
62
+ file.download_to(file_to_download)
63
+
64
+ def upload_to_catalog(self, file: Path) -> None:
65
+ run_catalog = self.get_catalog_location()
66
+
67
+ relative_file_path = file.relative_to(self.compute_data_folder)
68
+ (run_catalog / relative_file_path.parent).mkdir(parents=True, exist_ok=True)
69
+
70
+ file_in_cloud = run_catalog / file
71
+ assert isinstance(file_in_cloud, S3Path)
72
+ file_in_cloud.upload_from(file)
@@ -0,0 +1,11 @@
1
+ from cloudpathlib import S3Path
2
+
3
+ from extensions.catalog.any_path import AnyPathCatalog
4
+
5
+
6
+ class S3Catalog(AnyPathCatalog):
7
+ service_name: str = "s3"
8
+
9
+ def get_path(self, path: str) -> S3Path:
10
+ # TODO: Might need to assert the credentials are set
11
+ return S3Path(path)
@@ -151,54 +151,25 @@ class GenericPipelineExecutor(BasePipelineExecutor):
151
151
  # Nothing to get/put from the catalog
152
152
  return None
153
153
 
154
- compute_data_folder = self.get_effective_compute_data_folder()
155
-
156
154
  data_catalogs = []
157
155
  for name_pattern in node_catalog_settings.get(stage) or []:
158
156
  if stage == "get":
159
157
  data_catalog = self._context.catalog_handler.get(
160
158
  name=name_pattern,
161
- run_id=self._context.run_id,
162
- compute_data_folder=compute_data_folder,
163
159
  )
164
160
 
165
161
  elif stage == "put":
166
162
  data_catalog = self._context.catalog_handler.put(
167
163
  name=name_pattern,
168
- run_id=self._context.run_id,
169
- compute_data_folder=compute_data_folder,
170
- synced_catalogs=synced_catalogs,
171
164
  )
165
+ else:
166
+ raise Exception(f"Stage {stage} not supported")
172
167
 
173
168
  logger.debug(f"Added data catalog: {data_catalog} to step log")
174
169
  data_catalogs.extend(data_catalog)
175
170
 
176
171
  return data_catalogs
177
172
 
178
- def get_effective_compute_data_folder(self) -> str:
179
- """
180
- Get the effective compute data folder for the given stage.
181
- If there is nothing to catalog, we return None.
182
-
183
- The default is the compute data folder of the catalog but this can be over-ridden by the node.
184
-
185
- Args:
186
- stage (str): The stage we are in the process of cataloging
187
-
188
-
189
- Returns:
190
- str: The compute data folder as defined by the node defaulting to catalog handler
191
- """
192
- assert isinstance(self._context_node, BaseNode)
193
- compute_data_folder = self._context.catalog_handler.compute_data_folder
194
-
195
- catalog_settings = self._context_node._get_catalog_settings()
196
- effective_compute_data_folder = (
197
- catalog_settings.get("compute_data_folder", "") or compute_data_folder
198
- )
199
-
200
- return effective_compute_data_folder
201
-
202
173
  @property
203
174
  def step_attempt_number(self) -> int:
204
175
  """
@@ -219,9 +190,7 @@ class GenericPipelineExecutor(BasePipelineExecutor):
219
190
  )
220
191
  task_console.save_text(log_file_name)
221
192
  # Put the log file in the catalog
222
- self._context.catalog_handler.put(
223
- name=log_file_name, run_id=self._context.run_id
224
- )
193
+ self._context.catalog_handler.put(name=log_file_name)
225
194
  os.remove(log_file_name)
226
195
 
227
196
  def _execute_node(