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