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