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": "/tmp"}
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 container_request["mounts"] = mounts
94 container_request["runtime_constraints"] = runtime_constraints
97 response = self.arvrunner.api.container_requests().create(
98 body=container_request
99 ).execute(num_retries=self.arvrunner.num_retries)
101 self.arvrunner.processes[response["container_uuid"]] = self
103 logger.info("Container %s (%s) request state is %s", self.name, response["uuid"], response["state"])
105 if response["state"] == "Final":
107 except Exception as e:
108 logger.error("Got error %s" % str(e))
109 self.output_callback({}, "permanentFail")
111 def done(self, record):
113 if record["state"] == "Complete":
114 rcode = record["exit_code"]
115 if self.successCodes and rcode in self.successCodes:
116 processStatus = "success"
117 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
118 processStatus = "temporaryFail"
119 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
120 processStatus = "permanentFail"
122 processStatus = "success"
124 processStatus = "permanentFail"
126 processStatus = "permanentFail"
131 outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
132 except WorkflowException as e:
133 logger.error("Error while collecting container outputs:\n%s", e, exc_info=(e if self.arvrunner.debug else False))
134 processStatus = "permanentFail"
135 except Exception as e:
136 logger.exception("Got unknown exception while collecting job outputs:")
137 processStatus = "permanentFail"
139 self.output_callback(outputs, processStatus)
141 del self.arvrunner.processes[record["uuid"]]
144 class RunnerContainer(Runner):
145 """Submit and manage a container that runs arvados-cwl-runner."""
147 def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
148 """Create an Arvados container request for this workflow.
150 The returned dict can be used to create a container passed as
151 the +body+ argument to container_requests().create().
154 workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
156 with arvados.collection.Collection(api_client=self.arvrunner.api) as jobobj:
157 with jobobj.open("cwl.input.json", "w") as f:
158 json.dump(self.job_order, f, sort_keys=True, indent=4)
159 jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
161 workflowname = os.path.basename(self.tool.tool["id"])
162 workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
163 workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
164 workflowcollection = workflowcollection[5:workflowcollection.index('/')]
165 jobpath = "/var/lib/cwl/job/cwl.input.json"
167 container_image = arv_docker_get_image(self.arvrunner.api,
168 {"dockerImageId": "arvados/jobs"},
170 self.arvrunner.project_uuid)
173 "command": ["arvados-cwl-runner", "--local", "--api=containers", workflowpath, jobpath],
174 "owner_uuid": self.arvrunner.project_uuid,
176 "output_path": "/var/spool/cwl",
177 "cwd": "/var/spool/cwl",
179 "state": "Committed",
180 "container_image": container_image,
182 "/var/lib/cwl/workflow": {
183 "kind": "collection",
184 "portable_data_hash": "%s" % workflowcollection
187 "kind": "collection",
188 "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
192 "path": "/var/spool/cwl/cwl.output.json"
195 "kind": "collection",
199 "runtime_constraints": {
201 "ram": 1024*1024*256,
206 def run(self, *args, **kwargs):
207 kwargs["keepprefix"] = "keep:"
208 job_spec = self.arvados_job_spec(*args, **kwargs)
209 job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
211 response = self.arvrunner.api.container_requests().create(
213 ).execute(num_retries=self.arvrunner.num_retries)
215 self.uuid = response["uuid"]
216 self.arvrunner.processes[response["container_uuid"]] = self
218 logger.info("Submitted container %s", response["uuid"])
220 if response["state"] in ("Complete", "Failed", "Cancelled"):