11308: Merge branch 'master' into 11308-python3
[arvados.git] / sdk / cwl / arvados_cwl / pathmapper.py
1 import re
2 import logging
3 import uuid
4 import os
5 import urllib
6
7 import arvados.commands.run
8 import arvados.collection
9
10 from schema_salad.sourceline import SourceLine
11
12 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
13 from cwltool.workflow import WorkflowException
14
15 logger = logging.getLogger('arvados.cwl-runner')
16
17 class ArvPathMapper(PathMapper):
18     """Convert container-local paths to and from Keep collection ids."""
19
20     pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
21     pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.*)?$')
22
23     def __init__(self, arvrunner, referenced_files, input_basedir,
24                  collection_pattern, file_pattern, name=None, **kwargs):
25         self.arvrunner = arvrunner
26         self.input_basedir = input_basedir
27         self.collection_pattern = collection_pattern
28         self.file_pattern = file_pattern
29         self.name = name
30         super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
31
32     def visit(self, srcobj, uploadfiles):
33         src = srcobj["location"]
34         if "#" in src:
35             src = src[:src.index("#")]
36
37         if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
38             self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), srcobj["class"], True)
39
40         if src not in self._pathmap:
41             if src.startswith("file:"):
42                 # Local FS ref, may need to be uploaded or may be on keep
43                 # mount.
44                 ab = abspath(src, self.input_basedir)
45                 st = arvados.commands.run.statfile("", ab,
46                                                    fnPattern="keep:%s/%s",
47                                                    dirPattern="keep:%s/%s")
48                 with SourceLine(srcobj, "location", WorkflowException):
49                     if isinstance(st, arvados.commands.run.UploadFile):
50                         uploadfiles.add((src, ab, st))
51                     elif isinstance(st, arvados.commands.run.ArvFile):
52                         self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % urllib.unquote(st.fn[5:]), "File", True)
53                     else:
54                         raise WorkflowException("Input file path '%s' is invalid" % st)
55             elif src.startswith("_:"):
56                 if srcobj["class"] == "File" and "contents" not in srcobj:
57                     raise WorkflowException("File literal '%s' is missing `contents`" % src)
58                 if srcobj["class"] == "Directory" and "listing" not in srcobj:
59                     raise WorkflowException("Directory literal '%s' is missing `listing`" % src)
60             else:
61                 self._pathmap[src] = MapperEnt(src, src, srcobj["class"], True)
62
63         with SourceLine(srcobj, "secondaryFiles", WorkflowException):
64             for l in srcobj.get("secondaryFiles", []):
65                 self.visit(l, uploadfiles)
66         with SourceLine(srcobj, "listing", WorkflowException):
67             for l in srcobj.get("listing", []):
68                 self.visit(l, uploadfiles)
69
70     def addentry(self, obj, c, path, subdirs):
71         if obj["location"] in self._pathmap:
72             src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
73             if srcpath == "":
74                 srcpath = "."
75             c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
76             for l in obj.get("secondaryFiles", []):
77                 self.addentry(l, c, path, subdirs)
78         elif obj["class"] == "Directory":
79             for l in obj.get("listing", []):
80                 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
81             subdirs.append((obj["location"], path + "/" + obj["basename"]))
82         elif obj["location"].startswith("_:") and "contents" in obj:
83             with c.open(path + "/" + obj["basename"], "w") as f:
84                 f.write(obj["contents"].encode("utf-8"))
85         else:
86             raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
87
88     def setup(self, referenced_files, basedir):
89         # type: (List[Any], unicode) -> None
90         uploadfiles = set()
91
92         already_uploaded = self.arvrunner.get_uploaded()
93         for k in referenced_files:
94             loc = k["location"]
95             if loc in already_uploaded:
96                 v = already_uploaded[loc]
97                 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % urllib.unquote(v.resolved[5:]), "File", True)
98
99         for srcobj in referenced_files:
100             self.visit(srcobj, uploadfiles)
101
102         if uploadfiles:
103             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
104                                              self.arvrunner.api,
105                                              dry_run=False,
106                                              num_retries=self.arvrunner.num_retries,
107                                              fnPattern="keep:%s/%s",
108                                              name=self.name,
109                                              project=self.arvrunner.project_uuid)
110
111         for src, ab, st in uploadfiles:
112             self._pathmap[src] = MapperEnt(urllib.quote(st.fn, "/:+@"), self.collection_pattern % st.fn[5:],
113                                            "Directory" if os.path.isdir(ab) else "File", True)
114             self.arvrunner.add_uploaded(src, self._pathmap[src])
115
116         for srcobj in referenced_files:
117             subdirs = []
118             if srcobj["class"] == "Directory":
119                 if srcobj["location"] not in self._pathmap:
120                     c = arvados.collection.Collection(api_client=self.arvrunner.api,
121                                                       keep_client=self.arvrunner.keep_client,
122                                                       num_retries=self.arvrunner.num_retries)
123                     for l in srcobj.get("listing", []):
124                         self.addentry(l, c, ".", subdirs)
125
126                     check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
127                     if not check["items"]:
128                         c.save_new(owner_uuid=self.arvrunner.project_uuid)
129
130                     ab = self.collection_pattern % c.portable_data_hash()
131                     self._pathmap[srcobj["location"]] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
132             elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
133                 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
134
135                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
136                                                   keep_client=self.arvrunner.keep_client,
137                                                   num_retries=self.arvrunner.num_retries                                                  )
138                 self.addentry(srcobj, c, ".", subdirs)
139
140                 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
141                 if not check["items"]:
142                     c.save_new(owner_uuid=self.arvrunner.project_uuid)
143
144                 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
145                 self._pathmap[srcobj["location"]] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), srcobj["basename"]),
146                                                               ab, "File", True)
147                 if srcobj.get("secondaryFiles"):
148                     ab = self.collection_pattern % c.portable_data_hash()
149                     self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
150
151             if subdirs:
152                 for loc, sub in subdirs:
153                     # subdirs will all start with "./", strip it off
154                     ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
155                     self._pathmap[loc] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), sub[2:]),
156                                                    ab, "Directory", True)
157
158         self.keepdir = None
159
160     def reversemap(self, target):
161         if target.startswith("keep:"):
162             return (target, target)
163         elif self.keepdir and target.startswith(self.keepdir):
164             return (target, "keep:" + target[len(self.keepdir)+1:])
165         else:
166             return super(ArvPathMapper, self).reversemap(target)
167
168 class StagingPathMapper(PathMapper):
169     _follow_dirs = True
170
171     def visit(self, obj, stagedir, basedir, copy=False, staged=False):
172         # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
173         loc = obj["location"]
174         tgt = os.path.join(stagedir, obj["basename"])
175         if obj["class"] == "Directory":
176             self._pathmap[loc] = MapperEnt(loc, tgt, "Directory", staged)
177             if loc.startswith("_:") or self._follow_dirs:
178                 self.visitlisting(obj.get("listing", []), tgt, basedir)
179         elif obj["class"] == "File":
180             if loc in self._pathmap:
181                 return
182             if "contents" in obj and loc.startswith("_:"):
183                 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile", staged)
184             else:
185                 if copy:
186                     self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile", staged)
187                 else:
188                     self._pathmap[loc] = MapperEnt(loc, tgt, "File", staged)
189                 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
190
191
192 class VwdPathMapper(StagingPathMapper):
193     def setup(self, referenced_files, basedir):
194         # type: (List[Any], unicode) -> None
195
196         # Go through each file and set the target to its own directory along
197         # with any secondary files.
198         self.visitlisting(referenced_files, self.stagedir, basedir)
199
200         for path, (ab, tgt, type, staged) in self._pathmap.items():
201             if type in ("File", "Directory") and ab.startswith("keep:"):
202                 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type, staged)
203
204
205 class NoFollowPathMapper(StagingPathMapper):
206     _follow_dirs = False
207     def setup(self, referenced_files, basedir):
208         # type: (List[Any], unicode) -> None
209         self.visitlisting(referenced_files, self.stagedir, basedir)