Coverage for python/lsst/ctrl/bps/panda/panda_service.py: 12%
170 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-24 11:10 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-24 11:10 +0000
1# This file is part of ctrl_bps_panda.
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"""Interface between generic workflow to PanDA/iDDS workflow system.
28"""
31__all__ = ["PanDAService", "PandaBpsWmsWorkflow"]
34import json
35import logging
36import os
37import pickle
38import re
40from idds.workflowv2.workflow import Workflow as IDDS_client_workflow
41from lsst.ctrl.bps import BaseWmsService, BaseWmsWorkflow, WmsRunReport, WmsStates
42from lsst.ctrl.bps.panda.constants import PANDA_DEFAULT_MAX_COPY_WORKERS
43from lsst.ctrl.bps.panda.utils import (
44 add_final_idds_work,
45 add_idds_work,
46 copy_files_for_distribution,
47 get_idds_client,
48 get_idds_result,
49)
51_LOG = logging.getLogger(__name__)
54class PanDAService(BaseWmsService):
55 """PanDA version of WMS service."""
57 def prepare(self, config, generic_workflow, out_prefix=None):
58 # Docstring inherited from BaseWmsService.prepare.
59 _LOG.debug("out_prefix = '%s'", out_prefix)
60 workflow = PandaBpsWmsWorkflow.from_generic_workflow(
61 config, generic_workflow, out_prefix, f"{self.__class__.__module__}.{self.__class__.__name__}"
62 )
63 workflow.write(out_prefix)
64 return workflow
66 def submit(self, workflow):
67 _, max_copy_workers = self.config.search(
68 "maxCopyWorkers", opt={"default": PANDA_DEFAULT_MAX_COPY_WORKERS}
69 )
70 # Docstring inherited from BaseWmsService.submit.
71 file_distribution_uri = self.config["fileDistributionEndPoint"]
72 lsst_temp = "LSST_RUN_TEMP_SPACE"
73 if lsst_temp in file_distribution_uri and lsst_temp not in os.environ:
74 file_distribution_uri = self.config["fileDistributionEndPointDefault"]
76 copy_files_for_distribution(workflow.files_to_pre_stage, file_distribution_uri, max_copy_workers)
78 idds_client = get_idds_client(self.config)
79 ret = idds_client.submit(workflow.idds_client_workflow, username=None, use_dataset_name=False)
80 _LOG.debug("iDDS client manager submit returned = %s", ret)
82 # Check submission success
83 status, result, error = get_idds_result(ret)
84 if status:
85 request_id = int(result)
86 else:
87 raise RuntimeError(f"Error submitting to PanDA service: {error}")
89 _LOG.info("Submitted into iDDs with request id=%s", request_id)
90 workflow.run_id = request_id
92 def restart(self, wms_workflow_id):
93 # Docstring inherited from BaseWmsService.restart.
94 idds_client = get_idds_client(self.config)
95 ret = idds_client.retry(request_id=wms_workflow_id)
96 _LOG.debug("Restart PanDA workflow returned = %s", ret)
98 status, result, error = get_idds_result(ret)
99 if status:
100 _LOG.info("Restarting PanDA workflow %s", result)
101 return wms_workflow_id, None, json.dumps(result)
103 return None, None, f"Error retry PanDA workflow: {str(error)}"
105 def report(
106 self,
107 wms_workflow_id=None,
108 user=None,
109 hist=0,
110 pass_thru=None,
111 is_global=False,
112 return_exit_codes=False,
113 ):
114 # Docstring inherited from BaseWmsService.report.
115 message = ""
116 run_reports = []
118 if not wms_workflow_id:
119 message = "Run summary not implemented yet, use 'bps report --id <workflow_id>' instead"
120 return run_reports, message
122 idds_client = get_idds_client(self.config)
123 ret = idds_client.get_requests(request_id=wms_workflow_id, with_detail=True)
124 _LOG.debug("PanDA get workflow status returned = %s", str(ret))
126 request_status = ret[0]
127 if request_status != 0:
128 raise RuntimeError(f"Error to get workflow status: {ret} for id: {wms_workflow_id}")
130 tasks = ret[1][1]
131 if not tasks:
132 message = f"No records found for workflow id '{wms_workflow_id}'. Hint: double check the id"
133 else:
134 head = tasks[0]
135 wms_report = WmsRunReport(
136 wms_id=str(head["request_id"]),
137 operator=head["username"],
138 project="",
139 campaign="",
140 payload="",
141 run=head["name"],
142 state=WmsStates.UNKNOWN,
143 total_number_jobs=0,
144 job_state_counts={state: 0 for state in WmsStates},
145 job_summary={},
146 run_summary="",
147 exit_code_summary=[],
148 )
150 # The status of a task is taken from the first item of state_map.
151 # The workflow is in status WmsStates.FAILED when:
152 # All tasks have failed.
153 # SubFinished tasks has jobs in
154 # output_processed_files: Finished
155 # output_failed_files: Failed
156 # output_missing_files: Missing
157 state_map = {
158 "Finished": [WmsStates.SUCCEEDED],
159 "SubFinished": [
160 WmsStates.SUCCEEDED,
161 WmsStates.FAILED,
162 WmsStates.PRUNED,
163 ],
164 "Transforming": [
165 WmsStates.RUNNING,
166 WmsStates.SUCCEEDED,
167 WmsStates.FAILED,
168 WmsStates.UNREADY,
169 WmsStates.PRUNED,
170 ],
171 "Failed": [WmsStates.FAILED, WmsStates.PRUNED],
172 }
174 file_map = {
175 WmsStates.SUCCEEDED: "output_processed_files",
176 WmsStates.RUNNING: "output_processing_files",
177 WmsStates.FAILED: "output_failed_files",
178 WmsStates.UNREADY: "input_new_files",
179 WmsStates.PRUNED: "output_missing_files",
180 }
182 workflow_status = head["status"]["attributes"]["_name_"]
183 if workflow_status in ["Finished", "SubFinished"]:
184 wms_report.state = WmsStates.SUCCEEDED
185 elif workflow_status in ["Failed", "Expired"]:
186 wms_report.state = WmsStates.FAILED
187 elif workflow_status in ["Cancelled"]:
188 wms_report.state = WmsStates.DELETED
189 elif workflow_status in ["Suspended"]:
190 wms_report.state = WmsStates.HELD
191 else:
192 wms_report.state = WmsStates.RUNNING
194 try:
195 tasks.sort(key=lambda x: x["transform_workload_id"])
196 except Exception:
197 tasks.sort(key=lambda x: x["transform_id"])
199 exit_codes_all = {}
200 # Loop over all tasks data returned by idds_client
201 for task in tasks:
202 exit_codes = []
203 totaljobs = task["output_total_files"]
204 wms_report.total_number_jobs += totaljobs
205 tasklabel = task["transform_name"]
206 tasklabel = re.sub(wms_report.run + "_", "", tasklabel)
207 status = task["transform_status"]["attributes"]["_name_"]
208 taskstatus = {}
209 # if the state is failed, gather exit code information
210 if status in ["SubFinished", "Failed"]:
211 transform_workload_id = task["transform_workload_id"]
212 new_ret = idds_client.get_contents_output_ext(
213 request_id=wms_workflow_id, workload_id=transform_workload_id
214 )
215 request_status = new_ret[0]
216 if request_status != 0:
217 raise RuntimeError(
218 f"Error to get workflow status: {new_ret} for id: {wms_workflow_id}"
219 )
220 # task_info is a dictionary of len 1 that contains a list
221 # of dicts containing panda job info
222 task_info = new_ret[1][1]
224 if len(task_info) == 1:
225 wmskey = list(task_info.keys())[0]
226 wmsjobs = task_info[wmskey]
227 else:
228 raise RuntimeError(
229 f"Unexpected job return from PanDA: {task_info} for id: {transform_workload_id}"
230 )
231 exit_codes = [
232 wmsjob["trans_exit_code"]
233 for wmsjob in wmsjobs
234 if wmsjob["trans_exit_code"] is not None and int(wmsjob["trans_exit_code"]) != 0
235 ]
236 exit_codes_all[tasklabel] = exit_codes
237 # Fill number of jobs in all WmsStates
238 for state in WmsStates:
239 njobs = 0
240 # Each WmsState have many iDDS status mapped to it.
241 if status in state_map:
242 for mappedstate in state_map[status]:
243 if state in file_map and mappedstate == state:
244 if task[file_map[mappedstate]] is not None:
245 njobs = task[file_map[mappedstate]]
246 if state == WmsStates.RUNNING:
247 njobs += task["output_new_files"] - task["input_new_files"]
248 break
249 wms_report.job_state_counts[state] += njobs
250 taskstatus[state] = njobs
251 wms_report.job_summary[tasklabel] = taskstatus
253 # To fill the EXPECTED column
254 if wms_report.run_summary:
255 wms_report.run_summary += ";"
256 wms_report.run_summary += f"{tasklabel}:{str(totaljobs)}"
258 wms_report.exit_code_summary = exit_codes_all
259 run_reports.append(wms_report)
261 return run_reports, message
263 def list_submitted_jobs(self, wms_id=None, user=None, require_bps=True, pass_thru=None, is_global=False):
264 # Docstring inherited from BaseWmsService.list_submitted_jobs.
265 if wms_id is None and user is not None:
266 raise RuntimeError(
267 "Error to get workflow status report: wms_id is required"
268 " and filtering workflows with 'user' is not supported."
269 )
271 idds_client = get_idds_client(self.config)
272 ret = idds_client.get_requests(request_id=wms_id)
273 _LOG.debug("PanDA get workflows returned = %s", ret)
275 status, result, error = get_idds_result(ret)
276 if status:
277 req_ids = [req["request_id"] for req in result]
278 return req_ids
280 raise RuntimeError(f"Error list PanDA workflow requests: {error}")
282 def cancel(self, wms_id, pass_thru=None):
283 # Docstring inherited from BaseWmsService.cancel.
284 idds_client = get_idds_client(self.config)
285 ret = idds_client.abort(request_id=wms_id)
286 _LOG.debug("Abort PanDA workflow returned = %s", ret)
288 status, result, error = get_idds_result(ret)
289 if status:
290 _LOG.info("Aborting PanDA workflow %s", result)
291 return True, json.dumps(result)
293 return False, f"Error abort PanDA workflow: {str(error)}"
295 def ping(self, pass_thru=None):
296 # Docstring inherited from BaseWmsService.ping.
297 idds_client = get_idds_client(self.config)
298 ret = idds_client.ping()
299 _LOG.debug("Ping PanDA service returned = %s", ret)
301 status, result, error = get_idds_result(ret)
302 if status:
303 if "Status" in result and result["Status"] == "OK":
304 return 0, None
306 return -1, f"Error ping PanDA service: {str(result)}"
308 return -1, f"Error ping PanDA service: {str(error)}"
310 def run_submission_checks(self):
311 # Docstring inherited from BaseWmsService.run_submission_checks.
312 for key in ["PANDA_URL"]:
313 if key not in os.environ:
314 raise OSError(f"Missing environment variable {key}")
316 status, message = self.ping()
317 if status != 0:
318 raise RuntimeError(message)
321class PandaBpsWmsWorkflow(BaseWmsWorkflow):
322 """A single Panda based workflow.
324 Parameters
325 ----------
326 name : `str`
327 Unique name for Workflow.
328 config : `lsst.ctrl.bps.BpsConfig`
329 BPS configuration that includes necessary submit/runtime information.
330 """
332 def __init__(self, name, config=None):
333 super().__init__(name, config)
334 self.files_to_pre_stage = {} # src, dest
335 self.idds_client_workflow = IDDS_client_workflow(name=name)
337 @classmethod
338 def from_generic_workflow(cls, config, generic_workflow, out_prefix, service_class):
339 # Docstring inherited from BaseWmsWorkflow.from_generic_workflow.
340 wms_workflow = cls(generic_workflow.name, config)
342 files, dag_sink_work, task_count = add_idds_work(
343 config, generic_workflow, wms_workflow.idds_client_workflow
344 )
345 wms_workflow.files_to_pre_stage.update(files)
347 files = add_final_idds_work(
348 config, generic_workflow, wms_workflow.idds_client_workflow, dag_sink_work, task_count + 1, 1
349 )
350 wms_workflow.files_to_pre_stage.update(files)
352 return wms_workflow
354 def write(self, out_prefix):
355 # Docstring inherited from BaseWmsWorkflow.write.
356 with open(os.path.join(out_prefix, "panda_workflow.pickle"), "wb") as fh:
357 pickle.dump(self, fh)