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