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