Merge master to output-tags branch and resolve conflict
[arvados.git] / sdk / cwl / arvados_cwl / arvcontainer.py
1 import logging
2 import json
3 import os
4
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
9
10 import arvados.collection
11
12 from .arvdocker import arv_docker_get_image
13 from . import done
14 from .runner import Runner, arvados_jobs_image
15
16 logger = logging.getLogger('arvados.cwl-runner')
17
18 class ArvadosContainer(object):
19     """Submit and manage a Crunch container request for executing a CWL CommandLineTool."""
20
21     def __init__(self, runner):
22         self.arvrunner = runner
23         self.running = False
24         self.uuid = None
25
26     def update_pipeline_component(self, r):
27         pass
28
29     def run(self, dry_run=False, pull_image=True, **kwargs):
30         container_request = {
31             "command": self.command_line,
32             "owner_uuid": self.arvrunner.project_uuid,
33             "name": self.name,
34             "output_path": self.outdir,
35             "cwd": self.outdir,
36             "priority": 1,
37             "state": "Committed"
38         }
39         runtime_constraints = {}
40         mounts = {
41             self.outdir: {
42                 "kind": "tmp"
43             }
44         }
45         scheduling_parameters = {}
46
47         dirs = set()
48         for f in self.pathmapper.files():
49             _, p, tp = self.pathmapper.mapper(f)
50             if tp == "Directory" and '/' not in p[6:]:
51                 mounts[p] = {
52                     "kind": "collection",
53                     "portable_data_hash": p[6:]
54                 }
55                 dirs.add(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:
59                 mounts[p] = {
60                     "kind": "collection",
61                     "portable_data_hash": p[6:]
62                 }
63
64         if self.generatefiles["listing"]:
65             raise UnsupportedRequirement("Generate files not supported")
66
67         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
68         if self.environment:
69             container_request["environment"].update(self.environment)
70
71         if self.stdin:
72             raise UnsupportedRequirement("Stdin redirection currently not suppported")
73
74         if self.stderr:
75             raise UnsupportedRequirement("Stderr redirection currently not suppported")
76
77         if self.stdout:
78             mounts["stdout"] = {"kind": "file",
79                                 "path": "%s/%s" % (self.outdir, self.stdout)}
80
81         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
82         if not docker_req:
83             docker_req = {"dockerImageId": arvados_jobs_image(self.arvrunner)}
84
85         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
86                                                                      docker_req,
87                                                                      pull_image,
88                                                                      self.arvrunner.project_uuid)
89
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
94
95         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
96         if api_req:
97             runtime_constraints["API"] = True
98
99         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
100         if runtime_req:
101             if "keep_cache" in runtime_req:
102                 runtime_constraints["keep_cache_ram"] = runtime_req["keep_cache"]
103
104         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
105         if partition_req:
106             scheduling_parameters["partitions"] = aslist(partition_req["partition"])
107
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
112
113         try:
114             response = self.arvrunner.api.container_requests().create(
115                 body=container_request
116             ).execute(num_retries=self.arvrunner.num_retries)
117
118             self.arvrunner.processes[response["container_uuid"]] = self
119
120             container = self.arvrunner.api.containers().get(
121                 uuid=response["container_uuid"]
122             ).execute(num_retries=self.arvrunner.num_retries)
123
124             logger.info("Container request %s (%s) state is %s with container %s %s", self.name, response["uuid"], response["state"], container["uuid"], container["state"])
125
126             if container["state"] in ("Complete", "Cancelled"):
127                 self.done(container)
128         except Exception as e:
129             logger.error("Got error %s" % str(e))
130             self.output_callback({}, "permanentFail")
131
132     def done(self, record):
133         try:
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"
142                 elif rcode == 0:
143                     processStatus = "success"
144                 else:
145                     processStatus = "permanentFail"
146             else:
147                 processStatus = "permanentFail"
148
149             try:
150                 outputs = {}
151                 if record["output"]:
152                     outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
153             except WorkflowException as e:
154                 logger.error("Error while collecting container outputs:\n%s", 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 job outputs:")
158                 processStatus = "permanentFail"
159
160             self.output_callback(outputs, processStatus)
161         finally:
162             del self.arvrunner.processes[record["uuid"]]
163
164
165 class RunnerContainer(Runner):
166     """Submit and manage a container that runs arvados-cwl-runner."""
167
168     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
169         """Create an Arvados container request for this workflow.
170
171         The returned dict can be used to create a container passed as
172         the +body+ argument to container_requests().create().
173         """
174
175         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
176
177         with arvados.collection.Collection(api_client=self.arvrunner.api,
178                                            keep_client=self.arvrunner.keep_client,
179                                            num_retries=self.arvrunner.num_retries) as jobobj:
180             with jobobj.open("cwl.input.json", "w") as f:
181                 json.dump(self.job_order, f, sort_keys=True, indent=4)
182             jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
183
184         workflowname = os.path.basename(self.tool.tool["id"])
185         workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
186         workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
187         workflowcollection = workflowcollection[5:workflowcollection.index('/')]
188         jobpath = "/var/lib/cwl/job/cwl.input.json"
189
190         command = ["arvados-cwl-runner", "--local", "--api=containers"]
191         if self.output_name:
192             command.append("--output-name=" + self.output_name)
193
194         if self.output_tags:
195             command.append("--output-tags=" + self.output_tags)
196
197         if self.enable_reuse:
198             command.append("--enable-reuse")
199         else:
200             command.append("--disable-reuse")
201
202         command.extend([workflowpath, jobpath])
203
204         return {
205             "command": command,
206             "owner_uuid": self.arvrunner.project_uuid,
207             "name": self.name,
208             "output_path": "/var/spool/cwl",
209             "cwd": "/var/spool/cwl",
210             "priority": 1,
211             "state": "Committed",
212             "container_image": arvados_jobs_image(self.arvrunner),
213             "mounts": {
214                 "/var/lib/cwl/workflow": {
215                     "kind": "collection",
216                     "portable_data_hash": "%s" % workflowcollection
217                 },
218                 jobpath: {
219                     "kind": "collection",
220                     "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
221                 },
222                 "stdout": {
223                     "kind": "file",
224                     "path": "/var/spool/cwl/cwl.output.json"
225                 },
226                 "/var/spool/cwl": {
227                     "kind": "collection",
228                     "writable": True
229                 }
230             },
231             "runtime_constraints": {
232                 "vcpus": 1,
233                 "ram": 1024*1024*256,
234                 "API": True
235             }
236         }
237
238     def run(self, *args, **kwargs):
239         kwargs["keepprefix"] = "keep:"
240         job_spec = self.arvados_job_spec(*args, **kwargs)
241         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
242
243         response = self.arvrunner.api.container_requests().create(
244             body=job_spec
245         ).execute(num_retries=self.arvrunner.num_retries)
246
247         self.uuid = response["uuid"]
248         self.arvrunner.processes[response["container_uuid"]] = self
249
250         logger.info("Submitted container %s", response["uuid"])
251
252         if response["state"] in ("Complete", "Failed", "Cancelled"):
253             self.done(response)