1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
13 import ruamel.yaml as yaml
15 import cwltool.stdfsaccess
16 from cwltool.pathmapper import abspath
17 import cwltool.resolver
20 import arvados.collection
21 import arvados.arvfile
24 from schema_salad.ref_resolver import DefaultFetcher
26 logger = logging.getLogger('arvados.cwl-runner')
28 class CollectionCache(object):
29 def __init__(self, api_client, keep_client, num_retries):
30 self.api_client = api_client
31 self.keep_client = keep_client
33 self.lock = threading.Lock()
37 if pdh not in self.collections:
38 logger.debug("Creating collection reader for %s", pdh)
39 self.collections[pdh] = arvados.collection.CollectionReader(pdh, api_client=self.api_client,
40 keep_client=self.keep_client)
41 return self.collections[pdh]
44 class CollectionFsAccess(cwltool.stdfsaccess.StdFsAccess):
45 """Implement the cwltool FsAccess interface for Arvados Collections."""
47 def __init__(self, basedir, collection_cache=None):
48 super(CollectionFsAccess, self).__init__(basedir)
49 self.collection_cache = collection_cache
51 def get_collection(self, path):
52 sp = path.split("/", 1)
54 if p.startswith("keep:") and arvados.util.keep_locator_pattern.match(p[5:]):
56 return (self.collection_cache.get(pdh), sp[1] if len(sp) == 2 else None)
60 def _match(self, collection, patternsegments, parent):
61 if not patternsegments:
64 if not isinstance(collection, arvados.collection.RichCollectionBase):
68 # iterate over the files and subcollections in 'collection'
69 for filename in collection:
70 if patternsegments[0] == '.':
71 # Pattern contains something like "./foo" so just shift
73 ret.extend(self._match(collection, patternsegments[1:], parent))
74 elif fnmatch.fnmatch(filename, patternsegments[0]):
75 cur = os.path.join(parent, filename)
76 if len(patternsegments) == 1:
79 ret.extend(self._match(collection[filename], patternsegments[1:], cur))
82 def glob(self, pattern):
83 collection, rest = self.get_collection(pattern)
84 if collection and not rest:
86 patternsegments = rest.split("/")
87 return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
89 def open(self, fn, mode):
90 collection, rest = self.get_collection(fn)
92 return collection.open(rest, mode)
94 return super(CollectionFsAccess, self).open(self._abs(fn), mode)
97 collection, rest = self.get_collection(fn)
100 return collection.exists(rest)
104 return super(CollectionFsAccess, self).exists(fn)
106 def isfile(self, fn): # type: (unicode) -> bool
107 collection, rest = self.get_collection(fn)
110 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
114 return super(CollectionFsAccess, self).isfile(fn)
116 def isdir(self, fn): # type: (unicode) -> bool
117 collection, rest = self.get_collection(fn)
120 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
124 return super(CollectionFsAccess, self).isdir(fn)
126 def listdir(self, fn): # type: (unicode) -> List[unicode]
127 collection, rest = self.get_collection(fn)
130 dir = collection.find(rest)
134 raise IOError(errno.ENOENT, "Directory '%s' in '%s' not found" % (rest, collection.portable_data_hash()))
135 if not isinstance(dir, arvados.collection.RichCollectionBase):
136 raise IOError(errno.ENOENT, "Path '%s' in '%s' is not a Directory" % (rest, collection.portable_data_hash()))
137 return [abspath(l, fn) for l in dir.keys()]
139 return super(CollectionFsAccess, self).listdir(fn)
141 def join(self, path, *paths): # type: (unicode, *unicode) -> unicode
142 if paths and paths[-1].startswith("keep:") and arvados.util.keep_locator_pattern.match(paths[-1][5:]):
144 return os.path.join(path, *paths)
146 def realpath(self, path):
147 if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
149 collection, rest = self.get_collection(path)
153 return os.path.realpath(path)
155 class CollectionFetcher(DefaultFetcher):
156 def __init__(self, cache, session, api_client=None, fs_access=None, num_retries=4, overrides=None):
157 super(CollectionFetcher, self).__init__(cache, session)
158 self.api_client = api_client
159 self.fsaccess = fs_access
160 self.num_retries = num_retries
161 self.overrides = overrides if overrides else {}
163 def fetch_text(self, url):
164 if url in self.overrides:
165 return self.overrides[url]
166 if url.startswith("keep:"):
167 with self.fsaccess.open(url, "r") as f:
169 if url.startswith("arvwf:"):
170 record = self.api_client.workflows().get(uuid=url[6:]).execute(num_retries=self.num_retries)
171 definition = record["definition"] + ('\nlabel: "%s"\n' % record["name"].replace('"', '\\"'))
173 return super(CollectionFetcher, self).fetch_text(url)
175 def check_exists(self, url):
176 if url in self.overrides:
179 if url.startswith("http://arvados.org/cwl"):
181 if url.startswith("keep:"):
182 return self.fsaccess.exists(url)
183 if url.startswith("arvwf:"):
184 if self.fetch_text(url):
186 except arvados.errors.NotFoundError:
189 logger.exception("Got unexpected exception checking if file exists:")
191 return super(CollectionFetcher, self).check_exists(url)
193 def urljoin(self, base_url, url):
197 urlsp = urlparse.urlsplit(url)
198 if urlsp.scheme or not base_url:
201 basesp = urlparse.urlsplit(base_url)
202 if basesp.scheme in ("keep", "arvwf"):
204 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
206 baseparts = basesp.path.split("/")
207 urlparts = urlsp.path.split("/") if urlsp.path else []
209 pdh = baseparts.pop(0)
211 if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
212 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
214 if urlsp.path.startswith("/"):
218 if baseparts and urlsp.path:
221 path = "/".join([pdh] + baseparts + urlparts)
222 return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
224 return super(CollectionFetcher, self).urljoin(base_url, url)
226 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
227 pipeline_template_uuid_pattern = re.compile(r'[a-z0-9]{5}-p5p6p-[a-z0-9]{15}')
229 def collectionResolver(api_client, document_loader, uri, num_retries=4):
230 if workflow_uuid_pattern.match(uri):
231 return "arvwf:%s#main" % (uri)
233 if pipeline_template_uuid_pattern.match(uri):
234 pt = api_client.pipeline_templates().get(uuid=uri).execute(num_retries=num_retries)
235 return "keep:" + pt["components"].values()[0]["script_parameters"]["cwl:tool"]
238 if arvados.util.keep_locator_pattern.match(p[0]):
239 return "keep:%s" % (uri)
241 if arvados.util.collection_uuid_pattern.match(p[0]):
242 return "keep:%s%s" % (api_client.collections().
243 get(uuid=p[0]).execute()["portable_data_hash"],
246 return cwltool.resolver.tool_resolver(document_loader, uri)