Coverage for python/lsst/ctrl/bps/htcondor/report_utils.py: 7%

290 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-10-11 01:37 -0700

1# This file is part of ctrl_bps_htcondor. 

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 software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <https://www.gnu.org/licenses/>. 

27 

28"""Utility functions used for reporting.""" 

29 

30import logging 

31import os 

32import re 

33from pathlib import Path 

34from typing import Any 

35 

36import htcondor 

37 

38from lsst.ctrl.bps import ( 

39 WmsJobReport, 

40 WmsRunReport, 

41 WmsSpecificInfo, 

42 WmsStates, 

43) 

44 

45from .common_utils import _htc_status_to_wms_state 

46from .lssthtc import ( 

47 MISSING_ID, 

48 WmsNodeType, 

49 condor_search, 

50 htc_check_dagman_output, 

51 htc_tweak_log_info, 

52 pegasus_name_to_label, 

53 read_dag_info, 

54 read_dag_log, 

55 read_dag_status, 

56 read_node_status, 

57 summarize_dag, 

58) 

59 

60_LOG = logging.getLogger(__name__) 

61 

62 

63def _get_status_from_id( 

64 wms_workflow_id: str, hist: float, schedds: dict[str, htcondor.Schedd] 

65) -> tuple[WmsStates, str]: 

66 """Gather run information using workflow id. 

67 

68 Parameters 

69 ---------- 

70 wms_workflow_id : `str` 

71 Limit to specific run based on id. 

72 hist : `float` 

73 Limit history search to this many days. 

74 schedds : `dict` [ `str`, `htcondor.Schedd` ] 

75 HTCondor schedulers which to query for job information. If empty 

76 dictionary, all queries will be run against the local scheduler only. 

77 

78 Returns 

79 ------- 

80 state : `lsst.ctrl.bps.WmsStates` 

81 Status for the corresponding run. 

82 message : `str` 

83 Message with extra error information. 

84 """ 

85 _LOG.debug("_get_status_from_id: id=%s, hist=%s, schedds=%s", wms_workflow_id, hist, schedds) 

86 

87 message = "" 

88 

89 # Collect information about the job by querying HTCondor schedd and 

90 # HTCondor history. 

91 schedd_dag_info = _get_info_from_schedd(wms_workflow_id, hist, schedds) 

92 if len(schedd_dag_info) == 1: 

93 schedd_name = next(iter(schedd_dag_info)) 

94 dag_id = next(iter(schedd_dag_info[schedd_name])) 

95 dag_ad = schedd_dag_info[schedd_name][dag_id] 

96 state = _htc_status_to_wms_state(dag_ad) 

97 else: 

98 state = WmsStates.UNKNOWN 

99 message = f"DAGMan job {wms_workflow_id} not found in queue or history. Check id or try path." 

100 return state, message 

101 

102 

103def _get_status_from_path(wms_path: str | os.PathLike) -> tuple[WmsStates, str]: 

104 """Gather run status from a given run directory. 

105 

106 Parameters 

107 ---------- 

108 wms_path : `str` | `os.PathLike` 

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

110 

111 Returns 

112 ------- 

113 state : `lsst.ctrl.bps.WmsStates` 

114 Status for the run. 

115 message : `str` 

116 Message to be printed. 

117 """ 

118 wms_path = Path(wms_path).resolve() 

119 message = "" 

120 try: 

121 wms_workflow_id, dag_ad = read_dag_log(wms_path) 

122 except FileNotFoundError: 

123 wms_workflow_id = MISSING_ID 

124 message = f"DAGMan log not found in {wms_path}. Check path." 

125 

126 if wms_workflow_id == MISSING_ID: 

127 state = WmsStates.UNKNOWN 

128 else: 

129 state = _htc_status_to_wms_state(dag_ad[wms_workflow_id]) 

130 

131 return state, message 

132 

133 

134def _report_from_path(wms_path): 

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

136 

137 Parameters 

138 ---------- 

139 wms_path : `str` 

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

141 

142 Returns 

143 ------- 

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

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

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

147 message : `str` 

