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 srcobj["class"] == "File":
35             if "#" in src:
36                 src = src[:src.index("#")]
37             if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
38                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), "File")
39             if src not in self._pathmap:
40                 # Local FS ref, may need to be uploaded or may be on keep
41                 # mount.
42                 ab = abspath(src, self.input_basedir)
43                 st = arvados.commands.run.statfile("", ab, fnPattern="keep:%s/%s")
44                 with SourceLine(srcobj, "location", WorkflowException):
45                     if isinstance(st, arvados.commands.run.UploadFile):
46                         uploadfiles.add((src, ab, st))
47                     elif isinstance(st, arvados.commands.run.ArvFile):
48                         self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % urllib.unquote(st.fn[5:]), "File")
49                     elif src.startswith("_:"):
50                         if "contents" in srcobj:
51                             pass
52                         else:
53                             raise WorkflowException("File literal '%s' is missing contents" % src)
54                     elif src.startswith("arvwf:"):
55                         self._pathmap[src] = MapperEnt(src, src, "File")
56                     else:
57                         raise WorkflowException("Input file path '%s' is invalid" % st)
58             if "secondaryFiles" in srcobj:
59                 for l in srcobj["secondaryFiles"]:
60                     self.visit(l, uploadfiles)
61         elif srcobj["class"] == "Directory":
62             if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
63                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), "Directory")
64             for l in srcobj.get("listing", []):
65                 self.visit(l, uploadfiles)
66
67     def addentry(self, obj, c, path, subdirs):
68         if obj["location"] in self._pathmap:
69             src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
70             if srcpath == "":
71                 srcpath = "."
72             c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
73             for l in obj.get("secondaryFiles", []):
74                 self.addentry(l, c, path, subdirs)
75         elif obj["class"] == "Directory":
76             for l in obj["listing"]:
77                 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
78             subdirs.append((obj["location"], path + "/" + obj["basename"]))
79         elif obj["location"].startswith("_:") and "contents" in obj:
80             with c.open(path + "/" + obj["basename"], "w") as f:
81                 f.write(obj["contents"].encode("utf-8"))
82         else:
83             raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
84
85     def setup(self, referenced_files, basedir):
86         # type: (List[Any], unicode) -> None
87         uploadfiles = set()
88
89         already_uploaded = self.arvrunner.get_uploaded()
90         for k in referenced_files:
91             loc = k["location"]
92             if loc in already_uploaded:
93                 v = already_uploaded[loc]
94                 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % urllib.unquote(v.resolved[5:]), "File")
95
96         for srcobj in referenced_files:
97             self.visit(srcobj, uploadfiles)
98
99         if uploadfiles:
100             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
101                                              self.arvrunner.api,
102                                              dry_run=False,
103                                              num_retries=self.arvrunner.num_retries,
104                                              fnPattern="keep:%s/%s",
105                                              name=self.name,
106                                              project=self.arvrunner.project_uuid)
107
108         for src, ab, st in uploadfiles:
109             self._pathmap[src] = MapperEnt(urllib.quote(st.fn, "/:+@"), self.collection_pattern % st.fn[5:], "File")
110             self.arvrunner.add_uploaded(src, self._pathmap[src])
111
112         for srcobj in referenced_files:
113             if srcobj["class"] == "Directory":
114                 if srcobj["location"] not in self._pathmap:
115                     c = arvados.collection.Collection(api_client=self.arvrunner.api,
116                                                       keep_client=self.arvrunner.keep_client,
117                                                       num_retries=self.arvrunner.num_retries)
118                     subdirs = []
119                     for l in srcobj["listing"]:
120                         self.addentry(l, c, ".", subdirs)
121
122                     check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
123                     if not check["items"]:
124                         c.save_new(owner_uuid=self.arvrunner.project_uuid)
125
126                     ab = self.collection_pattern % c.portable_data_hash()
127                     self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
128                     for loc, sub in subdirs:
129                         ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
130                         self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
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                 subdirs = []
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(ab, ab, "File")
146                 if srcobj.get("secondaryFiles"):
147                     ab = self.collection_pattern % c.portable_data_hash()
148                     self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
149                 for loc, sub in subdirs:
150                     ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
151                     self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
152
153         self.keepdir = None
154
155     def reversemap(self, target):
156         if target.startswith("keep:"):
157             return (target, target)
158         elif self.keepdir and target.startswith(self.keepdir):
159             return (target, "keep:" + target[len(self.keepdir)+1:])
160         else:
161             return super(ArvPathMapper, self).reversemap(target)
162
163 class StagingPathMapper(PathMapper):
164     _follow_dirs = True
165
166     def visit(self, obj, stagedir, basedir, copy=False):
167         # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
168         loc = obj["location"]
169         tgt = os.path.join(stagedir, obj["basename"])
170         if obj["class"] == "Directory":
171             self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
172             if loc.startswith("_:") or self._follow_dirs:
173                 self.visitlisting(obj.get("listing", []), tgt, basedir)
174         elif obj["class"] == "File":
175             if loc in self._pathmap:
176                 return
177             if "contents" in obj and loc.startswith("_:"):
178                 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
179             else:
180                 if copy:
181                     self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
182                 else:
183                     self._pathmap[loc] = MapperEnt(loc, tgt, "File")
184                 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
185
186
187 class VwdPathMapper(StagingPathMapper):
188     def setup(self, referenced_files, basedir):
189         # type: (List[Any], unicode) -> None
190
191         # Go through each file and set the target to its own directory along
192         # with any secondary files.
193         self.visitlisting(referenced_files, self.stagedir, basedir)
194
195         for path, (ab, tgt, type) in self._pathmap.items():
196             if type in ("File", "Directory") and ab.startswith("keep:"):
197                 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
198
199
200 class NoFollowPathMapper(StagingPathMapper):
201     _follow_dirs = False
202     def setup(self, referenced_files, basedir):
203         # type: (List[Any], unicode) -> None
204         self.visitlisting(referenced_files, self.stagedir, basedir)