5 import ruamel.yaml as yaml
7 from cwltool.errors import WorkflowException
8 from cwltool.process import get_feature, UnsupportedRequirement, shortname
9 from cwltool.pathmapper import adjustFiles, adjustDirObjs
10 from cwltool.utils import aslist
12 import arvados.collection
14 from .arvdocker import arv_docker_get_image
16 from .runner import Runner, arvados_jobs_image, packed_workflow, trim_listing
17 from .fsaccess import CollectionFetcher
18 from .pathmapper import NoFollowPathMapper
19 from .perf import Perf
21 logger = logging.getLogger('arvados.cwl-runner')
22 metrics = logging.getLogger('arvados.cwl-runner.metrics')
24 class ArvadosContainer(object):
25 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
27 def __init__(self, runner):
28 self.arvrunner = runner
32 def update_pipeline_component(self, r):
35 def run(self, dry_run=False, pull_image=True, **kwargs):
37 "command": self.command_line,
38 "owner_uuid": self.arvrunner.project_uuid,
40 "output_path": self.outdir,
46 runtime_constraints = {}
52 scheduling_parameters = {}
55 for f in self.pathmapper.files():
56 pdh, p, tp = self.pathmapper.mapper(f)
57 if tp == "Directory" and '/' not in pdh:
60 "portable_data_hash": pdh[5:]
64 for f in self.pathmapper.files():
65 res, p, tp = self.pathmapper.mapper(f)
66 if res.startswith("keep:"):
68 elif res.startswith("/keep/"):
72 sp = res.split("/", 1)
77 "portable_data_hash": pdh
80 mounts[p]["path"] = sp[1]
82 with Perf(metrics, "generatefiles %s" % self.name):
83 if self.generatefiles["listing"]:
84 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
85 keep_client=self.arvrunner.keep_client,
86 num_retries=self.arvrunner.num_retries)
87 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
90 with Perf(metrics, "createfiles %s" % self.name):
91 for f, p in generatemapper.items():
94 elif p.type in ("File", "Directory"):
95 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
96 vwd.copy(path, p.target, source_collection=source)
97 elif p.type == "CreateFile":
98 with vwd.open(p.target, "w") as n:
99 n.write(p.resolved.encode("utf-8"))
101 with Perf(metrics, "generatefiles.save_new %s" % self.name):
104 for f, p in generatemapper.items():
107 mountpoint = "%s/%s" % (self.outdir, p.target)
108 mounts[mountpoint] = {"kind": "collection",
109 "portable_data_hash": vwd.portable_data_hash(),
112 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
114 container_request["environment"].update(self.environment)
117 raise UnsupportedRequirement("Stdin redirection currently not suppported")
120 raise UnsupportedRequirement("Stderr redirection currently not suppported")
123 mounts["stdout"] = {"kind": "file",
124 "path": "%s/%s" % (self.outdir, self.stdout)}
126 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
128 docker_req = {"dockerImageId": "arvados/jobs"}
130 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
133 self.arvrunner.project_uuid)
135 resources = self.builder.resources
136 if resources is not None:
137 runtime_constraints["vcpus"] = resources.get("cores", 1)
138 runtime_constraints["ram"] = resources.get("ram") * 2**20
140 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
142 runtime_constraints["API"] = True
144 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
146 if "keep_cache" in runtime_req:
147 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
149 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
151 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
153 container_request["mounts"] = mounts
154 container_request["runtime_constraints"] = runtime_constraints
155 container_request["use_existing"] = kwargs.get("enable_reuse", True)
156 container_request["scheduling_parameters"] = scheduling_parameters
158 if kwargs.get("runnerjob", "").startswith("arvwf:"):
159 wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
160 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
161 if container_request["name"] == "main":
162 container_request["name"] = wfrecord["name"]
163 container_request["properties"]["template_uuid"] = wfuuid
166 response = self.arvrunner.api.container_requests().create(
167 body=container_request
168 ).execute(num_retries=self.arvrunner.num_retries)
170 self.uuid = response["uuid"]
171 self.arvrunner.processes[self.uuid] = self
173 if response["state"] == "Final":
174 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
177 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
178 except Exception as e:
179 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
180 self.output_callback({}, "permanentFail")
182 def done(self, record):
184 container = self.arvrunner.api.containers().get(
185 uuid=record["container_uuid"]
186 ).execute(num_retries=self.arvrunner.num_retries)
187 if container["state"] == "Complete":
188 rcode = container["exit_code"]
189 if self.successCodes and rcode in self.successCodes:
190 processStatus = "success"
191 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
192 processStatus = "temporaryFail"
193 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
194 processStatus = "permanentFail"
196 processStatus = "success"
198 processStatus = "permanentFail"
200 processStatus = "permanentFail"
202 if processStatus == "permanentFail":
203 logc = arvados.collection.CollectionReader(container["log"],
204 api_client=self.arvrunner.api,
205 keep_client=self.arvrunner.keep_client,
206 num_retries=self.arvrunner.num_retries)
207 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
210 if container["output"]:
211 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
212 except WorkflowException as e:
213 logger.error("%s unable to collect output from %s:\n%s",
214 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
215 processStatus = "permanentFail"
216 except Exception as e:
217 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
218 processStatus = "permanentFail"
220 self.output_callback(outputs, processStatus)
221 if record["uuid"] in self.arvrunner.processes:
222 del self.arvrunner.processes[record["uuid"]]
225 class RunnerContainer(Runner):
226 """Submit and manage a container that runs arvados-cwl-runner."""
228 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
229 """Create an Arvados container request for this workflow.
231 The returned dict can be used to create a container passed as
232 the +body+ argument to container_requests().create().
235 adjustDirObjs(self.job_order, trim_listing)
238 "owner_uuid": self.arvrunner.project_uuid,
240 "output_path": "/var/spool/cwl",
241 "cwd": "/var/spool/cwl",
243 "state": "Committed",
244 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
246 "/var/lib/cwl/cwl.input.json": {
248 "content": self.job_order
252 "path": "/var/spool/cwl/cwl.output.json"
255 "kind": "collection",
259 "runtime_constraints": {
261 "ram": 1024*1024 * self.submit_runner_ram,
267 if self.tool.tool.get("id", "").startswith("keep:"):
268 sp = self.tool.tool["id"].split('/')
269 workflowcollection = sp[0][5:]
270 workflowname = "/".join(sp[1:])
271 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
272 container_req["mounts"]["/var/lib/cwl/workflow"] = {
273 "kind": "collection",
274 "portable_data_hash": "%s" % workflowcollection
277 packed = packed_workflow(self.arvrunner, self.tool)
278 workflowpath = "/var/lib/cwl/workflow.json#main"
279 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
283 if self.tool.tool.get("id", "").startswith("arvwf:"):
284 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
286 command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
288 command.append("--output-name=" + self.output_name)
289 container_req["output_name"] = self.output_name
292 command.append("--output-tags=" + self.output_tags)
294 if kwargs.get("debug"):
295 command.append("--debug")
297 if self.enable_reuse:
298 command.append("--enable-reuse")
300 command.append("--disable-reuse")
303 command.append("--on-error=" + self.on_error)
305 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
307 container_req["command"] = command
312 def run(self, *args, **kwargs):
313 kwargs["keepprefix"] = "keep:"
314 job_spec = self.arvados_job_spec(*args, **kwargs)
315 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
317 response = self.arvrunner.api.container_requests().create(
319 ).execute(num_retries=self.arvrunner.num_retries)
321 self.uuid = response["uuid"]
322 self.arvrunner.processes[self.uuid] = self
324 logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
326 if response["state"] == "Final":
329 def done(self, record):
331 container = self.arvrunner.api.containers().get(
332 uuid=record["container_uuid"]
333 ).execute(num_retries=self.arvrunner.num_retries)
334 except Exception as e:
335 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
336 self.arvrunner.output_callback({}, "permanentFail")
338 super(RunnerContainer, self).done(container)
340 if record["uuid"] in self.arvrunner.processes:
341 del self.arvrunner.processes[record["uuid"]]