Hide keyboard shortcuts

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 <https://www.gnu.org/licenses/>. 

21 

22"""Interface between generic workflow to HTCondor workflow system. 

23""" 

24 

25__all__ = ["HTCondorService", "HTCondorWorkflow"] 

26 

27 

28import dataclasses 

29import os 

30import re 

31import logging 

32from datetime import datetime, timedelta 

33from pathlib import Path 

34 

35import htcondor 

36 

37from ... import ( 

38 BaseWmsWorkflow, 

39 BaseWmsService, 

40 GenericWorkflow, 

41 GenericWorkflowJob, 

42 WmsRunReport, 

43 WmsJobReport, 

44 WmsStates 

45) 

46from ...bps_utils import chdir 

47from .lssthtc import ( 

48 HTCDag, 

49 HTCJob, 

50 MISSING_ID, 

51 JobStatus, 

52 NodeStatus, 

53 htc_check_dagman_output, 

54 htc_escape, 

55 htc_submit_dag, 

56 read_dag_log, 

57 read_dag_status, 

58 read_node_status, 

59 condor_history, 

60 condor_q, 

61 condor_status, 

62 pegasus_name_to_label, 

63 summary_from_dag, 

64) 

65 

66 

67DEFAULT_HTC_EXEC_PATT = ".*worker.*" 

68"""Default pattern for searching execute machines in an HTCondor pool. 

69""" 

70 

71_LOG = logging.getLogger(__name__) 

72 

73 

74class HTCondorService(BaseWmsService): 

75 """HTCondor version of WMS service. 

76 """ 

77 def prepare(self, config, generic_workflow, out_prefix=None): 

78 """Convert generic workflow to an HTCondor DAG ready for submission. 

79 

80 Parameters 

81 ---------- 

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

83 BPS configuration that includes necessary submit/runtime 

84 information. 

85 generic_workflow : `lsst.ctrl.bps.GenericWorkflow` 

86 The generic workflow (e.g., has executable name and arguments). 

87 out_prefix : `str` 

88 The root directory into which all WMS-specific files are written. 

89 

90 Returns 

91 ---------- 

92 workflow : `lsst.ctrl.bps.wms.htcondor.HTCondorWorkflow` 

93 HTCondor workflow ready to be run. 

94 """ 

95 _LOG.debug("out_prefix = '%s'", out_prefix) 

96 workflow = HTCondorWorkflow.from_generic_workflow(config, generic_workflow, out_prefix, 

97 f"{self.__class__.__module__}." 

98 f"{self.__class__.__name__}") 

99 workflow.write(out_prefix) 

100 return workflow 

101 

102 def submit(self, workflow): 

103 """Submit a single HTCondor workflow. 

104 

105 Parameters 

106 ---------- 

107 workflow : `lsst.ctrl.bps.BaseWorkflow` 

108 A single HTCondor workflow to submit. run_id is updated after 

109 successful submission to WMS. 

110 """ 

111 # For workflow portability, internal paths are all relative. Hence 

112 # the DAG needs to be submitted to HTCondor from inside the submit 

113 # directory. 

114 with chdir(workflow.submit_path): 

115 _LOG.info("Submitting from directory: %s", os.getcwd()) 

116 htc_submit_dag(workflow.dag, dict()) 

117 workflow.run_id = workflow.dag.run_id 

118 

119 def list_submitted_jobs(self, wms_id=None, user=None, require_bps=True, pass_thru=None): 

120 """Query WMS for list of submitted WMS workflows/jobs. 

121 

122 This should be a quick lookup function to create list of jobs for 

123 other functions. 

124 

125 Parameters 

126 ---------- 

127 wms_id : `int` or `str`, optional 

128 Id or path that can be used by WMS service to look up job. 

129 user : `str`, optional 

130 User whose submitted jobs should be listed. 

131 require_bps : `bool`, optional 

132 Whether to require jobs returned in list to be bps-submitted jobs. 

133 pass_thru : `str`, optional 

134 Information to pass through to WMS. 

135 

136 Returns 

137 ------- 

138 job_ids : `list` [`Any`] 

139 Only job ids to be used by cancel and other functions. Typically 

140 this means top-level jobs (i.e., not children jobs). 

141 """ 

142 _LOG.debug("list_submitted_jobs params: wms_id=%s, user=%s, require_bps=%s, pass_thru=%s", 

143 wms_id, user, require_bps, pass_thru) 

144 constraint = "" 

145 

146 if wms_id is None: 

147 if user is not None: 

148 constraint = f'(Owner == "{user}")' 

149 else: 

150 cluster_id = _wms_id_to_cluster(wms_id) 

151 if cluster_id != 0: 

152 constraint = f"(DAGManJobId == {cluster_id} || ClusterId == {cluster_id})" 

153 

154 if require_bps: 

155 constraint += ' && (bps_isjob == "True")' 

156 

157 if pass_thru: 

158 if "-forcex" in pass_thru: 

159 pass_thru_2 = pass_thru.replace("-forcex", "") 

160 if pass_thru_2 and not pass_thru_2.isspace(): 

161 constraint += f"&& ({pass_thru_2})" 

162 else: 

163 constraint += f" && ({pass_thru})" 

164 

165 _LOG.debug("constraint = %s", constraint) 

166 jobs = condor_q(constraint) 

167 

168 # Prune child jobs where DAG job is in queue (i.e., aren't orphans). 

169 job_ids = [] 

170 for job_id, job_info in jobs.items(): 

171 _LOG.debug("job_id=%s DAGManJobId=%s", job_id, job_info.get("DAGManJobId", "None")) 

172 if "DAGManJobId" not in job_info: # orphaned job 

173 job_ids.append(job_id) 

174 else: 

175 _LOG.debug("Looking for %s", f"{job_info['DAGManJobId']}.0") 

176 _LOG.debug("\tin jobs.keys() = %s", jobs.keys()) 

177 if f"{job_info['DAGManJobId']}.0" not in jobs: 

178 job_ids.append(job_id) 

179 

180 _LOG.debug("job_ids = %s", job_ids) 

181 return job_ids 

182 

183 def report(self, wms_workflow_id=None, user=None, hist=0, pass_thru=None): 

