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, stg = 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, stg = 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 raise UnsupportedRequirement("Stdin redirection currently not suppported")
121 raise UnsupportedRequirement("Stderr redirection currently not suppported")
124 mounts["stdout"] = {"kind": "file",
125 "path": "%s/%s" % (self.outdir, self.stdout)}
127 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
129 docker_req = {"dockerImageId": "arvados/jobs"}
131 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
134 self.arvrunner.project_uuid)
136 resources = self.builder.resources
137 if resources is not None:
138 runtime_constraints["vcpus"] = resources.get("cores", 1)
139 runtime_constraints["ram"] = resources.get("ram") * 2**20
141 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
143 runtime_constraints["API"] = True
145 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
147 if "keep_cache" in runtime_req:
148 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
150 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
152 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
154 container_request["mounts"] = mounts
155 container_request["runtime_constraints"] = runtime_constraints
156 container_request["use_existing"] = kwargs.get("enable_reuse", True)
157 container_request["scheduling_parameters"] = scheduling_parameters
159 if kwargs.get("runnerjob", "").startswith("arvwf:"):
160 wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
161 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
162 if container_request["name"] == "main":
163 container_request["name"] = wfrecord["name"]
164 container_request["properties"]["template_uuid"] = wfuuid
167 response = self.arvrunner.api.container_requests().create(
168 body=container_request
169 ).execute(num_retries=self.arvrunner.num_retries)
171 self.uuid = response["uuid"]
172 self.arvrunner.processes[self.uuid] = self
174 if response["state"] == "Final":
175 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
178 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
179 except Exception as e:
180 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
181 self.output_callback({}, "permanentFail")
183 def done(self, record):
185 container = self.arvrunner.api.containers().get(
186 uuid=record["container_uuid"]
187 ).execute(num_retries=self.arvrunner.num_retries)
188 if container["state"] == "Complete":
189 rcode = container["exit_code"]
190 if self.successCodes and rcode in self.successCodes:
191 processStatus = "success"
192 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
193 processStatus = "temporaryFail"
194 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
195 processStatus = "permanentFail"
197 processStatus = "success"
199 processStatus = "permanentFail"
201 processStatus = "permanentFail"
203 if processStatus == "permanentFail":
204 logc = arvados.collection.CollectionReader(container["log"],
205 api_client=self.arvrunner.api,
206 keep_client=self.arvrunner.keep_client,
207 num_retries=self.arvrunner.num_retries)
208 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
211 if container["output"]:
212 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
213 except WorkflowException as e:
214 logger.error("%s unable to collect output from %s:\n%s",
215 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
216 processStatus = "permanentFail"
217 except Exception as e:
218 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
219 processStatus = "permanentFail"
221 self.output_callback(outputs, processStatus)
222 if record["uuid"] in self.arvrunner.processes:
223 del self.arvrunner.processes[record["uuid"]]
226 class RunnerContainer(Runner):
227 """Submit and manage a container that runs arvados-cwl-runner."""
229 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
230 """Create an Arvados container request for this workflow.
232 The returned dict can be used to create a container passed as
233 the +body+ argument to container_requests().create().
236 adjustDirObjs(self.job_order, trim_listing)
239 "owner_uuid": self.arvrunner.project_uuid,
241 "output_path": "/var/spool/cwl",
242 "cwd": "/var/spool/cwl",
244 "state": "Committed",
245 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
247 "/var/lib/cwl/cwl.input.json": {
249 "content": self.job_order
253 "path": "/var/spool/cwl/cwl.output.json"
256 "kind": "collection",
260 "runtime_constraints": {
262 "ram": 1024*1024 * self.submit_runner_ram,
268 if self.tool.tool.get("id", "").startswith("keep:"):
269 sp = self.tool.tool["id"].split('/')
270 workflowcollection = sp[0][5:]
271 workflowname = "/".join(sp[1:])
272 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
273 container_req["mounts"]["/var/lib/cwl/workflow"] = {
274 "kind": "collection",
275 "portable_data_hash": "%s" % workflowcollection
278 packed = packed_workflow(self.arvrunner, self.tool)
279 workflowpath = "/var/lib/cwl/workflow.json#main"
280 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
284 if self.tool.tool.get("id", "").startswith("arvwf:"):
285 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
287 command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
289 command.append("--output-name=" + self.output_name)
290 container_req["output_name"] = self.output_name
293 command.append("--output-tags=" + self.output_tags)
295 if kwargs.get("debug"):
296 command.append("--debug")
298 if self.enable_reuse:
299 command.append("--enable-reuse")
301 command.append("--disable-reuse")
304 command.append("--on-error=" + self.on_error)
306 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
308 container_req["command"] = command
313 def run(self, *args, **kwargs):
314 kwargs["keepprefix"] = "keep:"
315 job_spec = self.arvados_job_spec(*args, **kwargs)
316 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
318 response = self.arvrunner.api.container_requests().create(
320 ).execute(num_retries=self.arvrunner.num_retries)
322 self.uuid = response["uuid"]
323 self.arvrunner.processes[self.uuid] = self
325 logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
327 if response["state"] == "Final":
330 def done(self, record):
332 container = self.arvrunner.api.containers().get(
333 uuid=record["container_uuid"]
334 ).execute(num_retries=self.arvrunner.num_retries)
335 except Exception as e:
336 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
337 self.arvrunner.output_callback({}, "permanentFail")
339 super(RunnerContainer, self).done(container)
341 if record["uuid"] in self.arvrunner.processes:
342 del self.arvrunner.processes[record["uuid"]]