7 import ruamel.yaml as yaml
9 import cwltool.stdfsaccess
10 from cwltool.pathmapper import abspath
11 import cwltool.resolver
14 import arvados.collection
15 import arvados.arvfile
17 from schema_salad.ref_resolver import DefaultFetcher
19 class CollectionFsAccess(cwltool.stdfsaccess.StdFsAccess):
20 """Implement the cwltool FsAccess interface for Arvados Collections."""
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
28 def get_collection(self, path):
30 if p[0].startswith("keep:") and arvados.util.keep_locator_pattern.match(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:]))
39 def _match(self, collection, patternsegments, parent):
40 if not patternsegments:
43 if not isinstance(collection, arvados.collection.RichCollectionBase):
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
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:
58 ret.extend(self._match(collection[filename], patternsegments[1:], cur))
61 def glob(self, pattern):
62 collection, rest = self.get_collection(pattern)
63 if collection and not rest:
65 patternsegments = rest.split("/")
66 return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
68 def open(self, fn, mode):
69 collection, rest = self.get_collection(fn)
71 return collection.open(rest, mode)
73 return super(CollectionFsAccess, self).open(self._abs(fn), mode)
76 collection, rest = self.get_collection(fn)
78 return collection.exists(rest)
80 return super(CollectionFsAccess, self).exists(fn)
82 def isfile(self, fn): # type: (unicode) -> bool
83 collection, rest = self.get_collection(fn)
86 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
90 return super(CollectionFsAccess, self).isfile(fn)
92 def isdir(self, fn): # type: (unicode) -> bool
93 collection, rest = self.get_collection(fn)
96 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
100 return super(CollectionFsAccess, self).isdir(fn)
102 def listdir(self, fn): # type: (unicode) -> List[unicode]
103 collection, rest = self.get_collection(fn)
106 dir = collection.find(rest)
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()]
115 return super(CollectionFsAccess, self).listdir(fn)
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:]):
120 return os.path.join(path, *paths)
122 def realpath(self, path):
123 if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
125 collection, rest = self.get_collection(path)
129 return os.path.realpath(path)
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)
137 def fetch_text(self, url):
138 if url.startswith("keep:"):
139 with self.fsaccess.open(url, "r") as f:
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)
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):
151 return super(CollectionFetcher, self).check_exists(url)
153 def urljoin(self, base_url, url):
157 urlsp = urlparse.urlsplit(url)
158 if urlsp.scheme or not base_url:
161 basesp = urlparse.urlsplit(base_url)
162 if basesp.scheme in ("keep", "arvwf"):
164 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
166 baseparts = basesp.path.split("/")
167 urlparts = urlsp.path.split("/") if urlsp.path else []
169 pdh = baseparts.pop(0)
171 if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
172 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
174 if urlsp.path.startswith("/"):
178 if baseparts and urlsp.path:
181 path = "/".join([pdh] + baseparts + urlparts)
182 return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
184 return super(CollectionFetcher, self).urljoin(base_url, url)
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}')
189 def collectionResolver(api_client, document_loader, uri):
190 if workflow_uuid_pattern.match(uri):
191 return "arvwf:%s#main" % (uri)
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"]
198 if arvados.util.keep_locator_pattern.match(p[0]):
199 return "keep:%s" % (uri)
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"],
206 return cwltool.resolver.tool_resolver(document_loader, uri)