8460: Move loggedDuration from keepstore to sdk pkg as stats.Duration.
[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 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"
159
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)
164                 outputs = {}
165                 processStatus = "permanentFail"
166
167             self.output_callback(outputs, processStatus)
168         finally:
169             del self.arvrunner.processes[record["uuid"]]
170
171
172 class RunnerContainer(Runner):
173     """Submit and manage a container that runs arvados-cwl-runner."""
174
175     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
176         """Create an Arvados container request for this workflow.
177
178         The returned dict can be used to create a container passed as
179         the +body+ argument to container_requests().create().
180         """
181
182         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
183
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)
190
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"
196
197         command = ["arvados-cwl-runner", "--local", "--api=containers"]
198         if self.output_name:
199             command.append("--output-name=" + self.output_name)
200
201         if self.output_tags:
202             command.append("--output-tags=" + self.output_tags)
203
204         if self.enable_reuse:
205             command.append("--enable-reuse")
206         else:
207             command.append("--disable-reuse")
208
209         command.extend([workflowpath, jobpath])
210
211         return {
212             "command": command,
213             "owner_uuid": self.arvrunner.project_uuid,
214             "name": self.name,
215             "output_path": "/var/spool/cwl",
216             "cwd": "/var/spool/cwl",
217             "priority": 1,
218             "state": "Committed",
219             "container_image": arvados_jobs_image(self.arvrunner),
220             "mounts": {
221                 "/var/lib/cwl/workflow": {
222                     "kind": "collection",
223                     "portable_data_hash": "%s" % workflowcollection
224                 },
225                 jobpath: {
226                     "kind": "collection",
227                     "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
228                 },
229                 "stdout": {
230                     "kind": "file",
231                     "path": "/var/spool/cwl/cwl.output.json"
232                 },
233                 "/var/spool/cwl": {
234                     "kind": "collection",
235                     "writable": True
236                 }
237             },
238             "runtime_constraints": {
239                 "vcpus": 1,
240                 "ram": 1024*1024*256,
241                 "API": True
242             }
243         }
244
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)
249
250         response = self.arvrunner.api.container_requests().create(
251             body=job_spec
252         ).execute(num_retries=self.arvrunner.num_retries)
253
254         self.uuid = response["uuid"]
255         self.arvrunner.processes[response["container_uuid"]] = self
256
257         logger.info("Submitted container %s", response["uuid"])
258
259         if response["state"] in ("Complete", "Failed", "Cancelled"):
260             self.done(response)