10576: Add resolver to execute from keep references and arvados workflow
[arvados.git] / sdk / cwl / arvados_cwl / fsaccess.py
1 import fnmatch
2 import os
3 import errno
4 import urlparse
5 import re
6
7 import cwltool.stdfsaccess
8 from cwltool.pathmapper import abspath
9 import cwltool.resolver
10
11 import arvados.util
12 import arvados.collection
13 import arvados.arvfile
14
15 from schema_salad.ref_resolver import DefaultFetcher
16
17 class CollectionFsAccess(cwltool.stdfsaccess.StdFsAccess):
18     """Implement the cwltool FsAccess interface for Arvados Collections."""
19
20     def __init__(self, basedir, api_client=None, keep_client=None):
21         super(CollectionFsAccess, self).__init__(basedir)
22         self.api_client = api_client
23         self.keep_client = keep_client
24         self.collections = {}
25
26     def get_collection(self, path):
27         p = path.split("/")
28         if p[0].startswith("keep:") and arvados.util.keep_locator_pattern.match(p[0][5:]):
29             pdh = p[0][5:]
30             if pdh not in self.collections:
31                 self.collections[pdh] = arvados.collection.CollectionReader(pdh, api_client=self.api_client,
32                                                                             keep_client=self.keep_client)
33             return (self.collections[pdh], "/".join(p[1:]))
34         else:
35             return (None, path)
36
37     def _match(self, collection, patternsegments, parent):
38         if not patternsegments:
39             return []
40
41         if not isinstance(collection, arvados.collection.RichCollectionBase):
42             return []
43
44         ret = []
45         # iterate over the files and subcollections in 'collection'
46         for filename in collection:
47             if patternsegments[0] == '.':
48                 # Pattern contains something like "./foo" so just shift
49                 # past the "./"
50                 ret.extend(self._match(collection, patternsegments[1:], parent))
51             elif fnmatch.fnmatch(filename, patternsegments[0]):
52                 cur = os.path.join(parent, filename)
53                 if len(patternsegments) == 1:
54                     ret.append(cur)
55                 else:
56                     ret.extend(self._match(collection[filename], patternsegments[1:], cur))
57         return ret
58
59     def glob(self, pattern):
60         collection, rest = self.get_collection(pattern)
61         if collection and not rest:
62             return [pattern]
63         patternsegments = rest.split("/")
64         return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
65
66     def open(self, fn, mode):
67         collection, rest = self.get_collection(fn)
68         if collection:
69             return collection.open(rest, mode)
70         else:
71             return super(CollectionFsAccess, self).open(self._abs(fn), mode)
72
73     def exists(self, fn):
74         collection, rest = self.get_collection(fn)
75         if collection:
76             return collection.exists(rest)
77         else:
78             return super(CollectionFsAccess, self).exists(fn)
79
80     def isfile(self, fn):  # type: (unicode) -> bool
81         collection, rest = self.get_collection(fn)
82         if collection:
83             if rest:
84                 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
85             else:
86                 return False
87         else:
88             return super(CollectionFsAccess, self).isfile(fn)
89
90     def isdir(self, fn):  # type: (unicode) -> bool
91         collection, rest = self.get_collection(fn)
92         if collection:
93             if rest:
94                 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
95             else:
96                 return True
97         else:
98             return super(CollectionFsAccess, self).isdir(fn)
99
100     def listdir(self, fn):  # type: (unicode) -> List[unicode]
101         collection, rest = self.get_collection(fn)
102         if collection:
103             if rest:
104                 dir = collection.find(rest)
105             else:
106                 dir = collection
107             if dir is None:
108                 raise IOError(errno.ENOENT, "Directory '%s' in '%s' not found" % (rest, collection.portable_data_hash()))
109             if not isinstance(dir, arvados.collection.RichCollectionBase):
110                 raise IOError(errno.ENOENT, "Path '%s' in '%s' is not a Directory" % (rest, collection.portable_data_hash()))
111             return [abspath(l, fn) for l in dir.keys()]
112         else:
113             return super(CollectionFsAccess, self).listdir(fn)
114
115     def join(self, path, *paths): # type: (unicode, *unicode) -> unicode
116         if paths and paths[-1].startswith("keep:") and arvados.util.keep_locator_pattern.match(paths[-1][5:]):
117             return paths[-1]
118         return os.path.join(path, *paths)
119
120     def realpath(self, path):
121         if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
122             return path
123         collection, rest = self.get_collection(path)
124         if collection:
125             return path
126         else:
127             return os.path.realpath(path)
128
129 class CollectionFetcher(DefaultFetcher):
130     def __init__(self, cache, session, api_client=None, keep_client=None):
131         super(CollectionFetcher, self).__init__(cache, session)
132         self.api_client = api_client
133         self.fsaccess = CollectionFsAccess("", api_client=api_client, keep_client=keep_client)
134
135     def fetch_text(self, url):
136         if url.startswith("keep:"):
137             with self.fsaccess.open(url) as f:
138                 return f.read()
139         if url.startswith("arv:"):
140             return self.api_client.workflows().get(uuid=url[4:]).execute()["definition"]
141         return super(CollectionFetcher, self).fetch_text(url)
142
143     def check_exists(self, url):
144         if url.startswith("keep:"):
145             return self.fsaccess.exists(url)
146         if url.startswith("arv:"):
147             if self.fetch_text(url):
148                 return True
149         return super(CollectionFetcher, self).check_exists(url)
150
151     def urljoin(self, base_url, url):
152         if not url:
153             return base_url
154
155         urlsp = urlparse.urlsplit(url)
156         if urlsp.scheme or not base_url:
157             return url
158
159         basesp = urlparse.urlsplit(base_url)
160         if basesp.scheme == "keep":
161             if not basesp.path:
162                 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
163
164             baseparts = basesp.path.split("/")
165             urlparts = urlsp.path.split("/") if urlsp.path else []
166
167             pdh = baseparts.pop(0)
168
169             if not arvados.util.keep_locator_pattern.match(pdh):
170                 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
171
172             if urlsp.path.startswith("/"):
173                 baseparts = []
174                 urlparts.pop(0)
175
176             if baseparts and urlsp.path:
177                 baseparts.pop()
178
179             path = "/".join([pdh] + baseparts + urlparts)
180             return urlparse.urlunsplit(("keep", "", path, "", urlsp.fragment))
181
182         return super(CollectionFetcher, self).urljoin(base_url, url)
183
184 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
185
186 def collectionResolver(api_client, document_loader, uri):
187     if workflow_uuid_pattern.match(uri):
188         return "arv:%s" % uri
189
190     p = uri.split("/")
191     if arvados.util.keep_locator_pattern.match(p[0]):
192         return "keep:" + uri
193
194     if arvados.util.collection_uuid_pattern.match(p[0]):
195         return "keep:%s%s" % (self.api_client.collections().
196                               get(uuid=uri).execute()["portable_data_hash"],
197                               uri[len(p[0]):])
198
199     return cwltool.resolver.tool_resolver(document_loader, uri)