23 """This module provides registry classes for maintaining dataset metadata
24 for use by the Data Butler. Currently only a SQLite3-based registry is
25 implemented, but registries based on a text file, a policy file, a MySQL
26 (or other) relational database, and data gathered from scanning a filesystem
29 Currently this module assumes posix access (for both PosixRegistry AND
30 SqliteRegistry). It is possible that it can be factored so that at least the
31 SqliteRegistry can be remote/not on the local filesystem. For now this module
32 is only used by CameraMapper and by PosixStorage, both of which work on the
33 local filesystem only, so this works for the time being.
35 from __future__
import absolute_import
36 from builtins
import object
37 from past.builtins
import basestring
40 from .
import fsScanner, sequencify
42 import astropy.io.fits
50 import sqlite
as sqlite3
57 """The registry base class."""
64 """Create a registry object of an appropriate type.
65 @param location (string) Path or URL for registry, or None if
77 if haveSqlite3
and re.match(
r'.*\.sqlite3', location):
79 if registry.conn
is None:
88 if os.path.exists(location):
91 raise RuntimeError(
"Unable to create registry using location: " + location)
95 """A glob-based filesystem registry"""
98 Registry.__init__(self)
103 """Looks up the HDU number for a given template+dataId.
104 :param template: template with HDU specifier (ends with brackets and an
105 identifier that can be populated by a key-value pair in dataId.
106 e.g. "%(visit)07d/instcal%(visit)07d.fits.fz[%(ccdnum)d]"
107 :param dataId: dictionary that hopefully has a key-value pair whose key
108 matches (has the same name) as the key specifier in the template.
109 :return: the HDU specified by the template+dataId pair, or None if the
110 HDU can not be determined.
113 if not template.endswith(
']'):
117 hduKey = template[template.rfind(
'[') + 1:template.rfind(
']')]
119 hduKey = hduKey[hduKey.rfind(
'(') + 1:hduKey.rfind(
')')]
122 return dataId[hduKey]
129 lookupProperties =
sequencify(lookupProperties)
136 return "LookupData lookupProperties:%s dataId:%s foundItems:%s cachedStatus:%s" % \
140 """Query the lookup status
142 :return: 'match' if the key+value pairs in dataId have been satisifed and keys in
143 lookupProperties have found and their key+value added to resolvedId
144 'incomplete' if the found data matches but there are still incomplete data matching in dataId or
146 'not match' if data in foundId does not match data in dataId
169 self.foundItems.update(items)
172 return self.
neededKeys - set(self.foundItems.keys())
174 def lookup(self, lookupProperties, reference, dataId, **kwargs):
175 """Perform a lookup in the registry.
177 Return values are refined by the values in dataId.
178 Returns a list of values that match keys in lookupProperties.
179 e.g. if the template is 'raw/raw_v%(visit)d_f%(filter)s.fits.gz', and
180 dataId={'visit':1}, and lookupProperties is ['filter'], and the
181 filesystem under self.root has exactly one file 'raw/raw_v1_fg.fits.gz'
182 then the return value will be [('g',)]
184 :param lookupProperties: keys whose values will be returned.
185 :param reference: other data types that may be used to search for values.
186 :param dataId: must be an iterable. Keys must be string.
187 If value is a string then will look for elements in the repository that match value for key.
188 If value is a 2-item iterable then will look for elements in the repository are between (inclusive)
189 the first and second items in the value.
190 :param **kwargs: keys required for the posix registry to search for items. If required keys are not
191 provide will return an empty list.
192 'template': required. template parameter (typically from a policy) that can be used to look for files
193 'storage': optional. Needed to look for metadata in files. Currently supported values: 'FitsStorage'.
194 :return: a list of values that match keys in lookupProperties.
197 if 'template' in kwargs:
198 template = kwargs[
'template']
202 storage = kwargs[
'storage']
if 'storage' in kwargs
else None
206 allPaths = scanner.processPath(self.
root)
208 for path, foundProperties
in allPaths.items():
213 lookupData.setFoundItems(foundProperties)
214 if 'incomplete' == lookupData.status():
215 PosixRegistry.lookupMetadata(os.path.join(self.
root, path), template, lookupData, storage)
216 if 'match' == lookupData.status():
217 l = tuple(lookupData.foundItems[key]
for key
in lookupData.lookupProperties)
223 """Dispatcher for looking up metadata in a file of a given storage type
225 if storage ==
'FitsStorage':
226 PosixRegistry.lookupFitsMetadata(filepath, template, lookupData, storage)
230 """Look up metadata in a fits file.
231 Will try to discover the correct HDU to look in by testing if the
232 template has a value in brackets at the end.
233 If the HDU is specified but the metadata key is not discovered in
234 that HDU, will look in the primary HDU before giving up.
235 :param filepath: path to the file
236 :param template: template that was used to discover the file. This can
237 be used to look up the correct HDU as needed.
238 :param lookupData: an instance if LookupData that contains the
239 lookupProperties, the dataId, and the data that has been found so far.
240 Will be updated with new information as discovered.
245 hdulist = astropy.io.fits.open(filepath, memmap=
True)
248 hduNumber = PosixRegistry.getHduNumber(template=template, dataId=dataId)
249 if hduNumber
is not None and hduNumber < len(hdulist):
250 hdu = hdulist[hduNumber]
254 primaryHdu = hdulist[0]
258 for property
in lookupData.getMissingKeys():
260 if hdu
is not None and property
in hdu.header:
261 propertyValue = hdu.header[property]
263 elif primaryHdu
is not None and property
in primaryHdu.header:
264 propertyValue = primaryHdu.header[property]
265 lookupData.addFoundItems({property: propertyValue})
269 """A SQLite3-based registry."""
273 @param location (string) Path to SQLite3 file"""
275 Registry.__init__(self)
276 if os.path.exists(location):
277 self.
conn = sqlite3.connect(location)
278 self.conn.text_factory = str
282 def lookup(self, lookupProperties, reference, dataId, **kwargs):
283 """Perform a lookup in the registry.
285 Return values are refined by the values in dataId.
286 Returns a list of values that match keys in lookupProperties.
287 e.g. if the template is 'raw/raw_v%(visit)d_f%(filter)s.fits.gz', and
288 dataId={'visit':1}, and lookupProperties is ['filter'], and the
289 filesystem under self.root has exactly one file 'raw/raw_v1_fg.fits.gz'
290 then the return value will be [('g',)]
292 :param lookupProperties:
293 :param dataId: must be an iterable. Keys must be string.
294 If key is a string then will look for elements in the repository that match value for key.
295 If key is a 2-item iterable then will look for elements in the repository where the value is between
296 the values of key[0] and key[1].
297 :param reference: other data types that may be used to search for values.
298 :param **kwargs: nothing needed for sqlite lookup
299 :return: a list of values that match keys in lookupProperties.
306 lookupProperties =
sequencify(lookupProperties)
308 cmd =
"SELECT DISTINCT "
309 cmd +=
", ".join(lookupProperties)
310 cmd +=
" FROM " +
" NATURAL JOIN ".join(reference)
312 if dataId
is not None and len(dataId) > 0:
314 for k, v
in dataId.items():
315 if hasattr(k,
'__iter__')
and not isinstance(k, basestring):
317 raise RuntimeError(
"Wrong number of keys for range:%s" % (k,))
318 whereList.append(
"(? BETWEEN %s AND %s)" % (k[0], k[1]))
321 whereList.append(
"%s = ?" % k)
323 cmd +=
" WHERE " +
" AND ".join(whereList)
324 c = self.conn.execute(cmd, valueList)
330 def executeQuery(self, returnFields, joinClause, whereFields, range, values):
331 """Extract metadata from the registry.
332 @param returnFields (list of strings) Metadata fields to be extracted.
333 @param joinClause (list of strings) Tables in which metadata fields
335 @param whereFields (list of tuples) First tuple element is metadata
336 field to query; second is the value that field
337 must have (often '?').
338 @param range (tuple) Value, lower limit, and upper limit for a
339 range condition on the metadata. Any of these can
341 @param values (tuple) Tuple of values to be substituted for '?'
342 characters in the whereFields values or the range
344 @return (list of tuples) All sets of field values that meet the
348 cmd =
"SELECT DISTINCT "
349 cmd +=
", ".join(returnFields)
350 cmd +=
" FROM " +
" NATURAL JOIN ".join(joinClause)
353 for k, v
in whereFields:
354 whereList.append(
"(%s = %s)" % (k, v))
355 if range
is not None:
356 whereList.append(
"(%s BETWEEN %s AND %s)" % range)
357 if len(whereList) > 0:
358 cmd +=
" WHERE " +
" AND ".join(whereList)
359 c = self.conn.execute(cmd, values)