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 = {}
47 for f in self.pathmapper.files():
48 _, p, tp = self.pathmapper.mapper(f)
49 if tp == "Directory" and '/' not in p[6:]:
52 "portable_data_hash": p[6:]
55 for f in self.pathmapper.files():
56 _, p, tp = self.pathmapper.mapper(f)
57 if p[6:].split("/")[0] not in dirs:
60 "portable_data_hash": p[6:]
63 if self.generatefiles["listing"]:
64 raise UnsupportedRequirement("Generate files not supported")
66 container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
68 container_request["environment"].update(self.environment)
71 raise UnsupportedRequirement("Stdin redirection currently not suppported")
74 raise UnsupportedRequirement("Stderr redirection currently not suppported")
77 mounts["stdout"] = {"kind": "file",
78 "path": "%s/%s" % (self.outdir, self.stdout)}
80 (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
82 docker_req = {"dockerImageId": arvados_jobs_image(self.arvrunner)}
84 container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
87 self.arvrunner.project_uuid)
89 resources = self.builder.resources
90 if resources is not None:
91 runtime_constraints["vcpus"] = resources.get("cores", 1)
92 runtime_constraints["ram"] = resources.get("ram") * 2**20
94 api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
96 runtime_constraints["API"] = True
98 runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
100 if "keep_cache" in runtime_req:
101 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"]
103 partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
105 runtime_constraints["partition"] = aslist(partition_req["partition"])
107 container_request["mounts"] = mounts
108 container_request["runtime_constraints"] = runtime_constraints
109 container_request["use_existing"] = kwargs.get("enable_reuse", True)
112 response = self.arvrunner.api.container_requests().create(
113 body=container_request
114 ).execute(num_retries=self.arvrunner.num_retries)
116 self.arvrunner.processes[response["container_uuid"]] = self
118 container = self.arvrunner.api.containers().get(
119 uuid=response["container_uuid"]
120 ).execute(num_retries=self.arvrunner.num_retries)
122 logger.info("Container request %s (%s) state is %s with container %s %s", self.name, response["uuid"], response["state"], container["uuid"], container["state"])
124 if container["state"] in ("Complete", "Cancelled"):
126 except Exception as e:
127 logger.error("Got error %s" % str(e))
128 self.output_callback({}, "permanentFail")
130 def done(self, record):
132 if record["state"] == "Complete":
133 rcode = record["exit_code"]
134 if self.successCodes and rcode in self.successCodes:
135 processStatus = "success"
136 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
137 processStatus = "temporaryFail"
138 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
139 processStatus = "permanentFail"
141 processStatus = "success"
143 processStatus = "permanentFail"
145 processStatus = "permanentFail"
150 outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
151 except WorkflowException as e:
152 logger.error("Error while collecting container outputs:\n%s", e, exc_info=(e if self.arvrunner.debug else False))
153 processStatus = "permanentFail"
154 except Exception as e:
155 logger.exception("Got unknown exception while collecting job outputs:")
156 processStatus = "permanentFail"
158 self.output_callback(outputs, processStatus)
160 del self.arvrunner.processes[record["uuid"]]
163 class RunnerContainer(Runner):
164 """Submit and manage a container that runs arvados-cwl-runner."""
166 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
167 """Create an Arvados container request for this workflow.
169 The returned dict can be used to create a container passed as
170 the +body+ argument to container_requests().create().
173 workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
175 with arvados.collection.Collection(api_client=self.arvrunner.api,
176 keep_client=self.arvrunner.keep_client,
177 num_retries=self.arvrunner.num_retries) as jobobj:
178 with jobobj.open("cwl.input.json", "w") as f:
179 json.dump(self.job_order, f, sort_keys=True, indent=4)
180 jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
182 workflowname = os.path.basename(self.tool.tool["id"])
183 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
184 workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
185 workflowcollection = workflowcollection[5:workflowcollection.index('/')]
186 jobpath = "/var/lib/cwl/job/cwl.input.json"
188 command = ["arvados-cwl-runner", "--local", "--api=containers"]
190 command.append("--output-name=" + self.output_name)
192 if self.enable_reuse:
193 command.append("--enable-reuse")
195 command.append("--disable-reuse")
197 command.extend([workflowpath, jobpath])
201 "owner_uuid": self.arvrunner.project_uuid,
203 "output_path": "/var/spool/cwl",
204 "cwd": "/var/spool/cwl",
206 "state": "Committed",
207 "container_image": arvados_jobs_image(self.arvrunner),
209 "/var/lib/cwl/workflow": {
210 "kind": "collection",
211 "portable_data_hash": "%s" % workflowcollection
214 "kind": "collection",
215 "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
219 "path": "/var/spool/cwl/cwl.output.json"
222 "kind": "collection",
226 "runtime_constraints": {
228 "ram": 1024*1024*256,
233 def run(self, *args, **kwargs):
234 kwargs["keepprefix"] = "keep:"
235 job_spec = self.arvados_job_spec(*args, **kwargs)
236 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
238 response = self.arvrunner.api.container_requests().create(
240 ).execute(num_retries=self.arvrunner.num_retries)
242 self.uuid = response["uuid"]
243 self.arvrunner.processes[response["container_uuid"]] = self
245 logger.info("Submitted container %s", response["uuid"])
247 if response["state"] in ("Complete", "Failed", "Cancelled"):