184 """Return run information based upon given constraints. 

185 

186 Parameters 

187 ---------- 

188 wms_workflow_id : `str` 

189 Limit to specific run based on id. 

190 user : `str` 

191 Limit results to runs for this user. 

192 hist : `float` 

193 Limit history search to this many days. 

194 pass_thru : `str` 

195 Constraints to pass through to HTCondor. 

196 

197 Returns 

198 ------- 

199 runs : `list` [`lsst.ctrl.bps.WmsRunReport`] 

200 Information about runs from given job information. 

201 message : `str` 

202 Extra message for report command to print. This could be pointers 

203 to documentation or to WMS specific commands. 

204 """ 

205 message = "" 

206 

207 if wms_workflow_id: 

208 # Explicitly checking if wms_workflow_id can be converted to a 

209 # float instead of using try/except to avoid catching a different 

210 # ValueError from _report_from_id 

211 try: 

212 float(wms_workflow_id) 

213 is_float = True 

214 except ValueError: # Don't need TypeError here as None goes to else branch. 

215 is_float = False 

216 

217 if is_float: 

218 run_reports, message = _report_from_id(float(wms_workflow_id), hist) 

219 else: 

220 run_reports, message = _report_from_path(wms_workflow_id) 

221 else: 

222 run_reports, message = _summary_report(user, hist, pass_thru) 

223 _LOG.debug("report: %s, %s", run_reports, message) 

224 

225 return list(run_reports.values()), message 

226 

227 def cancel(self, wms_id, pass_thru=None): 

228 """Cancel submitted workflows/jobs. 

229 

230 Parameters 

231 ---------- 

232 wms_id : `str` 

233 ID or path of job that should be canceled. 

234 pass_thru : `str`, optional 

235 Information to pass through to WMS. 

236 

237 Returns 

238 -------- 

239 deleted : `bool` 

240 Whether successful deletion or not. Currently, if any doubt or any 

241 individual jobs not deleted, return False. 

242 message : `str` 

243 Any message from WMS (e.g., error details). 

244 """ 

245 _LOG.debug("Canceling wms_id = %s", wms_id) 

246 

247 cluster_id = _wms_id_to_cluster(wms_id) 

248 if cluster_id == 0: 

249 deleted = False 

250 message = "Invalid id" 

251 else: 

252 _LOG.debug("Canceling cluster_id = %s", cluster_id) 

253 schedd = htcondor.Schedd() 

254 constraint = f"ClusterId == {cluster_id}" 

255 if pass_thru is not None and "-forcex" in pass_thru: 

256 pass_thru_2 = pass_thru.replace("-forcex", "") 

257 if pass_thru_2 and not pass_thru_2.isspace(): 

258 constraint += f"&& ({pass_thru_2})" 

259 _LOG.debug("JobAction.RemoveX constraint = %s", constraint) 

260 results = schedd.act(htcondor.JobAction.RemoveX, constraint) 

261 else: 

262 if pass_thru: 

263 constraint += f"&& ({pass_thru})" 

264 _LOG.debug("JobAction.Remove constraint = %s", constraint) 

265 results = schedd.act(htcondor.JobAction.Remove, constraint) 

266 _LOG.debug("Remove results: %s", results) 

267 

268 if results["TotalSuccess"] > 0 and results["TotalError"] == 0: 

269 deleted = True 

270 message = "" 

271 else: 

272 deleted = False 

273 if results["TotalSuccess"] == 0 and results["TotalError"] == 0: 

274 message = "no such bps job in batch queue" 

275 else: 

276 message = f"unknown problems deleting: {results}" 

277 

278 _LOG.debug("deleted: %s; message = %s", deleted, message) 

279 return deleted, message 

280 

281 

282class HTCondorWorkflow(BaseWmsWorkflow): 

283 """Single HTCondor workflow. 

284 

285 Parameters 

286 ---------- 

287 name : `str` 

288 Unique name for Workflow used when naming files. 

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

290 BPS configuration that includes necessary submit/runtime information. 

291 """ 

292 def __init__(self, name, config=None): 

293 super().__init__(name, config) 

294 self.dag = None 

295 

296 @classmethod 

297 def from_generic_workflow(cls, config, generic_workflow, out_prefix, service_class): 

298 # Docstring inherited 

299 htc_workflow = cls(generic_workflow.name, config) 

300 htc_workflow.dag = HTCDag(name=generic_workflow.name) 

301 

302 _LOG.debug("htcondor dag attribs %s", generic_workflow.run_attrs) 

303 htc_workflow.dag.add_attribs(generic_workflow.run_attrs) 

304 htc_workflow.dag.add_attribs({"bps_wms_service": service_class, 

305 "bps_wms_workflow": f"{cls.__module__}.{cls.__name__}"}) 

306 

307 # Determine pool specific settings for future reference. 

308 search_opts = {"default": DEFAULT_HTC_EXEC_PATT} 

309 _, site = config.search("computeSite") 

310 if site: 

311 search_opts["curvals"] = {"curr_site": site} 

312 _, patt = config.search("executeMachinesPattern", opt=search_opts) 

313 

314 # Determine the hard limit for the memory requirement. 

315 # 

316 # Note: 

317 # To reduce the number of data that need to be dealt with we are 

318 # ignoring dynamic slots (if any) as, by definition, they cannot have 

319 # more memory than the partitionable slot they are the part of. 

320 constraint = f'SlotType != "Dynamic" && regexp("{patt}", Machine)' 

321 pool_info = condor_status(constraint=constraint) 

322 if not pool_info: 

323 raise RuntimeError(f"No nodes in the HTCondor pool matches pattern '{patt}'") 

324 config["bps_mem_limit"] = max(int(info["TotalSlotMemory"]) for info in pool_info.values()) 

325 

326 # Create all DAG jobs 

327 for job_name in generic_workflow: 

328 gwjob = generic_workflow.get_job(job_name) 

329 htc_job = HTCondorWorkflow._create_job(config, generic_workflow, gwjob, out_prefix) 

330 htc_workflow.dag.add_job(htc_job) 

331 

332 # Add job dependencies to the DAG 

333 for job_name in generic_workflow: 

334 htc_workflow.dag.add_job_relationships([job_name], generic_workflow.successors(job_name)) 

335 

336 # If final job exists in generic workflow, create DAG final job 

337 final = generic_workflow.get_final() 

338 if final and isinstance(final, GenericWorkflowJob): 

339 final_htjob = HTCondorWorkflow._create_job(config, generic_workflow, final, out_prefix) 

340 if "post" not in final_htjob.dagcmds: 

