8 import ruamel.yaml as yaml
10 import cwltool.stdfsaccess
11 from cwltool.pathmapper import abspath
12 import cwltool.resolver
15 import arvados.collection
16 import arvados.arvfile
19 from schema_salad.ref_resolver import DefaultFetcher
21 logger = logging.getLogger('arvados.cwl-runner')
23 class CollectionFsAccess(cwltool.stdfsaccess.StdFsAccess):
24 """Implement the cwltool FsAccess interface for Arvados Collections."""
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
32 def get_collection(self, path):
33 sp = path.split("/", 1)
35 if p.startswith("keep:") and arvados.util.keep_locator_pattern.match(p[5:]):
37 if pdh not in self.collections:
38 self.collections[pdh] = arvados.collection.CollectionReader(pdh, api_client=self.api_client,
39 keep_client=self.keep_client)
40 return (self.collections[pdh], sp[1] if len(sp) == 2 else None)
44 def _match(self, collection, patternsegments, parent):
45 if not patternsegments:
48 if not isinstance(collection, arvados.collection.RichCollectionBase):
52 # iterate over the files and subcollections in 'collection'
53 for filename in collection:
54 if patternsegments[0] == '.':
55 # Pattern contains something like "./foo" so just shift
57 ret.extend(self._match(collection, patternsegments[1:], parent))
58 elif fnmatch.fnmatch(filename, patternsegments[0]):
59 cur = os.path.join(parent, filename)
60 if len(patternsegments) == 1:
63 ret.extend(self._match(collection[filename], patternsegments[1:], cur))
66 def glob(self, pattern):
67 collection, rest = self.get_collection(pattern)
68 if collection and not rest:
70 patternsegments = rest.split("/")
71 return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
73 def open(self, fn, mode):
74 collection, rest = self.get_collection(fn)
76 return collection.open(rest, mode)
78 return super(CollectionFsAccess, self).open(self._abs(fn), mode)
81 collection, rest = self.get_collection(fn)
83 return collection.exists(rest)
85 return super(CollectionFsAccess, self).exists(fn)
87 def isfile(self, fn): # type: (unicode) -> bool
88 collection, rest = self.get_collection(fn)
91 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
95 return super(CollectionFsAccess, self).isfile(fn)
97 def isdir(self, fn): # type: (unicode) -> bool
98 collection, rest = self.get_collection(fn)
101 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
105 return super(CollectionFsAccess, self).isdir(fn)
107 def listdir(self, fn): # type: (unicode) -> List[unicode]
108 collection, rest = self.get_collection(fn)
111 dir = collection.find(rest)
115 raise IOError(errno.ENOENT, "Directory '%s' in '%s' not found" % (rest, collection.portable_data_hash()))
116 if not isinstance(dir, arvados.collection.RichCollectionBase):
117 raise IOError(errno.ENOENT, "Path '%s' in '%s' is not a Directory" % (rest, collection.portable_data_hash()))
118 return [abspath(l, fn) for l in dir.keys()]
120 return super(CollectionFsAccess, self).listdir(fn)
122 def join(self, path, *paths): # type: (unicode, *unicode) -> unicode
123 if paths and paths[-1].startswith("keep:") and arvados.util.keep_locator_pattern.match(paths[-1][5:]):
125 return os.path.join(path, *paths)
127 def realpath(self, path):
128 if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
130 collection, rest = self.get_collection(path)
134 return os.path.realpath(path)
136 class CollectionFetcher(DefaultFetcher):
137 def __init__(self, cache, session, api_client=None, keep_client=None, num_retries=4):
138 super(CollectionFetcher, self).__init__(cache, session)
139 self.api_client = api_client
140 self.fsaccess = CollectionFsAccess("", api_client=api_client, keep_client=keep_client)
141 self.num_retries = num_retries
143 def fetch_text(self, url):
144 if url.startswith("keep:"):
145 with self.fsaccess.open(url, "r") as f:
147 if url.startswith("arvwf:"):
148 record = self.api_client.workflows().get(uuid=url[6:]).execute(num_retries=self.num_retries)
149 definition = record["definition"] + ('\nlabel: "%s"\n' % record["name"].replace('"', '\\"'))
151 return super(CollectionFetcher, self).fetch_text(url)
153 def check_exists(self, url):
155 if url.startswith("http://arvados.org/cwl"):
157 if url.startswith("keep:"):
158 return self.fsaccess.exists(url)
159 if url.startswith("arvwf:"):
160 if self.fetch_text(url):
162 except arvados.errors.NotFoundError:
165 logger.exception("Got unexpected exception checking if file exists:")
167 return super(CollectionFetcher, self).check_exists(url)
169 def urljoin(self, base_url, url):
173 urlsp = urlparse.urlsplit(url)
174 if urlsp.scheme or not base_url:
177 basesp = urlparse.urlsplit(base_url)
178 if basesp.scheme in ("keep", "arvwf"):
180 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
182 baseparts = basesp.path.split("/")
183 urlparts = urlsp.path.split("/") if urlsp.path else []
185 pdh = baseparts.pop(0)
187 if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
188 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
190 if urlsp.path.startswith("/"):
194 if baseparts and urlsp.path:
197 path = "/".join([pdh] + baseparts + urlparts)
198 return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
200 return super(CollectionFetcher, self).urljoin(base_url, url)
202 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
203 pipeline_template_uuid_pattern = re.compile(r'[a-z0-9]{5}-p5p6p-[a-z0-9]{15}')
205 def collectionResolver(api_client, document_loader, uri, num_retries=4):
206 if workflow_uuid_pattern.match(uri):
207 return "arvwf:%s#main" % (uri)
209 if pipeline_template_uuid_pattern.match(uri):
210 pt = api_client.pipeline_templates().get(uuid=uri).execute(num_retries=num_retries)
211 return "keep:" + pt["components"].values()[0]["script_parameters"]["cwl:tool"]
214 if arvados.util.keep_locator_pattern.match(p[0]):
215 return "keep:%s" % (uri)
217 if arvados.util.collection_uuid_pattern.match(p[0]):
218 return "keep:%s%s" % (api_client.collections().
219 get(uuid=p[0]).execute()["portable_data_hash"],
222 return cwltool.resolver.tool_resolver(document_loader, uri)