Coverage for python/lsst/ctrl/bps/drivers.py : 21%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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 time
45import shutil
48from lsst.obs.base import Instrument
50from . import BPS_SEARCH_ORDER, BpsConfig
51from .pre_transform import acquire_quantum_graph, cluster_quanta
52from .transform import transform
53from .prepare import prepare
54from .submit import submit
55from .cancel import cancel
56from .report import report
59_LOG = logging.getLogger(__name__)
62def _init_submission_driver(config_file, **kwargs):
63 """Initialize runtime environment.
65 Parameters
66 ----------
67 config_file : `str`
68 Name of the configuration file.
70 Returns
71 -------
72 config : `lsst.ctrl.bps.BpsConfig`
73 Batch Processing Service configuration.
74 """
75 config = BpsConfig(config_file, BPS_SEARCH_ORDER)
77 # Override config with command-line values
78 # Handle diffs between pipetask argument names vs bps yaml
79 translation = {"input": "inCollection",
80 "output_run": "outCollection",
81 "qgraph": "qgraphFile",
82 "pipeline": "pipelineYaml"}
83 for key, value in kwargs.items():
84 # Don't want to override config with None or empty string values.
85 if value:
86 # pipetask argument parser converts some values to list,
87 # but bps will want string.
88 if not isinstance(value, str):
89 value = ",".join(value)
90 new_key = translation.get(key, re.sub(r"_(\S)", lambda match: match.group(1).upper(), key))
91 config[f".bps_cmdline.{new_key}"] = value
93 # Set some initial values
94 config[".bps_defined.timestamp"] = Instrument.makeCollectionTimestamp()
95 if "operator" not in config:
96 config[".bps_defined.operator"] = getpass.getuser()
98 if "uniqProcName" not in config:
99 config[".bps_defined.uniqProcName"] = config["outCollection"].replace("/", "_")
101 # make submit directory to contain all outputs
102 submit_path = config["submitPath"]
103 os.makedirs(submit_path, exist_ok=True)
104 config[".bps_defined.submitPath"] = submit_path
106 # save copy of configs (orig and expanded config)
107 shutil.copy2(config_file, submit_path)
108 with open(f"{submit_path}/{config['uniqProcName']}_config.yaml", "w") as fh:
109 config.dump(fh)
111 return config
114def acquire_qgraph_driver(config_file, **kwargs):
115 """Read a quantum graph from a file or create one from pipeline definition.
117 Parameters
118 ----------
119 config_file : `str`
120 Name of the configuration file.
122 Returns
123 -------
124 config : `lsst.ctrl.bps.BpsConfig`
125 Updated configuration.
126 qgraph : `lsst.pipe.base.graph.QuantumGraph`
127 A graph representing quanta.
128 """
129 stime = time.time()
130 config = _init_submission_driver(config_file, **kwargs)
131 submit_path = config[".bps_defined.submitPath"]
132 _LOG.info("Acquiring QuantumGraph (it will be created from pipeline definition if needed)")
133 qgraph_file, qgraph, execution_butler_dir = acquire_quantum_graph(config, out_prefix=submit_path)
134 config[".bps_defined.executionButlerDir"] = execution_butler_dir
135 _LOG.info("Run QuantumGraph file %s", qgraph_file)
136 config[".bps_defined.runQgraphFile"] = qgraph_file
137 _LOG.info("Acquiring QuantumGraph took %.2f seconds", time.time() - stime)
139 return config, qgraph
142def cluster_qgraph_driver(config_file, **kwargs):
143 """Group quanta into clusters.
145 Parameters
146 ----------
147 config_file : `str`
148 Name of the configuration file.
150 Returns
151 -------
152 config : `lsst.ctrl.bps.BpsConfig`
153 Updated configuration.
154 clustered_qgraph : `lsst.ctrl.bps.ClusteredQuantumGraph`
155 A graph representing clustered quanta.
156 """
157 stime = time.time()
158 config, qgraph = acquire_qgraph_driver(config_file, **kwargs)
159 _LOG.info("Clustering quanta")
160 clustered_qgraph = cluster_quanta(config, qgraph, config["uniqProcName"])
161 _LOG.info("Clustering quanta took %.2f seconds", time.time() - stime)
163 submit_path = config[".bps_defined.submitPath"]
164 _, save_clustered_qgraph = config.search("saveClusteredQgraph", opt={"default": False})
165 if save_clustered_qgraph:
166 clustered_qgraph.save(os.path.join(submit_path, "bps_clustered_qgraph.pickle"))
167 _, save_dot = config.search("saveDot", opt={"default": False})
168 if save_dot:
169 clustered_qgraph.draw(os.path.join(submit_path, "bps_clustered_qgraph.dot"))
170 return config, clustered_qgraph
173def transform_driver(config_file, **kwargs):
174 """Create a workflow for a specific workflow management system.
176 Parameters
177 ----------
178 config_file : `str`
179 Name of the configuration file.
181 Returns
182 -------
183 generic_workflow_config : `lsst.ctrl.bps.BpsConfig`
184 Configuration to use when creating the workflow.
185 generic_workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
186 Representation of the abstract/scientific workflow specific to a given
187 workflow management system.
188 """
189 stime = time.time()
190 config, clustered_qgraph = cluster_qgraph_driver(config_file, **kwargs)
191 submit_path = config[".bps_defined.submitPath"]
192 _LOG.info("Creating Generic Workflow")
193 generic_workflow, generic_workflow_config = transform(config, clustered_qgraph, submit_path)
194 _LOG.info("Creating Generic Workflow took %.2f seconds", time.time() - stime)
195 _LOG.info("Generic Workflow name %s", generic_workflow.name)
197 _, save_workflow = config.search("saveGenericWorkflow", opt={"default": False})
198 if save_workflow:
199 with open(os.path.join(submit_path, "bps_generic_workflow.pickle"), "wb") as outfh:
200 generic_workflow.save(outfh, "pickle")
201 _, save_dot = config.search("saveDot", opt={"default": False})
202 if save_dot:
203 with open(os.path.join(submit_path, "bps_generic_workflow.dot"), "w") as outfh:
204 generic_workflow.draw(outfh, "dot")
205 return generic_workflow_config, generic_workflow
208def prepare_driver(config_file, **kwargs):
209 """Create a representation of the generic workflow.
211 Parameters
212 ----------
213 config_file : `str`
214 Name of the configuration file.
216 Returns
217 -------
218 wms_config : `lsst.ctrl.bps.BpsConfig`
219 Configuration to use when creating the workflow.
220 workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
221 Representation of the abstract/scientific workflow specific to a given
222 workflow management system.
223 """
224 stime = time.time()
225 generic_workflow_config, generic_workflow = transform_driver(config_file, **kwargs)
226 submit_path = generic_workflow_config[".bps_defined.submitPath"]
227 _LOG.info("Creating specific implementation of workflow")
228 wms_workflow = prepare(generic_workflow_config, generic_workflow, submit_path)
229 wms_workflow_config = generic_workflow_config
230 _LOG.info("Creating specific implementation of workflow took %.2f seconds", time.time() - stime)
231 print(f"Submit dir: {wms_workflow.submit_path}")
232 return wms_workflow_config, wms_workflow
235def submit_driver(config_file, **kwargs):
236 """Submit workflow for execution.
238 Parameters
239 ----------
240 config_file : `str`
241 Name of the configuration file.
242 """
243 wms_workflow_config, wms_workflow = prepare_driver(config_file, **kwargs)
244 submit(wms_workflow_config, wms_workflow)
245 print(f"Run Id: {wms_workflow.run_id}")
248def report_driver(wms_service, run_id, user, hist_days, pass_thru):
249 """Print out summary of jobs submitted for execution.
251 Parameters
252 ----------
253 wms_service : `str`
254 Name of the class.
255 run_id : `str`
256 A run id the report will be restricted to.
257 user : `str`
258 A user name the report will be restricted to.
259 hist_days : int
260 Number of days
261 pass_thru : `str`
262 A string to pass directly to the WMS service class.
263 """
264 report(wms_service, run_id, user, hist_days, pass_thru)
267def cancel_driver(wms_service, run_id, user, require_bps, pass_thru):
268 """Cancel submitted workflows.
270 Parameters
271 ----------
272 wms_service : `str`
273 Name of the Workload Management System service class.
274 run_id : `str`
275 ID or path of job that should be canceled.
276 user : `str`
277 User whose submitted jobs should be canceled.
278 require_bps : `bool`
279 Whether to require given run_id/user to be a bps submitted job.
280 pass_thru : `str`
281 Information to pass through to WMS.
282 """
283 cancel(wms_service, run_id, user, require_bps, pass_thru)