341 final_htjob.dagcmds["post"] = f"{os.path.dirname(__file__)}/final_post.sh" \ 

342 f" {final.name} $DAG_STATUS $RETURN" 

343 htc_workflow.dag.add_final_job(final_htjob) 

344 elif final and isinstance(final, GenericWorkflow): 

345 raise NotImplementedError("HTCondor plugin does not support a workflow as the final job") 

346 elif final: 

347 return TypeError(f"Invalid type for GenericWorkflow.get_final() results ({type(final)})") 

348 

349 return htc_workflow 

350 

351 @staticmethod 

352 def _create_job(config, generic_workflow, gwjob, out_prefix): 

353 """Convert GenericWorkflow job nodes to DAG jobs. 

354 

355 Parameters 

356 ---------- 

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

358 BPS configuration that includes necessary submit/runtime 

359 information. 

360 generic_workflow : `lsst.ctrl.bps.GenericWorkflow` 

361 Generic workflow that is being converted. 

362 gwjob : `lsst.ctrl.bps.GenericWorkflowJob` 

363 The generic job to convert to a HTCondor job. 

364 out_prefix : `str` 

365 Directory prefix for HTCondor files. 

366 

367 Returns 

368 ------- 

369 htc_job : `lsst.ctrl.bps.wms.htcondor.HTCJob` 

370 The HTCondor job equivalent to the given generic job. 

371 """ 

372 htc_job = HTCJob(gwjob.name, label=gwjob.label) 

373 

374 curvals = dataclasses.asdict(gwjob) 

375 if gwjob.tags: 

376 curvals.update(gwjob.tags) 

377 found, subdir = config.search("subDirTemplate", opt={'curvals': curvals}) 

378 if not found: 

379 subdir = "jobs" 

380 htc_job.subfile = Path("jobs") / subdir / f"{gwjob.name}.sub" 

381 

382 htc_job_cmds = { 

383 "universe": "vanilla", 

384 "should_transfer_files": "YES", 

385 "when_to_transfer_output": "ON_EXIT_OR_EVICT", 

386 "transfer_executable": "False", 

387 "getenv": "True", 

388 

389 # Exceeding memory sometimes triggering SIGBUS error. Tell htcondor 

390 # to put SIGBUS jobs on hold. 

391 "on_exit_hold": "(ExitBySignal == true) && (ExitSignal == 7)", 

392 "on_exit_hold_reason": '"Job raised a signal 7. Usually means job has gone over memory limit."', 

393 "on_exit_hold_subcode": "34" 

394 } 

395 

396 htc_job_cmds.update(_translate_job_cmds(config, generic_workflow, gwjob)) 

397 

398 # job stdout, stderr, htcondor user log. 

399 for key in ("output", "error", "log"): 

400 htc_job_cmds[key] = htc_job.subfile.with_suffix(f".$(Cluster).{key[:3]}") 

401 _LOG.debug("HTCondor %s = %s", key, htc_job_cmds[key]) 

402 

403 _, use_shared = config.search("bpsUseShared", opt={"default": False}) 

404 htc_job_cmds.update(_handle_job_inputs(generic_workflow, gwjob.name, use_shared, out_prefix)) 

405 

406 # Add the job cmds dict to the job object. 

407 htc_job.add_job_cmds(htc_job_cmds) 

408 

409 htc_job.add_dag_cmds(_translate_dag_cmds(gwjob)) 

410 

411 # Add run level attributes to job. 

412 htc_job.add_job_attrs(generic_workflow.run_attrs) 

413 

414 # Add job attributes to job. 

415 _LOG.debug("gwjob.attrs = %s", gwjob.attrs) 

416 htc_job.add_job_attrs(gwjob.attrs) 

417 if gwjob.tags: 

418 htc_job.add_job_attrs({"bps_job_quanta": gwjob.tags.get("quanta_summary", "")}) 

419 htc_job.add_job_attrs({"bps_job_name": gwjob.name, 

420 "bps_job_label": gwjob.label}) 

421 

422 return htc_job 

423 

424 def write(self, out_prefix): 

425 """Output HTCondor DAGMan files needed for workflow submission. 

426 

427 Parameters 

428 ---------- 

429 out_prefix : `str` 

430 Directory prefix for HTCondor files. 

431 """ 

432 self.submit_path = out_prefix 

433 os.makedirs(out_prefix, exist_ok=True) 

434 

435 # Write down the workflow in HTCondor format. 

436 self.dag.write(out_prefix, "jobs/{self.label}") 

437 

438 

439def _translate_job_cmds(config, generic_workflow, gwjob): 

440 """Translate the job data that are one to one mapping 

441 

442 Parameters 

443 ---------- 

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

445 BPS configuration that includes necessary submit/runtime 

446 information. 

447 generic_workflow : `lsst.ctrl.bps.GenericWorkflow` 

448 Generic workflow that contains job to being converted. 

449 gwjob : `lsst.ctrl.bps.GenericWorkflowJob` 

450 Generic workflow job to be converted. 

451 

452 Returns 

453 ------- 

454 htc_job_commands : `dict` [`str`, `Any`] 

455 Contains commands which can appear in the HTCondor submit description 

456 file. 

457 """ 

458 # Values in the job script that just are name mappings. 

459 job_translation = {"mail_to": "notify_user", 

460 "when_to_mail": "notification", 

461 "request_cpus": "request_cpus", 

462 "priority": "priority", 

463 "category": "category"} 

464 

465 jobcmds = {} 

466 for gwkey, htckey in job_translation.items(): 

467 jobcmds[htckey] = getattr(gwjob, gwkey, None) 

468 

469 # job commands that need modification 

470 if gwjob.number_of_retries: 

471 jobcmds["max_retries"] = f"{gwjob.number_of_retries}" 

472 

473 if gwjob.retry_unless_exit: 

474 jobcmds["retry_until"] = f"{gwjob.retry_unless_exit}" 

475 

476 if gwjob.request_disk: 

477 jobcmds["request_disk"] = f"{gwjob.request_disk}MB" 

478 

479 if gwjob.request_memory: 

480 jobcmds["request_memory"] = f"{gwjob.request_memory}" 

481 

482 if gwjob.memory_multiplier: 

483 _, memory_limit = config.search("bps_mem_limit") 

484 jobcmds["request_memory"] = _create_request_memory_expr(gwjob.request_memory, gwjob.memory_multiplier) 

485 

