]> git.arvados.org - arvados.git/blob - sdk/cwl/arvados_cwl/arvcontainer.py
10259: Workaround for spurious "job_order" on command line. --no-wait returns
[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
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
46         dirs = set()
47         for f in self.pathmapper.files():
48             _, p, tp = self.pathmapper.mapper(f)
49             if tp == "Directory" and '/' not in p[6:]:
50                 mounts[p] = {
51                     "kind": "collection",
52                     "portable_data_hash": p[6:]
53                 }
54                 dirs.add(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:
58                 mounts[p] = {
59                     "kind": "collection",
60                     "portable_data_hash": p[6:]
61                 }
62
63         if self.generatefiles["listing"]:
64             raise UnsupportedRequirement("Generate files not supported")
65
66         container_request["environment"] = {"TMPDIR": self.tmpdir, "HOME": self.outdir}
67         if self.environment:
68             container_request["environment"].update(self.environment)
69
70         if self.stdin:
71             raise UnsupportedRequirement("Stdin redirection currently not suppported")
72
73         if self.stderr:
74             raise UnsupportedRequirement("Stderr redirection currently not suppported")
75
76         if self.stdout:
77             mounts["stdout"] = {"kind": "file",
78                                 "path": "%s/%s" % (self.outdir, self.stdout)}
79
80         (docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
81         if not docker_req:
82             docker_req = {"dockerImageId": "arvados/jobs"}
83
84         container_request["container_image"] = arv_docker_get_image(self.arvrunner.api,
85                                                                      docker_req,
86                                                                      pull_image,
87                                                                      self.arvrunner.project_uuid)
88
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
93
94         api_req, _ = get_feature(self, "http://arvados.org/cwl#APIRequirement")
95         if api_req:
96             runtime_constraints["API"] = True
97
98         runtime_req, _ = get_feature(self, "http://arvados.org/cwl#RuntimeConstraints")
99         if runtime_req:
100             logger.warn("RuntimeConstraints not yet supported by container API")
101
102         partition_req, _ = get_feature(self, "http://arvados.org/cwl#PartitionRequirement")
103         if partition_req:
104             runtime_constraints["partition"] = aslist(partition_req["partition"])
105
106         container_request["mounts"] = mounts
107         container_request["runtime_constraints"] = runtime_constraints
108
109         try:
110             response = self.arvrunner.api.container_requests().create(
111                 body=container_request
112             ).execute(num_retries=self.arvrunner.num_retries)
113
114             self.arvrunner.processes[response["container_uuid"]] = self
115
116             logger.info("Container %s (%s) request state is %s", self.name, response["uuid"], response["state"])
117
118             if response["state"] == "Final":
119                 self.done(response)
120         except Exception as e:
121             logger.error("Got error %s" % str(e))
122             self.output_callback({}, "permanentFail")
123
124     def done(self, record):
125         try:
126             if record["state"] == "Complete":
127                 rcode = record["exit_code"]
128                 if self.successCodes and rcode in self.successCodes:
129                     processStatus = "success"
130                 elif self.temporaryFailCodes and rcode in self.temporaryFailCodes:
131                     processStatus = "temporaryFail"
132                 elif self.permanentFailCodes and rcode in self.permanentFailCodes:
133                     processStatus = "permanentFail"
134                 elif rcode == 0:
135                     processStatus = "success"
136                 else:
137                     processStatus = "permanentFail"
138             else:
139                 processStatus = "permanentFail"
140
141             try:
142                 outputs = {}
143                 if record["output"]:
144                     outputs = done.done(self, record, "/tmp", self.outdir, "/keep")
145             except WorkflowException as e:
146                 logger.error("Error while collecting container outputs:\n%s", e, exc_info=(e if self.arvrunner.debug else False))
147                 processStatus = "permanentFail"
148             except Exception as e:
149                 logger.exception("Got unknown exception while collecting job outputs:")
150                 processStatus = "permanentFail"
151
152             self.output_callback(outputs, processStatus)
153         finally:
154             del self.arvrunner.processes[record["uuid"]]
155
156
157 class RunnerContainer(Runner):
158     """Submit and manage a container that runs arvados-cwl-runner."""
159
160     def arvados_job_spec(self, dry_run=False, pull_image=True, **kwargs):
161         """Create an Arvados container request for this workflow.
162
163         The returned dict can be used to create a container passed as
164         the +body+ argument to container_requests().create().
165         """
166
167         workflowmapper = super(RunnerContainer, self).arvados_job_spec(dry_run=dry_run, pull_image=pull_image, **kwargs)
168
169         with arvados.collection.Collection(api_client=self.arvrunner.api,
170                                            keep_client=self.arvrunner.keep_client,
171                                            num_retries=self.arvrunner.num_retries) as jobobj:
172             with jobobj.open("cwl.input.json", "w") as f:
173                 json.dump(self.job_order, f, sort_keys=True, indent=4)
174             jobobj.save_new(owner_uuid=self.arvrunner.project_uuid)
175
176         workflowname = os.path.basename(self.tool.tool["id"])
177         workflowpath = "/var/lib/cwl/workflow/%s" % workflowname
178         workflowcollection = workflowmapper.mapper(self.tool.tool["id"])[1]
179         workflowcollection = workflowcollection[5:workflowcollection.index('/')]
180         jobpath = "/var/lib/cwl/job/cwl.input.json"
181
182         container_image = arv_docker_get_image(self.arvrunner.api,
183                                                {"dockerImageId": "arvados/jobs"},
184                                                pull_image,
185                                                self.arvrunner.project_uuid)
186
187         command = ["arvados-cwl-runner", "--local", "--api=containers"]
188         if self.output_name:
189             command.append("--output-name=" + self.output_name)
190         command.extend([workflowpath, jobpath])
191
192         return {
193             "command": command,
194             "owner_uuid": self.arvrunner.project_uuid,
195             "name": self.name,
196             "output_path": "/var/spool/cwl",
197             "cwd": "/var/spool/cwl",
198             "priority": 1,
199             "state": "Committed",
200             "container_image": container_image,
201             "mounts": {
202                 "/var/lib/cwl/workflow": {
203                     "kind": "collection",
204                     "portable_data_hash": "%s" % workflowcollection
205                 },
206                 jobpath: {
207                     "kind": "collection",
208                     "portable_data_hash": "%s/cwl.input.json" % jobobj.portable_data_hash()
209                 },
210                 "stdout": {
211                     "kind": "file",
212                     "path": "/var/spool/cwl/cwl.output.json"
213                 },
214                 "/var/spool/cwl": {
215                     "kind": "collection",
216                     "writable": True
217                 }
218             },
219             "runtime_constraints": {
220                 "vcpus": 1,
221                 "ram": 1024*1024*256,
222                 "API": True
223             }
224         }
225
226     def run(self, *args, **kwargs):
227         kwargs["keepprefix"] = "keep:"
228         job_spec = self.arvados_job_spec(*args, **kwargs)
229         job_spec.setdefault("owner_uuid", self.arvrunner.project_uuid)
230
231         response = self.arvrunner.api.container_requests().create(
232             body=job_spec
233         ).execute(num_retries=self.arvrunner.num_retries)
234
235         self.uuid = response["uuid"]
236         self.arvrunner.processes[response["container_uuid"]] = self
237
238         logger.info("Submitted container %s", response["uuid"])
239
240         if response["state"] in ("Complete", "Failed", "Cancelled"):
241             self.done(response)