desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test swift.object_server.ObjectController.GET'
def test_GET_quarantine_zbyte(self):
timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = self.object_controller.PUT(req) self.assertEquals(resp.status_int, 201) file = obje...
'Test swift.object_server.ObjectController.GET'
def test_GET_quarantine_range(self):
timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = self.object_controller.PUT(req) self.assertEquals(resp.status_int, 201) file = obje...
'Test swift.object_server.ObjectController.DELETE'
def test_DELETE(self):
req = Request.blank('/sda1/p/a/c', environ={'REQUEST_METHOD': 'DELETE'}) resp = self.object_controller.DELETE(req) self.assertEquals(resp.status_int, 400) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'DELETE'}) resp = self.object_controller.DELETE(req) self.assertEquals(resp.s...
'Test swift.object_server.ObjectController.__call__'
def test_call(self):
inbuf = StringIO() errbuf = StringIO() outbuf = StringIO() def start_response(*args): ' Sends args to outbuf ' outbuf.writelines(args) self.object_controller.__call__({'REQUEST_METHOD': 'PUT', 'SCRIPT_NAME': '', 'PATH_INFO': '/sda1/p/a/c/o', 'SERVER_NAME': '127.0.0.1',...
'After running xfs_repair, a partition directory could become a zero-byte file. If this happens, collect_jobs() should clean it up and *not* create a job which will hit an exception as it tries to listdir() a file.'
def test_collect_jobs_removes_zbf(self):
part_1_path = os.path.join(self.objects, '1') rmtree(part_1_path) with open(part_1_path, 'w'): pass self.assertTrue(os.path.isfile(part_1_path)) jobs = self.replicator.collect_jobs() jobs_to_delete = [j for j in jobs if j['delete']] jobs_to_keep = [j for j in jobs if (not j['delete']...
'Set up for testing swift.account_server.AccountController'
def setUp(self):
self.testdir = os.path.join(os.path.dirname(__file__), 'account_server') self.controller = AccountController({'devices': self.testdir, 'mount_check': 'false'})
'Tear down for testing swift.account_server.AccountController'
def tearDown(self):
try: rmtree(self.testdir) except OSError as err: if (err.errno != errno.ENOENT): raise
'Get the account ring. Load it if it hasn\'t been yet.'
def get_account_ring(self):
if (not self.account_ring): self.account_ring = Ring(self.swift_dir, ring_name='account') return self.account_ring
'Get paths to all of the partitions on each drive to be processed. :returns: a list of paths'
def get_paths(self):
paths = [] for device in os.listdir(self.devices): dev_path = os.path.join(self.devices, device) if (self.mount_check and (not os.path.ismount(dev_path))): self.logger.warn(_('%s is not mounted'), device) continue con_path = os.path.join(dev_path, DATADIR...
'Run the updator continuously.'
def run_forever(self, *args, **kwargs):
time.sleep((random() * self.interval)) while True: self.logger.info(_('Begin container update sweep')) begin = time.time() now = time.time() expired_suppressions = [a for (a, u) in self.account_suppressions.iteritems() if (u < now)] for account in expired_suppres...
'Run the updater once.'
def run_once(self, *args, **kwargs):
patcher.monkey_patch(all=False, socket=True) self.logger.info(_('Begin container update single threaded sweep')) begin = time.time() self.no_changes = 0 self.successes = 0 self.failures = 0 for path in self.get_paths(): self.container_sweep(path) elapsed = (time.ti...
'Walk the path looking for container DBs and process them. :param path: path to walk'
def container_sweep(self, path):
for (root, dirs, files) in os.walk(path): for file in files: if file.endswith('.db'): self.process_container(os.path.join(root, file)) time.sleep(self.slowdown)
'Process a container, and update the information in the account. :param dbfile: container DB to process'
def process_container(self, dbfile):
start_time = time.time() broker = ContainerBroker(dbfile, logger=self.logger) info = broker.get_info() if (float(info['put_timestamp']) <= 0): return if (self.account_suppressions.get(info['account'], 0) > time.time()): return if ((info['put_timestamp'] > info['reported_put_times...
'Report container info to an account server. :param node: node dictionary from the account ring :param part: partition the account is on :param container: container name :param put_timestamp: put timestamp :param delete_timestamp: delete timestamp :param count: object count in the container :param bytes: bytes used in ...
def container_report(self, node, part, container, put_timestamp, delete_timestamp, count, bytes):
with ConnectionTimeout(self.conn_timeout): try: conn = http_connect(node['ip'], node['port'], node['device'], part, 'PUT', container, headers={'X-Put-Timestamp': put_timestamp, 'X-Delete-Timestamp': delete_timestamp, 'X-Object-Count': count, 'X-Bytes-Used': bytes, 'X-Account-Override-Deleted': '...
'Get a DB broker for the container. :param drive: drive that holds the container :param part: partition the container is in :param account: account name :param container: container name :returns: ContainerBroker object'
def _get_container_broker(self, drive, part, account, container):
hsh = hash_path(account, container) db_dir = storage_directory(DATADIR, part, hsh) db_path = os.path.join(self.root, drive, db_dir, (hsh + '.db')) return ContainerBroker(db_path, account=account, container=container, logger=self.logger)
'Update the account server(s) with latest container info. :param req: swob.Request object :param account: account name :param container: container name :param broker: container DB broker object :returns: if all the account requests return a 404 error code, HTTPNotFound response object, if the account cannot be updated ...
def account_update(self, req, account, container, broker):
account_hosts = [h.strip() for h in req.headers.get('X-Account-Host', '').split(',')] account_devices = [d.strip() for d in req.headers.get('X-Account-Device', '').split(',')] account_partition = req.headers.get('X-Account-Partition', '') if (len(account_hosts) != len(account_devices)): self.log...
'Handle HTTP DELETE request.'
@public @timing_stats() def DELETE(self, req):
try: (drive, part, account, container, obj) = req.split_path(4, 5, True) validate_device_partition(drive, part) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (('x-timestamp' not in req.headers) or (not check_float(req.header...
'Handle HTTP PUT request.'
@public @timing_stats() def PUT(self, req):
try: (drive, part, account, container, obj) = req.split_path(4, 5, True) validate_device_partition(drive, part) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (('x-timestamp' not in req.headers) or (not check_float(req.header...
'Handle HTTP HEAD request.'
@public @timing_stats(sample_rate=0.1) def HEAD(self, req):
try: (drive, part, account, container, obj) = req.split_path(4, 5, True) validate_device_partition(drive, part) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (self.mount_check and (not check_mount(self.root, drive))): ...
'Will check the last parameter and if it starts with \'swift_bytes=\' will strip it off. Returns either the passed in content_type and size or the content_type without the swift_bytes param and its value as the new size. :params content_type: Content Type from db :params size: # bytes from db, an int :returns: tuple: c...
def derive_content_type_metadata(self, content_type, size):
if (';' in content_type): (new_content_type, param) = content_type.rsplit(';', 1) if param.lstrip().startswith('swift_bytes='): (key, value) = param.split('=') try: return (new_content_type, int(value)) except ValueError: self.logge...
'Handle HTTP GET request.'
@public @timing_stats() def GET(self, req):
try: (drive, part, account, container, obj) = req.split_path(4, 5, True) validate_device_partition(drive, part) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (self.mount_check and (not check_mount(self.root, drive))): ...
'Handle HTTP REPLICATE request (json-encoded RPC calls for replication.)'
@public @timing_stats(sample_rate=0.01) def REPLICATE(self, req):
try: post_args = req.split_path(3) (drive, partition, hash) = post_args validate_device_partition(drive, partition) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (self.mount_check and (not check_mount(self.root, driv...
'Handle HTTP POST request.'
@public @timing_stats() def POST(self, req):
try: (drive, part, account, container) = req.split_path(4) validate_device_partition(drive, part) except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req) if (('x-timestamp' not in req.headers) or (not check_float(req.headers['x-timestamp...
'Run the container audit until stopped.'
def run_forever(self, *args, **kwargs):
reported = time.time() time.sleep((random() * self.interval)) while True: self.logger.info(_('Begin container audit pass.')) begin = time.time() try: reported = self._one_audit_pass(reported) except (Exception, Timeout): self.logger.increment(...
'Run the container audit once.'
def run_once(self, *args, **kwargs):
self.logger.info(_('Begin container audit "once" mode')) begin = reported = time.time() self._one_audit_pass(reported) elapsed = (time.time() - begin) self.logger.info(_('Container audit "once" mode completed: %.02fs'), elapsed) dump_recon_cache({'container_auditor_pas...
'Audits the given container path :param path: the path to a container db'
def container_audit(self, path):
start_time = time.time() try: if (not path.endswith('.db')): return broker = ContainerBroker(path) if (not broker.is_deleted()): broker.get_info() self.logger.increment('passes') self.container_passes += 1 self.logger.debug(_('A...
'read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.'
def read(self, size=(-1)):
if (size < 0): chunk = self._chunk self._chunk = '' return (chunk + ''.join(self.iterator)) chunk = self._chunk self._chunk = '' if (chunk and (len(chunk) <= size)): return chunk try: chunk += self.iterator.next() except StopIteration: pass if ...
'Runs container sync scans until stopped.'
def run_forever(self):
sleep((random() * self.interval)) while True: begin = time() all_locs = audit_location_generator(self.devices, container_server.DATADIR, mount_check=self.mount_check, logger=self.logger) for (path, device, partition) in all_locs: self.container_sync(path) if ((tim...
'Runs a single container sync scan.'
def run_once(self):
self.logger.info(_('Begin container sync "once" mode')) begin = time() all_locs = audit_location_generator(self.devices, container_server.DATADIR, mount_check=self.mount_check, logger=self.logger) for (path, device, partition) in all_locs: self.container_sync(path) if ((time(...
'Writes a report of the stats to the logger and resets the stats for the next report.'
def report(self):
self.logger.info(_('Since %(time)s: %(sync)s synced [%(delete)s deletes, %(put)s puts], %(skip)s skipped, %(fail)s failed'), {'time': ctime(self.reported), 'sync': self.container_syncs, 'delete': self.container_deletes, 'put': self.container_puts, 'skip': self.container_skips, 'fail...
'Checks the given path for a container database, determines if syncing is turned on for that database and, if so, sends any updates to the other container. :param path: the path to a container db'
def container_sync(self, path):
try: if (not path.endswith('.db')): return broker = ContainerBroker(path) info = broker.get_info() (x, nodes) = self.container_ring.get_nodes(info['account'], info['container']) for (ordinal, node) in enumerate(nodes): if ((node['ip'] in self._myips) a...
'Sends the update the row indicates to the sync_to container. :param row: The updated row in the local database triggering the sync update. :param sync_to: The URL to the remote container. :param sync_key: The X-Container-Sync-Key to use when sending requests to the other container. :param broker: The local container d...
def container_sync_row(self, row, sync_to, sync_key, broker, info):
try: start_time = time() if row['deleted']: try: delete_object(sync_to, name=row['name'], headers={'x-timestamp': row['created_at'], 'x-container-sync-key': sync_key}, proxy=self.proxy) except ClientException as err: if (err.http_status != HTTP...
'Encapsulates working with a database.'
def __init__(self, db_file, timeout=BROKER_TIMEOUT, logger=None, account=None, container=None, pending_timeout=10, stale_reads_ok=False):
self.conn = None self.db_file = db_file self.pending_file = (self.db_file + '.pending') self.pending_timeout = pending_timeout self.stale_reads_ok = stale_reads_ok self.db_dir = os.path.dirname(db_file) self.timeout = timeout self.logger = (logger or logging.getLogger()) self.account...
'Create the DB :param put_timestamp: timestamp of initial PUT request'
def initialize(self, put_timestamp=None):
if (self.db_file == ':memory:'): tmp_db_file = None conn = get_db_connection(self.db_file, self.timeout) else: mkdirs(self.db_dir) (fd, tmp_db_file) = mkstemp(suffix='.tmp', dir=self.db_dir) os.close(fd) conn = sqlite3.connect(tmp_db_file, check_same_thread=False,...
'Mark the DB as deleted :param timestamp: delete timestamp'
def delete_db(self, timestamp):
timestamp = normalize_timestamp(timestamp) cleared_meta = {} for k in self.metadata.iterkeys(): cleared_meta[k] = ('', timestamp) self.update_metadata(cleared_meta) with self.get() as conn: self._delete_db(conn, timestamp) conn.commit()
'Checks the exception info to see if it indicates a quarantine situation (malformed or corrupted database). If not, the original exception will be reraised. If so, the database will be quarantined and a new sqlite3.DatabaseError will be raised indicating the action taken.'
def possibly_quarantine(self, exc_type, exc_value, exc_traceback):
if ('database disk image is malformed' in str(exc_value)): exc_hint = 'malformed' elif ('file is encrypted or is not a database' in str(exc_value)): exc_hint = 'corrupted' else: raise exc_type(*exc_value.args), None, exc_traceback prefix_path = os...
'Use with the "with" statement; returns a database connection.'
@contextmanager def get(self):
if (not self.conn): if ((self.db_file != ':memory:') and os.path.exists(self.db_file)): try: self.conn = get_db_connection(self.db_file, self.timeout) except (sqlite3.DatabaseError, DatabaseConnectionError): self.possibly_quarantine(*sys.exc_info()) ...
'Use with the "with" statement; locks a database.'
@contextmanager def lock(self):
if (not self.conn): if ((self.db_file != ':memory:') and os.path.exists(self.db_file)): self.conn = get_db_connection(self.db_file, self.timeout) else: raise DatabaseConnectionError(self.db_file, "DB doesn't exist") conn = self.conn self.conn = None orig_iso...
'Re-id the database. This should be called after an rsync. :param remote_id: the ID of the remote database being rsynced in'
def newid(self, remote_id):
with self.get() as conn: row = conn.execute(('\n UPDATE %s_stat SET id=?\n ' % self.db_type), (str(uuid4()),)) row = conn.execute(('\n ...
'Used in replication to handle updating timestamps. :param created_at: create timestamp :param put_timestamp: put timestamp :param delete_timestamp: delete timestamp'
def merge_timestamps(self, created_at, put_timestamp, delete_timestamp):
with self.get() as conn: conn.execute(('\n UPDATE %s_stat SET created_at=MIN(?, created_at),\n ...
'Get a list of objects in the database between start and end. :param start: start ROWID :param count: number to get :returns: list of objects between start and end'
def get_items_since(self, start, count):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: curs = conn.execute(('\n SELECT * FROM %s WHERE ROWID > ? ORDER BY ROWID ...
'Gets the most recent sync point for a server from the sync table. :param id: remote ID to get the sync_point for :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync :returns: the sync point, or -1 if the id doesn\'t exist.'
def get_sync(self, id, incoming=True):
with self.get() as conn: row = conn.execute(('SELECT sync_point FROM %s_sync WHERE remote_id=?' % ('incoming' if incoming else 'outgoing')), (id,)).fetchone() if (not row): return (-1) return row['sync_point']
'Get a serialized copy of the sync table. :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync :returns: list of {\'remote_id\', \'sync_point\'}'
def get_syncs(self, incoming=True):
with self.get() as conn: curs = conn.execute((('\n SELECT remote_id, sync_point FROM %s_sync\n ' % 'incoming') if incoming else 'outgoing')) result = [] for row in curs: ...
'Get information about the DB required for replication. :returns: dict containing keys: hash, id, created_at, put_timestamp, delete_timestamp, count, max_row, and metadata'
def get_replication_info(self):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise query_part1 = ('\n SELECT hash, id, created_at, put_timestamp, delete_timestamp,\n ...
'Merge a list of sync points with the incoming sync table. :param sync_points: list of sync points where a sync point is a dict of {\'sync_point\', \'remote_id\'} :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync'
def merge_syncs(self, sync_points, incoming=True):
with self.get() as conn: for rec in sync_points: try: conn.execute(('\n INSERT INTO %s_sync (sync_point, remote_id)\n ...
'The idea is to allocate space in front of an expanding db. If it gets within 512k of a boundary, it allocates to the next boundary. Boundaries are 2m, 5m, 10m, 25m, 50m, then every 50m after.'
def _preallocate(self):
if ((not DB_PREALLOCATION) or (self.db_file == ':memory:')): return MB = (1024 * 1024) def prealloc_points(): for pm in (1, 2, 5, 10, 25, 50): (yield (pm * MB)) while True: pm += 50 (yield (pm * MB)) stat = os.stat(self.db_file) file_size =...
'Returns the metadata dict for the database. The metadata dict values are tuples of (value, timestamp) where the timestamp indicates when that key was set to that value.'
@property def metadata(self):
with self.get() as conn: try: metadata = conn.execute(('SELECT metadata FROM %s_stat' % self.db_type)).fetchone()[0] except sqlite3.OperationalError as err: if ('no such column: metadata' not in str(err)): raise metadata = '' ...
'Updates the metadata dict for the database. The metadata dict values are tuples of (value, timestamp) where the timestamp indicates when that key was set to that value. Key/values will only be overwritten if the timestamp is newer. To delete a key, set its value to (\'\', timestamp). These empty keys will eventually b...
def update_metadata(self, metadata_updates):
old_metadata = self.metadata if set(metadata_updates).issubset(set(old_metadata)): for (key, (value, timestamp)) in metadata_updates.iteritems(): if (timestamp > old_metadata[key][1]): break else: return with self.get() as conn: try: ...
'Removes any empty metadata values older than the timestamp'
def reclaim(self, timestamp):
if (not self.metadata): return with self.get() as conn: if self._reclaim(conn, timestamp): conn.commit()
'Removes any empty metadata values older than the timestamp using the given database connection. This function will not call commit on the conn, but will instead return True if the database needs committing. This function was created as a worker to limit transactions and commits from other related functions. :param con...
def _reclaim(self, conn, timestamp):
try: md = conn.execute(('SELECT metadata FROM %s_stat' % self.db_type)).fetchone()[0] if md: md = json.loads(md) keys_to_delete = [] for (key, (value, value_timestamp)) in md.iteritems(): if ((value == '') and (value_timestamp < timestamp)...
'Creates a brand new database (tables, indices, triggers, etc.)'
def _initialize(self, conn, put_timestamp):
if (not self.account): raise ValueError('Attempting to create a new database with no account set') if (not self.container): raise ValueError('Attempting to create a new database with no container set') self.create_object_table(conn) s...
'Create the object table which is specifc to the container DB. :param conn: DB connection object'
def create_object_table(self, conn):
conn.executescript("\n CREATE TABLE object (\n ROWID INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n ...
'Create the container_stat table which is specific to the container DB. :param conn: DB connection object :param put_timestamp: put timestamp'
def create_container_stat_table(self, conn, put_timestamp=None):
if (put_timestamp is None): put_timestamp = normalize_timestamp(0) conn.executescript("\n CREATE TABLE container_stat (\n account TEXT,\n ...
'Update the put_timestamp. Only modifies it if it is greater than the current timestamp. :param timestamp: put timestamp'
def update_put_timestamp(self, timestamp):
with self.get() as conn: conn.execute('\n UPDATE container_stat SET put_timestamp = ?\n WHERE put_timestamp < ? ', (timestamp, timestamp)) conn.com...
'Mark the DB as deleted :param conn: DB connection object :param timestamp: timestamp to mark as deleted'
def _delete_db(self, conn, timestamp):
conn.execute("\n UPDATE container_stat\n SET delete_timestamp = ?,\n status = 'DELETED',\n ...
'Check if the DB is empty. :returns: True if the database has no active objects, False otherwise'
def empty(self):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: row = conn.execute('SELECT object_count from container_stat').fetchone() return (row[0] == 0)
'Handles committing rows in .pending files.'
def _commit_puts(self, item_list=None):
if ((self.db_file == ':memory:') or (not os.path.exists(self.pending_file))): return if (item_list is None): item_list = [] with lock_parent_directory(self.pending_file, self.pending_timeout): self._preallocate() if (not os.path.getsize(self.pending_file)): if ite...
'Delete rows from the object table that are marked deleted and whose created_at timestamp is < object_timestamp. Also deletes rows from incoming_sync and outgoing_sync where the updated_at timestamp is < sync_timestamp. In addition, this calls the DatabaseBroker\'s :func:_reclaim method. :param object_timestamp: max c...
def reclaim(self, object_timestamp, sync_timestamp):
self._commit_puts() with self.get() as conn: conn.execute('\n DELETE FROM object\n WHERE deleted = 1\n ...
'Mark an object deleted. :param name: object name to be deleted :param timestamp: timestamp when the object was marked as deleted'
def delete_object(self, name, timestamp):
self.put_object(name, timestamp, 0, 'application/deleted', 'noetag', 1)
'Creates an object in the DB with its metadata. :param name: object name to be created :param timestamp: timestamp of when the object was created :param size: object size :param content_type: object content-type :param etag: object etag :param deleted: if True, marks the object as deleted and sets the deteleted_at time...
def put_object(self, name, timestamp, size, content_type, etag, deleted=0):
record = {'name': name, 'created_at': timestamp, 'size': size, 'content_type': content_type, 'etag': etag, 'deleted': deleted} if (self.db_file == ':memory:'): self.merge_items([record]) return if (not os.path.exists(self.db_file)): raise DatabaseConnectionError(self.db_file, "DB ...
'Check if the DB is considered to be deleted. :returns: True if the DB is considered to be deleted, False otherwise'
def is_deleted(self, timestamp=None):
if ((self.db_file != ':memory:') and (not os.path.exists(self.db_file))): return True try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: row = conn.execute('\n ...
'Get global data for the container. :returns: dict with keys: account, container, created_at, put_timestamp, delete_timestamp, object_count, bytes_used, reported_put_timestamp, reported_delete_timestamp, reported_object_count, reported_bytes_used, hash, id, x_container_sync_point1, and x_container_sync_point2. If inclu...
def get_info(self, include_metadata=False):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: data = None trailing1 = 'metadata' trailing2 = 'x_container_sync_point1, x_container_sync_point2' while (not data): try: ...
'Update reported stats. :param put_timestamp: put_timestamp to update :param delete_timestamp: delete_timestamp to update :param object_count: object_count to update :param bytes_used: bytes_used to update'
def reported(self, put_timestamp, delete_timestamp, object_count, bytes_used):
with self.get() as conn: conn.execute('\n UPDATE container_stat\n SET reported_put_timestamp = ?, reported_delete_timestamp = ?,\n ...
'Get a list of objects sorted by name starting at marker onward, up to limit entries. Entries will begin with the prefix and will not have the delimiter after the prefix. :param limit: maximum number of entries to get :param marker: marker query :param end_marker: end marker query :param prefix: prefix query :param de...
def list_objects_iter(self, limit, marker, end_marker, prefix, delimiter, path=None):
(marker, end_marker, prefix, delimiter, path) = utf8encode(marker, end_marker, prefix, delimiter, path) try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise if (path is not None): prefix = path if path: prefix = path = (...
'Merge items into the object table. :param item_list: list of dictionaries of {\'name\', \'created_at\', \'size\', \'content_type\', \'etag\', \'deleted\'} :param source: if defined, update incoming_sync with the source'
def merge_items(self, item_list, source=None):
with self.get() as conn: max_rowid = (-1) for rec in item_list: query = '\n DELETE FROM object\n WHERE name = ? ...
'Create a brand new database (tables, indices, triggers, etc.) :param conn: DB connection object :param put_timestamp: put timestamp'
def _initialize(self, conn, put_timestamp):
if (not self.account): raise ValueError('Attempting to create a new database with no account set') self.create_container_table(conn) self.create_account_stat_table(conn, put_timestamp)
'Create container table which is specific to the account DB. :param conn: DB connection object'
def create_container_table(self, conn):
conn.executescript("\n CREATE TABLE container (\n ROWID INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n ...
'Create account_stat table which is specific to the account DB. :param conn: DB connection object :param put_timestamp: put timestamp'
def create_account_stat_table(self, conn, put_timestamp):
conn.executescript("\n CREATE TABLE account_stat (\n account TEXT,\n created_at TEXT,\n ...
'Update the put_timestamp. Only modifies it if it is greater than the current timestamp. :param timestamp: put timestamp'
def update_put_timestamp(self, timestamp):
with self.get() as conn: conn.execute('\n UPDATE account_stat SET put_timestamp = ?\n WHERE put_timestamp < ? ', (timestamp, timestamp)) conn.commi...
'Mark the DB as deleted. :param conn: DB connection object :param timestamp: timestamp to mark as deleted'
def _delete_db(self, conn, timestamp, force=False):
conn.execute("\n UPDATE account_stat\n SET delete_timestamp = ?,\n status = 'DELETED',\n ...
'Handles committing rows in .pending files.'
def _commit_puts(self, item_list=None):
if ((self.db_file == ':memory:') or (not os.path.exists(self.pending_file))): return if (item_list is None): item_list = [] with lock_parent_directory(self.pending_file, self.pending_timeout): self._preallocate() if (not os.path.getsize(self.pending_file)): if ite...
'Check if the account DB is empty. :returns: True if the database has no active containers.'
def empty(self):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: row = conn.execute('SELECT container_count from account_stat').fetchone() return (row[0] == 0)
'Delete rows from the container table that are marked deleted and whose created_at timestamp is < container_timestamp. Also deletes rows from incoming_sync and outgoing_sync where the updated_at timestamp is < sync_timestamp. In addition, this calls the DatabaseBroker\'s :func:_reclaim method. :param container_timesta...
def reclaim(self, container_timestamp, sync_timestamp):
self._commit_puts() with self.get() as conn: conn.execute('\n DELETE FROM container WHERE\n deleted = 1 AND delete_timestamp < ?\n ...
'Create a container with the given attributes. :param name: name of the container to create :param put_timestamp: put_timestamp of the container to create :param delete_timestamp: delete_timestamp of the container to create :param object_count: number of objects in the container :param bytes_used: number of bytes used ...
def put_container(self, name, put_timestamp, delete_timestamp, object_count, bytes_used):
if ((delete_timestamp > put_timestamp) and (object_count in (None, '', 0, '0'))): deleted = 1 else: deleted = 0 record = {'name': name, 'put_timestamp': put_timestamp, 'delete_timestamp': delete_timestamp, 'object_count': object_count, 'bytes_used': bytes_used, 'deleted': deleted} if (se...
'Check if the accont DB can be deleted. :returns: True if the account can be deleted, False otherwise'
def can_delete_db(self, cutoff):
self._commit_puts() with self.get() as conn: row = conn.execute('\n SELECT status, put_timestamp, delete_timestamp, container_count\n FROM account_stat').fetchone(...
'Check if the account DB is considered to be deleted. :returns: True if the account DB is considered to be deleted, False otherwise'
def is_deleted(self):
if ((self.db_file != ':memory:') and (not os.path.exists(self.db_file))): return True try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: row = conn.execute('\n ...
'Only returns true if the status field is set to DELETED.'
def is_status_deleted(self):
with self.get() as conn: row = conn.execute('\n SELECT status\n FROM account_stat').fetchone() return (row['status'] == 'DELETED')
'Get global data for the account. :returns: dict with keys: account, created_at, put_timestamp, delete_timestamp, container_count, object_count, bytes_used, hash, id'
def get_info(self):
try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise with self.get() as conn: return dict(conn.execute('\n SELECT account, created_at, put_timestamp, delete_timestam...
'Get a list of containerss sorted by name starting at marker onward, up to limit entries. Entries will begin with the prefix and will not have the delimiter after the prefix. :param limit: maximum number of entries to get :param marker: marker query :param end_marker: end marker query :param prefix: prefix query :para...
def list_containers_iter(self, limit, marker, end_marker, prefix, delimiter):
(marker, end_marker, prefix, delimiter) = utf8encode(marker, end_marker, prefix, delimiter) try: self._commit_puts() except LockTimeout: if (not self.stale_reads_ok): raise if (delimiter and (not prefix)): prefix = '' orig_marker = marker with self.get() as co...
'Merge items into the container table. :param item_list: list of dictionaries of {\'name\', \'put_timestamp\', \'delete_timestamp\', \'object_count\', \'bytes_used\', \'deleted\'} :param source: if defined, update incoming_sync with the source'
def merge_items(self, item_list, source=None):
with self.get() as conn: max_rowid = (-1) for rec in item_list: record = [rec['name'], rec['put_timestamp'], rec['delete_timestamp'], rec['object_count'], rec['bytes_used'], rec['deleted']] query = '\n ...
'Override this to run the script once'
def run_once(self, *args, **kwargs):
raise NotImplementedError('run_once not implemented')
'Override this to run forever'
def run_forever(self, *args, **kwargs):
raise NotImplementedError('run_forever not implemented')
'Run the daemon'
def run(self, once=False, **kwargs):
utils.validate_configuration() utils.drop_privileges(self.conf.get('user', 'swift')) utils.capture_stdio(self.logger, **kwargs) def kill_children(*args): signal.signal(signal.SIGTERM, signal.SIG_IGN) os.killpg(0, signal.SIGTERM) sys.exit() signal.signal(signal.SIGTERM, kill_c...
'Accepts a standard WSGI application call, authenticating the request and installing callback hooks for authorization and ACL header validation. For an authenticated request, REMOTE_USER will be set to a comma separated list of the user\'s groups. With a non-empty reseller prefix, acts as the definitive auth service fo...
def __call__(self, env, start_response):
if (self.allow_overrides and env.get('swift.authorize_override', False)): return self.app(env, start_response) if env.get('PATH_INFO', '').startswith(self.auth_prefix): return self.handle(env, start_response) s3 = env.get('HTTP_AUTHORIZATION') token = env.get('HTTP_X_AUTH_TOKEN', env.get...
'Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated list of groups the authenticated user is a member of. The first group in the list is also c...
def get_groups(self, env, token):
groups = None memcache_client = cache_from_env(env) if (not memcache_client): raise Exception('Memcache required') memcache_token_key = ('%s/token/%s' % (self.reseller_prefix, token)) cached_auth_data = memcache_client.get(memcache_token_key) if cached_auth_data: (expires, gro...
'Returns None if the request is authorized to continue or a standard WSGI response callable if not.'
def authorize(self, req):
try: (version, account, container, obj) = req.split_path(1, 4, True) except ValueError: self.logger.increment('errors') return HTTPNotFound(request=req) if ((not account) or (not account.startswith(self.reseller_prefix))): self.logger.debug(("Account name: %s doesn't...
'Returns a standard WSGI response callable with the status of 403 or 401 depending on whether the REMOTE_USER is set or not.'
def denied_response(self, req):
if req.remote_user: self.logger.increment('forbidden') return HTTPForbidden(request=req) else: self.logger.increment('unauthorized') return HTTPUnauthorized(request=req)
'WSGI entry point for auth requests (ones that match the self.auth_prefix). Wraps env in swob.Request object and passes it down. :param env: WSGI environment dictionary :param start_response: WSGI callable'
def handle(self, env, start_response):
try: req = Request(env) if self.auth_prefix: req.path_info_pop() req.bytes_transferred = '-' req.client_disconnect = False if (('x-storage-token' in req.headers) and ('x-auth-token' not in req.headers)): req.headers['x-auth-token'] = req.headers['x-sto...
'Entry point for auth requests (ones that match the self.auth_prefix). Should return a WSGI-style callable (such as swob.Response). :param req: swob.Request object'
def handle_request(self, req):
req.start_time = time() handler = None try: (version, account, user, _junk) = req.split_path(1, 4, True) except ValueError: self.logger.increment('errors') return HTTPNotFound(request=req) if (version in ('v1', 'v1.0', 'auth')): if (req.method == 'GET'): h...
'Handles the various `request for token and service end point(s)` calls. There are various formats to support the various auth servers in the past. Examples:: GET <auth-prefix>/v1/<act>/auth X-Auth-User: <act>:<usr> or X-Storage-User: <usr> X-Auth-Key: <key> or X-Storage-Pass: <key> GET <auth-prefix>/auth X-...
def handle_get_token(self, req):
try: pathsegs = split_path(req.path_info, 1, 3, True) except ValueError: self.logger.increment('errors') return HTTPNotFound(request=req) if ((pathsegs[0] == 'v1') and (pathsegs[2] == 'auth')): account = pathsegs[1] user = req.headers.get('x-storage-user') if ...
'Sends the error response to the remote client, possibly resolving a custom error response body based on x-container-meta-web-error. :param response: The error response we should default to sending. :param env: The original request WSGI environment. :param start_response: The WSGI start_response hook.'
def _error_response(self, response, env, start_response):
if (not self._error): start_response(self._response_status, self._response_headers, self._response_exc_info) return response save_response_status = self._response_status save_response_headers = self._response_headers save_response_exc_info = self._response_exc_info resp = self._app_c...
'Retrieves x-container-meta-web-index, x-container-meta-web-error, x-container-meta-web-listings, and x-container-meta-web-listings-css from memcache or from the cluster and stores the result in memcache and in self._index, self._error, self._listings, and self._listings_css. :param env: The WSGI environment dict.'
def _get_container_info(self, env):
self._index = self._error = self._listings = self._listings_css = None memcache_client = cache_from_env(env) if memcache_client: memcache_key = ('/staticweb/%s/%s/%s' % (self.version, self.account, self.container)) cached_data = memcache_client.get(memcache_key) if cached_data: ...
'Sends an HTML object listing to the remote client. :param env: The original WSGI environment dict. :param start_response: The original WSGI start_response hook. :param prefix: Any prefix desired for the container listing.'
def _listing(self, env, start_response, prefix=None):
if (not config_true_value(self._listings)): resp = HTTPNotFound()(env, self._start_response) return self._error_response(resp, env, start_response) tmp_env = make_pre_authed_env(env, 'GET', ('/%s/%s/%s' % (self.version, self.account, self.container)), self.agent, swift_source='SW') tmp_env['...
'Constructs a relative path from a given prefix within the container. URLs and paths starting with \'/\' are not modified. :param prefix: The prefix for the container listing.'
def _build_css_path(self, prefix=''):
if self._listings_css.startswith(('/', 'http://', 'https://')): css_path = quote(self._listings_css, ':/') else: css_path = (('../' * prefix.count('/')) + quote(self._listings_css)) return css_path
'Handles a possible static web request for a container. :param env: The original WSGI environment dict. :param start_response: The original WSGI start_response hook.'
def handle_container(self, env, start_response):
self._get_container_info(env) if ((not self._listings) and (not self._index)): if config_true_value(env.get('HTTP_X_WEB_MODE', 'f')): return HTTPNotFound()(env, start_response) return self.app(env, start_response) if (env['PATH_INFO'][(-1)] != '/'): resp = HTTPMovedPerman...
'Handles a possible static web request for an object. This object could resolve into an index or listing request. :param env: The original WSGI environment dict. :param start_response: The original WSGI start_response hook.'
def handle_object(self, env, start_response):
tmp_env = dict(env) tmp_env['HTTP_USER_AGENT'] = ('%s StaticWeb' % env.get('HTTP_USER_AGENT')) tmp_env['swift.source'] = 'SW' resp = self._app_call(tmp_env) status_int = self._get_status_int() if (is_success(status_int) or is_redirection(status_int)): start_response(self._response_sta...
'Main hook into the WSGI paste.deploy filter/app pipeline. :param env: The WSGI environment dict. :param start_response: The WSGI start_response hook.'
def __call__(self, env, start_response):
env['staticweb.start_time'] = time.time() try: (version, account, container, obj) = split_path(env['PATH_INFO'], 2, 4, True) except ValueError: return self.app(env, start_response) if ((env['REQUEST_METHOD'] in ('PUT', 'POST')) and container and (not obj)): memcache_client = cach...
'Checks req.path for any forbidden characters Returns True if there are any forbidden characters Returns False if there aren\'t any forbidden characters'
def check_character(self, req):
self.logger.debug(('name_check: path %s' % req.path)) self.logger.debug(('name_check: self.forbidden_chars %s' % self.forbidden_chars)) for c in unquote(req.path): if (c in self.forbidden_chars): return True else: pass return False
'Checks that req.path doesn\'t exceed the defined maximum length Returns True if the length exceeds the maximum Returns False if the length is <= the maximum'
def check_length(self, req):
length = len(unquote(req.path)) if (length > self.maximum_length): return True else: return False
'Checks that req.path doesn\'t contain a substring matching regexps. Returns True if there are any forbidden substring Returns False if there aren\'t any forbidden substring'
def check_regexp(self, req):
if (self.forbidden_regexp_compiled is None): return False self.logger.debug(('name_check: path %s' % req.path)) self.logger.debug(('name_check: self.forbidden_regexp %s' % self.forbidden_regexp)) unquoted_path = unquote(req.path) match = self.forbidden_regexp_compiled.search(unqu...