486 # Periodically release jobs which are being held due to exceeding 

487 # memory. Stop doing that (by removing the job from the HTCondor queue) 

488 # after the maximal number of retries has been reached or the memory 

489 # requirements cannot be satisfied. 

490 jobcmds["periodic_release"] = \ 

491 "NumJobStarts <= JobMaxRetries && (HoldReasonCode == 34 || HoldReasonSubCode == 34)" 

492 jobcmds["periodic_remove"] = \ 

493 f"JobStatus == 1 && RequestMemory > {memory_limit} || " \ 

494 f"JobStatus == 5 && NumJobStarts > JobMaxRetries" 

495 

496 # Assume concurrency_limit implemented using HTCondor concurrency limits. 

497 # May need to move to special site-specific implementation if sites use 

498 # other mechanisms. 

499 if gwjob.concurrency_limit: 

500 jobcmds["concurrency_limit"] = ",".join(gwjob.concurrency_limit) 

501 

502 # Handle command line 

503 if gwjob.executable.transfer_executable: 

504 jobcmds["transfer_executable"] = "True" 

505 jobcmds["executable"] = os.path.basename(gwjob.executable.src_uri) 

506 else: 

507 jobcmds["executable"] = _fix_env_var_syntax(gwjob.executable.src_uri) 

508 

509 if gwjob.arguments: 

510 arguments = gwjob.arguments 

511 arguments = _replace_cmd_vars(arguments, gwjob) 

512 arguments = _replace_file_vars(config, arguments, generic_workflow, gwjob) 

513 arguments = _fix_env_var_syntax(arguments) 

514 jobcmds["arguments"] = arguments 

515 

516 # Add extra "pass-thru" job commands 

517 if gwjob.profile: 

518 for key, val in gwjob.profile.items(): 

519 jobcmds[key] = htc_escape(val) 

520 

521 return jobcmds 

522 

523 

524def _translate_dag_cmds(gwjob): 

525 """Translate job values into DAGMan commands. 

526 

527 Parameters 

528 ---------- 

529 gwjob : `lsst.ctrl.bps.GenericWorkflowJob` 

530 Job containing values to be translated. 

531 

532 Returns 

533 ------- 

534 dagcmds : `dict` [`str`, `Any`] 

535 DAGMan commands for the job. 

536 """ 

537 # Values in the dag script that just are name mappings. 

538 dag_translation = {"abort_on_value": "abort_dag_on", 

539 "abort_return_value": "abort_exit"} 

540 

541 dagcmds = {} 

542 for gwkey, htckey in dag_translation.items(): 

543 dagcmds[htckey] = getattr(gwjob, gwkey, None) 

544 

545 # Still to be coded: vars "pre_cmdline", "post_cmdline" 

546 return dagcmds 

547 

548 

549def _fix_env_var_syntax(oldstr): 

550 """Change ENV place holders to HTCondor Env var syntax. 

551 

552 Parameters 

553 ---------- 

554 oldstr : `str` 

555 String in which environment variable syntax is to be fixed. 

556 

557 Returns 

558 ------- 

559 newstr : `str` 

560 Given string with environment variable syntax fixed. 

561 """ 

562 newstr = oldstr 

563 for key in re.findall(r"<ENV:([^>]+)>", oldstr): 

564 newstr = newstr.replace(rf"<ENV:{key}>", f"$ENV({key})") 

565 return newstr 

566 

567 

568def _replace_file_vars(config, arguments, workflow, gwjob): 

569 """Replace file placeholders in command line arguments with correct 

570 physical file names. 

571 

572 Parameters 

573 ---------- 

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

575 BPS configuration that includes necessary submit/runtime 

576 information. 

577 arguments : `str` 

578 Arguments string in which to replace file placeholders. 

579 workflow : `lsst.ctrl.bps.GenericWorkflow` 

580 Generic workflow that contains file information. 

581 gwjob : `lsst.ctrl.bps.GenericWorkflowJob` 

582 The job corresponding to the arguments. 

583 

584 Returns 

585 ------- 

586 arguments : `str` 

587 Given arguments string with file placeholders replaced. 

588 """ 

589 _, use_shared = config.search("bpsUseShared", opt={"default": False}) 

590 

591 # Replace input file placeholders with paths. 

592 for gwfile in workflow.get_job_inputs(gwjob.name, data=True, transfer_only=False): 

593 if gwfile.wms_transfer and not use_shared or not gwfile.job_shared: 

594 uri = os.path.basename(gwfile.src_uri) 

595 else: 

596 uri = gwfile.src_uri 

597 arguments = arguments.replace(f"<FILE:{gwfile.name}>", uri) 

598 

599 # Replace output file placeholders with paths. 

600 for gwfile in workflow.get_job_outputs(gwjob.name, data=True, transfer_only=False): 

601 if gwfile.wms_transfer and not use_shared or not gwfile.job_shared: 

602 uri = os.path.basename(gwfile.src_uri) 

603 else: 

604 uri = gwfile.src_uri 

605 arguments = arguments.replace(f"<FILE:{gwfile.name}>", uri) 

606 return arguments 

607 

608 

609def _replace_cmd_vars(arguments, gwjob): 

610 """Replace format-style placeholders in arguments. 

611 

612 Parameters 

613 ---------- 

614 arguments : `str` 

615 Arguments string in which to replace placeholders. 

616 gwjob : `lsst.ctrl.bps.GenericWorkflowJob` 

617 Job containing values to be used to replace placeholders 

618 (in particular gwjob.cmdvals). 

619 

620 Returns 

621 ------- 

622 arguments : `str` 

623 Given arguments string with placeholders replaced. 

624 """ 

625 try: 

626 arguments = arguments.format(**gwjob.cmdvals) 

627 except (KeyError, TypeError): # TypeError in case None instead of {} 

628 _LOG.error("Could not replace command variables:\n" 

629 "arguments: %s\n" 

630 "cmdvals: %s", arguments, gwjob.cmdvals) 

631 raise 

632 return arguments 

633 

634 

635def _handle_job_inputs(generic_workflow: GenericWorkflow, job_name: str, use_shared: bool, out_prefix: str): 