148 Message to be printed with the summary report. 

149 """ 

150 wms_workflow_id, jobs, message = _get_info_from_path(wms_path) 

151 if wms_workflow_id == MISSING_ID: 

152 run_reports = {} 

153 else: 

154 run_reports = _create_detailed_report_from_jobs(wms_workflow_id, jobs) 

155 return run_reports, message 

156 

157 

158def _report_from_id(wms_workflow_id, hist, schedds=None): 

159 """Gather run information using workflow id. 

160 

161 Parameters 

162 ---------- 

163 wms_workflow_id : `str` 

164 Limit to specific run based on id. 

165 hist : `float` 

166 Limit history search to this many days. 

167 schedds : `dict` [ `str`, `htcondor.Schedd` ], optional 

168 HTCondor schedulers which to query for job information. If None 

169 (default), all queries will be run against the local scheduler only. 

170 

171 Returns 

172 ------- 

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

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

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

176 message : `str` 

177 Message to be printed with the summary report. 

178 """ 

179 messages = [] 

180 

181 # Collect information about the job by querying HTCondor schedd and 

182 # HTCondor history. 

183 schedd_dag_info = _get_info_from_schedd(wms_workflow_id, hist, schedds) 

184 if len(schedd_dag_info) == 1: 

185 # Extract the DAG info without altering the results of the query. 

186 schedd_name = next(iter(schedd_dag_info)) 

187 dag_id = next(iter(schedd_dag_info[schedd_name])) 

188 dag_ad = schedd_dag_info[schedd_name][dag_id] 

189 

190 # If the provided workflow id does not correspond to the one extracted 

191 # from the DAGMan log file in the submit directory, rerun the query 

192 # with the id found in the file. 

193 # 

194 # This is to cover the situation in which the user provided the old job 

195 # id of a restarted run. 

196 try: 

197 path_dag_id, _ = read_dag_log(dag_ad["Iwd"]) 

198 except FileNotFoundError as exc: 

199 # At the moment missing DAGMan log is pretty much a fatal error. 

200 # So empty the DAG info to finish early (see the if statement 

201 # below). 

202 schedd_dag_info.clear() 

203 messages.append(f"Cannot create the report for '{dag_id}': {exc}") 

204 else: 

205 if path_dag_id != dag_id: 

206 schedd_dag_info = _get_info_from_schedd(path_dag_id, hist, schedds) 

207 messages.append( 

208 f"WARNING: Found newer workflow executions in same submit directory as id '{dag_id}'. " 

209 "This normally occurs when a run is restarted. The report shown is for the most " 

210 f"recent status with run id '{path_dag_id}'" 

211 ) 

212 

213 if len(schedd_dag_info) == 0: 

214 run_reports = {} 

215 elif len(schedd_dag_info) == 1: 

216 _, dag_info = schedd_dag_info.popitem() 

217 dag_id, dag_ad = dag_info.popitem() 

218 

219 # Create a mapping between jobs and their classads. The keys will 

220 # be of format 'ClusterId.ProcId'. 

221 job_info = {dag_id: dag_ad} 

222 

223 # Find jobs (nodes) belonging to that DAGMan job. 

224 job_constraint = f"DAGManJobId == {int(float(dag_id))}" 

225 schedd_job_info = condor_search(constraint=job_constraint, hist=hist, schedds=schedds) 

226 if schedd_job_info: 

227 _, node_info = schedd_job_info.popitem() 

228 job_info.update(node_info) 

229 

230 # Collect additional pieces of information about jobs using HTCondor 

231 # files in the submission directory. 

232 _, path_jobs, message = _get_info_from_path(dag_ad["Iwd"]) 

233 _update_jobs(job_info, path_jobs) 

234 if message: 

235 messages.append(message) 

236 run_reports = _create_detailed_report_from_jobs(dag_id, job_info) 

237 else: 

238 ids = [ad["GlobalJobId"] for dag_info in schedd_dag_info.values() for ad in dag_info.values()] 

239 message = ( 

240 f"More than one job matches id '{wms_workflow_id}', " 

241 f"their global ids are: {', '.join(ids)}. Rerun with one of the global ids" 

242 ) 

243 messages.append(message) 

244 run_reports = {} 

245 

246 message = "\n".join(messages) 

247 return run_reports, message 

248 

249 

250def _get_info_from_schedd( 

251 wms_workflow_id: str, hist: float, schedds: dict[str, htcondor.Schedd] 

252) -> dict[str, dict[str, dict[str, Any]]]: 

253 """Gather run information from HTCondor. 

