/usr/share/pyshared/glance/store/__init__.py is in python-glance 2012.1.3+stable~20120821-120fcf-0ubuntu1.5.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os
import sys
import time
from glance.common import cfg
from glance.common import exception
from glance.common import utils
from glance import registry
from glance.store import location
logger = logging.getLogger('glance.store')
# Set of known store modules
REGISTERED_STORE_MODULES = []
# Set of store objects, constructed in create_stores()
STORES = {}
class ImageAddResult(object):
"""
Class that represents the succesful result of adding
an image to a backend store.
"""
def __init__(self, location, bytes_written, checksum=None):
"""
Initialize the object
:param location: `glance.store.StoreLocation` object representing
the location of the image in the backend store
:param bytes_written: Number of bytes written to store
:param checksum: Optional checksum of the image data
"""
self.location = location
self.bytes_written = bytes_written
self.checksum = checksum
class BackendException(Exception):
pass
class UnsupportedBackend(BackendException):
pass
class Indexable(object):
"""
Wrapper that allows an iterator or filelike be treated as an indexable
data structure. This is required in the case where the return value from
Store.get() is passed to Store.add() when adding a Copy-From image to a
Store where the client library relies on eventlet GreenSockets, in which
case the data to be written is indexed over.
"""
def __init__(self, wrapped, size):
"""
Initialize the object
:param wrappped: the wrapped iterator or filelike.
:param size: the size of data available
"""
self.wrapped = wrapped
self.size = int(size) if size else (wrapped.len
if hasattr(wrapped, 'len') else 0)
self.cursor = 0
self.chunk = None
def __iter__(self):
"""
Delegate iteration to the wrapped instance.
"""
for self.chunk in self.wrapped:
yield self.chunk
def __getitem__(self, i):
"""
Index into the next chunk (or previous chunk in the case where
the last data returned was not fully consumed).
:param i: a slice-to-the-end
"""
start = i.start if isinstance(i, slice) else i
if start < self.cursor:
return self.chunk[(start - self.cursor):]
self.chunk = self.another()
if self.chunk:
self.cursor += len(self.chunk)
return self.chunk
def another(self):
"""Implemented by subclasses to return the next element"""
raise NotImplementedError
def getvalue(self):
"""
Return entire string value... used in testing
"""
return self.wrapped.getvalue()
def __len__(self):
"""
Length accessor.
"""
return self.size
def register_store(store_module, schemes):
"""
Registers a store module and a set of schemes
for which a particular URI request should be routed.
:param store_module: String representing the store module
:param schemes: List of strings representing schemes for
which this store should be used in routing
"""
try:
utils.import_class(store_module + '.Store')
except exception.NotFound:
raise BackendException('Unable to register store. Could not find '
'a class named Store in module %s.'
% store_module)
REGISTERED_STORE_MODULES.append(store_module)
scheme_map = {}
for scheme in schemes:
scheme_map[scheme] = store_module
location.register_scheme_map(scheme_map)
def create_stores(conf):
"""
Construct the store objects with supplied configuration options
"""
for store_module in REGISTERED_STORE_MODULES:
try:
store_class = utils.import_class(store_module + '.Store')
except exception.NotFound:
raise BackendException('Unable to create store. Could not find '
'a class named Store in module %s.'
% store_module)
STORES[store_module] = store_class(conf)
def get_store_from_scheme(scheme):
"""
Given a scheme, return the appropriate store object
for handling that scheme
"""
if scheme not in location.SCHEME_TO_STORE_MAP:
raise exception.UnknownScheme(scheme=scheme)
return STORES[location.SCHEME_TO_STORE_MAP[scheme]]
def get_store_from_uri(uri):
"""
Given a URI, return the store object that would handle
operations on the URI.
:param uri: URI to analyze
"""
scheme = uri[0:uri.find('/') - 1]
return get_store_from_scheme(scheme)
def get_from_backend(uri, **kwargs):
"""Yields chunks of data from backend specified by uri"""
store = get_store_from_uri(uri)
loc = location.get_location_from_uri(uri)
return store.get(loc)
def get_size_from_backend(uri):
"""Retrieves image size from backend specified by uri"""
store = get_store_from_uri(uri)
loc = location.get_location_from_uri(uri)
return store.get_size(loc)
def delete_from_backend(uri, **kwargs):
"""Removes chunks of data from backend specified by uri"""
store = get_store_from_uri(uri)
loc = location.get_location_from_uri(uri)
try:
return store.delete(loc)
except NotImplementedError:
raise exception.StoreDeleteNotSupported
def get_store_from_location(uri):
"""
Given a location (assumed to be a URL), attempt to determine
the store from the location. We use here a simple guess that
the scheme of the parsed URL is the store...
:param uri: Location to check for the store
"""
loc = location.get_location_from_uri(uri)
return loc.store_name
scrubber_datadir_opt = cfg.StrOpt('scrubber_datadir',
default='/var/lib/glance/scrubber')
def get_scrubber_datadir(conf):
conf.register_opt(scrubber_datadir_opt)
return conf.scrubber_datadir
delete_opts = [
cfg.BoolOpt('delayed_delete', default=False),
cfg.IntOpt('scrub_time', default=0)
]
def schedule_delete_from_backend(uri, conf, context, image_id, **kwargs):
"""
Given a uri and a time, schedule the deletion of an image.
"""
conf.register_opts(delete_opts)
if not conf.delayed_delete:
registry.update_image_metadata(context, image_id,
{'status': 'deleted'})
try:
return delete_from_backend(uri, **kwargs)
except (UnsupportedBackend,
exception.StoreDeleteNotSupported,
exception.NotFound):
exc_type = sys.exc_info()[0].__name__
msg = _("Failed to delete image at %s from store (%s)") % \
(uri, exc_type)
logger.error(msg)
finally:
# avoid falling through to the delayed deletion logic
return
datadir = get_scrubber_datadir(conf)
delete_time = time.time() + conf.scrub_time
file_path = os.path.join(datadir, str(image_id))
utils.safe_mkdirs(datadir)
if os.path.exists(file_path):
msg = _("Image id %(image_id)s already queued for delete") % {
'image_id': image_id}
raise exception.Duplicate(msg)
with open(file_path, 'w') as f:
f.write('\n'.join([uri, str(int(delete_time))]))
os.chmod(file_path, 0600)
os.utime(file_path, (delete_time, delete_time))
registry.update_image_metadata(context, image_id,
{'status': 'pending_delete'})
|