636 """Add job input files from generic workflow to job. 

637 

638 Parameters 

639 ---------- 

640 generic_workflow : `lsst.ctrl.bps.GenericWorkflow` 

641 The generic workflow (e.g., has executable name and arguments). 

642 job_name : `str` 

643 Unique name for the job. 

644 use_shared : `bool` 

645 Whether job has access to files via shared filesystem. 

646 out_prefix : `str` 

647 The root directory into which all WMS-specific files are written. 

648 

649 Returns 

650 ------- 

651 htc_commands : `dict` [`str`, `str`] 

652 HTCondor commands for the job submission script. 

653 """ 

654 htc_commands = {} 

655 inputs = [] 

656 for gwf_file in generic_workflow.get_job_inputs(job_name, data=True, transfer_only=True): 

657 _LOG.debug("src_uri=%s", gwf_file.src_uri) 

658 if not use_shared or not gwf_file.job_shared: 

659 inputs.append(os.path.relpath(gwf_file.src_uri, out_prefix)) 

660 

661 if inputs: 

662 htc_commands["transfer_input_files"] = ",".join(inputs) 

663 _LOG.debug("transfer_input_files=%s", htc_commands["transfer_input_files"]) 

664 return htc_commands 

665 

666 

667def _report_from_path(wms_path): 

668 """Gather run information from a given run directory. 

669 

670 Parameters 

671 ---------- 

672 wms_path : `str` 

673 The directory containing the submit side files (e.g., HTCondor files). 

674 

675 Returns 

676 ------- 

677 run_reports : `dict` [`str`, `lsst.ctrl.bps.WmsRunReport`] 

678 Run information for the detailed report. The key is the HTCondor id 

679 and the value is a collection of report information for that run. 

680 message : `str` 

681 Message to be printed with the summary report. 

682 """ 

683 wms_workflow_id, jobs, message = _get_info_from_path(wms_path) 

684 if wms_workflow_id == MISSING_ID: 

685 run_reports = {} 

686 else: 

687 run_reports = _create_detailed_report_from_jobs(wms_workflow_id, jobs) 

688 return run_reports, message 

689 

690 

691def _report_from_id(wms_workflow_id, hist): 

692 """Gather run information from a given run directory. 

693 

694 Parameters 

695 ---------- 

696 wms_workflow_id : `int` or `str` 

697 Limit to specific run based on id. 

698 hist : `float` 

699 Limit history search to this many days. 

700 

701 Returns 

702 ------- 

703 run_reports : `dict` [`str`, `lsst.ctrl.bps.WmsRunReport`] 

704 Run information for the detailed report. The key is the HTCondor id 

705 and the value is a collection of report information for that run. 

706 message : `str` 

707 Message to be printed with the summary report. 

708 """ 

709 constraint = f"(DAGManJobId == {int(float(wms_workflow_id))} || ClusterId == " \ 

710 f"{int(float(wms_workflow_id))})" 

711 jobs = condor_q(constraint) 

712 if hist: 

713 epoch = (datetime.now() - timedelta(days=hist)).timestamp() 

714 constraint += f" && (CompletionDate >= {epoch} || JobFinishedHookDone >= {epoch})" 

715 hist_jobs = condor_history(constraint) 

716 _update_jobs(jobs, hist_jobs) 

717 

718 # keys in dictionary will be strings of format "ClusterId.ProcId" 

719 wms_workflow_id = str(wms_workflow_id) 

720 if not wms_workflow_id.endswith(".0"): 

721 wms_workflow_id += ".0" 

722 

723 if wms_workflow_id in jobs: 

724 _, path_jobs, message = _get_info_from_path(jobs[wms_workflow_id]["Iwd"]) 

725 _update_jobs(jobs, path_jobs) 

726 run_reports = _create_detailed_report_from_jobs(wms_workflow_id, jobs) 

727 else: 

728 run_reports = {} 

729 message = f"Found 0 records for run id {wms_workflow_id}" 

730 return run_reports, message 

731 

732 

733def _get_info_from_path(wms_path): 

734 """Gather run information from a given run directory. 

735 

736 Parameters 

737 ---------- 

738 wms_path : `str` 

739 Directory containing HTCondor files. 

740 

741 Returns 

742 ------- 

743 wms_workflow_id : `str` 

744 The run id which is a DAGman job id. 

745 jobs : `dict` [`str`, `dict` [`str`, `Any`]] 

746 Information about jobs read from files in the given directory. 

747 The key is the HTCondor id and the value is a dictionary of HTCondor 

748 keys and values. 

749 message : `str` 

750 Message to be printed with the summary report. 

751 """ 

752 try: 

753 wms_workflow_id, jobs = read_dag_log(wms_path) 

754 _LOG.debug("_get_info_from_path: from dag log %s = %s", wms_workflow_id, jobs) 

755 _update_jobs(jobs, read_node_status(wms_path)) 

756 _LOG.debug("_get_info_from_path: after node status %s = %s", wms_workflow_id, jobs) 

757 

758 # Add more info for DAGman job 

759 job = jobs[wms_workflow_id] 

760 job.update(read_dag_status(wms_path)) 

761 job["total_jobs"], job["state_counts"] = _get_state_counts_from_jobs(wms_workflow_id, jobs) 

762 if "bps_run" not in job: 

763 _add_run_info(wms_path, job) 

764 

765 message = htc_check_dagman_output(wms_path) 

766 _LOG.debug("_get_info: id = %s, total_jobs = %s", wms_workflow_id, 

767 jobs[wms_workflow_id]["total_jobs"]) 

768 except StopIteration: 

769 message = f"Could not find HTCondor files in {wms_path}" 

770 _LOG.warning(message) 

771 wms_workflow_id = MISSING_ID 

772 jobs = {} 

773 

774 return wms_workflow_id, jobs, message 

775 

776 

777def _create_detailed_report_from_jobs(wms_workflow_id, jobs): 

778 """Gather run information to be used in generating summary reports. 

779 

780 Parameters 

781 ---------- 

782 wms_workflow_id : `str` 

783 Run lookup restricted to given user. 

784 jobs : `float` 

785 How many previous days to search for run information. 

786 

787 Returns 

788 ------- 

789 run_reports : `dict` [`str`, `lsst.ctrl.bps.WmsRunReport`] 

790 Run information for the detailed report. The key is the given HTCondor 

791 id and the value is a collection of report information for that run. 

792 """ 

793 _LOG.debug("_create_detailed_report: id = %s, job = %s", wms_workflow_id, jobs[wms_workflow_id]) 

794 dag_job = jobs[wms_workflow_id] 

795 if "total_jobs" not in dag_job or "DAGNodeName" in dag_job: 