254 

255 Parameters 

256 ---------- 

257 wms_workflow_id : `str` 

258 Limit to specific run based on id. 

259 hist : `float` 

260 Limit history search to this many days. 

261 schedds : `dict` [ `str`, `htcondor.Schedd` ] 

262 HTCondor schedulers which to query for job information. If empty 

263 dictionary, all queries will be run against the local scheduler only. 

264 

265 Returns 

266 ------- 

267 schedd_dag_info : `dict` [`str`, `dict` [`str`, `dict` [`str` Any]]] 

268 Information about jobs satisfying the search criteria where for each 

269 Scheduler, local HTCondor job ids are mapped to their respective 

270 classads. 

271 """ 

272 _LOG.debug("_get_info_from_schedd: id=%s, hist=%s, schedds=%s", wms_workflow_id, hist, schedds) 

273 

274 dag_constraint = 'regexp("dagman$", Cmd)' 

275 try: 

276 cluster_id = int(float(wms_workflow_id)) 

277 except ValueError: 

278 dag_constraint += f' && GlobalJobId == "{wms_workflow_id}"' 

279 else: 

280 dag_constraint += f" && ClusterId == {cluster_id}" 

281 

282 # With the current implementation of the condor_* functions the query 

283 # will always return only one match per Scheduler. 

284 # 

285 # Even in the highly unlikely situation where HTCondor history (which 

286 # condor_search queries too) is long enough to have jobs from before 

287 # the cluster ids were rolled over (and as a result there is more then 

288 # one job with the same cluster id) they will not show up in 

289 # the results. 

290 schedd_dag_info = condor_search(constraint=dag_constraint, hist=hist, schedds=schedds) 

291 return schedd_dag_info 

292 

293 

294def _get_info_from_path(wms_path: str | os.PathLike) -> tuple[str, dict[str, dict[str, Any]], str]: 

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

296 

297 Parameters 

298 ---------- 

299 wms_path : `str` or `os.PathLike` 

300 Directory containing HTCondor files. 

301 

302 Returns 

303 ------- 

304 wms_workflow_id : `str` 

305 The run id which is a DAGman job id. 

306 jobs : `dict` [`str`, `dict` [`str`, `~typing.Any`]] 

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

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

309 keys and values. 

310 message : `str` 

311 Message to be printed with the summary report. 

312 """ 

313 # Ensure path is absolute, in particular for folks helping 

314 # debug failures that need to dig around submit files. 

315 wms_path = Path(wms_path).resolve() 

316 

317 messages = [] 

318 try: 

319 wms_workflow_id, jobs = read_dag_log(wms_path) 

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

321 _update_jobs(jobs, read_node_status(wms_path)) 

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

323 

324 # Add more info for DAGman job 

325 job = jobs[wms_workflow_id] 

326 job.update(read_dag_status(wms_path)) 

327 

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

329 if "bps_run" not in job: 

330 _add_run_info(wms_path, job) 

331 

332 message = htc_check_dagman_output(wms_path) 

333 if message: 

334 messages.append(message) 

335 _LOG.debug( 

336 "_get_info: id = %s, total_jobs = %s", wms_workflow_id, jobs[wms_workflow_id]["total_jobs"] 

337 ) 

338 

339 # Add extra pieces of information which cannot be found in HTCondor 

340 # generated files like 'GlobalJobId'. 

341 # 

342 # Do not treat absence of this file as a serious error. Neither runs 

343 # submitted with earlier versions of the plugin nor the runs submitted 

344 # with Pegasus plugin will have it at the moment. However, once enough 

345 # time passes and Pegasus plugin will have its own report() method 

