Debian Codegraph @

jupyter_cache/executors/basic.py

raw
1 import logging
2 import multiprocessing as mproc
3 import os
4 from pathlib import Path
5 import tempfile
6 from typing import NamedTuple, Tuple
7
8 from jupyter_cache.base import JupyterCacheAbstract, ProjectNb
9 from jupyter_cache.cache.db import NbProjectRecord
10 from jupyter_cache.executors.base import ExecutorRunResult, JupyterExecutorAbstract
11 from jupyter_cache.executors.utils import (
12 ExecutionResult,
13 copy_assets,
14 create_cache_bundle,
15 single_nb_execution,
16 )
17
18 REPORT_LEVEL = logging.INFO + 1
19 logging.addLevelName(REPORT_LEVEL, "REPORT")
20
21
22 class ProcessData(NamedTuple):
23 """Data for the process worker."""
24
25 pk: int
26 uri: str
27 cache: JupyterCacheAbstract
28 timeout: int
29 allow_errors: bool
30
31
32 class ExecutionWorkerBase:
33 """Base execution worker.
34
35 Note this must be pickleable.
36 """
37
38 @property
39 def logger(self) -> logging.Logger:
40 raise NotImplementedError
41
42 def log_info(self, msg: str):
43 self.logger.info(msg)
44
45 def execute(self, project_nb: ProjectNb, data: ProcessData) -> ExecutionResult:
46 raise NotImplementedError
47
48 def __call__(self, data: ProcessData) -> Tuple[int, str]:
49 try:
50 project_nb = data.cache.get_project_notebook(data.pk)
51 except Exception:
52 self.logger.error(
53 "Failed Retrieving: %s" % data.uri,
54 exc_info=True,
55 )
56 return (2, data.uri)
57
58 try:
59 self.log_info("Executing: %s" % project_nb.uri)
60 result = self.execute(project_nb, data)
61 except Exception:
62 self.logger.error(
63 "Failed Executing: %s" % data.uri,
64 exc_info=True,
65 )
66 return (2, data.uri)
67
68 if result.err:
69 self.logger.warning(
70 "Execution Excepted: %s\n%s: %s"
71 % (project_nb.uri, type(result.err).__name__, str(result.err))
72 )
73 NbProjectRecord.set_traceback(
74 project_nb.uri, result.exc_string, data.cache.db
75 )
76 return (1, data.uri)
77
78 self.log_info("Execution Successful: %s" % project_nb.uri)
79 try:
80 # TODO deal with artifact retrieval
81 bundle = create_cache_bundle(
82 project_nb, result.cwd, None, result.time, result.exc_string
83 )
84 data.cache.cache_notebook_bundle(
85 bundle, check_validity=False, overwrite=True
86 )
87 except Exception:
88 self.logger.error(
89 "Failed Caching: %s" % data.uri,
90 exc_info=True,
91 )
92 return (2, data.uri)
93
94 return (0, data.uri)
95
96
97 class ExecutionWorkerLocalSerial(ExecutionWorkerBase):
98 """Execution worker, that executes in local folder."""
99
100 def __init__(self, logger: logging.Logger) -> None:
101 super().__init__()
102 self._logger = logger
103
104 @property
105 def logger(self) -> logging.Logger:
106 return self._logger
107
108 @staticmethod
109 def execute(project_nb: ProjectNb, data: ProcessData) -> ExecutionResult:
110 cwd = str(Path(project_nb.uri).parent)
111 return single_nb_execution(
112 project_nb.nb,
113 cwd=cwd,
114 timeout=data.timeout,
115 allow_errors=data.allow_errors,
116 )
117
118
119 class ExecutionWorkerTempSerial(ExecutionWorkerBase):
120 """Execution worker, that executes in temporary folder."""
121
122 def __init__(self, logger: logging.Logger) -> None:
123 super().__init__()
124 self._logger = logger
125
126 @property
127 def logger(self) -> logging.Logger:
128 return self._logger
129
130 @staticmethod
131 def execute(project_nb: ProjectNb, data: ProcessData) -> ExecutionResult:
132 with tempfile.TemporaryDirectory() as cwd:
133 copy_assets(project_nb.uri, project_nb.assets, cwd)
134 return single_nb_execution(
135 project_nb.nb,
136 cwd=cwd,
137 timeout=data.timeout,
138 allow_errors=data.allow_errors,
139 )
140
141
142 class ExecutionWorkerLocalMProc(ExecutionWorkerBase):
143 """Execution worker, that executes in local folder."""
144
145 @property
146 def logger(self) -> logging.Logger:
147 return mproc.get_logger()
148
149 def log_info(self, msg: str):
150 # multiprocessing logs a lot at info level that we do not want to see
151 self.logger.log(REPORT_LEVEL, msg)
152
153 @staticmethod
154 def execute(project_nb: ProjectNb, data: ProcessData) -> ExecutionResult:
155 cwd = str(Path(project_nb.uri).parent)
156 return single_nb_execution(
157 project_nb.nb,
158 cwd=cwd,
159 timeout=data.timeout,
160 allow_errors=data.allow_errors,
161 )
162
163
164 class ExecutionWorkerTempMProc(ExecutionWorkerBase):
165 """Execution worker, that executes in temporary folder."""
166
167 @property
168 def logger(self) -> logging.Logger:
169 return mproc.get_logger()
170
171 def log_info(self, msg: str):
172 # multiprocessing logs a lot at info level that we do not want to see
173 self.logger.log(REPORT_LEVEL, msg)
174
175 @staticmethod
176 def execute(project_nb: ProjectNb, data: ProcessData) -> ExecutionResult:
177 with tempfile.TemporaryDirectory() as cwd:
178 copy_assets(project_nb.uri, project_nb.assets, cwd)
179 return single_nb_execution(
180 project_nb.nb,
181 cwd=cwd,
182 timeout=data.timeout,
183 allow_errors=data.allow_errors,
184 )
185
186
187 class JupyterExecutorLocalSerial(JupyterExecutorAbstract):
188 """An implementation of an executor; executing locally in serial."""
189
190 _EXECUTION_WORKER = ExecutionWorkerLocalSerial
191
192 def run_and_cache(
193 self,
194 *,
195 filter_uris=None,
196 filter_pks=None,
197 timeout=30,
198 allow_errors=False,
199 force=False,
200 ) -> ExecutorRunResult:
201 # Get the notebook that require re-execution
202 execute_records = self.get_records(
203 filter_uris, filter_pks, clear_tracebacks=True, force=force
204 )
205
206 self.logger.info("Executing %s notebook(s) in serial" % len(execute_records))
207
208 results = [
209 self._EXECUTION_WORKER(self.logger)(
210 ProcessData(record.pk, record.uri, self.cache, timeout, allow_errors)
211 )
212 for record in execute_records
213 ]
214
215 return ExecutorRunResult(
216 succeeded=[p for i, p in results if i == 0],
217 excepted=[p for i, p in results if i == 1],
218 errored=[p for i, p in results if i == 2],
219 )
220
221
222 class JupyterExecutorTempSerial(JupyterExecutorLocalSerial):
223 """An implementation of an executor; executing in a temporary folder in serial."""
224
225 _EXECUTION_WORKER = ExecutionWorkerTempSerial
226
227
228 class JupyterExecutorLocalMproc(JupyterExecutorAbstract):
229 """An implementation of an executor; executing locally in parallel."""
230
231 _EXECUTION_WORKER = ExecutionWorkerLocalMProc
232
233 def run_and_cache(
234 self,
235 *,
236 filter_uris=None,
237 filter_pks=None,
238 timeout=30,
239 allow_errors=False,
240 force=False,
241 ) -> ExecutorRunResult:
242 # Get the notebook that require re-execution
243 execute_records = self.get_records(
244 filter_uris, filter_pks, clear_tracebacks=True
245 )
246
247 self.logger.info(
248 "Executing %s notebook(s) over pool of %s processors"
249 % (len(execute_records), os.cpu_count())
250 )
251 mproc.log_to_stderr(
252 REPORT_LEVEL if self.logger.level == logging.INFO else self.logger.level
253 )
254
255 with mproc.Pool() as pool:
256 results = pool.map(
257 self._EXECUTION_WORKER(),
258 [
259 ProcessData(
260 record.pk, record.uri, self.cache, timeout, allow_errors
261 )
262 for record in execute_records
263 ],
264 )
265 return ExecutorRunResult(
266 succeeded=[p for i, p in results if i == 0],
267 excepted=[p for i, p in results if i == 1],
268 errored=[p for i, p in results if i == 2],
269 )
270
271
272 class JupyterExecutorTempMproc(JupyterExecutorLocalMproc):
273 """An implementation of an executor; executing in a temporary directory and in parallel."""
274
275 _EXECUTION_WORKER = ExecutionWorkerTempMProc