796 _LOG.error("Job ID %s is not a DAG job.", wms_workflow_id) 

797 return {} 

798 report = WmsRunReport(wms_id=wms_workflow_id, 

799 path=dag_job["Iwd"], 

800 label=dag_job.get("bps_job_label", "MISS"), 

801 run=dag_job.get("bps_run", "MISS"), 

802 project=dag_job.get("bps_project", "MISS"), 

803 campaign=dag_job.get("bps_campaign", "MISS"), 

804 payload=dag_job.get("bps_payload", "MISS"), 

805 operator=_get_owner(dag_job), 

806 run_summary=_get_run_summary(dag_job), 

807 state=_htc_status_to_wms_state(dag_job), 

808 jobs=[], 

809 total_number_jobs=dag_job["total_jobs"], 

810 job_state_counts=dag_job["state_counts"]) 

811 

812 try: 

813 for job in jobs.values(): 

814 if job["ClusterId"] != int(float(wms_workflow_id)): 

815 job_report = WmsJobReport(wms_id=job["ClusterId"], 

816 name=job.get("DAGNodeName", str(job["ClusterId"])), 

817 label=job.get("bps_job_label", 

818 pegasus_name_to_label(job["DAGNodeName"])), 

819 state=_htc_status_to_wms_state(job)) 

820 if job_report.label == "init": 

821 job_report.label = "pipetaskInit" 

822 report.jobs.append(job_report) 

823 except KeyError as ex: 

824 _LOG.error("Job missing key '%s': %s", str(ex), job) 

825 raise 

826 

827 run_reports = {report.wms_id: report} 

828 _LOG.debug("_create_detailed_report: run_reports = %s", run_reports) 

829 return run_reports 

830 

831 

832def _summary_report(user, hist, pass_thru): 

833 """Gather run information to be used in generating summary reports. 

834 

835 Parameters 

836 ---------- 

837 user : `str` 

838 Run lookup restricted to given user. 

839 hist : `float` 

840 How many previous days to search for run information. 

841 pass_thru : `str` 

842 Advanced users can define the HTCondor constraint to be used 

843 when searching queue and history. 

844 

845 Returns 

846 ------- 

847 run_reports : `dict` [`str`, `lsst.ctrl.bps.WmsRunReport`] 

848 Run information for the summary report. The keys are HTCondor ids and 

849 the values are collections of report information for each run. 

850 message : `str` 

851 Message to be printed with the summary report. 

852 """ 

853 # only doing summary report so only look for dagman jobs 

854 if pass_thru: 

855 constraint = pass_thru 

856 else: 

857 # Notes: 

858 # * bps_isjob == 'True' isn't getting set for DAG jobs that are 

859 # manually restarted. 

860 # * Any job with DAGManJobID isn't a DAG job 

861 constraint = 'bps_isjob == "True" && JobUniverse == 7' 

862 if user: 

863 constraint += f' && (Owner == "{user}" || bps_operator == "{user}")' 

864 

865 # Check runs in queue. 

866 jobs = condor_q(constraint) 

867 

868 if hist: 

869 epoch = (datetime.now() - timedelta(days=hist)).timestamp() 

870 constraint += f" && (CompletionDate >= {epoch} || JobFinishedHookDone >= {epoch})" 

871 hist_jobs = condor_history(constraint) 

872 _update_jobs(jobs, hist_jobs) 

873 

874 _LOG.debug("Job ids from queue and history %s", jobs.keys()) 

875 

876 # Have list of DAGMan jobs, need to get run_report info. 

877 run_reports = {} 

878 for job in jobs.values(): 

879 total_jobs, state_counts = _get_state_counts_from_dag_job(job) 

880 # If didn't get from queue information (e.g., Kerberos bug), 

881 # try reading from file. 

882 if total_jobs == 0: 

883 try: 

884 job.update(read_dag_status(job["Iwd"])) 

885 total_jobs, state_counts = _get_state_counts_from_dag_job(job) 

886 except StopIteration: 

887 pass # don't kill report can't find htcondor files 

888 

889 if "bps_run" not in job: 

890 _add_run_info(job["Iwd"], job) 

891 report = WmsRunReport(wms_id=str(job.get("ClusterId", MISSING_ID)), 

892 path=job["Iwd"], 

893 label=job.get("bps_job_label", "MISS"), 

894 run=job.get("bps_run", "MISS"), 

895 project=job.get("bps_project", "MISS"), 

896 campaign=job.get("bps_campaign", "MISS"), 

897 payload=job.get("bps_payload", "MISS"), 

898 operator=_get_owner(job), 

899 run_summary=_get_run_summary(job), 

900 state=_htc_status_to_wms_state(job), 

901 jobs=[], 

902 total_number_jobs=total_jobs, 

903 job_state_counts=state_counts) 

904 

905 run_reports[report.wms_id] = report 

906 

907 return run_reports, "" 

908 

909 

910def _add_run_info(wms_path, job): 

911 """Find BPS run information elsewhere for runs without bps attributes. 

912 

913 Parameters 

914 ---------- 

915 wms_path : `str` 

916 Path to submit files for the run. 

917 job : `dict` [`str`, `Any`] 

918 HTCondor dag job information. 

919 

920 Raises 

921 ------ 

922 StopIteration 

923 If cannot find file it is looking for. Permission errors are 

924 caught and job's run is marked with error. 

925 """ 

926 path = Path(wms_path) / "jobs" 

927 try: 

928 jobdir = next(path.glob("*"), Path(wms_path)) 

929 try: 

930 subfile = next(jobdir.glob("*.sub")) 

931 _LOG.debug("_add_run_info: subfile = %s", subfile) 

932 with open(subfile, "r") as fh: 

933 for line in fh: 

934 if line.startswith("+bps_"): 

935 m = re.match(r"\+(bps_[^\s]+)\s*=\s*(.+)$", line) 

936 if m: 

937 _LOG.debug("Matching line: %s", line) 

938 job[m.group(1)] = m.group(2).replace('"', "") 

939 else: 

940 _LOG.debug("Could not parse attribute: %s", line) 

941 except StopIteration: 

942 job["bps_run"] = "Missing" 

943 

944 except PermissionError: 

945 job["bps_run"] = "PermissionError" 

946 _LOG.debug("After adding job = %s", job) 

947 

948 

949def _get_owner(job): 