346 # (instead of sneakily using HTCondor's one), the lack of that file 

347 # should be treated as seriously as lack of any other file. 

348 try: 

349 job_info = read_dag_info(wms_path) 

350 except FileNotFoundError as exc: 

351 message = f"Warn: Some information may not be available: {exc}" 

352 messages.append(message) 

353 else: 

354 schedd_name = next(iter(job_info)) 

355 job_ad = next(iter(job_info[schedd_name].values())) 

356 job.update(job_ad) 

357 except FileNotFoundError as err: 

358 message = f"Could not find HTCondor files in '{wms_path}' ({err})" 

359 _LOG.debug(message) 

360 messages.append(message) 

361 message = htc_check_dagman_output(wms_path) 

362 if message: 

363 messages.append(message) 

364 wms_workflow_id = MISSING_ID 

365 jobs = {} 

366 

367 # Add more condor_q-like info. 

368 for job in jobs.values(): 

369 htc_tweak_log_info(wms_path, job) 

370 

371 message = "\n".join([msg for msg in messages if msg]) 

372 _LOG.debug("wms_workflow_id = %s, jobs = %s", wms_workflow_id, jobs.keys()) 

373 _LOG.debug("message = %s", message) 

374 return wms_workflow_id, jobs, message 

375 

376 

377def _create_detailed_report_from_jobs( 

378 wms_workflow_id: str, jobs: dict[str, dict[str, Any]] 

379) -> dict[str, WmsRunReport]: 

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

381 

382 Parameters 

383 ---------- 

384 wms_workflow_id : `str` 

385 The run id to create the report for. 

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

387 Mapping HTCondor job id to job information. 

388 

389 Returns 

390 ------- 

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

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

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

394 """ 

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

396 

397 dag_ad = jobs[wms_workflow_id] 

398 

399 report = WmsRunReport( 

400 wms_id=f"{dag_ad['ClusterId']}.{dag_ad['ProcId']}", 

401 global_wms_id=dag_ad.get("GlobalJobId", "MISS"), 

402 path=dag_ad["Iwd"], 

403 label=dag_ad.get("bps_job_label", "MISS"), 

404 run=dag_ad.get("bps_run", "MISS"), 

405 project=dag_ad.get("bps_project", "MISS"), 

406 campaign=dag_ad.get("bps_campaign", "MISS"), 

407 payload=dag_ad.get("bps_payload", "MISS"), 

408 operator=_get_owner(dag_ad), 

409 run_summary=_get_run_summary(dag_ad), 

410 state=_htc_status_to_wms_state(dag_ad), 

411 total_number_jobs=0, 

412 jobs=[], 

413 job_state_counts=dict.fromkeys(WmsStates, 0), 

414 exit_code_summary={}, 

415 ) 

416 

417 payload_jobs = {} # keep track for later processing 

418 specific_info = WmsSpecificInfo() 

419 for job_id, job_ad in jobs.items(): 

420 if job_ad.get("wms_node_type", WmsNodeType.UNKNOWN) in [WmsNodeType.PAYLOAD, WmsNodeType.FINAL]: 

421 try: 

422 name = job_ad.get("DAGNodeName", job_id) 

423 wms_state = _htc_status_to_wms_state(job_ad) 

424 job_report = WmsJobReport( 

425 wms_id=job_id, 

426 name=name, 

427 label=job_ad.get("bps_job_label", pegasus_name_to_label(name)), 

428 state=wms_state, 

429 ) 

430 if job_report.label == "init": 

431 job_report.label = "pipetaskInit" 

432 report.job_state_counts[wms_state] += 1 

433 report.jobs.append(job_report) 

434 payload_jobs[job_id] = job_ad 

435 except KeyError as ex: 

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

437 raise 

438 elif is_service_job(job_ad): 

439 _LOG.debug( 

440 "Found service job: id='%s', name='%s', label='%s', NodeStatus='%s', JobStatus='%s'", 

441 job_id, 

442 job_ad["DAGNodeName"], 

443 job_ad.get("bps_job_label", "MISS"), 

444 job_ad.get("NodeStatus", "MISS"), 

445 job_ad.get("JobStatus", "MISS"), 

446 ) 

447 _add_service_job_specific_info(job_ad, specific_info) 

448 

449 report.total_number_jobs = len(payload_jobs) 

450 report.exit_code_summary = _get_exit_code_summary(payload_jobs) 

451 if specific_info: 

452 report.specific_info = specific_info 

453 

454 # Workflow will exit with non-zero DAG_STATUS if problem with 

455 # any of the wms jobs. So change FAILED to SUCCEEDED if all 

456 # payload jobs SUCCEEDED. 

457 if report.total_number_jobs == report.job_state_counts[WmsStates.SUCCEEDED]: 

458 report.state = WmsStates.SUCCEEDED 

459 

460 run_reports = {report.wms_id: report} 

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

462 return run_reports 

463 

464 

465def _add_service_job_specific_info(job_ad: dict[str, Any], specific_info: WmsSpecificInfo) -> None: 

466 """Generate report information for service job. 

