7 import cwltool.stdfsaccess
8 from cwltool.pathmapper import abspath
9 import cwltool.resolver
12 import arvados.collection
13 import arvados.arvfile
15 from schema_salad.ref_resolver import DefaultFetcher
17 class CollectionFsAccess(cwltool.stdfsaccess.StdFsAccess):
18 """Implement the cwltool FsAccess interface for Arvados Collections."""
20 def __init__(self, basedir, api_client=None, keep_client=None):
21 super(CollectionFsAccess, self).__init__(basedir)
22 self.api_client = api_client
23 self.keep_client = keep_client
26 def get_collection(self, path):
28 if p[0].startswith("keep:") and arvados.util.keep_locator_pattern.match(p[0][5:]):
30 if pdh not in self.collections:
31 self.collections[pdh] = arvados.collection.CollectionReader(pdh, api_client=self.api_client,
32 keep_client=self.keep_client)
33 return (self.collections[pdh], "/".join(p[1:]))
37 def _match(self, collection, patternsegments, parent):
38 if not patternsegments:
41 if not isinstance(collection, arvados.collection.RichCollectionBase):
45 # iterate over the files and subcollections in 'collection'
46 for filename in collection:
47 if patternsegments[0] == '.':
48 # Pattern contains something like "./foo" so just shift
50 ret.extend(self._match(collection, patternsegments[1:], parent))
51 elif fnmatch.fnmatch(filename, patternsegments[0]):
52 cur = os.path.join(parent, filename)
53 if len(patternsegments) == 1:
56 ret.extend(self._match(collection[filename], patternsegments[1:], cur))
59 def glob(self, pattern):
60 collection, rest = self.get_collection(pattern)
61 if collection and not rest:
63 patternsegments = rest.split("/")
64 return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
66 def open(self, fn, mode):
67 collection, rest = self.get_collection(fn)
69 return collection.open(rest, mode)
71 return super(CollectionFsAccess, self).open(self._abs(fn), mode)
74 collection, rest = self.get_collection(fn)
76 return collection.exists(rest)
78 return super(CollectionFsAccess, self).exists(fn)
80 def isfile(self, fn): # type: (unicode) -> bool
81 collection, rest = self.get_collection(fn)
84 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
88 return super(CollectionFsAccess, self).isfile(fn)
90 def isdir(self, fn): # type: (unicode) -> bool
91 collection, rest = self.get_collection(fn)
94 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
98 return super(CollectionFsAccess, self).isdir(fn)
100 def listdir(self, fn): # type: (unicode) -> List[unicode]
101 collection, rest = self.get_collection(fn)
104 dir = collection.find(rest)
108 raise IOError(errno.ENOENT, "Directory '%s' in '%s' not found" % (rest, collection.portable_data_hash()))
109 if not isinstance(dir, arvados.collection.RichCollectionBase):
110 raise IOError(errno.ENOENT, "Path '%s' in '%s' is not a Directory" % (rest, collection.portable_data_hash()))
111 return [abspath(l, fn) for l in dir.keys()]
113 return super(CollectionFsAccess, self).listdir(fn)
115 def join(self, path, *paths): # type: (unicode, *unicode) -> unicode
116 if paths and paths[-1].startswith("keep:") and arvados.util.keep_locator_pattern.match(paths[-1][5:]):
118 return os.path.join(path, *paths)
120 def realpath(self, path):
121 if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
123 collection, rest = self.get_collection(path)
127 return os.path.realpath(path)
129 class CollectionFetcher(DefaultFetcher):
130 def __init__(self, cache, session, api_client=None, keep_client=None):
131 super(CollectionFetcher, self).__init__(cache, session)
132 self.api_client = api_client
133 self.fsaccess = CollectionFsAccess("", api_client=api_client, keep_client=keep_client)
135 def fetch_text(self, url):
136 if url.startswith("keep:"):
137 with self.fsaccess.open(url) as f:
139 if url.startswith("arv:"):
140 return self.api_client.workflows().get(uuid=url[4:]).execute()["definition"]
141 return super(CollectionFetcher, self).fetch_text(url)
143 def check_exists(self, url):
144 if url.startswith("keep:"):
145 return self.fsaccess.exists(url)
146 if url.startswith("arv:"):
147 if self.fetch_text(url):
149 return super(CollectionFetcher, self).check_exists(url)
151 def urljoin(self, base_url, url):
155 urlsp = urlparse.urlsplit(url)
156 if urlsp.scheme or not base_url:
159 basesp = urlparse.urlsplit(base_url)
160 if basesp.scheme == "keep":
162 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
164 baseparts = basesp.path.split("/")
165 urlparts = urlsp.path.split("/") if urlsp.path else []
167 pdh = baseparts.pop(0)
169 if not arvados.util.keep_locator_pattern.match(pdh):
170 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
172 if urlsp.path.startswith("/"):
176 if baseparts and urlsp.path:
179 path = "/".join([pdh] + baseparts + urlparts)
180 return urlparse.urlunsplit(("keep", "", path, "", urlsp.fragment))
182 return super(CollectionFetcher, self).urljoin(base_url, url)
184 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
186 def collectionResolver(api_client, document_loader, uri):
187 if workflow_uuid_pattern.match(uri):
188 return "arv:%s" % uri
191 if arvados.util.keep_locator_pattern.match(p[0]):
194 if arvados.util.collection_uuid_pattern.match(p[0]):
195 return "keep:%s%s" % (self.api_client.collections().
196 get(uuid=uri).execute()["portable_data_hash"],
199 return cwltool.resolver.tool_resolver(document_loader, uri)