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 shutil
47from lsst.daf.butler.core.utils import time_this
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 config = _init_submission_driver(config_file, **kwargs)
130 submit_path = config[".bps_defined.submitPath"]
132 _LOG.info("Starting acquire stage (generating and/or reading quantum graph)")
133 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Acquire stage completed"):
134 qgraph_file, qgraph, execution_butler_dir = acquire_quantum_graph(config, out_prefix=submit_path)
136 config[".bps_defined.executionButlerDir"] = execution_butler_dir
137 config[".bps_defined.runQgraphFile"] = qgraph_file
138 return config, qgraph
141def cluster_qgraph_driver(config_file, **kwargs):
142 """Group quanta into clusters.
144 Parameters
145 ----------
146 config_file : `str`
147 Name of the configuration file.
149 Returns
150 -------
151 config : `lsst.ctrl.bps.BpsConfig`
152 Updated configuration.
153 clustered_qgraph : `lsst.ctrl.bps.ClusteredQuantumGraph`
154 A graph representing clustered quanta.
155 """
156 config, qgraph = acquire_qgraph_driver(config_file, **kwargs)
158 _LOG.info("Starting cluster stage (grouping quanta into jobs)")
159 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Cluster stage completed"):
160 clustered_qgraph = cluster_quanta(config, qgraph, config["uniqProcName"])
162 submit_path = config[".bps_defined.submitPath"]
163 _, save_clustered_qgraph = config.search("saveClusteredQgraph", opt={"default": False})
164 if save_clustered_qgraph:
165 clustered_qgraph.save(os.path.join(submit_path, "bps_clustered_qgraph.pickle"))
166 _, save_dot = config.search("saveDot", opt={"default": False})
167 if save_dot:
168 clustered_qgraph.draw(os.path.join(submit_path, "bps_clustered_qgraph.dot"))
169 return config, clustered_qgraph
172def transform_driver(config_file, **kwargs):
173 """Create a workflow for a specific workflow management system.
175 Parameters
176 ----------
177 config_file : `str`
178 Name of the configuration file.
180 Returns
181 -------
182 generic_workflow_config : `lsst.ctrl.bps.BpsConfig`
183 Configuration to use when creating the workflow.
184 generic_workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
185 Representation of the abstract/scientific workflow specific to a given
186 workflow management system.
187 """
188 config, clustered_qgraph = cluster_qgraph_driver(config_file, **kwargs)
189 submit_path = config[".bps_defined.submitPath"]
191 _LOG.info("Starting transform stage (creating generic workflow)")
192 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Transform stage completed"):
193 generic_workflow, generic_workflow_config = transform(config, clustered_qgraph, submit_path)
194 _LOG.info("Generic workflow name '%s'", generic_workflow.name)
196 _, save_workflow = config.search("saveGenericWorkflow", opt={"default": False})
197 if save_workflow:
198 with open(os.path.join(submit_path, "bps_generic_workflow.pickle"), "wb") as outfh:
199 generic_workflow.save(outfh, "pickle")
200 _, save_dot = config.search("saveDot", opt={"default": False})
201 if save_dot:
202 with open(os.path.join(submit_path, "bps_generic_workflow.dot"), "w") as outfh:
203 generic_workflow.draw(outfh, "dot")
204 return generic_workflow_config, generic_workflow
207def prepare_driver(config_file, **kwargs):
208 """Create a representation of the generic workflow.
210 Parameters
211 ----------
212 config_file : `str`
213 Name of the configuration file.
215 Returns
216 -------
217 wms_config : `lsst.ctrl.bps.BpsConfig`
218 Configuration to use when creating the workflow.
219 workflow : `lsst.ctrl.bps.BaseWmsWorkflow`
220 Representation of the abstract/scientific workflow specific to a given
221 workflow management system.
222 """
223 generic_workflow_config, generic_workflow = transform_driver(config_file, **kwargs)
224 submit_path = generic_workflow_config[".bps_defined.submitPath"]
226 _LOG.info("Starting prepare stage (creating specific implementation of workflow)")
227 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Prepare stage completed"):
228 wms_workflow = prepare(generic_workflow_config, generic_workflow, submit_path)
230 wms_workflow_config = generic_workflow_config
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 _LOG.info("Starting submission process")
244 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Completed entire submission process"):
245 wms_workflow_config, wms_workflow = prepare_driver(config_file, **kwargs)
247 _LOG.info("Starting submit stage")
248 with time_this(log=_LOG, level=logging.INFO, prefix=None, msg="Completed submit stage"):
249 submit(wms_workflow_config, wms_workflow)
250 _LOG.info("Run '%s' submitted for execution with id '%s'", wms_workflow.name, wms_workflow.run_id)
252 print(f"Run Id: {wms_workflow.run_id}")
255def report_driver(wms_service, run_id, user, hist_days, pass_thru):
256 """Print out summary of jobs submitted for execution.
258 Parameters
259 ----------
260 wms_service : `str`
261 Name of the class.
262 run_id : `str`
263 A run id the report will be restricted to.
264 user : `str`
265 A user name the report will be restricted to.
266 hist_days : int
267 Number of days
268 pass_thru : `str`
269 A string to pass directly to the WMS service class.
270 """
271 report(wms_service, run_id, user, hist_days, pass_thru)
274def cancel_driver(wms_service, run_id, user, require_bps, pass_thru):
275 """Cancel submitted workflows.
277 Parameters
278 ----------
279 wms_service : `str`
280 Name of the Workload Management System service class.
281 run_id : `str`
282 ID or path of job that should be canceled.
283 user : `str`
284 User whose submitted jobs should be canceled.
285 require_bps : `bool`
286 Whether to require given run_id/user to be a bps submitted job.
287 pass_thru : `str`
288 Information to pass through to WMS.
289 """
290 cancel(wms_service, run_id, user, require_bps, pass_thru)