Coverage for python/lsst/ctrl/bps/drivers.py: 18%
119 statements
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-12 03:01 -0700
« prev ^ index » next coverage.py v7.2.1, created at 2023-03-12 03:01 -0700
1# This file is part of ctrl_bps.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22"""Driver functions for each subcommand.
24Driver functions ensure that ensure all setup work is done before running
25the subcommand method.
26"""
29__all__ = [
30 "acquire_qgraph_driver",
31 "cluster_qgraph_driver",
32 "transform_driver",
33 "prepare_driver",
34 "submit_driver",
35 "report_driver",
36 "cancel_driver",
37]
40import getpass
41import logging
42import os
43import re
44import shutil
45from collections import Iterable
48from lsst.daf.butler.core.utils import time_this
49from lsst.obs.base import Instrument
50from lsst.utils import doImport
52from . import BPS_SEARCH_ORDER, BpsConfig
53from .pre_transform import acquire_quantum_graph, cluster_quanta
54from .transform import transform
55from .prepare import prepare
56from .submit import submit
57from .cancel import cancel
58from .report import report
60_LOG = logging.getLogger(__name__)
63def _init_submission_driver(config_file, **kwargs):
64 """Initialize runtime environment.
66 Parameters
67 ----------
68 config_file : `str`
69 Name of the configuration file.
71 Returns
72 -------
73 config : `lsst.ctrl.bps.BpsConfig`
74 Batch Processing Service configuration.
75 """
76 config = BpsConfig(config_file, BPS_SEARCH_ORDER)
78 # Override config with command-line values
79 # Handle diffs between pipetask argument names vs bps yaml
80 translation = {"input": "inCollection",
81 "output_run": "outputRun",
82 "qgraph": "qgraphFile",
83 "pipeline": "pipelineYaml"}
84 for key, value in kwargs.items():
85 # Don't want to override config with None or empty string values.
86 if value:
87 # pipetask argument parser converts some values to list,
88 # but bps will want string.
89 if not isinstance(value, str) and isinstance(value, Iterable):
90 value = ",".join(value)
91 new_key = translation.get(key, re.sub(r"_(\S)", lambda match: match.group(1).upper(), key))
92 config[f".bps_cmdline.{new_key}"] = value
94 # Set some initial values
95 config[".bps_defined.timestamp"] = Instrument.makeCollectionTimestamp()
96 if "operator" not in config:
97 config[".bps_defined.operator"] = getpass.getuser()
99 if "outCollection" in config:
100 raise KeyError("outCollection is deprecated. Replace all outCollection references with outputRun.")
102 if "outputRun" not in config:
103 raise KeyError("Must specify the output run collection using outputRun")
105 if "uniqProcName" not in config:
106 config[".bps_defined.uniqProcName"] = config["outputRun"].replace("/", "_")
108 if "submitPath" not in config:
109 raise KeyError("Must specify the submit-side run directory using submitPath")
111 # If requested, run WMS plugin checks early in submission process to
112 # ensure WMS has what it will need for prepare() or submit().
114 if kwargs.get("runWmsSubmissionChecks", False):
115 found, wms_class = config.search("wmsServiceClass")
116 if not found:
117 raise KeyError("Missing wmsServiceClass in bps config. Aborting.")
119 # Check that can import wms service class.
120 wms_service_class = doImport(wms_class)
121 wms_service = wms_service_class(config)
123 try:
124 wms_service.run_submission_checks()
125 except NotImplementedError:
126 # Allow various plugins to implement only when needed to do extra
127 # checks.
128 _LOG.debug("run_submission_checks is not implemented in %s.", wms_class)
129 else:
130 _LOG.debug("Skipping submission checks.")
132 # make submit directory to contain all outputs
133 submit_path = config["submitPath"]
134 os.makedirs(submit_path, exist_ok=True)
135 config[".bps_defined.submitPath"] = submit_path
136 print(f"Submit dir: {submit_path}")
138 # save copy of configs (orig and expanded config)
139 shutil.copy2(config_file, submit_path)
140 with open(f"{submit_path}/{config['uniqProcName']}_config.yaml", "w") as fh:
141 config.dump(fh)
143 return config
146def acquire_qgraph_driver(config_file, **kwargs):
147 """Read a quantum graph from a file or create one from pipeline definition.
149 Parameters
150 ----------
151 config_file : `str`
152 Name of the configuration file.
154 Returns
155 -------
156 config : `lsst.ctrl.bps.BpsConfig`
157 Updated configuration.
158 qgraph : `lsst.pipe.base.graph.QuantumGraph`
159 A graph representing quanta.
160 """
161 config = _init_submission_driver(config_file, **kwargs)
162 submit_path = config[".bps_defined.submitPath"]
164 _LOG.info("Starting acquire stage (generating and/or reading quantum graph)")
165 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Acquire stage completed"):
166 qgraph_file, qgraph, execution_butler_dir = acquire_quantum_graph(config, out_prefix=submit_path)
168 config[".bps_defined.executionButlerDir"] = execution_butler_dir
169 config[".bps_defined.runQgraphFile"] = qgraph_file
170 return config, qgraph
173def cluster_qgraph_driver(config_file, **kwargs):
174 """Group quanta into clusters.
176 Parameters
177 ----------
178 config_file : `str`
179 Name of the configuration file.
181 Returns
182 -------
183 config : `lsst.ctrl.bps.BpsConfig`
184 Updated configuration.
185 clustered_qgraph : `lsst.ctrl.bps.ClusteredQuantumGraph`
186 A graph representing clustered quanta.
187 """
188 config, qgraph = acquire_qgraph_driver(config_file, **kwargs)
190 _LOG.info("Starting cluster stage (grouping quanta into jobs)")
191 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Cluster stage completed"):
192 clustered_qgraph = cluster_quanta(config, qgraph, config["uniqProcName"])
194 submit_path = config[".bps_defined.submitPath"]
195 _, save_clustered_qgraph = config.search("saveClusteredQgraph", opt={"default": False})
196 if save_clustered_qgraph:
197 clustered_qgraph.save(os.path.join(submit_path, "bps_clustered_qgraph.pickle"))
198 _, save_dot = config.search("saveDot", opt={"default": False})
199 if save_dot:
200 clustered_qgraph.draw(os.path.join(submit_path, "bps_clustered_qgraph.dot"))
201 return config, clustered_qgraph
204def transform_driver(config_file, **kwargs):
205 """Create a workflow for a specific workflow management system.
207 Parameters
208 ----------
209 config_file : `str`
210 Name of the configuration file.
212 Returns
213 -------
214 generic_workflow_config : `lsst.ctrl.bps.BpsConfig`
215 Configuration to use when creating the workflow.
216 generic_workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
217 Representation of the abstract/scientific workflow specific to a given
218 workflow management system.
219 """
220 config, clustered_qgraph = cluster_qgraph_driver(config_file, **kwargs)
221 submit_path = config[".bps_defined.submitPath"]
223 _LOG.info("Starting transform stage (creating generic workflow)")
224 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Transform stage completed"):
225 generic_workflow, generic_workflow_config = transform(config, clustered_qgraph, submit_path)
226 _LOG.info("Generic workflow name '%s'", generic_workflow.name)
228 _, save_workflow = config.search("saveGenericWorkflow", opt={"default": False})
229 if save_workflow:
230 with open(os.path.join(submit_path, "bps_generic_workflow.pickle"), "wb") as outfh:
231 generic_workflow.save(outfh, "pickle")
232 _, save_dot = config.search("saveDot", opt={"default": False})
233 if save_dot:
234 with open(os.path.join(submit_path, "bps_generic_workflow.dot"), "w") as outfh:
235 generic_workflow.draw(outfh, "dot")
236 return generic_workflow_config, generic_workflow
239def prepare_driver(config_file, **kwargs):
240 """Create a representation of the generic workflow.
242 Parameters
243 ----------
244 config_file : `str`
245 Name of the configuration file.
247 Returns
248 -------
249 wms_config : `lsst.ctrl.bps.BpsConfig`
250 Configuration to use when creating the workflow.
251 workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
252 Representation of the abstract/scientific workflow specific to a given
253 workflow management system.
254 """
255 kwargs.setdefault("runWmsSubmissionChecks", True)
256 generic_workflow_config, generic_workflow = transform_driver(config_file, **kwargs)
257 submit_path = generic_workflow_config[".bps_defined.submitPath"]
259 _LOG.info("Starting prepare stage (creating specific implementation of workflow)")
260 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Prepare stage completed"):
261 wms_workflow = prepare(generic_workflow_config, generic_workflow, submit_path)
263 wms_workflow_config = generic_workflow_config
264 return wms_workflow_config, wms_workflow
267def submit_driver(config_file, **kwargs):
268 """Submit workflow for execution.
270 Parameters
271 ----------
272 config_file : `str`
273 Name of the configuration file.
274 """
275 kwargs.setdefault("runWmsSubmissionChecks", True)
277 _LOG.info("Starting submission process")
278 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Completed entire submission process"):
279 wms_workflow_config, wms_workflow = prepare_driver(config_file, **kwargs)
281 _LOG.info("Starting submit stage")
282 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Completed submit stage"):
283 submit(wms_workflow_config, wms_workflow)
284 _LOG.info("Run '%s' submitted for execution with id '%s'", wms_workflow.name, wms_workflow.run_id)
286 print(f"Run Id: {wms_workflow.run_id}")
289def report_driver(wms_service, run_id, user, hist_days, pass_thru):
290 """Print out summary of jobs submitted for execution.
292 Parameters
293 ----------
294 wms_service : `str`
295 Name of the class.
296 run_id : `str`
297 A run id the report will be restricted to.
298 user : `str`
299 A user name the report will be restricted to.
300 hist_days : int
301 Number of days
302 pass_thru : `str`
303 A string to pass directly to the WMS service class.
304 """
305 report(wms_service, run_id, user, hist_days, pass_thru)
308def cancel_driver(wms_service, run_id, user, require_bps, pass_thru):
309 """Cancel submitted workflows.
311 Parameters
312 ----------
313 wms_service : `str`
314 Name of the Workload Management System service class.
315 run_id : `str`
316 ID or path of job that should be canceled.
317 user : `str`
318 User whose submitted jobs should be canceled.
319 require_bps : `bool`
320 Whether to require given run_id/user to be a bps submitted job.
321 pass_thru : `str`
322 Information to pass through to WMS.
323 """
324 cancel(wms_service, run_id, user, require_bps, pass_thru)