467 

468 Parameters 

469 ---------- 

470 job_ad : `dict` [`str`, `~typing.Any`] 

471 Provisioning job information. 

472 specific_info : `lsst.ctrl.bps.WmsSpecificInfo` 

473 Where to add message. 

474 """ 

475 status_details = "" 

476 job_status = _htc_status_to_wms_state(job_ad) 

477 

478 # Service jobs in queue are deleted when DAG is done. 

479 # To get accurate status, need to check other info. 

480 if ( 

481 job_status == WmsStates.DELETED 

482 and "Reason" in job_ad 

483 and ( 

484 "Removed by DAGMan" in job_ad["Reason"] 

485 or "removed because <OtherJobRemoveRequirements = DAGManJobId =?=" in job_ad["Reason"] 

486 or "DAG is exiting and writing rescue file." in job_ad["Reason"] 

487 ) 

488 ): 

489 if "HoldReason" in job_ad: 

490 # HoldReason exists even if released, so check. 

491 if "job_released_time" in job_ad and job_ad["job_held_time"] < job_ad["job_released_time"]: 

492 # If released, assume running until deleted. 

493 job_status = WmsStates.SUCCEEDED 

494 status_details = "" 

495 else: 

496 # If job held when deleted by DAGMan, still want to 

497 # report hold reason 

498 status_details = f"(Job was held for the following reason: {job_ad['HoldReason']})" 

499 

500 else: 

501 job_status = WmsStates.SUCCEEDED 

502 elif job_status == WmsStates.SUCCEEDED: 

503 status_details = "(Note: Finished before workflow.)" 

504 elif job_status == WmsStates.HELD: 

505 status_details = f"({job_ad['HoldReason']})" 

506 

507 template = "Status of {job_name}: {status} {status_details}" 

508 context = { 

509 "job_name": job_ad["DAGNodeName"], 

510 "status": job_status.name, 

511 "status_details": status_details, 

512 } 

513 specific_info.add_message(template=template, context=context) 

514 

515 

516def _summary_report(user, hist, pass_thru, schedds=None): 

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

518 

519 Parameters 

520 ---------- 

521 user : `str` 

522 Run lookup restricted to given user. 

523 hist : `float` 

524 How many previous days to search for run information. 

525 pass_thru : `str` 

526 Advanced users can define the HTCondor constraint to be used 

527 when searching queue and history. 

528 

529 Returns 

530 ------- 

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

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

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

534 message : `str` 

535 Message to be printed with the summary report. 

536 """ 

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

538 if pass_thru: 

539 constraint = pass_thru 

540 else: 

541 # Notes: 

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

543 # manually restarted. 

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

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

546 if user: 

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

548 

549 job_info = condor_search(constraint=constraint, hist=hist, schedds=schedds) 

550 

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

552 run_reports = {} 

553 msg = "" 

554 for jobs in job_info.values(): 

555 for job_id, job in jobs.items(): 

556 total_jobs, state_counts = _get_state_counts_from_dag_job(job) 

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

558 # try reading from file. 

