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):
34 if p[0].startswith("keep:") and arvados.util.keep_locator_pattern.match(p[0][5:]):
36 if pdh not in self.collections:
37 self.collections[pdh] = arvados.collection.CollectionReader(pdh, api_client=self.api_client,
38 keep_client=self.keep_client)
39 return (self.collections[pdh], "/".join(p[1:]))
43 def _match(self, collection, patternsegments, parent):
44 if not patternsegments:
47 if not isinstance(collection, arvados.collection.RichCollectionBase):
51 # iterate over the files and subcollections in 'collection'
52 for filename in collection:
53 if patternsegments[0] == '.':
54 # Pattern contains something like "./foo" so just shift
56 ret.extend(self._match(collection, patternsegments[1:], parent))
57 elif fnmatch.fnmatch(filename, patternsegments[0]):
58 cur = os.path.join(parent, filename)
59 if len(patternsegments) == 1:
62 ret.extend(self._match(collection[filename], patternsegments[1:], cur))
65 def glob(self, pattern):
66 collection, rest = self.get_collection(pattern)
67 if collection and not rest:
69 patternsegments = rest.split("/")
70 return self._match(collection, patternsegments, "keep:" + collection.manifest_locator())
72 def open(self, fn, mode):
73 collection, rest = self.get_collection(fn)
75 return collection.open(rest, mode)
77 return super(CollectionFsAccess, self).open(self._abs(fn), mode)
80 collection, rest = self.get_collection(fn)
82 return collection.exists(rest)
84 return super(CollectionFsAccess, self).exists(fn)
86 def isfile(self, fn): # type: (unicode) -> bool
87 collection, rest = self.get_collection(fn)
90 return isinstance(collection.find(rest), arvados.arvfile.ArvadosFile)
94 return super(CollectionFsAccess, self).isfile(fn)
96 def isdir(self, fn): # type: (unicode) -> bool
97 collection, rest = self.get_collection(fn)
100 return isinstance(collection.find(rest), arvados.collection.RichCollectionBase)
104 return super(CollectionFsAccess, self).isdir(fn)
106 def listdir(self, fn): # type: (unicode) -> List[unicode]
107 collection, rest = self.get_collection(fn)
110 dir = collection.find(rest)
114 raise IOError(errno.ENOENT, "Directory '%s' in '%s' not found" % (rest, collection.portable_data_hash()))
115 if not isinstance(dir, arvados.collection.RichCollectionBase):
116 raise IOError(errno.ENOENT, "Path '%s' in '%s' is not a Directory" % (rest, collection.portable_data_hash()))
117 return [abspath(l, fn) for l in dir.keys()]
119 return super(CollectionFsAccess, self).listdir(fn)
121 def join(self, path, *paths): # type: (unicode, *unicode) -> unicode
122 if paths and paths[-1].startswith("keep:") and arvados.util.keep_locator_pattern.match(paths[-1][5:]):
124 return os.path.join(path, *paths)
126 def realpath(self, path):
127 if path.startswith("$(task.tmpdir)") or path.startswith("$(task.outdir)"):
129 collection, rest = self.get_collection(path)
133 return os.path.realpath(path)
135 class CollectionFetcher(DefaultFetcher):
136 def __init__(self, cache, session, api_client=None, keep_client=None, num_retries=4):
137 super(CollectionFetcher, self).__init__(cache, session)
138 self.api_client = api_client
139 self.fsaccess = CollectionFsAccess("", api_client=api_client, keep_client=keep_client)
140 self.num_retries = num_retries
142 def fetch_text(self, url):
143 if url.startswith("keep:"):
144 with self.fsaccess.open(url, "r") as f:
146 if url.startswith("arvwf:"):
147 record = self.api_client.workflows().get(uuid=url[6:]).execute(num_retries=self.num_retries)
148 definition = record["definition"] + ('\nlabel: "%s"\n' % record["name"].replace('"', '\\"'))
150 return super(CollectionFetcher, self).fetch_text(url)
152 def check_exists(self, url):
154 if url.startswith("keep:"):
155 return self.fsaccess.exists(url)
156 if url.startswith("arvwf:"):
157 if self.fetch_text(url):
159 except arvados.errors.NotFoundError:
162 logger.exception("Got unexpected exception checking if file exists:")
164 return super(CollectionFetcher, self).check_exists(url)
166 def urljoin(self, base_url, url):
170 urlsp = urlparse.urlsplit(url)
171 if urlsp.scheme or not base_url:
174 basesp = urlparse.urlsplit(base_url)
175 if basesp.scheme in ("keep", "arvwf"):
177 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
179 baseparts = basesp.path.split("/")
180 urlparts = urlsp.path.split("/") if urlsp.path else []
182 pdh = baseparts.pop(0)
184 if basesp.scheme == "keep" and not arvados.util.keep_locator_pattern.match(pdh):
185 raise IOError(errno.EINVAL, "Invalid Keep locator", base_url)
187 if urlsp.path.startswith("/"):
191 if baseparts and urlsp.path:
194 path = "/".join([pdh] + baseparts + urlparts)
195 return urlparse.urlunsplit((basesp.scheme, "", path, "", urlsp.fragment))
197 return super(CollectionFetcher, self).urljoin(base_url, url)
199 workflow_uuid_pattern = re.compile(r'[a-z0-9]{5}-7fd4e-[a-z0-9]{15}')
200 pipeline_template_uuid_pattern = re.compile(r'[a-z0-9]{5}-p5p6p-[a-z0-9]{15}')
202 def collectionResolver(api_client, document_loader, uri, num_retries=4):
203 if workflow_uuid_pattern.match(uri):
204 return "arvwf:%s#main" % (uri)
206 if pipeline_template_uuid_pattern.match(uri):
207 pt = api_client.pipeline_templates().get(uuid=uri).execute(num_retries=num_retries)
208 return "keep:" + pt["components"].values()[0]["script_parameters"]["cwl:tool"]
211 if arvados.util.keep_locator_pattern.match(p[0]):
212 return "keep:%s" % (uri)
214 if arvados.util.collection_uuid_pattern.match(p[0]):
215 return "keep:%s%s" % (api_client.collections().
216 get(uuid=p[0]).execute()["portable_data_hash"],
219 return cwltool.resolver.tool_resolver(document_loader, uri)