10812: Handle workflow keep references.
[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             record = self.api_client.workflows().get(uuid=url[6:]).execute()
143             definition = record["definition"] + ('\nlabel: "%s"\n' % record["name"].replace('"', '\\"'))
144             return definition
145         return super(CollectionFetcher, self).fetch_text(url)
146
147     def check_exists(self, url):
148         if url.startswith("keep:"):
149             return self.fsaccess.exists(url)
150         if url.startswith("arvwf:"):
151             if self.fetch_text(url):
152                 return True
153         return super(CollectionFetcher, self).check_exists(url)
154
155     def urljoin(self, base_url, url):
156         if not url:
157             return base_url
158
159         urlsp = urlparse.urlsplit(url)
160         if urlsp.scheme or not base_url:
161             return url
162
163         basesp = urlparse.urlsplit(base_url)
164         if basesp.scheme in ("keep", "arvwf"):
165             if not basesp.path:
166                 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
167
168             baseparts = basesp.path.split("/")
169             urlparts = urlsp.path.split("/") if urlsp.path else []
170
171             pdh = baseparts.pop(0)
172
173             if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
174                 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
175
176             if urlsp.path.startswith("/"):
177                 baseparts = []
178                 urlparts.pop(0)
179
180             if baseparts and urlsp.path:
181                 baseparts.pop()
182
183             path = "/".join([pdh] + baseparts + urlparts)
184             return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
185
186         return super(CollectionFetcher, self).urljoin(base_url, url)
187
188 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
189 pipeline_template_uuid_pattern = re.compile(r'[a-z0-9]{5}-p5p6p-[a-z0-9]{15}')
190
191 def collectionResolver(api_client, document_loader, uri):
192     if workflow_uuid_pattern.match(uri):
193         return "arvwf:%s#main" % (uri)
194
195     if pipeline_template_uuid_pattern.match(uri):
196         pt = api_client.pipeline_templates().get(uuid=uri).execute()
197         return "keep:" + pt["components"].values()[0]["script_parameters"]["cwl:tool"]
198
199     p = uri.split("/")
200     if arvados.util.keep_locator_pattern.match(p[0]):
201         return "keep:%s" % (uri)
202
203     if arvados.util.collection_uuid_pattern.match(p[0]):
204         return "keep:%s%s" % (api_client.collections().
205                               get(uuid=p[0]).execute()["portable_data_hash"],
206                               uri[len(p[0]):])
207
208     return cwltool.resolver.tool_resolver(document_loader, uri)