559 if total_jobs == 0: 

560 try: 

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

562 total_jobs, state_counts = _get_state_counts_from_dag_job(job) 

563 except StopIteration: 

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

565 

566 if "bps_run" not in job: 

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

568 report = WmsRunReport( 

569 wms_id=job_id, 

570 global_wms_id=job["GlobalJobId"], 

571 path=job["Iwd"], 

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

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

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

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

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

577 operator=_get_owner(job), 

578 run_summary=_get_run_summary(job), 

579 state=_htc_status_to_wms_state(job), 

580 jobs=[], 

581 total_number_jobs=total_jobs, 

582 job_state_counts=state_counts, 

583 ) 

584 run_reports[report.global_wms_id] = report 

585 

586 return run_reports, msg 

587 

588 

589def _add_run_info(wms_path, job): 

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

591 

592 Parameters 

593 ---------- 

594 wms_path : `str` 

595 Path to submit files for the run. 

596 job : `dict` [`str`, `~typing.Any`] 

597 HTCondor dag job information. 

598 

599 Raises 

600 ------ 

601 StopIteration 

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

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

604 """ 

605 path = Path(wms_path) / "jobs" 

606 try: 

607 subfile = next(path.glob("**/*.sub")) 

608 except (StopIteration, PermissionError): 

609 job["bps_run"] = "Unavailable" 

610 else: 

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

612 try: 

613 with open(subfile, encoding="utf-8") as fh: 

614 for line in fh: 

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

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

617 if m: 

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

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

620 else: 

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

622 except PermissionError: 

623 job["bps_run"] = "PermissionError" 

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

625 

626 

627def _get_owner(job): 

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

629 

630 Parameters 

631 ---------- 

632 job : `dict` [`str`, `~typing.Any`] 

633 HTCondor dag job information. 

634 

635 Returns 

636 ------- 

637 owner : `str` 

638 Owner of the dag job. 

639 """ 

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

641 if not owner: 

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

643 if not owner: 

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

645 owner = "MISS" 

646 return owner 

647 

648 

649def _get_run_summary(job): 

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

651 

652 Parameters 

653 ---------- 

654 job : `dict` [`str`, `~typing.Any`] 

655 HTCondor dag job information. 

656 

657 Returns 

658 ------- 

659 summary : `str` 

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

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

662 """ 

663 summary = job.get("bps_job_summary", job.get("bps_run_summary", None)) 

664 if not summary: 

665 summary, _, _ = summarize_dag(job["Iwd"]) 

666 if not summary: 

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

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

669 

670 # Workaround sometimes using init vs pipetaskInit 

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

672 

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

674 summary += ";pegasus:0" 

675 

676 return summary 

677 

678 

679def _get_exit_code_summary(jobs): 

680 """Get the exit code summary for a run. 

681 

682 Parameters 

683 ---------- 

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

685 Mapping HTCondor job id to job information. 

686 

687 Returns 

688 ------- 

689 summary : `dict` [`str`, `list` [`int`]] 

690 Jobs' exit codes per job label. 

691 """ 

692 summary = {} 

693 for job_id, job_ad in jobs.items(): 

694 job_label = job_ad["bps_job_label"] 

695 summary.setdefault(job_label, []) 

696 try: 

697 exit_code = 0 

698 job_status = job_ad["JobStatus"] 

699 match job_status: 

700 case htcondor.JobStatus.COMPLETED | htcondor.JobStatus.HELD | htcondor.JobStatus.REMOVED: 

701 exit_code = job_ad["ExitSignal"] if job_ad["ExitBySignal"] else job_ad["ExitCode"] 

702 case ( 

703 htcondor.JobStatus.IDLE 

704 | htcondor.JobStatus.RUNNING 

705 | htcondor.JobStatus.TRANSFERRING_OUTPUT 

706 | htcondor.JobStatus.SUSPENDED 

707 ): 

708 pass 

709 case _: 

710 _LOG.debug("Unknown 'JobStatus' value ('%d') in classad for job '%s'", job_status, job_id) 

711 if exit_code != 0: 

712 summary[job_label].append(exit_code) 

713 except KeyError as ex: 

714 _LOG.debug("Attribute '%s' not found in the classad for job '%s'", ex, job_id) 

715 return summary 

716 

717 

718def _get_state_counts_from_jobs( 

719 wms_workflow_id: str, jobs: dict[str, dict[str, Any]] 

720) -> tuple[int, dict[WmsStates, int]]: 

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

722 

723 The workflow job and the service jobs are excluded from the count. 

724 

725 Parameters 

726 ---------- 

727 wms_workflow_id : `str` 

728 HTCondor job id. 

729 jobs : `dict [`dict` [`str`, `~typing.Any`]] 

730 HTCondor dag job information. 

731 

732 Returns 

733 ------- 

734 total_count : `int` 

735 Total number of dag nodes. 

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

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

738 that are in that WMS state. 

739 """ 

