Adding API call to query for cache entries

This commit is contained in:
Rick Harris 2011-07-12 04:09:36 -05:00
parent a4369c75b3
commit 2dbc2fb65a
4 changed files with 56 additions and 1 deletions

View File

@ -34,7 +34,8 @@ class API(wsgi.Router):
mapper = routes.Mapper()
resource = images.create_resource(options)
mapper.resource("image", "images", controller=resource,
collection={'detail': 'GET'})
collection={'detail': 'GET',
'cached': 'GET'})
mapper.connect("/", controller=resource, action="index")
mapper.connect("/images/{id}", controller=resource, action="meta",
conditions=dict(method=["HEAD"]))

View File

@ -132,6 +132,11 @@ class Controller(object):
raise HTTPBadRequest(explanation=str(e))
return dict(images=images)
def cached(self, req):
cache = image_cache.ImageCache(self.options)
entries = cache.entries()
return dict(images=entries)
def _get_query_params(self, req):
"""
Extracts necessary query params from request.

View File

@ -19,15 +19,29 @@
LRU Cache for Image Data
"""
from contextlib import contextmanager
import datetime
import logging
import os
import xattr
from glance.common import config
logger = logging.getLogger('glance.image_cache')
class ImageCache(object):
"""Cache Image Data locally.
ImageCache makes the following assumptions:
1. `noatime` is not enabled (access time is for LRU pruning)
2. `xattr` support by the filesystem (OPTIONAL, used to display image
name when /images/cached API request is made)
3. `glance-pruner` is run periocally to keep cache size in check
"""
def __init__(self, options):
self.options = options
self._make_cache_directory_if_needed()
@ -60,6 +74,11 @@ class ImageCache(object):
with open(path, mode) as cache_file:
yield cache_file
entry_xattr = xattr.xattr(path)
if 'w' in mode:
entry_xattr.set('image_name', image_meta['name'])
def hit(self, image_meta):
path = self.path_for_image(image_meta)
return os.path.exists(path)
@ -69,3 +88,32 @@ class ImageCache(object):
logger.debug("deleting image cache entry '%s'", path)
if os.path.exists(path):
os.unlink(path)
def entries(self):
"""Return cache info for each image that is cached"""
entries = []
for fname in os.listdir(self.path):
path = os.path.join(self.path, fname)
try:
image_id = int(fname)
except ValueError, TypeError:
continue
entry = {}
entry['id'] = image_id
entry_xattr = xattr.xattr(path)
try:
name = entry_xattr['image_name']
except KeyError:
name = "UNKNOWN"
entry['name'] = name
entry['size'] = os.path.getsize(path)
accessed = os.path.getatime(path) or os.path.getmtime(path)
last_accessed = datetime.datetime.fromtimestamp(accessed)\
.isoformat()
entry['last_accessed'] = last_accessed
entries.append(entry)
return entries

View File

@ -18,3 +18,4 @@ sqlalchemy-migrate>=0.6,<0.7
bzr
httplib2
hashlib
xattr