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 record = self.api_client.workflows().get(uuid=url[6:]).execute()
143 definition = record["definition"] + ('\nlabel: "%s"\n' % record["name"].replace('"', '\\"'))
145 return super(CollectionFetcher, self).fetch_text(url)
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):
153 return super(CollectionFetcher, self).check_exists(url)
155 def urljoin(self, base_url, url):
159 urlsp = urlparse.urlsplit(url)
160 if urlsp.scheme or not base_url:
163 basesp = urlparse.urlsplit(base_url)
164 if basesp.scheme in ("keep", "arvwf"):
166 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
168 baseparts = basesp.path.split("/")
169 urlparts = urlsp.path.split("/") if urlsp.path else []
171 pdh = baseparts.pop(0)
173 if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
174 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
176 if urlsp.path.startswith("/"):
180 if baseparts and urlsp.path:
183 path = "/".join([pdh] + baseparts + urlparts)
184 return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
186 return super(CollectionFetcher, self).urljoin(base_url, url)
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}')
191 def collectionResolver(api_client, document_loader, uri):
192 if workflow_uuid_pattern.match(uri):
193 return "arvwf:%s#main" % (uri)
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"]
200 if arvados.util.keep_locator_pattern.match(p[0]):
201 return "keep:%s" % (uri)
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"],
208 return cwltool.resolver.tool_resolver(document_loader, uri)