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