950 """Get the owner of a dag job. 

951 

952 Parameters 

953 ---------- 

954 job : `dict` [`str`, `Any`] 

955 HTCondor dag job information. 

956 

957 Returns 

958 ------- 

959 owner : `str` 

960 Owner of the dag job. 

961 """ 

962 owner = job.get("bps_operator", None) 

963 if not owner: 

964 owner = job.get("Owner", None) 

965 if not owner: 

966 _LOG.warning("Could not get Owner from htcondor job: %s", job) 

967 owner = "MISS" 

968 return owner 

969 

970 

971def _get_run_summary(job): 

972 """Get the run summary for a job. 

973 

974 Parameters 

975 ---------- 

976 job : `dict` [`str`, `Any`] 

977 HTCondor dag job information. 

978 

979 Returns 

980 ------- 

981 summary : `str` 

982 Number of jobs per PipelineTask label in approximate pipeline order. 

983 Format: <label>:<count>[;<label>:<count>]+ 

984 """ 

985 summary = job.get("bps_run_summary", None) 

986 if not summary: 

987 summary, _ = summary_from_dag(job["Iwd"]) 

988 if not summary: 

989 _LOG.warning("Could not get run summary for htcondor job: %s", job) 

990 _LOG.debug("_get_run_summary: summary=%s", summary) 

991 

992 # Workaround sometimes using init vs pipetaskInit 

993 summary = summary.replace("init:", "pipetaskInit:") 

994 

995 if "pegasus_version" in job and "pegasus" not in summary: 

996 summary += ";pegasus:0" 

997 

998 return summary 

999 

1000 

1001def _get_state_counts_from_jobs(wms_workflow_id, jobs): 

1002 """Count number of jobs per WMS state. 

1003 

1004 Parameters 

1005 ---------- 

1006 wms_workflow_id : `str` 

1007 HTCondor job id. 

1008 jobs : `dict` [`str`, `Any`] 

1009 HTCondor dag job information. 

1010 

1011 Returns 

1012 ------- 

1013 total_count : `int` 

1014 Total number of dag nodes. 

1015 state_counts : `dict` [`lsst.ctrl.bps.WmsStates`, `int`] 

1016 Keys are the different WMS states and values are counts of jobs 

1017 that are in that WMS state. 

1018 """ 

1019 state_counts = dict.fromkeys(WmsStates, 0) 

1020 

1021 for jid, jinfo in jobs.items(): 

1022 if jid != wms_workflow_id: 

1023 state_counts[_htc_status_to_wms_state(jinfo)] += 1 

1024 

1025 total_counted = sum(state_counts.values()) 

1026 if "NodesTotal" in jobs[wms_workflow_id]: 

1027 total_count = jobs[wms_workflow_id]["NodesTotal"] 

1028 else: 

1029 total_count = total_counted 

1030 

1031 state_counts[WmsStates.UNREADY] += total_count - total_counted 

1032 

1033 return total_count, state_counts 

1034 

1035 

1036def _get_state_counts_from_dag_job(job): 

1037 """Count number of jobs per WMS state. 

1038 

1039 Parameters 

1040 ---------- 

1041 job : `dict` [`str`, `Any`] 

1042 HTCondor dag job information. 

1043 

1044 Returns 

1045 ------- 

1046 total_count : `int` 

1047 Total number of dag nodes. 

1048 state_counts : `dict` [`lsst.ctrl.bps.WmsStates`, `int`] 

1049 Keys are the different WMS states and values are counts of jobs 

1050 that are in that WMS state. 

1051 """ 

1052 _LOG.debug("_get_state_counts_from_dag_job: job = %s %s", type(job), len(job)) 

1053 state_counts = dict.fromkeys(WmsStates, 0) 

1054 if "DAG_NodesReady" in job: 

1055 state_counts = { 

1056 WmsStates.UNREADY: job.get("DAG_NodesUnready", 0), 

1057 WmsStates.READY: job.get("DAG_NodesReady", 0), 

1058 WmsStates.HELD: job.get("JobProcsHeld", 0), 

1059 WmsStates.SUCCEEDED: job.get("DAG_NodesDone", 0), 

1060 WmsStates.FAILED: job.get("DAG_NodesFailed", 0), 

1061 WmsStates.MISFIT: job.get("DAG_NodesPre", 0) + job.get("DAG_NodesPost", 0)} 

1062 total_jobs = job.get("DAG_NodesTotal") 

1063 _LOG.debug("_get_state_counts_from_dag_job: from DAG_* keys, total_jobs = %s", total_jobs) 

1064 elif "NodesFailed" in job: 

1065 state_counts = { 

1066 WmsStates.UNREADY: job.get("NodesUnready", 0), 

1067 WmsStates.READY: job.get("NodesReady", 0), 

1068 WmsStates.HELD: job.get("JobProcsHeld", 0), 

1069 WmsStates.SUCCEEDED: job.get("NodesDone", 0), 

1070 WmsStates.FAILED: job.get("NodesFailed", 0), 

1071 WmsStates.MISFIT: job.get("NodesPre", 0) + job.get("NodesPost", 0)} 

1072 try: 

1073 total_jobs = job.get("NodesTotal") 

1074 except KeyError as ex: 

1075 _LOG.error("Job missing %s. job = %s", str(ex), job) 

1076 raise 

1077 _LOG.debug("_get_state_counts_from_dag_job: from NODES* keys, total_jobs = %s", total_jobs) 

1078 else: 

1079 # With Kerberos job auth and Kerberos bug, if warning would be printed 

1080 # for every DAG. 

1081 _LOG.debug("Can't get job state counts %s", job["Iwd"]) 

1082 total_jobs = 0 

1083 

1084 _LOG.debug("total_jobs = %s, state_counts: %s", total_jobs, state_counts) 

1085 return total_jobs, state_counts 

1086 

1087 

1088def _htc_status_to_wms_state(job): 

1089 """Convert HTCondor job status to generic wms state. 

1090 

1091 Parameters 

1092 ---------- 

1093 job : `dict` [`str`, `Any`] 

1094 HTCondor job information. 

1095 

1096 Returns 

1097 ------- 

1098 wms_state : `WmsStates` 

1099 The equivalent WmsState to given job's status. 

1100 """ 

1101 wms_state = WmsStates.MISFIT 

1102 if "JobStatus" in job: 

1103 wms_state = _htc_job_status_to_wms_state(job) 

1104 elif "NodeStatus" in job: 

