5 from cwltool.errors import WorkflowException
6 from cwltool.process import get_feature, UnsupportedRequirement, shortname
7 from cwltool.pathmapper import adjustFiles
8 from cwltool.utils import aslist
10 import arvados.collection
12 from .arvdocker import arv_docker_get_image
14 from .runner import Runner, arvados_jobs_image
16 logger = logging.getLogger('arvados.cwl-runner')
18 class ArvadosContainer(object):
19 """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
21 def __init__(self, runner):
22 self.arvrunner = runner
26 def update_pipeline_component(self, r):
29 def run(self, dry_run=False, pull_image=True, **kwargs):
31 "command": self.command_line,
32 "owner_uuid": self.arvrunner.project_uuid,
34 "output_path": self.outdir,
39 runtime_constraints = {}
45 scheduling_parameters = {}
48 for f in self.pathmapper.files():
49 _, p, tp = self.pathmapper.mapper(f)
50 if tp == "Directory" and '/' not in p[6:]:
53 "portable_data_hash": p[6:]
56 for f in self.pathmapper.files():
57 _, p, tp = self.pathmapper.mapper(f)
58 if p[6:].split("/")[0] not in dirs:
61 "portable_data_hash": p[6:]
64 if self.generatefiles["listing"]:
65 raise UnsupportedRequirement("Generate files not supported")
67 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
69 container_request["environment"].update(self.environment)
72 raise UnsupportedRequirement("Stdin redirection currently not suppported")
75 raise UnsupportedRequirement("Stderr redirection currently not suppported")
78 mounts["stdout"] = {"kind": "file",
79 "path": "%s/%s" % (self.outdir, self.stdout)}
81 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
83 docker_req = {"dockerImageId": arvados_jobs_image(self.arvrunner)}
85 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
88 self.arvrunner.project_uuid)
90 resources = self.builder.resources
91 if resources is not None:
92 runtime_constraints["vcpus"] = resources.get("cores", 1)
93 runtime_constraints["ram"] = resources.get("ram") * 2**20
95 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
97 runtime_constraints["API"] = True
99 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
101 if "keep_cache" in runtime_req:
102 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"]
104 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
106 scheduling_parameters["partitions"] = aslist(partition_req["partition"])
108 container_request["mounts"] = mounts
109 container_request["runtime_constraints"] = runtime_constraints
110 container_request["use_existing"] = kwargs.get("enable_reuse", True)
111 container_request["scheduling_parameters"] = scheduling_parameters
114 response = self.arvrunner.api.container_requests().create(
115 body=container_request
116 ).execute(num_retries=self.arvrunner.num_retries)
118 self.arvrunner.processes[response["container_uuid"]] = self
120 container = self.arvrunner.api.containers().get(
121 uuid=response["container_uuid"]
122 ).execute(num_retries=self.arvrunner.num_retries)
124 logger.info("Container request %s (%s) state is %s with container %s %s", self.name, response["uuid"], response["state"], container["uuid"], container["state"])
126 if container["state"] in ("Complete", "Cancelled"):
128 except Exception as e:
129 logger.error("Got error %s" % str(e))
130 self.output_callback({}, "permanentFail")
132 def done(self, record):
134 if record["state"] == "Complete":
135 rcode = record["exit_code"]
136 if self.successCodes and rcode in self.successCodes:
137 processStatus = "success"
138 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
139 processStatus = "temporaryFail"
140 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
141 processStatus = "permanentFail"
143 processStatus = "success"
145 processStatus = "permanentFail"
147 processStatus = "permanentFail"
152 outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
153 except WorkflowException as e:
154 logger.error("Error while collecting output for container %s:\n%s", self.name, e, exc_info=(e if self.arvrunner.debug else False))
155 processStatus = "permanentFail"
156 except Exception as e:
157 logger.exception("Got unknown exception while collecting output for container %s:", self.name)
158 processStatus = "permanentFail"
160 # Note: Currently, on error output_callback is expecting an empty dict,
161 # anything else will fail.
162 if not isinstance(outputs, dict):
163 logger.error("Unexpected output type %s '%s'", type(outputs), outputs)
165 processStatus = "permanentFail"
167 self.output_callback(outputs, processStatus)
169 del self.arvrunner.processes[record["uuid"]]
172 class RunnerContainer(Runner):
173 """Submit and manage a container that runs arvados-cwl-runner."""
175 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
176 """Create an Arvados container request for this workflow.
178 The returned dict can be used to create a container passed as
179 the +body+ argument to container_requests().create().
182 workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
184 with arvados.collection.Collection(api_client=self.arvrunner.api,
185 keep_client=self.arvrunner.keep_client,
186 num_retries=self.arvrunner.num_retries) as jobobj:
187 with jobobj.open("cwl.input.json", "w") as f:
188 json.dump(self.job_order, f, sort_keys=True, indent=4)
189 jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
191 workflowname = os.path.basename(self.tool.tool["id"])
192 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
193 workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
194 workflowcollection = workflowcollection[5:workflowcollection.index('/')]
195 jobpath = "/var/lib/cwl/job/cwl.input.json"
197 command = ["arvados-cwl-runner", "--local", "--api=containers"]
199 command.append("--output-name=" + self.output_name)
202 command.append("--output-tags=" + self.output_tags)
204 if self.enable_reuse:
205 command.append("--enable-reuse")
207 command.append("--disable-reuse")
209 command.extend([workflowpath, jobpath])
213 "owner_uuid": self.arvrunner.project_uuid,
215 "output_path": "/var/spool/cwl",
216 "cwd": "/var/spool/cwl",
218 "state": "Committed",
219 "container_image": arvados_jobs_image(self.arvrunner),
221 "/var/lib/cwl/workflow": {
222 "kind": "collection",
223 "portable_data_hash": "%s" % workflowcollection
226 "kind": "collection",
227 "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
231 "path": "/var/spool/cwl/cwl.output.json"
234 "kind": "collection",
238 "runtime_constraints": {
240 "ram": 1024*1024*256,
245 def run(self, *args, **kwargs):
246 kwargs["keepprefix"] = "keep:"
247 job_spec = self.arvados_job_spec(*args, **kwargs)
248 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
250 response = self.arvrunner.api.container_requests().create(
252 ).execute(num_retries=self.arvrunner.num_retries)
254 self.uuid = response["uuid"]
255 self.arvrunner.processes[response["container_uuid"]] = self
257 logger.info("Submitted container %s", response["uuid"])
259 if response["state"] in ("Complete", "Failed", "Cancelled"):