5 from cwltool.errors import WorkflowException
6 from cwltool.process import get_feature, UnsupportedRequirement, shortname
7 from cwltool.pathmapper import adjustFiles
9 import arvados.collection
11 from .arvdocker import arv_docker_get_image
13 from .runner import Runner
15 logger = logging.getLogger('arvados.cwl-runner')
17 class ArvadosContainer(object):
18 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
20 def __init__(self, runner):
21 self.arvrunner = runner
25 def update_pipeline_component(self, r):
28 def run(self, dry_run=False, pull_image=True, **kwargs):
30 "command": self.command_line,
31 "owner_uuid": self.arvrunner.project_uuid,
33 "output_path": self.outdir,
38 runtime_constraints = {}
46 for f in self.pathmapper.files():
47 _, p, tp = self.pathmapper.mapper(f)
48 if tp == "Directory" and '/' not in p[6:]:
51 "portable_data_hash": p[6:]
54 for f in self.pathmapper.files():
55 _, p, tp = self.pathmapper.mapper(f)
56 if p[6:].split("/")[0] not in dirs:
59 "portable_data_hash": p[6:]
62 if self.generatefiles["listing"]:
63 raise UnsupportedRequirement("Generate files not supported")
65 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
67 container_request["environment"].update(self.environment)
70 raise UnsupportedRequirement("Stdin redirection currently not suppported")
73 raise UnsupportedRequirement("Stderr redirection currently not suppported")
76 mounts["stdout"] = {"kind": "file",
77 "path": "%s/%s" % (self.outdir, self.stdout)}
79 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
81 docker_req = {"dockerImageId": "arvados/jobs"}
83 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
86 self.arvrunner.project_uuid)
88 resources = self.builder.resources
89 if resources is not None:
90 runtime_constraints["vcpus"] = resources.get("cores", 1)
91 runtime_constraints["ram"] = resources.get("ram") * 2**20
93 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
95 runtime_constraints["API"] = True
97 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
99 logger.warn("RuntimeConstraints not yet supported by container API")
101 container_request["mounts"] = mounts
102 container_request["runtime_constraints"] = runtime_constraints
105 response = self.arvrunner.api.container_requests().create(
106 body=container_request
107 ).execute(num_retries=self.arvrunner.num_retries)
109 self.arvrunner.processes[response["container_uuid"]] = self
111 logger.info("Container %s (%s) request state is %s", self.name, response["uuid"], response["state"])
113 if response["state"] == "Final":
115 except Exception as e:
116 logger.error("Got error %s" % str(e))
117 self.output_callback({}, "permanentFail")
119 def done(self, record):
121 if record["state"] == "Complete":
122 rcode = record["exit_code"]
123 if self.successCodes and rcode in self.successCodes:
124 processStatus = "success"
125 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
126 processStatus = "temporaryFail"
127 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
128 processStatus = "permanentFail"
130 processStatus = "success"
132 processStatus = "permanentFail"
134 processStatus = "permanentFail"
139 outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
140 except WorkflowException as e:
141 logger.error("Error while collecting container outputs:\n%s", e, exc_info=(e if self.arvrunner.debug else False))
142 processStatus = "permanentFail"
143 except Exception as e:
144 logger.exception("Got unknown exception while collecting job outputs:")
145 processStatus = "permanentFail"
147 self.output_callback(outputs, processStatus)
149 del self.arvrunner.processes[record["uuid"]]
152 class RunnerContainer(Runner):
153 """Submit and manage a container that runs arvados-cwl-runner."""
155 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
156 """Create an Arvados container request for this workflow.
158 The returned dict can be used to create a container passed as
159 the +body+ argument to container_requests().create().
162 workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
164 with arvados.collection.Collection(api_client=self.arvrunner.api) as jobobj:
165 with jobobj.open("cwl.input.json", "w") as f:
166 json.dump(self.job_order, f, sort_keys=True, indent=4)
167 jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
169 workflowname = os.path.basename(self.tool.tool["id"])
170 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
171 workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
172 workflowcollection = workflowcollection[5:workflowcollection.index('/')]
173 jobpath = "/var/lib/cwl/job/cwl.input.json"
175 container_image = arv_docker_get_image(self.arvrunner.api,
176 {"dockerImageId": "arvados/jobs"},
178 self.arvrunner.project_uuid)
181 "command": ["arvados-cwl-runner", "--local", "--api=containers", workflowpath, jobpath],
182 "owner_uuid": self.arvrunner.project_uuid,
184 "output_path": "/var/spool/cwl",
185 "cwd": "/var/spool/cwl",
187 "state": "Committed",
188 "container_image": container_image,
190 "/var/lib/cwl/workflow": {
191 "kind": "collection",
192 "portable_data_hash": "%s" % workflowcollection
195 "kind": "collection",
196 "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
200 "path": "/var/spool/cwl/cwl.output.json"
203 "kind": "collection",
207 "runtime_constraints": {
209 "ram": 1024*1024*256,
214 def run(self, *args, **kwargs):
215 kwargs["keepprefix"] = "keep:"
216 job_spec = self.arvados_job_spec(*args, **kwargs)
217 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
219 response = self.arvrunner.api.container_requests().create(
221 ).execute(num_retries=self.arvrunner.num_retries)
223 self.uuid = response["uuid"]
224 self.arvrunner.processes[response["container_uuid"]] = self
226 logger.info("Submitted container %s", response["uuid"])
228 if response["state"] in ("Complete", "Failed", "Cancelled"):