1105 wms_state = _htc_node_status_to_wms_state(job) 

1106 return wms_state 

1107 

1108 

1109def _htc_job_status_to_wms_state(job): 

1110 """Convert HTCondor job status to generic wms state. 

1111 

1112 Parameters 

1113 ---------- 

1114 job : `dict` [`str`, `Any`] 

1115 HTCondor job information. 

1116 

1117 Returns 

1118 ------- 

1119 wms_state : `lsst.ctrl.bps.WmsStates` 

1120 The equivalent WmsState to given job's status. 

1121 """ 

1122 _LOG.debug("htc_job_status_to_wms_state: %s=%s, %s", job["ClusterId"], job["JobStatus"], 

1123 type(job["JobStatus"])) 

1124 job_status = int(job["JobStatus"]) 

1125 wms_state = WmsStates.MISFIT 

1126 

1127 _LOG.debug("htc_job_status_to_wms_state: job_status = %s", job_status) 

1128 if job_status == JobStatus.IDLE: 

1129 wms_state = WmsStates.PENDING 

1130 elif job_status == JobStatus.RUNNING: 

1131 wms_state = WmsStates.RUNNING 

1132 elif job_status == JobStatus.REMOVED: 

1133 wms_state = WmsStates.DELETED 

1134 elif job_status == JobStatus.COMPLETED: 

1135 if job.get("ExitBySignal", False) or job.get("ExitCode", 0) or \ 

1136 job.get("ExitSignal", 0) or job.get("DAG_Status", 0) or \ 

1137 job.get("ReturnValue", 0): 

1138 wms_state = WmsStates.FAILED 

1139 else: 

1140 wms_state = WmsStates.SUCCEEDED 

1141 elif job_status == JobStatus.HELD: 

1142 wms_state = WmsStates.HELD 

1143 

1144 return wms_state 

1145 

1146 

1147def _htc_node_status_to_wms_state(job): 

1148 """Convert HTCondor status to generic wms state. 

1149 

1150 Parameters 

1151 ---------- 

1152 job : `dict` [`str`, `Any`] 

1153 HTCondor job information. 

1154 

1155 Returns 

1156 ------- 

1157 wms_state : `lsst.ctrl.bps.WmsStates` 

1158 The equivalent WmsState to given node's status. 

1159 """ 

1160 wms_state = WmsStates.MISFIT 

1161 

1162 status = job["NodeStatus"] 

1163 if status == NodeStatus.NOT_READY: 

1164 wms_state = WmsStates.UNREADY 

1165 elif status == NodeStatus.READY: 

1166 wms_state = WmsStates.READY 

1167 elif status == NodeStatus.PRERUN: 

1168 wms_state = WmsStates.MISFIT 

1169 elif status == NodeStatus.SUBMITTED: 

1170 if job["JobProcsHeld"]: 

1171 wms_state = WmsStates.HELD 

1172 elif job["StatusDetails"] == "not_idle": 

1173 wms_state = WmsStates.RUNNING 

1174 elif job["JobProcsQueued"]: 

1175 wms_state = WmsStates.PENDING 

1176 elif status == NodeStatus.POSTRUN: 

1177 wms_state = WmsStates.MISFIT 

1178 elif status == NodeStatus.DONE: 

1179 wms_state = WmsStates.SUCCEEDED 

1180 elif status == NodeStatus.ERROR: 

1181 wms_state = WmsStates.FAILED 

1182 

1183 return wms_state 

1184 

1185 

1186def _update_jobs(jobs1, jobs2): 

1187 """Update jobs1 with info in jobs2. 

1188 

1189 (Basically an update for nested dictionaries.) 

1190 

1191 Parameters 

1192 ---------- 

1193 jobs1 : `dict` [`str`, `dict` [`str`, `Any`]] 

1194 HTCondor job information to be updated. 

1195 jobs2 : `dict` [`str`, `dict` [`str`, `Any`]] 

1196 Additional HTCondor job information. 

1197 """ 

1198 for jid, jinfo in jobs2.items(): 

1199 if jid in jobs1: 

1200 jobs1[jid].update(jinfo) 

1201 else: 

1202 jobs1[jid] = jinfo 

1203 

1204 

1205def _wms_id_to_cluster(wms_id): 

1206 """Convert WMS ID to cluster ID. 

1207 

1208 Parameters 

1209 ---------- 

1210 wms_id : `int` or `float` or `str` 

1211 HTCondor job id or path. 

1212 

1213 Returns 

1214 ------- 

1215 cluster_id : `int` 

1216 HTCondor cluster id. 

1217 """ 

1218 # If wms_id represents path, get numeric id. 

1219 try: 

1220 cluster_id = int(float(wms_id)) 

1221 except ValueError: 

1222 wms_path = Path(wms_id) 

1223 if wms_path.exists(): 

1224 try: 

1225 cluster_id, _ = read_dag_log(wms_id) 

1226 cluster_id = int(float(cluster_id)) 

1227 except StopIteration: 

1228 cluster_id = 0 

1229 else: 

1230 cluster_id = 0 

1231 return cluster_id 

1232 

1233 

1234def _create_request_memory_expr(memory, multiplier): 

1235 """Construct an HTCondor ClassAd expression for safe memory scaling. 

1236 

1237 Parameters 

1238 ---------- 

1239 memory : `int` 

1240 Requested memory in MB. 

1241 multiplier : `float` 

1242 Memory growth rate between retires. 

1243 

1244 Returns 

1245 ------- 

1246 ad : `str` 

1247 A string representing an HTCondor ClassAd expression enabling safe 

1248 memory scaling between job retries. 

1249 """ 

1250 was_mem_exceeded = "LastJobStatus =?= 5 " \ 

1251 "&& (LastHoldReasonCode =?= 34 && LastHoldReasonSubCode =?= 0 " \ 

1252 "|| LastHoldReasonCode =?= 3 && LastHoldReasonSubCode =?= 34)" 

1253 

1254 # If job runs the first time ('MemoryUsage' is not defined), set the 

1255 # required memory to a given value. 

1256 ad = f"ifThenElse({was_mem_exceeded}, " \ 

1257 f"ifThenElse(isUndefined(MemoryUsage), {memory}, int({multiplier} * MemoryUsage)), " \ 

1258 f"ifThenElse(isUndefined(MemoryUsage), {memory}, max({memory}, MemoryUsage)))" 

1259 return ad