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