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 adjustFileObjs, 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_anonymous_location
18 from .fsaccess import CollectionFetcher
19 from .pathmapper import NoFollowPathMapper, trim_listing
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 = {}
49 resources = self.builder.resources
50 if resources is not None:
51 runtime_constraints["vcpus"] = resources.get("cores", 1)
52 runtime_constraints["ram"] = resources.get("ram") * 2**20
57 "capacity": resources.get("outdirSize", 0) * 2**20
61 "capacity": resources.get("tmpdirSize", 0) * 2**20
64 scheduling_parameters = {}
66 rf = [self.pathmapper.mapper(f) for f in self.pathmapper.referenced_files]
67 rf.sort(key=lambda k: k.resolved)
69 for resolved, target, tp, stg in rf:
72 if prevdir and target.startswith(prevdir):
77 targetdir = os.path.dirname(target)
78 sp = resolved.split("/", 1)
79 pdh = sp[0][5:] # remove "keep:"
82 "portable_data_hash": pdh
88 path = os.path.dirname(sp[1])
89 if path and path != "/":
90 mounts[targetdir]["path"] = path
91 prevdir = targetdir + "/"
93 with Perf(metrics, "generatefiles %s" % self.name):
94 if self.generatefiles["listing"]:
95 vwd = arvados.collection.Collection(api_client=self.arvrunner.api,
96 keep_client=self.arvrunner.keep_client,
97 num_retries=self.arvrunner.num_retries)
98 generatemapper = NoFollowPathMapper([self.generatefiles], "", "",
101 with Perf(metrics, "createfiles %s" % self.name):
102 for f, p in generatemapper.items():
105 elif p.type in ("File", "Directory"):
106 source, path = self.arvrunner.fs_access.get_collection(p.resolved)
107 vwd.copy(path, p.target, source_collection=source)
108 elif p.type == "CreateFile":
109 with vwd.open(p.target, "w") as n:
110 n.write(p.resolved.encode("utf-8"))
112 with Perf(metrics, "generatefiles.save_new %s" % self.name):
115 for f, p in generatemapper.items():
118 mountpoint = "%s/%s" % (self.outdir, p.target)
119 mounts[mountpoint] = {"kind": "collection",
120 "portable_data_hash": vwd.portable_data_hash(),
123 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
125 container_request["environment"].update(self.environment)
128 sp = self.stdin[6:].split("/", 1)
129 mounts["stdin"] = {"kind": "collection",
130 "portable_data_hash": sp[0],
134 mounts["stderr"] = {"kind": "file",
135 "path": "%s/%s" % (self.outdir, self.stderr)}
138 mounts["stdout"] = {"kind": "file",
139 "path": "%s/%s" % (self.outdir, self.stdout)}
141 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
143 docker_req = {"dockerImageId": "arvados/jobs"}
145 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
148 self.arvrunner.project_uuid)
150 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
152 runtime_constraints["API"] = True
154 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
156 if "keep_cache" in runtime_req:
157 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"] * 2**20
158 if "outputDirType" in runtime_req:
159 if runtime_req["outputDirType"] == "local_output_dir":
160 # Currently the default behavior.
162 elif runtime_req["outputDirType"] == "keep_output_dir":
163 mounts[self.outdir]= {
164 "kind": "collection",
168 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
170 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
172 container_request["mounts"] = mounts
173 container_request["runtime_constraints"] = runtime_constraints
174 container_request["use_existing"] = kwargs.get("enable_reuse", True)
175 container_request["scheduling_parameters"] = scheduling_parameters
177 if kwargs.get("runnerjob", "").startswith("arvwf:"):
178 wfuuid = kwargs["runnerjob"][6:kwargs["runnerjob"].index("#")]
179 wfrecord = self.arvrunner.api.workflows().get(uuid=wfuuid).execute(num_retries=self.arvrunner.num_retries)
180 if container_request["name"] == "main":
181 container_request["name"] = wfrecord["name"]
182 container_request["properties"]["template_uuid"] = wfuuid
185 response = self.arvrunner.api.container_requests().create(
186 body=container_request
187 ).execute(num_retries=self.arvrunner.num_retries)
189 self.uuid = response["uuid"]
190 self.arvrunner.processes[self.uuid] = self
192 if response["state"] == "Final":
193 logger.info("%s reused container %s", self.arvrunner.label(self), response["container_uuid"])
196 logger.info("%s %s state is %s", self.arvrunner.label(self), response["uuid"], response["state"])
197 except Exception as e:
198 logger.error("%s got error %s" % (self.arvrunner.label(self), str(e)))
199 self.output_callback({}, "permanentFail")
201 def done(self, record):
203 container = self.arvrunner.api.containers().get(
204 uuid=record["container_uuid"]
205 ).execute(num_retries=self.arvrunner.num_retries)
206 if container["state"] == "Complete":
207 rcode = container["exit_code"]
208 if self.successCodes and rcode in self.successCodes:
209 processStatus = "success"
210 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
211 processStatus = "temporaryFail"
212 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
213 processStatus = "permanentFail"
215 processStatus = "success"
217 processStatus = "permanentFail"
219 processStatus = "permanentFail"
221 if processStatus == "permanentFail":
222 logc = arvados.collection.CollectionReader(container["log"],
223 api_client=self.arvrunner.api,
224 keep_client=self.arvrunner.keep_client,
225 num_retries=self.arvrunner.num_retries)
226 done.logtail(logc, logger, "%s error log:" % self.arvrunner.label(self))
229 if container["output"]:
230 outputs = done.done_outputs(self, container, "/tmp", self.outdir, "/keep")
231 except WorkflowException as e:
232 logger.error("%s unable to collect output from %s:\n%s",
233 self.arvrunner.label(self), container["output"], e, exc_info=(e if self.arvrunner.debug else False))
234 processStatus = "permanentFail"
235 except Exception as e:
236 logger.exception("%s while getting output object: %s", self.arvrunner.label(self), e)
237 processStatus = "permanentFail"
239 self.output_callback(outputs, processStatus)
240 if record["uuid"] in self.arvrunner.processes:
241 del self.arvrunner.processes[record["uuid"]]
244 class RunnerContainer(Runner):
245 """Submit and manage a container that runs arvados-cwl-runner."""
247 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
248 """Create an Arvados container request for this workflow.
250 The returned dict can be used to create a container passed as
251 the +body+ argument to container_requests().create().
254 adjustDirObjs(self.job_order, trim_listing)
255 adjustFileObjs(self.job_order, trim_anonymous_location)
256 adjustDirObjs(self.job_order, trim_anonymous_location)
259 "owner_uuid": self.arvrunner.project_uuid,
261 "output_path": "/var/spool/cwl",
262 "cwd": "/var/spool/cwl",
264 "state": "Committed",
265 "container_image": arvados_jobs_image(self.arvrunner, self.jobs_image),
267 "/var/lib/cwl/cwl.input.json": {
269 "content": self.job_order
273 "path": "/var/spool/cwl/cwl.output.json"
276 "kind": "collection",
280 "runtime_constraints": {
282 "ram": 1024*1024 * self.submit_runner_ram,
288 if self.tool.tool.get("id", "").startswith("keep:"):
289 sp = self.tool.tool["id"].split('/')
290 workflowcollection = sp[0][5:]
291 workflowname = "/".join(sp[1:])
292 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
293 container_req["mounts"]["/var/lib/cwl/workflow"] = {
294 "kind": "collection",
295 "portable_data_hash": "%s" % workflowcollection
298 packed = packed_workflow(self.arvrunner, self.tool)
299 workflowpath = "/var/lib/cwl/workflow.json#main"
300 container_req["mounts"]["/var/lib/cwl/workflow.json"] = {
304 if self.tool.tool.get("id", "").startswith("arvwf:"):
305 container_req["properties"]["template_uuid"] = self.tool.tool["id"][6:33]
307 command = ["arvados-cwl-runner", "--local", "--api=containers", "--no-log-timestamps"]
309 command.append("--output-name=" + self.output_name)
310 container_req["output_name"] = self.output_name
313 command.append("--output-tags=" + self.output_tags)
315 if kwargs.get("debug"):
316 command.append("--debug")
318 if self.enable_reuse:
319 command.append("--enable-reuse")
321 command.append("--disable-reuse")
324 command.append("--on-error=" + self.on_error)
326 command.extend([workflowpath, "/var/lib/cwl/cwl.input.json"])
328 container_req["command"] = command
333 def run(self, *args, **kwargs):
334 kwargs["keepprefix"] = "keep:"
335 job_spec = self.arvados_job_spec(*args, **kwargs)
336 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
338 response = self.arvrunner.api.container_requests().create(
340 ).execute(num_retries=self.arvrunner.num_retries)
342 self.uuid = response["uuid"]
343 self.arvrunner.processes[self.uuid] = self
345 logger.info("%s submitted container %s", self.arvrunner.label(self), response["uuid"])
347 if response["state"] == "Final":
350 def done(self, record):
352 container = self.arvrunner.api.containers().get(
353 uuid=record["container_uuid"]
354 ).execute(num_retries=self.arvrunner.num_retries)
355 except Exception as e:
356 logger.exception("%s while getting runner container: %s", self.arvrunner.label(self), e)
357 self.arvrunner.output_callback({}, "permanentFail")
359 super(RunnerContainer, self).done(container)
361 if record["uuid"] in self.arvrunner.processes:
362 del self.arvrunner.processes[record["uuid"]]