740 state_counts = dict.fromkeys(WmsStates, 0) 

741 for job_id, job_ad in jobs.items(): 

742 if job_id != wms_workflow_id and job_ad.get("wms_node_type", WmsNodeType.UNKNOWN) in [ 

743 WmsNodeType.PAYLOAD, 

744 WmsNodeType.FINAL, 

745 ]: 

746 state_counts[_htc_status_to_wms_state(job_ad)] += 1 

747 total_count = sum(state_counts.values()) 

748 

749 return total_count, state_counts 

750 

751 

752def _get_state_counts_from_dag_job(job): 

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

754 

755 Parameters 

756 ---------- 

757 job : `dict` [`str`, `~typing.Any`] 

758 HTCondor dag job information. 

759 

760 Returns 

761 ------- 

762 total_count : `int` 

763 Total number of dag nodes. 

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

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

766 that are in that WMS state. 

767 """ 

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

769 state_counts = dict.fromkeys(WmsStates, 0) 

770 if "DAG_NodesReady" in job: 

771 state_counts = { 

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

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

774 WmsStates.HELD: job.get("DAG_JobsHeld", 0), 

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

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

777 WmsStates.PRUNED: job.get("DAG_NodesFutile", 0), 

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

779 } 

780 total_jobs = job.get("DAG_NodesTotal") 

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

782 elif "NodesFailed" in job: 

783 state_counts = { 

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

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

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

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

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

789 WmsStates.PRUNED: job.get("NodesFutile", 0), 

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

791 } 

792 try: 

793 total_jobs = job.get("NodesTotal") 

794 except KeyError as ex: 

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

796 raise 

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

798 else: 

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

800 # for every DAG. 

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

802 total_jobs = 0 

803 

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

805 return total_jobs, state_counts 

806 

807 

808def _update_jobs(jobs1, jobs2): 

809 """Update jobs1 with info in jobs2. 

810 

811 (Basically an update for nested dictionaries.) 

812 

813 Parameters 

814 ---------- 

815 jobs1 : `dict` [`str`, `dict` [`str`, `~typing.Any`]] 

816 HTCondor job information to be updated. 

817 jobs2 : `dict` [`str`, `dict` [`str`, `~typing.Any`]] 

818 Additional HTCondor job information. 

819 """ 

820 for job_id, job_ad in jobs2.items(): 

821 if job_id in jobs1: 

822 jobs1[job_id].update(job_ad) 

823 else: 

824 jobs1[job_id] = job_ad 

825 

826 

827def is_service_job(job_ad: dict[str, Any]) -> bool: 

828 """Determine if a job is a service one. 

829 

830 Parameters 

831 ---------- 

832 job_ad : `dict` [`str`, Any] 

833 Information about an HTCondor job. 

834 

835 Returns 

836 ------- 

837 is_service_job : `bool` 

838 True if the job is a service one, false otherwise. 

839 

840 Notes 

841 ----- 

842 At the moment, HTCondor does not provide a native way to distinguish 

843 between payload and service jobs in the workflow. This code depends 

844 on read_node_status adding wms_node_type. 

845 """ 

846 return job_ad.get("wms_node_type", WmsNodeType.UNKNOWN) == WmsNodeType.SERVICE