6 import ruamel.yaml as yaml
8 from cwltool.errors import WorkflowException
9 from cwltool.process import get_feature, UnsupportedRequirement, shortname
10 from cwltool.pathmapper import adjustFiles, adjustDirObjs
11 from cwltool.utils import aslist
13 import arvados.collection
15 from .arvdocker import arv_docker_get_image
17 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_listing
18 from .fsaccess import CollectionFetcher
19 from .pathmapper import NoFollowPathMapper
20 from .perf import Perf
22 logger = logging.getLogger('arvados.cwl-runner')
23 metrics = logging.getLogger('arvados.cwl-runner.metrics')
25 class ArvadosContainer(object):
26 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
28 def __init__(self, runner):
29 self.arvrunner = runner
33 def update_pipeline_component(self, r):
36 def run(self, dry_run=False, pull_image=True, **kwargs):
38 "command": self.command_line,
39 "owner_uuid": self.arvrunner.project_uuid,
41 "output_path": self.outdir,
47 runtime_constraints = {}
53 scheduling_parameters = {}
56 for f in self.pathmapper.files():
57 pdh, p, tp = self.pathmapper.mapper(f)
58 if tp == "Directory" and '/' not in pdh:
61 "portable_data_hash": pdh[5:]
65 for f in self.pathmapper.files():
66 res, p, tp = self.pathmapper.mapper(f)
67 if res.startswith("keep:"):
69 elif res.startswith("/keep/"):
73 sp = res.split("/", 1)
78 "portable_data_hash": pdh
81 mounts[p]["path"] = urllib.unquote(sp[1])
83 with Perf(metrics, "generatefiles %s" % self.name):
84 if self.generatefiles["listing"]:
85 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
86 keep_client=self.arvrunner.keep_client,
87 num_retries=self.arvrunner.num_retries)
88 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
91 with Perf(metrics, "createfiles %s" % self.name):
92 for f, p in generatemapper.items():
95 elif p.type in ("File", "Directory"):
96 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
97 vwd.copy(path, p.target, source_collection=source)
98 elif p.type == "CreateFile":
99 with vwd.open(p.target, "w") as n:
100 n.write(p.resolved.encode("utf-8"))
102 with Perf(metrics, "generatefiles.save_new %s" % self.name):
105 for f, p in generatemapper.items():
108 mountpoint = "%s/%s" % (self.outdir, p.target)
109 mounts[mountpoint] = {"kind": "collection",
110 "portable_data_hash": vwd.portable_data_hash(),
113 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
115 container_request["environment"].update(self.environment)
118 sp = self.stdin[6:].split("/", 1)
119 mounts["stdin"] = {"kind": "collection",
120 "portable_data_hash": sp[0],
124 mounts["stderr"] = {"kind": "file",
125 "path": "%s/%s" % (self.outdir, self.stderr)}
128 mounts["stdout"] = {"kind": "file",
129 "path": "%s/%s" % (self.outdir, self.stdout)}
131 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
133 docker_req = {"dockerImageId": "arvados/jobs"}
135 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
138 self.arvrunner.project_uuid)
140 resources = self.builder.resources
141 if resources is not None:
142 runtime_constraints["vcpus"] = resources.get("cores", 1)
143 runtime_constraints["ram"] = resources.get("ram") * 2**20
145 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
147 runtime_constraints["API"] = True
149 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
151 if "keep_cache" in runtime_req:
152 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
154 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
156 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
158 container_request["mounts"] = mounts
159 container_request["runtime_constraints"] = runtime_constraints
160 container_request["use_existing"] = kwargs.get("enable_reuse", True)
161 container_request["scheduling_parameters"] = scheduling_parameters
163 if kwargs.get("runnerjob", "").startswith("arvwf:"):
164 wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
165 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
166 if container_request["name"] == "main":
167 container_request["name"] = wfrecord["name"]
168 container_request["properties"]["template_uuid"] = wfuuid
171 response = self.arvrunner.api.container_requests().create(
172 body=container_request
173 ).execute(num_retries=self.arvrunner.num_retries)
175 self.uuid = response["uuid"]
176 self.arvrunner.processes[self.uuid] = self
178 if response["state"] == "Final":
179 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
182 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
183 except Exception as e:
184 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
185 self.output_callback({}, "permanentFail")
187 def done(self, record):
189 container = self.arvrunner.api.containers().get(
190 uuid=record["container_uuid"]
191 ).execute(num_retries=self.arvrunner.num_retries)
192 if container["state"] == "Complete":
193 rcode = container["exit_code"]
194 if self.successCodes and rcode in self.successCodes:
195 processStatus = "success"
196 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
197 processStatus = "temporaryFail"
198 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
199 processStatus = "permanentFail"
201 processStatus = "success"
203 processStatus = "permanentFail"
205 processStatus = "permanentFail"
207 if processStatus == "permanentFail":
208 logc = arvados.collection.CollectionReader(container["log"],
209 api_client=self.arvrunner.api,
210 keep_client=self.arvrunner.keep_client,
211 num_retries=self.arvrunner.num_retries)
212 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
215 if container["output"]:
216 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
217 except WorkflowException as e:
218 logger.error("%s unable to collect output from %s:\n%s",
219 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
220 processStatus = "permanentFail"
221 except Exception as e:
222 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
223 processStatus = "permanentFail"
225 self.output_callback(outputs, processStatus)
226 if record["uuid"] in self.arvrunner.processes:
227 del self.arvrunner.processes[record["uuid"]]
230 class RunnerContainer(Runner):
231 """Submit and manage a container that runs arvados-cwl-runner."""
233 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
234 """Create an Arvados container request for this workflow.
236 The returned dict can be used to create a container passed as
237 the +body+ argument to container_requests().create().
240 adjustDirObjs(self.job_order, trim_listing)
243 "owner_uuid": self.arvrunner.project_uuid,
245 "output_path": "/var/spool/cwl",
246 "cwd": "/var/spool/cwl",
248 "state": "Committed",
249 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
251 "/var/lib/cwl/cwl.input.json": {
253 "content": self.job_order
257 "path": "/var/spool/cwl/cwl.output.json"
260 "kind": "collection",
264 "runtime_constraints": {
266 "ram": 1024*1024 * self.submit_runner_ram,
272 if self.tool.tool.get("id", "").startswith("keep:"):
273 sp = self.tool.tool["id"].split('/')
274 workflowcollection = sp[0][5:]
275 workflowname = "/".join(sp[1:])
276 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
277 container_req["mounts"]["/var/lib/cwl/workflow"] = {
278 "kind": "collection",
279 "portable_data_hash": "%s" % workflowcollection
282 packed = packed_workflow(self.arvrunner, self.tool)
283 workflowpath = "/var/lib/cwl/workflow.json#main"
284 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
288 if self.tool.tool.get("id", "").startswith("arvwf:"):
289 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
291 command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
293 command.append("--output-name=" + self.output_name)
294 container_req["output_name"] = self.output_name
297 command.append("--output-tags=" + self.output_tags)
299 if kwargs.get("debug"):
300 command.append("--debug")
302 if self.enable_reuse:
303 command.append("--enable-reuse")
305 command.append("--disable-reuse")
308 command.append("--on-error=" + self.on_error)
310 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
312 container_req["command"] = command
317 def run(self, *args, **kwargs):
318 kwargs["keepprefix"] = "keep:"
319 job_spec = self.arvados_job_spec(*args, **kwargs)
320 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
322 response = self.arvrunner.api.container_requests().create(
324 ).execute(num_retries=self.arvrunner.num_retries)
326 self.uuid = response["uuid"]
327 self.arvrunner.processes[self.uuid] = self
329 logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
331 if response["state"] == "Final":
334 def done(self, record):
336 container = self.arvrunner.api.containers().get(
337 uuid=record["container_uuid"]
338 ).execute(num_retries=self.arvrunner.num_retries)
339 except Exception as e:
340 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
341 self.arvrunner.output_callback({}, "permanentFail")
343 super(RunnerContainer, self).done(container)
345 if record["uuid"] in self.arvrunner.processes:
346 del self.arvrunner.processes[record["uuid"]]