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

Shortcuts 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

119 statements  

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/>. 

21 

22"""Driver functions for each subcommand. 

23 

24Driver functions ensure that ensure all setup work is done before running 

25the subcommand method. 

26""" 

27 

28 

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] 

38 

39 

40import getpass 

41import logging 

42import os 

43import re 

44import shutil 

45from collections import Iterable 

46 

47 

48from lsst.daf.butler.core.utils import time_this 

49from lsst.obs.base import Instrument 

50from lsst.utils import doImport 

51 

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 

59 

60_LOG = logging.getLogger(__name__) 

61 

62 

63def _init_submission_driver(config_file, **kwargs): 

64 """Initialize runtime environment. 

65 

66 Parameters 

67 ---------- 

68 config_file : `str` 

69 Name of the configuration file. 

70 

71 Returns 

72 ------- 

73 config : `lsst.ctrl.bps.BpsConfig` 

74 Batch Processing Service configuration. 

75 """ 

76 config = BpsConfig(config_file, BPS_SEARCH_ORDER) 

77 

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 

93 

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() 

98 

99 if "outCollection" in config: 

100 raise KeyError("outCollection is deprecated. Replace all outCollection references with outputRun.") 

101 

102 if "outputRun" not in config: 

103 raise KeyError("Must specify the output run collection using outputRun") 

104 

105 if "uniqProcName" not in config: 

106 config[".bps_defined.uniqProcName"] = config["outputRun"].replace("/", "_") 

107 

108 if "submitPath" not in config: 

109 raise KeyError("Must specify the submit-side run directory using submitPath") 

110 

111 # If requested, run WMS plugin checks early in submission process to 

112 # ensure WMS has what it will need for prepare() or submit(). 

113 

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.") 

118 

119 # Check that can import wms service class. 

120 wms_service_class = doImport(wms_class) 

121 wms_service = wms_service_class(config) 

122 

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.") 

131 

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}") 

137 

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) 

142 

143 return config 

144 

145 

146def acquire_qgraph_driver(config_file, **kwargs): 

147 """Read a quantum graph from a file or create one from pipeline definition. 

148 

149 Parameters 

150 ---------- 

151 config_file : `str` 

152 Name of the configuration file. 

153 

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"] 

163 

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) 

167 

168 config[".bps_defined.executionButlerDir"] = execution_butler_dir 

169 config[".bps_defined.runQgraphFile"] = qgraph_file 

170 return config, qgraph 

171 

172 

173def cluster_qgraph_driver(config_file, **kwargs): 

174 """Group quanta into clusters. 

175 

176 Parameters 

177 ---------- 

178 config_file : `str` 

179 Name of the configuration file. 

180 

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) 

189 

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"]) 

193 

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 

202 

203 

204def transform_driver(config_file, **kwargs): 

205 """Create a workflow for a specific workflow management system. 

206 

207 Parameters 

208 ---------- 

209 config_file : `str` 

210 Name of the configuration file. 

211 

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"] 

222 

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) 

227 

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 

237 

238 

239def prepare_driver(config_file, **kwargs): 

240 """Create a representation of the generic workflow. 

241 

242 Parameters 

243 ---------- 

244 config_file : `str` 

245 Name of the configuration file. 

246 

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"] 

258 

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) 

262 

263 wms_workflow_config = generic_workflow_config 

264 return wms_workflow_config, wms_workflow 

265 

266 

267def submit_driver(config_file, **kwargs): 

268 """Submit workflow for execution. 

269 

270 Parameters 

271 ---------- 

272 config_file : `str` 

273 Name of the configuration file. 

274 """ 

275 kwargs.setdefault("runWmsSubmissionChecks", True) 

276 

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) 

280 

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) 

285 

286 print(f"Run Id: {wms_workflow.run_id}") 

287 

288 

289def report_driver(wms_service, run_id, user, hist_days, pass_thru): 

290 """Print out summary of jobs submitted for execution. 

291 

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) 

306 

307 

308def cancel_driver(wms_service, run_id, user, require_bps, pass_thru): 

309 """Cancel submitted workflows. 

310 

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)