desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Determine whether or not two replicas of a databases are considered
to be in sync.
:param rinfo: remote database info
:param info: local database info
:param broker: database broker object
:param local_sync: cached last sync point between replicas
:returns: boolean indicating whether or not the replicas are in sync'
| def _in_sync(self, rinfo, info, broker, local_sync):
| if (max(rinfo['point'], local_sync) >= info['max_row']):
self.stats['no_change'] += 1
self.logger.increment('no_changes')
return True
if (rinfo['hash'] == info['hash']):
self.stats['hashmatch'] += 1
self.logger.increment('hashmatches')
broker.merge_syncs([{'remote... |
'Make an http_connection using ReplConnection
:param node: node dictionary from the ring
:param partition: partition partition to send in the url
:param db_file: DB file
:returns: ReplConnection object'
| def _http_connect(self, node, partition, db_file):
| return ReplConnection(node, partition, os.path.basename(db_file).split('.', 1)[0], self.logger)
|
'Replicate a database to a node.
:param node: node dictionary from the ring to be replicated to
:param broker: DB broker for the DB to be replication
:param partition: partition on the node to replicate to
:param info: DB info as a dictionary of {\'max_row\', \'hash\', \'id\',
\'created_at\', \'put_timestamp\', \'delet... | def _repl_to_node(self, node, broker, partition, info):
| with ConnectionTimeout(self.conn_timeout):
http = self._http_connect(node, partition, broker.db_file)
if (not http):
self.logger.error(_('ERROR Unable to connect to remote server: %s'), node)
return False
with Timeout(self.node_timeout):
response = http.r... |
'Replicate the db, choosing method based on whether or not it
already exists on peers.
:param partition: partition to be replicated to
:param object_file: DB file name to be replicated
:param node_id: node id of the node to be replicated to'
| def _replicate_object(self, partition, object_file, node_id):
| start_time = time.time()
self.logger.debug(_('Replicating db %s'), object_file)
self.stats['attempted'] += 1
self.logger.increment('attempts')
try:
broker = self.brokerclass(object_file, pending_timeout=30)
broker.reclaim((time.time() - self.reclaim_age), (time.time() - (self.r... |
'Extract the device name from an object path. Returns "UNKNOWN" if the
path could not be extracted successfully for some reason.
:param object_file: the path to a database file.'
| def extract_device(self, object_file):
| match = self.extract_device_re.match(object_file)
if match:
return match.groups()[0]
return 'UNKNOWN'
|
'Run a replication pass once.'
| def run_once(self, *args, **kwargs):
| self._zero_stats()
dirs = []
ips = whataremyips()
if (not ips):
self.logger.error(_('ERROR Failed to get my own IPs?'))
return
for node in self.ring.devs:
if (node and (node['ip'] in ips) and (node['port'] == self.port)):
if (self.mount_check and... |
'Replicate dbs under the given root in an infinite loop.'
| def run_forever(self, *args, **kwargs):
| sleep((random.random() * self.interval))
while True:
begin = time.time()
try:
self.run_once()
except (Exception, Timeout):
self.logger.exception(_('ERROR trying to replicate'))
elapsed = (time.time() - begin)
if (elapsed < self.interval):
... |
'display status of tracked pids for server'
| @command
def status(self, **kwargs):
| status = 0
for server in self.servers:
status += server.status(**kwargs)
return status
|
'starts a server'
| @command
def start(self, **kwargs):
| setup_env()
status = 0
for server in self.servers:
server.launch(**kwargs)
if (not kwargs.get('daemon', True)):
for server in self.servers:
try:
status += server.interact(**kwargs)
except KeyboardInterrupt:
print _('\nuser quit')... |
'spawn server and return immediately'
| @command
def no_wait(self, **kwargs):
| kwargs['wait'] = False
return self.start(**kwargs)
|
'start a server interactively'
| @command
def no_daemon(self, **kwargs):
| kwargs['daemon'] = False
return self.start(**kwargs)
|
'start server and run one pass on supporting daemons'
| @command
def once(self, **kwargs):
| kwargs['once'] = True
return self.start(**kwargs)
|
'stops a server'
| @command
def stop(self, **kwargs):
| server_pids = {}
for server in self.servers:
signaled_pids = server.stop(**kwargs)
if (not signaled_pids):
print (_('No %s running') % server)
else:
server_pids[server] = signaled_pids
signaled_pids = [p for (server, pids) in server_pids.items() for p in... |
'allow current requests to finish on supporting servers'
| @command
def shutdown(self, **kwargs):
| kwargs['graceful'] = True
status = 0
status += self.stop(**kwargs)
return status
|
'stops then restarts server'
| @command
def restart(self, **kwargs):
| status = 0
status += self.stop(**kwargs)
status += self.start(**kwargs)
return status
|
'graceful shutdown then restart on supporting servers'
| @command
def reload(self, **kwargs):
| kwargs['graceful'] = True
status = 0
for server in self.servers:
m = Manager([server.server])
status += m.stop(**kwargs)
status += m.start(**kwargs)
return status
|
'alias for reload'
| @command
def force_reload(self, **kwargs):
| return self.reload(**kwargs)
|
'Find and return the decorated method named like cmd
:param cmd: the command to get, a string, if not found raises
UnknownCommandError'
| def get_command(self, cmd):
| cmd = cmd.lower().replace('-', '_')
try:
f = getattr(self, cmd)
except AttributeError:
raise UnknownCommandError(cmd)
if (not hasattr(f, 'publicly_accessible')):
raise UnknownCommandError(cmd)
return f
|
'Get all publicly accessible commands
:returns: a list of string tuples (cmd, help), the method names who are
decorated as commands'
| @classmethod
def list_commands(cls):
| get_method = (lambda cmd: getattr(cls, cmd))
return sorted([(x.replace('_', '-'), get_method(x).__doc__.strip()) for x in dir(cls) if getattr(get_method(x), 'publicly_accessible', False)])
|
'Find the named command and run it
:param cmd: the command name to run'
| def run_command(self, cmd, **kwargs):
| f = self.get_command(cmd)
return f(**kwargs)
|
'Translate conf_file to a corresponding pid_file
:param conf_file: an conf_file for this server, a string
:returns: the pid_file for this conf_file'
| def get_pid_file_name(self, conf_file):
| return (conf_file.replace(os.path.normpath(SWIFT_DIR), self.run_dir, 1).replace(('%s-server' % self.type), self.server, 1).rsplit('.conf', 1)[0] + '.pid')
|
'Translate pid_file to a corresponding conf_file
:param pid_file: a pid_file for this server, a string
:returns: the conf_file for this pid_file'
| def get_conf_file_name(self, pid_file):
| if (self.server in STANDALONE_SERVERS):
return (pid_file.replace(os.path.normpath(self.run_dir), SWIFT_DIR, 1).rsplit('.pid', 1)[0] + '.conf')
else:
return (pid_file.replace(os.path.normpath(self.run_dir), SWIFT_DIR, 1).replace(self.server, ('%s-server' % self.type), 1).rsplit('.pid', 1)[0] + '.... |
'Get conf files for this server
:param: number, if supplied will only lookup the nth server
:returns: list of conf files'
| def conf_files(self, **kwargs):
| if (self.server in STANDALONE_SERVERS):
found_conf_files = search_tree(SWIFT_DIR, (self.server + '*'), '.conf')
else:
found_conf_files = search_tree(SWIFT_DIR, ('%s-server*' % self.type), '.conf')
number = kwargs.get('number')
if number:
try:
conf_files = [found_conf_... |
'Get pid files for this server
:param: number, if supplied will only lookup the nth server
:returns: list of pid files'
| def pid_files(self, **kwargs):
| pid_files = search_tree(self.run_dir, ('%s*' % self.server), '.pid')
if kwargs.get('number', 0):
conf_files = self.conf_files(**kwargs)
pid_files = [pid_file for pid_file in pid_files if (self.get_conf_file_name(pid_file) in conf_files)]
return pid_files
|
'Generator, yields (pid_file, pids)'
| def iter_pid_files(self, **kwargs):
| for pid_file in self.pid_files(**kwargs):
(yield (pid_file, int(open(pid_file).read().strip())))
|
'Send a signal to pids for this server
:param sig: signal to send
:returns: a dict mapping pids (ints) to pid_files (paths)'
| def signal_pids(self, sig, **kwargs):
| pids = {}
for (pid_file, pid) in self.iter_pid_files(**kwargs):
try:
if (sig != signal.SIG_DFL):
print (_('Signal %s pid: %s signal: %s') % (self.server, pid, sig))
os.kill(pid, sig)
except OSError as e:
if (e.errno == er... |
'Get running pids
:returns: a dict mapping pids (ints) to pid_files (paths)'
| def get_running_pids(self, **kwargs):
| return self.signal_pids(signal.SIG_DFL, **kwargs)
|
'Kill running pids
:param graceful: if True, attempt SIGHUP on supporting servers
:returns: a dict mapping pids (ints) to pid_files (paths)'
| def kill_running_pids(self, **kwargs):
| graceful = kwargs.get('graceful')
if (graceful and (self.server in GRACEFUL_SHUTDOWN_SERVERS)):
sig = signal.SIGHUP
else:
sig = signal.SIGTERM
return self.signal_pids(sig, **kwargs)
|
'Display status of server
:param: pids, if not supplied pids will be populated automatically
:param: number, if supplied will only lookup the nth server
:returns: 1 if server is not running, 0 otherwise'
| def status(self, pids=None, **kwargs):
| if (pids is None):
pids = self.get_running_pids(**kwargs)
if (not pids):
number = kwargs.get('number', 0)
if number:
kwargs['quiet'] = True
conf_files = self.conf_files(**kwargs)
if conf_files:
print (_('%s #%d not running (... |
'Launch a subprocess for this server.
:param conf_file: path to conf_file to use as first arg
:param once: boolean, add once argument to command
:param wait: boolean, if true capture stdout with a pipe
:param daemon: boolean, if true ask server to log to console
:returns : the pid of the spawned process'
| def spawn(self, conf_file, once=False, wait=True, daemon=True, **kwargs):
| args = [self.cmd, conf_file]
if once:
args.append('once')
if (not daemon):
args.append('verbose')
if (not daemon):
re_out = None
re_err = None
else:
re_err = subprocess.STDOUT
if wait:
re_out = subprocess.PIPE
else:
re_o... |
'wait on spawned procs to start'
| def wait(self, **kwargs):
| status = 0
for proc in self.procs:
output = proc.stdout.read()
if output:
print output
start = time.time()
while ((time.time() - start) < WARNING_WAIT):
time.sleep(0.1)
if (proc.poll() is not None):
status +=... |
'wait on spawned procs to terminate'
| def interact(self, **kwargs):
| status = 0
for proc in self.procs:
proc.communicate()
if proc.returncode:
status += 1
return status
|
'Collect conf files and attempt to spawn the processes for this server'
| def launch(self, **kwargs):
| conf_files = self.conf_files(**kwargs)
if (not conf_files):
return []
pids = self.get_running_pids(**kwargs)
already_started = False
for (pid, pid_file) in pids.items():
conf_file = self.get_conf_file_name(pid_file)
if (conf_file in conf_files):
already_started = ... |
'Send stop signals to pids for this server
:returns: a dict mapping pids (ints) to pid_files (paths)'
| def stop(self, **kwargs):
| return self.kill_running_pids(**kwargs)
|
'Retrieves a server conn from the pool, or connects a new one.
Chooses the server based on a consistent hash of "key".'
| def _get_conns(self, key):
| pos = bisect(self._sorted, key)
served = []
while (len(served) < self._tries):
pos = ((pos + 1) % len(self._sorted))
server = self._ring[self._sorted[pos]]
if (server in served):
continue
served.append(server)
if (self._error_limited[server] > time.time())... |
'Returns a server connection to the pool'
| def _return_conn(self, server, fp, sock):
| self._client_cache[server].append((fp, sock))
|
'Set a key/value pair in memcache
:param key: key
:param value: value
:param serialize: if True, value is serialized with JSON before sending
to memcache, or with pickle if configured to use
pickle instead of JSON (to avoid cache poisoning)
:param timeout: ttl in memcache, this parameter is now deprecated. It
will be r... | def set(self, key, value, serialize=True, timeout=0, time=0, min_compress_len=0):
| key = md5hash(key)
if timeout:
logging.warn('parameter timeout has been deprecated, use time')
timeout = sanitize_timeout((time or timeout))
flags = 0
if (serialize and self._allow_pickle):
value = pickle.dumps(value, PICKLE_PROTOCOL)
flags |= PICKLE_FLAG
... |
'Gets the object specified by key. It will also unserialize the object
before returning if it is serialized in memcache with JSON, or if it
is pickled and unpickling is allowed.
:param key: key
:returns: value of the key in memcache'
| def get(self, key):
| key = md5hash(key)
value = None
for (server, fp, sock) in self._get_conns(key):
try:
sock.sendall(('get %s\r\n' % key))
line = fp.readline().strip().split()
while (line[0].upper() != 'END'):
if ((line[0].upper() == 'VALUE') and (line[1] == key))... |
'Increments a key which has a numeric value by delta.
If the key can\'t be found, it\'s added as delta or 0 if delta < 0.
If passed a negative number, will use memcached\'s decr. Returns
the int stored in memcached
Note: The data memcached stores as the result of incr/decr is
an unsigned int. decr\'s that result in a ... | def incr(self, key, delta=1, time=0, timeout=0):
| if timeout:
logging.warn('parameter timeout has been deprecated, use time')
key = md5hash(key)
command = 'incr'
if (delta < 0):
command = 'decr'
delta = str(abs(int(delta)))
timeout = sanitize_timeout((time or timeout))
for (server, fp, sock) in self._get_co... |
'Decrements a key which has a numeric value by delta. Calls incr with
-delta.
:param key: key
:param delta: amount to subtract to the value of key (or set the
value to 0 if the key is not found) will be cast to
an int
:param time: the time to live. This parameter depcates parameter
timeout. The addition of this paramet... | def decr(self, key, delta=1, time=0, timeout=0):
| if timeout:
logging.warn('parameter timeout has been deprecated, use time')
self.incr(key, delta=(- delta), time=(time or timeout))
|
'Deletes a key/value pair from memcache.
:param key: key to be deleted'
| def delete(self, key):
| key = md5hash(key)
for (server, fp, sock) in self._get_conns(key):
try:
sock.sendall(('delete %s noreply\r\n' % key))
self._return_conn(server, fp, sock)
return
except Exception as e:
self._exception_occurred(server, e)
|
'Sets multiple key/value pairs in memcache.
:param mapping: dictonary of keys and values to be set in memcache
:param servery_key: key to use in determining which server in the ring
is used
:param serialize: if True, value is serialized with JSON before sending
to memcache, or with pickle if configured to use
pickle in... | def set_multi(self, mapping, server_key, serialize=True, timeout=0, time=0, min_compress_len=0):
| if timeout:
logging.warn('parameter timeout has been deprecated, use time')
server_key = md5hash(server_key)
timeout = sanitize_timeout((time or timeout))
msg = ''
for (key, value) in mapping.iteritems():
key = md5hash(key)
flags = 0
if (serialize an... |
'Gets multiple values from memcache for the given keys.
:param keys: keys for values to be retrieved from memcache
:param servery_key: key to use in determining which server in the ring
is used
:returns: list of values'
| def get_multi(self, keys, server_key):
| server_key = md5hash(server_key)
keys = [md5hash(key) for key in keys]
for (server, fp, sock) in self._get_conns(server_key):
try:
sock.sendall(('get %s\r\n' % ' '.join(keys)))
line = fp.readline().strip().split()
responses = {}
while (line[0].up... |
'Saves response info without sending it to the remote client.
Uses the same semantics as the usual WSGI start_response.'
| def _start_response(self, status, headers, exc_info=None):
| self._response_status = status
self._response_headers = headers
self._response_exc_info = exc_info
|
'Ensures start_response has been called before returning.'
| def _app_call(self, env):
| self._response_status = None
self._response_headers = None
self._response_exc_info = None
resp = self.app(env, self._start_response)
if (self._response_status is not None):
return resp
resp = iter(resp)
try:
first_chunk = resp.next()
except StopIteration:
return i... |
'Returns the HTTP status int from the last called self._start_response
result.'
| def _get_status_int(self):
| return int(self._response_status.split(' ', 1)[0])
|
'Returns str of value for given header key or None'
| def _response_header_value(self, key):
| for (h_key, val) in self._response_headers:
if (h_key.lower() == key.lower()):
return val
return None
|
'Reads a chunk from the file object.
Params are passed directly to the underlying file object\'s read().
:returns: Compressed chunk from file object.'
| def read(self, *a, **kw):
| if self.done:
return ''
x = self._f.read(*a, **kw)
if x:
self.crc32 = (zlib.crc32(x, self.crc32) & 4294967295L)
self.total_size += len(x)
compressed = self._compressor.compress(x)
if (not compressed):
compressed = self._compressor.flush(zlib.Z_SYNC_FLUSH)
... |
'Makes a request to Swift with retries.
:param method: HTTP method of request.
:param path: Path of request.
:param headers: Headers to be sent with request.
:param acceptable_statuses: List of acceptable statuses for request.
:param body_file: Body file to be passed along with request,
defaults to None.
:returns : Res... | def make_request(self, method, path, headers, acceptable_statuses, body_file=None):
| headers = dict(headers)
headers['user-agent'] = self.user_agent
resp = exc_type = exc_value = exc_traceback = None
for attempt in xrange(self.request_tries):
req = Request.blank(path, environ={'REQUEST_METHOD': method}, headers=headers)
if (body_file is not None):
if hasattr(... |
'Gets metadata by doing a HEAD on a path and using the metadata_prefix
to get values from the headers returned.
:param path: Path to do HEAD on.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to \'\'.
:param acceptable_statu... | def _get_metadata(self, path, metadata_prefix='', acceptable_statuses=(2,)):
| resp = self.make_request('HEAD', path, {}, acceptable_statuses)
if (not ((resp.status_int // 100) == 2)):
return {}
metadata_prefix = metadata_prefix.lower()
metadata = {}
for (k, v) in resp.headers.iteritems():
if k.lower().startswith(metadata_prefix):
metadata[k[len(met... |
'Returns an iterator of items from a json listing. Assumes listing has
\'name\' key defined and uses markers.
:param path: Path to do GET on.
:param marker: Prefix of first desired item, defaults to \'\'.
:param end_marker: Last item returned will be \'less\' than this,
defaults to \'\'.
:param acceptable_statuses: Li... | def _iter_items(self, path, marker='', end_marker='', acceptable_statuses=(2, HTTP_NOT_FOUND)):
| if isinstance(marker, unicode):
marker = marker.encode('utf8')
if isinstance(end_marker, unicode):
end_marker = end_marker.encode('utf8')
while True:
resp = self.make_request('GET', ('%s?format=json&marker=%s&end_marker=%s' % (path, quote(marker), quote(end_marker))), {}, acceptable_... |
'Returns a swift path for a request quoting and utf-8 encoding the path
parts as need be.
:param account: swift account
:param container: container, defaults to None
:param obj: object, defaults to None
:raises ValueError: Is raised if obj is specified and container is
not.'
| def make_path(self, account, container=None, obj=None):
| if isinstance(account, unicode):
account = account.encode('utf-8')
if isinstance(container, unicode):
container = container.encode('utf-8')
if isinstance(obj, unicode):
obj = obj.encode('utf-8')
path = ('/v1/%s' % quote(account))
if container:
path += ('/%s' % quote(c... |
'Sets metadata on path using metadata_prefix to set values in headers of
POST request.
:param path: Path to do POST on.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in headers
of requests, used to prefix keys in metadata
when setting metadata, defaults to \'\'.
:p... | def _set_metadata(self, path, metadata, metadata_prefix='', acceptable_statuses=(2,)):
| headers = {}
for (k, v) in metadata.iteritems():
if k.lower().startswith(metadata_prefix):
headers[k] = v
else:
headers[('%s%s' % (metadata_prefix, k))] = v
self.make_request('POST', path, headers, acceptable_statuses)
|
'Returns an iterator of containers dicts from an account.
:param account: Account on which to do the container listing.
:param marker: Prefix of first desired item, defaults to \'\'.
:param end_marker: Last item returned will be \'less\' than this,
defaults to \'\'.
:param acceptable_statuses: List of status for valid ... | def iter_containers(self, account, marker='', end_marker='', acceptable_statuses=(2, HTTP_NOT_FOUND)):
| path = self.make_path(account)
return self._iter_items(path, marker, end_marker, acceptable_statuses)
|
'Returns (container_count, object_count) for an account.
:param account: Account on which to get the information.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:... | def get_account_info(self, account, acceptable_statuses=(2, HTTP_NOT_FOUND)):
| path = self.make_path(account)
resp = self.make_request('HEAD', path, {}, acceptable_statuses)
if (not ((resp.status_int // 100) == 2)):
return (0, 0)
return (int(resp.headers.get('x-account-container-count', 0)), int(resp.headers.get('x-account-object-count', 0)))
|
'Gets account metadata.
:param account: Account on which to get the metadata.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to \'\'.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:returns... | def get_account_metadata(self, account, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account)
return self._get_metadata(path, metadata_prefix, acceptable_statuses)
|
'Sets account metadata. A call to this will add to the account
metadata and not overwrite all of it with values in the metadata dict.
To clear an account metadata value, pass an empty string as
the value for the key in the metadata dict.
:param account: Account on which to get the metadata.
:param metadata: Dict of me... | def set_account_metadata(self, account, metadata, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account)
self._set_metadata(path, metadata, metadata_prefix, acceptable_statuses)
|
'Checks to see if a container exists.
:param account: The container\'s account.
:param container: Container to check.
:returns : True if container exists, false otherwise.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised w... | def container_exists(self, account, container):
| path = self.make_path(account, container)
resp = self.make_request('HEAD', path, {}, (2, HTTP_NOT_FOUND))
return (not (resp.status_int == HTTP_NOT_FOUND))
|
'Creates container.
:param account: The container\'s account.
:param container: Container to create.
:param headers: Defaults to empty dict.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an accepta... | def create_container(self, account, container, headers=None, acceptable_statuses=(2,)):
| headers = (headers or {})
path = self.make_path(account, container)
self.make_request('PUT', path, headers, acceptable_statuses)
|
'Deletes a container.
:param account: The container\'s account.
:param container: Container to delete.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exce... | def delete_container(self, account, container, acceptable_statuses=(2, HTTP_NOT_FOUND)):
| path = self.make_path(account, container)
self.make_request('DELETE', path, {}, acceptable_statuses)
|
'Gets container metadata.
:param account: The container\'s account.
:param container: Container to get metadata on.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to \'\'.
:param acceptable_statuses: List of status for valid... | def get_container_metadata(self, account, container, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account, container)
return self._get_metadata(path, metadata_prefix, acceptable_statuses)
|
'Returns an iterator of object dicts from a container.
:param account: The container\'s account.
:param container: Container to iterate objects on.
:param marker: Prefix of first desired item, defaults to \'\'.
:param end_marker: Last item returned will be \'less\' than this,
defaults to \'\'.
:param acceptable_statuse... | def iter_objects(self, account, container, marker='', end_marker='', acceptable_statuses=(2, HTTP_NOT_FOUND)):
| path = self.make_path(account, container)
return self._iter_items(path, marker, end_marker, acceptable_statuses)
|
'Sets container metadata. A call to this will add to the container
metadata and not overwrite all of it with values in the metadata dict.
To clear a container metadata value, pass an empty string as the value
for the key in the metadata dict.
:param account: The container\'s account.
:param container: Container to set... | def set_container_metadata(self, account, container, metadata, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account, container)
self._set_metadata(path, metadata, metadata_prefix, acceptable_statuses)
|
'Deletes an object.
:param account: The object\'s account.
:param container: The object\'s container.
:param obj: The object.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an accepta... | def delete_object(self, account, container, obj, acceptable_statuses=(2, HTTP_NOT_FOUND)):
| path = self.make_path(account, container, obj)
self.make_request('DELETE', path, {}, acceptable_statuses)
|
'Gets object metadata.
:param account: The object\'s account.
:param container: The object\'s container.
:param obj: The object.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to \'\'.
:param acceptable_statuses: List of sta... | def get_object_metadata(self, account, container, obj, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account, container, obj)
return self._get_metadata(path, metadata_prefix, acceptable_statuses)
|
'Returns an iterator of object lines from an uncompressed or compressed
text object.
Uncompress object as it is read if the object\'s name ends with \'.gz\'.
:param account: The object\'s account.
:param container: The object\'s container.
:param objec_namet: The object.
:param acceptable_statuses: List of status for v... | def iter_object_lines(self, account, container, obj, headers=None, acceptable_statuses=(2,)):
| headers = (headers or {})
path = self.make_path(account, container, obj)
resp = self.make_request('GET', path, headers, acceptable_statuses)
if (not ((resp.status_int // 100) == 2)):
return
last_part = ''
compressed = obj.endswith('.gz')
d = zlib.decompressobj((16 + zlib.MAX_WBITS))
... |
'Sets an object\'s metadata. The object\'s metadata will be overwritten
by the values in the metadata dict.
:param account: The object\'s account.
:param container: The object\'s container.
:param obj: The object.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in h... | def set_object_metadata(self, account, container, obj, metadata, metadata_prefix='', acceptable_statuses=(2,)):
| path = self.make_path(account, container, obj)
self._set_metadata(path, metadata, metadata_prefix, acceptable_statuses)
|
':param fobj: File object to read object\'s content from.
:param account: The object\'s account.
:param container: The object\'s container.
:param obj: The object.
:param headers: Headers to send with request, defaults ot empty dict.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with... | def upload_object(self, fobj, account, container, obj, headers=None):
| headers = dict((headers or {}))
headers['Transfer-Encoding'] = 'chunked'
path = self.make_path(account, container, obj)
self.make_request('PUT', path, headers, (2,), fobj)
|
'This method is used to return multiple ranges for a given length
which should represent the length of the underlying content.
The constructor method __init__ made sure that any range in ranges
list is syntactically valid. So if length is None or size of the
ranges is zero, then the Range header should be ignored which... | def ranges_for_length(self, length):
| if ((length is None) or (not self.ranges) or (self.ranges == [])):
return None
all_ranges = []
for single_range in self.ranges:
(begin, end) = single_range
if (begin is None):
if (end == 0):
continue
elif (end > length):
all_ran... |
'Returns the item from "options" that best matches the accept header.
Returns None if no available options are acceptable to the client.
:param options: a list of content-types the server can respond with'
| def best_match(self, options):
| try:
types = self._get_types()
except ValueError:
return None
if ((not types) and options):
return options[0]
for pattern in types:
for option in options:
if re.match(pattern, option):
return option
return None
|
'Create a new request object with the given parameters, and an
environment otherwise filled in with non-surprising default values.'
| @classmethod
def blank(cls, path, environ=None, headers=None, body=None):
| headers = (headers or {})
environ = (environ or {})
if isinstance(path, unicode):
path = path.encode('utf-8')
parsed_path = urlparse.urlparse(path)
server_name = 'localhost'
if parsed_path.netloc:
server_name = parsed_path.netloc.split(':', 1)[0]
server_port = parsed_path.por... |
'Provides QUERY_STRING parameters as a dictionary'
| @property
def params(self):
| if (self._params_cache is None):
if ('QUERY_STRING' in self.environ):
self._params_cache = dict(urlparse.parse_qsl(self.environ['QUERY_STRING'], True))
else:
self._params_cache = {}
return self._params_cache
|
'The path of the request, without host but with query string.'
| @property
def path_qs(self):
| path = self.path
if self.query_string:
path += ('?' + self.query_string)
return path
|
'Provides the full path of the request, excluding the QUERY_STRING'
| @property
def path(self):
| return urllib2.quote((self.environ.get('SCRIPT_NAME', '') + self.environ['PATH_INFO']))
|
'Provides the full url of the request'
| @property
def url(self):
| return (self.host_url + self.path_qs)
|
'Takes one path portion (delineated by slashes) from the
path_info, and appends it to the script_name. Returns
the path segment.'
| def path_info_pop(self):
| path_info = self.path_info
if ((not path_info) or (path_info[0] != '/')):
return None
try:
slash_loc = path_info.index('/', 1)
except ValueError:
slash_loc = len(path_info)
self.script_name += path_info[:slash_loc]
self.path_info = path_info[slash_loc:]
return path_in... |
'Makes a copy of the request, converting it to a GET.'
| def copy_get(self):
| env = self.environ.copy()
env.update({'REQUEST_METHOD': 'GET', 'CONTENT_LENGTH': '0', 'wsgi.input': StringIO('')})
return Request(env)
|
'Calls the application with this request\'s environment. Returns the
status, headers, and app_iter for the response as a tuple.
:param application: the WSGI application to call'
| def call_application(self, application):
| output = []
captured = []
def start_response(status, headers, exc_info=None):
captured[:] = [status, headers, exc_info]
return output.append
app_iter = application(self.environ, start_response)
if (not app_iter):
app_iter = output
if (not captured):
app_iter = rei... |
'Calls the application with this request\'s environment. Returns a
Response object that wraps up the application\'s result.
:param application: the WSGI application to call'
| def get_response(self, application):
| (status, headers, app_iter) = self.call_application(application)
return Response(status=status, headers=dict(headers), app_iter=app_iter, request=self)
|
'Validate and split the Request\'s path.
**Examples**::
[\'a\'] = split_path(\'/a\')
[\'a\', None] = split_path(\'/a\', 1, 2)
[\'a\', \'c\'] = split_path(\'/a/c\', 1, 2)
[\'a\', \'c\', \'o/r\'] = split_path(\'/a/c/o/r\', 1, 3, True)
:param path: HTTP Request path to be split
:param minsegs: Minimum number of segments t... | def split_path(self, minsegs=1, maxsegs=None, rest_with_last=False):
| return split_path((self.environ.get('SCRIPT_NAME', '') + self.environ['PATH_INFO']), minsegs, maxsegs, rest_with_last)
|
'Prepare the Response for multiple ranges.'
| def _prepare_for_ranges(self, ranges):
| content_size = self.content_length
content_type = self.content_type
self.content_type = ''.join(['multipart/byteranges;', 'boundary=', self.boundary])
section_header_fixed_len = (12 + (((len(self.boundary) + len('Content-Type: ')) + len(content_type)) + len('Content-Range: bytes ')))
body_s... |
'Attempt to construct an absolute location.'
| def absolute_location(self):
| if (not self.location.startswith('/')):
return self.location
return (self.host_url + self.location)
|
'Get the container ring. Load it, if it hasn\'t been yet.'
| def get_container_ring(self):
| if (not self.container_ring):
self.container_ring = Ring(self.swift_dir, ring_name='container')
return self.container_ring
|
'Run the updater continuously.'
| def run_forever(self, *args, **kwargs):
| time.sleep((random() * self.interval))
while True:
self.logger.info(_('Begin object update sweep'))
begin = time.time()
pids = []
self.get_container_ring().get_nodes('')
for device in os.listdir(self.devices):
if (self.mount_check and (not os.path.ism... |
'Run the updater once'
| def run_once(self, *args, **kwargs):
| self.logger.info(_('Begin object update single threaded sweep'))
begin = time.time()
self.successes = 0
self.failures = 0
for device in os.listdir(self.devices):
if (self.mount_check and (not os.path.ismount(os.path.join(self.devices, device)))):
self.logger.increm... |
'If there are async pendings on the device, walk each one and update.
:param device: path to device'
| def object_sweep(self, device):
| start_time = time.time()
async_pending = os.path.join(device, ASYNCDIR)
if (not os.path.isdir(async_pending)):
return
for prefix in os.listdir(async_pending):
prefix_path = os.path.join(async_pending, prefix)
if (not os.path.isdir(prefix_path)):
continue
last_... |
'Process the object information to be updated and update.
:param update_path: path to pickled object update file
:param device: path to device'
| def process_object_update(self, update_path, device):
| try:
update = pickle.load(open(update_path, 'rb'))
except Exception:
self.logger.exception(_('ERROR Pickle problem, quarantining %s'), update_path)
self.logger.increment('quarantines')
renamer(update_path, os.path.join(device, 'quarantined', 'objects', os.path.basenam... |
'Perform the object update to the container
:param node: node dictionary from the container ring
:param part: partition that holds the container
:param op: operation performed (ex: \'POST\' or \'DELETE\')
:param obj: object name being updated
:param headers: headers to send with the update'
| def object_update(self, node, part, op, obj, headers):
| try:
with ConnectionTimeout(self.conn_timeout):
conn = http_connect(node['ip'], node['port'], node['device'], part, op, obj, headers)
with Timeout(self.node_timeout):
resp = conn.getresponse()
resp.read()
return resp.status
except (Exception, Timeo... |
'Returns an iterator over the data file.'
| def __iter__(self):
| try:
dropped_cache = 0
read = 0
self.started_at_0 = False
self.read_to_eof = False
if (self.fp.tell() == 0):
self.started_at_0 = True
self.iter_etag = md5()
while True:
chunk = self.fp.read(self.disk_chunk_size)
if chunk... |
'Returns an iterator over the data file for range (start, stop)'
| def app_iter_range(self, start, stop):
| if (start or (start == 0)):
self.fp.seek(start)
if (stop is not None):
length = (stop - start)
else:
length = None
for chunk in self:
if (length is not None):
length -= len(chunk)
if (length < 0):
(yield chunk[:length])
... |
'Returns an iterator over the data file for a set of ranges'
| def app_iter_ranges(self, ranges, content_type, boundary, size):
| if (not ranges):
(yield '')
else:
try:
self.suppress_file_closing = True
for chunk in multi_range_iterator(ranges, content_type, boundary, size, self.app_iter_range):
(yield chunk)
finally:
self.suppress_file_closing = False
... |
'Check if file needs to be quarantined'
| def _handle_close_quarantine(self):
| try:
self.get_data_file_size()
except DiskFileError:
self.quarantine()
return
except DiskFileNotExist:
return
if (self.iter_etag and self.started_at_0 and self.read_to_eof and ('ETag' in self.metadata) and (self.iter_etag.hexdigest() != self.metadata.get('ETag'))):
... |
'Close the file. Will handle quarantining file if necessary.
:param verify_file: Defaults to True. If false, will not check
file to see if it needs quarantining.'
| def close(self, verify_file=True):
| if self.fp:
try:
if verify_file:
self._handle_close_quarantine()
except (Exception, Timeout) as e:
self.logger.error(_('ERROR DiskFile %(data_file)s in %(data_dir)s close failure: %(exc)s : %(stack)'), {'exc': e, 'stack': ''.join(tra... |
'Check if the file is deleted.
:returns: True if the file doesn\'t exist or has been flagged as
deleted.'
| def is_deleted(self):
| return ((not self.data_file) or ('deleted' in self.metadata))
|
'Check if the file is expired.
:returns: True if the file has an X-Delete-At in the past'
| def is_expired(self):
| return (('X-Delete-At' in self.metadata) and (int(self.metadata['X-Delete-At']) <= time.time()))
|
'Contextmanager to make a temporary file.'
| @contextmanager
def mkstemp(self):
| if (not os.path.exists(self.tmpdir)):
mkdirs(self.tmpdir)
(fd, self.tmppath) = mkstemp(dir=self.tmpdir)
try:
(yield fd)
finally:
try:
os.close(fd)
except OSError:
pass
(tmppath, self.tmppath) = (self.tmppath, None)
try:
... |
'Finalize writing the file on disk, and renames it from the temp file to
the real location. This should be called after the data has been
written to the temp file.
:param fd: file descriptor of the temp file
:param metadata: dictionary of metadata to be written
:param extension: extension to be used when making the fi... | def put(self, fd, metadata, extension='.data'):
| assert (self.tmppath is not None)
metadata['name'] = self.name
timestamp = normalize_timestamp(metadata['X-Timestamp'])
write_metadata(fd, metadata)
if ('Content-Length' in metadata):
self.drop_cache(fd, 0, int(metadata['Content-Length']))
tpool.execute(fsync, fd)
invalidate_hash(os.... |
'Short hand for putting metadata to .meta and .ts files.
:param metadata: dictionary of metadata to be written
:param tombstone: whether or not we are writing a tombstone'
| def put_metadata(self, metadata, tombstone=False):
| extension = ('.ts' if tombstone else '.meta')
with self.mkstemp() as fd:
self.put(fd, metadata, extension=extension)
|
'Remove any older versions of the object file. Any file that has an
older timestamp than timestamp will be deleted.
:param timestamp: timestamp to compare with each file'
| def unlinkold(self, timestamp):
| timestamp = normalize_timestamp(timestamp)
for fname in os.listdir(self.datadir):
if (fname < timestamp):
try:
os.unlink(os.path.join(self.datadir, fname))
except OSError as err:
if (err.errno != errno.ENOENT):
raise
|
'Method for no-oping buffer cache drop method.'
| def drop_cache(self, fd, offset, length):
| if (not self.keep_cache):
drop_buffer_cache(fd, offset, length)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.