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