desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'In the case that a file is corrupted, move it to a quarantined
area to allow replication to fix it.
:returns: if quarantine is successful, path to quarantined
directory otherwise None'
| def quarantine(self):
| if (not (self.is_deleted() or self.quarantined_dir)):
self.quarantined_dir = quarantine_renamer(self.device_path, self.data_file)
self.logger.increment('quarantines')
return self.quarantined_dir
|
'Returns the os.path.getsize for the file. Raises an exception if this
file does not match the Content-Length stored in the metadata. Or if
self.data_file does not exist.
:returns: file size as an int
:raises DiskFileError: on file size mismatch.
:raises DiskFileNotExist: on file not existing (including deleted)'
| def get_data_file_size(self):
| try:
file_size = 0
if self.data_file:
file_size = os.path.getsize(self.data_file)
if ('Content-Length' in self.metadata):
metadata_size = int(self.metadata['Content-Length'])
if (file_size != metadata_size):
raise DiskFileEr... |
'Creates a new WSGI application for the Swift Object Server. An
example configuration is given at
<source-dir>/etc/object-server.conf-sample or
/etc/swift/object-server.conf-sample.'
| def __init__(self, conf):
| self.logger = get_logger(conf, log_route='object-server')
self.devices = conf.get('devices', '/srv/node/')
self.mount_check = config_true_value(conf.get('mount_check', 'true'))
self.node_timeout = int(conf.get('node_timeout', 3))
self.conn_timeout = float(conf.get('conn_timeout', 0.5))
self.disk... |
'Sends or saves an async update.
:param op: operation performed (ex: \'PUT\', or \'DELETE\')
:param account: account name for the object
:param container: container name for the object
:param obj: object name
:param host: host that the container is on
:param partition: partition that the container is on
:param contdevi... | def async_update(self, op, account, container, obj, host, partition, contdevice, headers_out, objdevice):
| full_path = ('/%s/%s/%s' % (account, container, obj))
if all([host, partition, contdevice]):
try:
with ConnectionTimeout(self.conn_timeout):
(ip, port) = host.rsplit(':', 1)
conn = http_connect(ip, port, contdevice, partition, op, full_path, headers_out)
... |
'Update the container when objects are updated.
:param op: operation performed (ex: \'PUT\', or \'DELETE\')
:param account: account name for the object
:param container: container name for the object
:param obj: object name
:param headers_in: dictionary of headers from the original request
:param headers_out: dictionar... | def container_update(self, op, account, container, obj, headers_in, headers_out, objdevice):
| conthosts = [h.strip() for h in headers_in.get('X-Container-Host', '').split(',')]
contdevices = [d.strip() for d in headers_in.get('X-Container-Device', '').split(',')]
contpartition = headers_in.get('X-Container-Partition', '')
if (len(conthosts) != len(contdevices)):
self.logger.error(_(('ERR... |
'Update the expiring objects container when objects are updated.
:param op: operation performed (ex: \'PUT\', or \'DELETE\')
:param account: account name for the object
:param container: container name for the object
:param obj: object name
:param headers_in: dictionary of headers from the original request
:param objde... | def delete_at_update(self, op, delete_at, account, container, obj, headers_in, objdevice):
| delete_at = max(min(delete_at, 9999999999), 0)
updates = [(None, None)]
partition = None
hosts = contdevices = [None]
headers_out = {'x-timestamp': headers_in['x-timestamp'], 'x-trans-id': headers_in.get('x-trans-id', '-')}
if (op != 'DELETE'):
partition = headers_in.get('X-Delete-At-Par... |
'Handle HTTP POST requests for the Swift Object Server.'
| @public
@timing_stats()
def POST(self, request):
| try:
(device, partition, account, container, obj) = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError as err:
return HTTPBadRequest(body=str(err), request=request, content_type='text/plain')
if (('x-timestamp' not in request.... |
'Handle HTTP PUT requests for the Swift Object Server.'
| @public
@timing_stats()
def PUT(self, request):
| try:
(device, partition, account, container, obj) = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError as err:
return HTTPBadRequest(body=str(err), request=request, content_type='text/plain')
if (self.mount_check and (not chec... |
'Handle HTTP GET requests for the Swift Object Server.'
| @public
@timing_stats()
def GET(self, request):
| try:
(device, partition, account, container, obj) = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError as err:
return HTTPBadRequest(body=str(err), request=request, content_type='text/plain')
if (self.mount_check and (not chec... |
'Handle HTTP HEAD requests for the Swift Object Server.'
| @public
@timing_stats(sample_rate=0.8)
def HEAD(self, request):
| try:
(device, partition, account, container, obj) = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError as err:
resp = HTTPBadRequest(request=request)
resp.content_type = 'text/plain'
resp.body = str(err)
re... |
'Handle HTTP DELETE requests for the Swift Object Server.'
| @public
@timing_stats()
def DELETE(self, request):
| try:
(device, partition, account, container, obj) = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError as e:
return HTTPBadRequest(body=str(e), request=request, content_type='text/plain')
if (('x-timestamp' not in request.head... |
'Handle REPLICATE requests for the Swift Object Server. This is used
by the object replicator to get hashes for directories.'
| @public
@timing_stats(sample_rate=0.1)
def REPLICATE(self, request):
| try:
(device, partition, suffix) = split_path(unquote(request.path), 2, 3, True)
validate_device_partition(device, partition)
except ValueError as e:
return HTTPBadRequest(body=str(e), request=request, content_type='text/plain')
if (self.mount_check and (not check_mount(self.devices,... |
'WSGI Application entry point for the Swift Object Server.'
| def __call__(self, env, start_response):
| start_time = time.time()
req = Request(env)
self.logger.txn_id = req.headers.get('x-trans-id', None)
if (not check_utf8(req.path_info)):
res = HTTPPreconditionFailed(body='Invalid UTF8 or contains NULL')
else:
try:
try:
method = getattr(self, r... |
':param conf: configuration object obtained from ConfigParser
:param logger: logging object'
| def __init__(self, conf):
| self.conf = conf
self.logger = get_logger(conf, log_route='object-replicator')
self.devices_dir = conf.get('devices', '/srv/node')
self.mount_check = config_true_value(conf.get('mount_check', 'true'))
self.vm_test_mode = config_true_value(conf.get('vm_test_mode', 'no'))
self.swift_dir = conf.get... |
'Execute the rsync binary to replicate a partition.
:returns: return code of rsync process. 0 is successful'
| def _rsync(self, args):
| start_time = time.time()
ret_val = None
try:
with Timeout(self.rsync_timeout):
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
results = proc.stdout.read()
ret_val = proc.wait()
except Timeout:
self.logger.error(_('Killi... |
'Synchronize local suffix directories from a partition with a remote
node.
:param node: the "dev" entry for the remote node to sync with
:param job: information about the partition being synced
:param suffixes: a list of suffixes which need to be pushed
:returns: boolean indicating success or failure'
| def rsync(self, node, job, suffixes):
| if (not os.path.exists(job['path'])):
return False
args = ['rsync', '--recursive', '--whole-file', '--human-readable', '--xattrs', '--itemize-changes', '--ignore-existing', ('--timeout=%s' % self.rsync_io_timeout), ('--contimeout=%s' % self.rsync_io_timeout)]
node_ip = rsync_ip(node['ip'])
if se... |
'Check to see if the ring has been updated
:returns: boolean indicating whether or not the ring has changed'
| def check_ring(self):
| if (time.time() > self.next_check):
self.next_check = (time.time() + self.ring_check_interval)
if self.object_ring.has_changed():
return False
return True
|
'High-level method that replicates a single partition that doesn\'t
belong on this node.
:param job: a dict containing info about the partition to be replicated'
| def update_deleted(self, job):
| def tpool_get_suffixes(path):
return [suff for suff in os.listdir(path) if ((len(suff) == 3) and isdir(join(path, suff)))]
self.replication_count += 1
self.logger.increment(('partition.delete.count.%s' % (job['device'],)))
begin = time.time()
try:
responses = []
suffixes = tp... |
'High-level method that replicates a single partition.
:param job: a dict containing info about the partition to be replicated'
| def update(self, job):
| self.replication_count += 1
self.logger.increment(('partition.update.count.%s' % (job['device'],)))
begin = time.time()
try:
(hashed, local_hash) = tpool_reraise(get_hashes, job['path'], do_listdir=((self.replication_count % 10) == 0), reclaim_age=self.reclaim_age)
self.suffix_hash += ha... |
'Logs various stats for the currently running replication pass.'
| def stats_line(self):
| if self.replication_count:
elapsed = ((time.time() - self.start) or 1e-06)
rate = (self.replication_count / elapsed)
self.logger.info(_('%(replicated)d/%(total)d (%(percentage).2f%%) partitions replicated in %(time).2fs (%(rate).2f/sec, %(remaining)s remaining)'), {'r... |
'Utility function that kills all coroutines currently running.'
| def kill_coros(self):
| for coro in list(self.run_pool.coroutines_running):
try:
coro.kill(GreenletExit)
except GreenletExit:
pass
|
'Loop that runs in the background during replication. It periodically
logs progress.'
| def heartbeat(self):
| while True:
eventlet.sleep(self.stats_interval)
self.stats_line()
|
'In testing, the pool.waitall() call very occasionally failed to return.
This is an attempt to make sure the replicator finishes its replication
pass in some eventuality.'
| def detect_lockups(self):
| while True:
eventlet.sleep(self.lockup_timeout)
if (self.replication_count == self.last_replication_count):
self.logger.error(_('Lockup detected.. killing live coros.'))
self.kill_coros()
self.last_replication_count = self.replication_count
|
'Returns a sorted list of jobs (dictionaries) that specify the
partitions, nodes, etc to be rsynced.'
| def collect_jobs(self):
| jobs = []
ips = whataremyips()
for local_dev in [dev for dev in self.object_ring.devs if (dev and (dev['ip'] in ips) and (dev['port'] == self.port))]:
dev_path = join(self.devices_dir, local_dev['device'])
obj_path = join(dev_path, 'objects')
tmp_path = join(dev_path, 'tmp')
... |
'Run a replication pass'
| def replicate(self, override_devices=[], override_partitions=[]):
| self.start = time.time()
self.suffix_count = 0
self.suffix_sync = 0
self.suffix_hash = 0
self.replication_count = 0
self.last_replication_count = (-1)
self.partition_times = []
stats = eventlet.spawn(self.heartbeat)
lockup_detector = eventlet.spawn(self.detect_lockups)
eventlet.s... |
'Audits the given object path.
:param path: a path to an object
:param device: the device the path is on
:param partition: the partition the path is on'
| def object_audit(self, path, device, partition):
| try:
if (not path.endswith('.data')):
return
try:
name = object_server.read_metadata(path)['name']
except (Exception, Timeout) as exc:
raise AuditException(('Error when reading metadata: %s' % exc))
(_junk, account, container, obj) = na... |
'Run the object audit until stopped.'
| def run_forever(self, *args, **kwargs):
| zbo_fps = kwargs.get('zero_byte_fps', 0)
if zbo_fps:
parent = True
else:
parent = os.fork()
kwargs = {'mode': 'forever'}
if parent:
kwargs['zero_byte_fps'] = (zbo_fps or self.conf_zero_byte_fps)
while True:
try:
self.run_once(**kwargs)
except (... |
'Run the object audit once.'
| def run_once(self, *args, **kwargs):
| mode = kwargs.get('mode', 'once')
zero_byte_only_at_fps = kwargs.get('zero_byte_fps', 0)
worker = AuditorWorker(self.conf, self.logger, zero_byte_only_at_fps=zero_byte_only_at_fps)
worker.audit_all_objects(mode=mode)
|
'Emits a log line report of the progress so far, or the final progress
is final=True.
:param final: Set to True for the last report once the expiration pass
has completed.'
| def report(self, final=False):
| if final:
elapsed = (time() - self.report_first_time)
self.logger.info((_('Pass completed in %ds; %d objects expired') % (elapsed, self.report_objects)))
dump_recon_cache({'object_expiration_pass': elapsed, 'expired_last_pass': self.report_objects}, self.rcache, self.logger... |
'Executes a single pass, looking for objects to expire.
:param args: Extra args to fulfill the Daemon interface; this daemon
has no additional args.
:param kwargs: Extra keyword args to fulfill the Daemon interface; this
daemon has no additional keyword args.'
| def run_once(self, *args, **kwargs):
| self.report_first_time = self.report_last_time = time()
self.report_objects = 0
try:
self.logger.debug(_('Run begin'))
(containers, objects) = self.swift.get_account_info(self.expiring_objects_account)
self.logger.info((_('Pass beginning; %s possible containers; %s ... |
'Executes passes forever, looking for objects to expire.
:param args: Extra args to fulfill the Daemon interface; this daemon
has no additional args.
:param kwargs: Extra keyword args to fulfill the Daemon interface; this
daemon has no additional keyword args.'
| def run_forever(self, *args, **kwargs):
| sleep((random() * self.interval))
while True:
begin = time()
try:
self.run_once()
except (Exception, Timeout):
self.logger.exception(_('Unhandled exception'))
elapsed = (time() - begin)
if (elapsed < self.interval):
sleep((random() *... |
'Deletes the end-user object indicated by the actual object name given
\'<account>/<container>/<object>\' if and only if the X-Delete-At value
of the object is exactly the timestamp given.
:param actual_obj: The name of the end-user object to delete:
\'<account>/<container>/<object>\'
:param timestamp: The timestamp th... | def delete_actual_object(self, actual_obj, timestamp):
| self.swift.make_request('DELETE', ('/v1/%s' % actual_obj.lstrip('/')), {'X-If-Delete-At': str(timestamp)}, (2, HTTP_NOT_FOUND, HTTP_PRECONDITION_FAILED))
|
'Get the controller to handle a request.
:param path: path from request
:returns: tuple of (controller class, path dictionary)
:raises: ValueError (thrown by split_path) if given invalid path'
| def get_controller(self, path):
| (version, account, container, obj) = split_path(path, 1, 4, True)
d = dict(version=version, account_name=account, container_name=container, object_name=obj)
if (obj and container and account):
return (ObjectController, d)
elif (container and account):
return (ContainerController, d)
... |
'WSGI entry point.
Wraps env in swob.Request object and passes it down.
:param env: WSGI environment dictionary
:param start_response: WSGI callable'
| def __call__(self, env, start_response):
| try:
if (self.memcache is None):
self.memcache = cache_from_env(env)
req = self.update_request(Request(env))
return self.handle_request(req)(env, start_response)
except UnicodeError:
err = HTTPPreconditionFailed(request=req, body='Invalid UTF8 or contains ... |
'Entry point for proxy server.
Should return a WSGI-style callable (such as swob.Response).
:param req: swob.Request object'
| def handle_request(self, req):
| try:
self.logger.set_statsd_prefix('proxy-server')
if (req.content_length and (req.content_length < 0)):
self.logger.increment('errors')
return HTTPBadRequest(request=req, body='Invalid Content-Length')
try:
if (not check_utf8(req.path_info)):
... |
'Sorts nodes in-place (and returns the sorted list) according to
the configured strategy. The default "sorting" is to randomly
shuffle the nodes. If the "timing" strategy is chosen, the nodes
are sorted according to the stored timing data.'
| def sort_nodes(self, nodes):
| shuffle(nodes)
if (self.sorting_method == 'timing'):
now = time()
def key_func(node):
(timing, expires) = self.node_timings.get(node['ip'], ((-1.0), 0))
return (timing if (expires > now) else (-1.0))
nodes.sort(key=key_func)
return nodes
|
'Handles incrementing error counts when talking to nodes.
:param node: dictionary of node to increment the error count for'
| def error_increment(self, node):
| node['errors'] = (node.get('errors', 0) + 1)
node['last_error'] = time.time()
|
'Handle logging, and handling of errors.
:param node: dictionary of node to handle errors for
:param msg: error message'
| def error_occurred(self, node, msg):
| self.error_increment(node)
self.app.logger.error(_('%(msg)s %(ip)s:%(port)s'), {'msg': msg, 'ip': node['ip'], 'port': node['port']})
|
'Handle logging of generic exceptions.
:param node: dictionary of node to log the error for
:param typ: server type
:param additional_info: additional information to log'
| def exception_occurred(self, node, typ, additional_info):
| self.app.logger.exception(_('ERROR with %(type)s server %(ip)s:%(port)s/%(device)s re: %(info)s'), {'type': typ, 'ip': node['ip'], 'port': node['port'], 'device': node['device'], 'info': additional_info})
|
'Check if the node is currently error limited.
:param node: dictionary of node to check
:returns: True if error limited, False otherwise'
| def error_limited(self, node):
| now = time.time()
if ('errors' not in node):
return False
if (('last_error' in node) and (node['last_error'] < (now - self.app.error_suppression_interval))):
del node['last_error']
if ('errors' in node):
del node['errors']
return False
limited = (node['errors'... |
'Mark a node as error limited.
:param node: dictionary of node to error limit'
| def error_limit(self, node):
| node['errors'] = (self.app.error_suppression_limit + 1)
node['last_error'] = time.time()
|
'Get account information, and also verify that the account exists.
:param account: name of the account to get the info for
:returns: tuple of (account partition, account nodes, container_count)
or (None, None, None) if it does not exist'
| def account_info(self, account, autocreate=False):
| (partition, nodes) = self.app.account_ring.get_nodes(account)
account_info = {'status': 0, 'container_count': 0, 'total_object_count': None, 'bytes': None, 'meta': {}}
if self.app.memcache:
cache_key = get_account_memcache_key(account)
cache_value = self.app.memcache.get(cache_key)
i... |
'Get container information and thusly verify container existence.
This will also make a call to account_info to verify that the
account exists.
:param account: account name for the container
:param container: container name to look up
:returns: dict containing at least container partition (\'partition\'),
container nod... | def container_info(self, account, container, account_autocreate=False):
| (part, nodes) = self.app.container_ring.get_nodes(account, container)
path = ('/%s/%s' % (account, container))
container_info = {'status': 0, 'read_acl': None, 'write_acl': None, 'sync_key': None, 'count': None, 'bytes': None, 'versions': None, 'partition': None, 'nodes': None}
if self.app.memcache:
... |
'Node iterator that will first iterate over the normal nodes for a
partition and then the handoff partitions for the node.
:param partition: partition to iterate nodes for
:param nodes: list of node dicts from the ring
:param ring: ring to get handoff nodes from'
| def iter_nodes(self, partition, nodes, ring):
| for node in nodes:
if (not self.error_limited(node)):
(yield node)
handoffs = 0
for node in ring.get_more_nodes(partition):
if (not self.error_limited(node)):
handoffs += 1
if self.app.log_handoffs:
self.app.logger.increment('handoff_count'... |
'Sends an HTTP request to multiple nodes and aggregates the results.
It attempts the primary nodes concurrently, then iterates over the
handoff nodes as needed.
:param headers: a list of dicts, where each dict represents one
backend request that should be made.
:returns: a swob.Response object'
| def make_requests(self, req, ring, part, method, path, headers, query_string=''):
| start_nodes = ring.get_part_nodes(part)
nodes = self.iter_nodes(part, start_nodes, ring)
pile = GreenPile(len(start_nodes))
for head in headers:
pile.spawn(self._make_request, nodes, part, method, path, head, query_string, self.app.logger.thread_locals)
response = [resp for resp in pile if r... |
'Given a list of responses from several servers, choose the best to
return to the API.
:param req: swob.Request object
:param statuses: list of statuses returned
:param reasons: list of reasons for each status
:param bodies: bodies of each response
:param server_type: type of server the responses came from
:param etag:... | def best_response(self, req, statuses, reasons, bodies, server_type, etag=None):
| resp = Response(request=req)
if len(statuses):
for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
hstatuses = [s for s in statuses if (hundred <= s < (hundred + 100))]
if (len(hstatuses) > (len(statuses) / 2)):
status = max(hstatuses)
... |
'Handler for HTTP GET requests.'
| @public
def GET(self, req):
| return self.GETorHEAD(req)
|
'Handler for HTTP HEAD requests.'
| @public
def HEAD(self, req):
| return self.GETorHEAD(req)
|
'Reads from the source and places data in the queue. It expects
something else be reading from the queue and, if nothing does within
self.app.client_timeout seconds, the process will be aborted.
:param node: The node dict that the source is connected to, for
logging/error-limiting purposes.
:param source: The httplib.R... | def _make_app_iter_reader(self, node, source, queue, logger_thread_locals):
| self.app.logger.thread_locals = logger_thread_locals
success = True
try:
while True:
with ChunkReadTimeout(self.app.node_timeout):
chunk = source.read(self.app.object_chunk_size)
if (not chunk):
break
queue.put(chunk, timeout=self.a... |
'Returns an iterator over the contents of the source (via its read
func). There is also quite a bit of cleanup to ensure garbage
collection works and the underlying socket of the source is closed.
:param source: The httplib.Response object this iterator should read
from.
:param node: The node the source is reading fro... | def _make_app_iter(self, node, source):
| try:
queue = Queue(1)
spawn_n(self._make_app_iter_reader, node, source, queue, self.app.logger.thread_locals)
source = node = None
while True:
chunk = queue.get(timeout=self.app.node_timeout)
if isinstance(chunk, bool):
success = chunk
... |
'Indicates whether or not the request made to the backend found
what it was looking for.'
| def is_good_source(self, src):
| return (is_success(src.status) or is_redirection(src.status))
|
'Base handler for HTTP GET or HEAD requests.
:param req: swob.Request object
:param server_type: server type
:param partition: partition
:param nodes: nodes
:param path: path for the request
:param attempts: number of attempts to try
:returns: swob.Response object'
| def GETorHEAD_base(self, req, server_type, partition, nodes, path, attempts):
| statuses = []
reasons = []
bodies = []
sources = []
newest = config_true_value(req.headers.get('x-newest', 'f'))
nodes = iter(nodes)
while (len(statuses) < attempts):
try:
node = nodes.next()
except StopIteration:
break
if self.error_limited(no... |
'Is the given Origin allowed to make requests to this resource
:param cors_info: the resource\'s CORS related metadata headers
:param origin: the origin making the request
:return: True or False'
| def is_origin_allowed(self, cors_info, origin):
| allowed_origins = set()
if cors_info.get('allow_origin'):
allowed_origins.update([a.strip() for a in cors_info['allow_origin'].split(' ') if a.strip()])
if self.app.cors_allow_origin:
allowed_origins.update(self.app.cors_allow_origin)
return ((origin in allowed_origins) or ('*' in all... |
'Base handler for OPTIONS requests
:param req: swob.Request object
:returns: swob.Response object'
| @public
def OPTIONS(self, req):
| headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req, headers=headers)
req_origin_value = req.headers.get('Origin', None)
if (not req_origin_value):
return resp
try:
container_info = self.container_info(self.account_name, self.container_name... |
'Handler for HTTP GET/HEAD requests.'
| def GETorHEAD(self, req):
| (partition, nodes) = self.app.account_ring.get_nodes(self.account_name)
nodes = self.app.sort_nodes(nodes)
resp = self.GETorHEAD_base(req, _('Account'), partition, nodes, req.path_info.rstrip('/'), len(nodes))
if ((resp.status_int == HTTP_NOT_FOUND) and self.app.account_autocreate):
if (len(self... |
'HTTP PUT request handler.'
| @public
def PUT(self, req):
| if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
error_response = check_metadata(req, 'account')
if error_response:
return error_response
if (len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH):
... |
'HTTP POST request handler.'
| @public
def POST(self, req):
| error_response = check_metadata(req, 'account')
if error_response:
return error_response
(account_partition, accounts) = self.app.account_ring.get_nodes(self.account_name)
headers = {'X-Timestamp': normalize_timestamp(time.time()), 'X-Trans-Id': self.trans_id, 'Connection': 'close'}
self.tra... |
'HTTP DELETE request handler.'
| @public
def DELETE(self, req):
| if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
(account_partition, accounts) = self.app.account_ring.get_nodes(self.account_name)
headers = {'X-Timestamp': normalize_timestamp(time.time()), 'X-Trans-Id': sel... |
'Loads the self.segment_iter with the next object segment\'s contents.
:raises: StopIteration when there are no more object segments or
segment no longer matches SLO manifest specifications.'
| def _load_next_segment(self):
| try:
self.segment += 1
self.segment_dict = (self.segment_peek or self.listing.next())
self.segment_peek = None
if (self.container is None):
(container, obj) = self.segment_dict['name'].lstrip('/').split('/', 1)
else:
(container, obj) = (self.container,... |
'Standard iterator function that returns the object\'s contents.'
| def __iter__(self):
| try:
while True:
if (not self.segment_iter):
self._load_next_segment()
while True:
with ChunkReadTimeout(self.controller.app.node_timeout):
try:
chunk = self.segment_iter.next()
break
... |
'Non-standard iterator function for use with Swob in serving Range
requests more quickly. This will skip over segments and do a range
request on the first segment to return data from, if needed.
:param start: The first byte (zero-based) to return. None for 0.
:param stop: The last byte (zero-based) to return. None for ... | def app_iter_range(self, start, stop):
| try:
if start:
self.segment_peek = self.listing.next()
while (start >= (self.position + self.segment_peek['bytes'])):
self.segment += 1
self.position += self.segment_peek['bytes']
self.segment_peek = self.listing.next()
self... |
'Returns an item-by-item iterator for a page-by-page iterator
of item listings.
Swallows listing-related errors; this iterator is only used
after we\'ve already started streaming a response to the
client, and so if we start getting errors from the container
servers now, it\'s too late to send an error to the client, so... | def _remaining_items(self, listing_iter):
| try:
for page in listing_iter:
for item in page:
(yield item)
except ListingIterNotFound:
pass
except ListingIterError:
pass
except ListingIterNotAuthorized:
pass
|
'Indicates whether or not the request made to the backend found
what it was looking for.
In the case of an object, a 416 indicates that we found a
backend with the object.'
| def is_good_source(self, src):
| return ((src.status == 416) or super(ObjectController, self).is_good_source(src))
|
'Handle HTTP GET or HEAD requests.'
| def GETorHEAD(self, req):
| container_info = self.container_info(self.account_name, self.container_name)
req.acl = container_info['read_acl']
if ('swift.authorize' in req.environ):
aresp = req.environ['swift.authorize'](req)
if aresp:
return aresp
(partition, nodes) = self.app.object_ring.get_nodes(self... |
'Handler for HTTP GET requests.'
| @public
@cors_validation
@delay_denial
def GET(self, req):
| return self.GETorHEAD(req)
|
'Handler for HTTP HEAD requests.'
| @public
@cors_validation
@delay_denial
def HEAD(self, req):
| return self.GETorHEAD(req)
|
'HTTP POST request handler.'
| @public
@cors_validation
@delay_denial
def POST(self, req):
| if ('x-delete-after' in req.headers):
try:
x_delete_after = int(req.headers['x-delete-after'])
except ValueError:
return HTTPBadRequest(request=req, content_type='text/plain', body='Non-integer X-Delete-After')
req.headers['x-delete-at'] = ('%d' % (time.time() + x_... |
'Method for a file PUT coro'
| def _send_file(self, conn, path):
| while True:
chunk = conn.queue.get()
if (not conn.failed):
try:
with ChunkWriteTimeout(self.app.node_timeout):
conn.send(chunk)
except (Exception, ChunkWriteTimeout):
conn.failed = True
self.exception_occurre... |
'Method for a file PUT connect'
| def _connect_put_node(self, nodes, part, path, headers, logger_thread_locals):
| self.app.logger.thread_locals = logger_thread_locals
for node in nodes:
try:
start_time = time.time()
with ConnectionTimeout(self.app.conn_timeout):
conn = http_connect(node['ip'], node['port'], node['device'], part, 'PUT', path, headers)
self.app.set_... |
'HTTP PUT request handler.'
| @public
@cors_validation
@delay_denial
def PUT(self, req):
| container_info = self.container_info(self.account_name, self.container_name, account_autocreate=self.app.account_autocreate)
container_partition = container_info['partition']
containers = container_info['nodes']
req.acl = container_info['write_acl']
req.environ['swift_sync_key'] = container_info['sy... |
'HTTP DELETE request handler.'
| @public
@cors_validation
@delay_denial
def DELETE(self, req):
| container_info = self.container_info(self.account_name, self.container_name)
container_partition = container_info['partition']
containers = container_info['nodes']
req.acl = container_info['write_acl']
req.environ['swift_sync_key'] = container_info['sync_key']
object_versions = container_info['v... |
'HTTP COPY request handler.'
| @public
@cors_validation
@delay_denial
def COPY(self, req):
| dest = req.headers.get('Destination')
if (not dest):
return HTTPPreconditionFailed(request=req, body='Destination header required')
dest = unquote(dest)
if (not dest.startswith('/')):
dest = ('/' + dest)
try:
(_junk, dest_container, dest_object) = dest.split('/', 2)
... |
'Handler for HTTP GET/HEAD requests.'
| def GETorHEAD(self, req):
| if (not self.account_info(self.account_name)[1]):
return HTTPNotFound(request=req)
(part, nodes) = self.app.container_ring.get_nodes(self.account_name, self.container_name)
nodes = self.app.sort_nodes(nodes)
resp = self.GETorHEAD_base(req, _('Container'), part, nodes, req.path_info, len(nodes))
... |
'Handler for HTTP GET requests.'
| @public
@delay_denial
@cors_validation
def GET(self, req):
| return self.GETorHEAD(req)
|
'Handler for HTTP HEAD requests.'
| @public
@delay_denial
@cors_validation
def HEAD(self, req):
| return self.GETorHEAD(req)
|
'HTTP PUT request handler.'
| @public
@cors_validation
def PUT(self, req):
| error_response = (self.clean_acls(req) or check_metadata(req, 'container'))
if error_response:
return error_response
if (len(self.container_name) > MAX_CONTAINER_NAME_LENGTH):
resp = HTTPBadRequest(request=req)
resp.body = ('Container name length of %d longer than ... |
'HTTP POST request handler.'
| @public
@cors_validation
def POST(self, req):
| error_response = (self.clean_acls(req) or check_metadata(req, 'container'))
if error_response:
return error_response
(account_partition, accounts, container_count) = self.account_info(self.account_name, autocreate=self.app.account_autocreate)
if (not accounts):
return HTTPNotFound(reques... |
'HTTP DELETE request handler.'
| @public
@cors_validation
def DELETE(self, req):
| (account_partition, accounts, container_count) = self.account_info(self.account_name)
if (not accounts):
return HTTPNotFound(request=req)
(container_partition, containers) = self.app.container_ring.get_nodes(self.account_name, self.container_name)
headers = self._backend_requests(req, len(contai... |
'The account :class:`swift.common.ring.Ring` for the cluster.'
| def get_account_ring(self):
| if (not self.account_ring):
self.account_ring = Ring(self.swift_dir, ring_name='account')
return self.account_ring
|
'The container :class:`swift.common.ring.Ring` for the cluster.'
| def get_container_ring(self):
| if (not self.container_ring):
self.container_ring = Ring(self.swift_dir, ring_name='container')
return self.container_ring
|
'The object :class:`swift.common.ring.Ring` for the cluster.'
| def get_object_ring(self):
| if (not self.object_ring):
self.object_ring = Ring(self.swift_dir, ring_name='object')
return self.object_ring
|
'Main entry point when running the reaper in its normal daemon mode.
This repeatedly calls :func:`reap_once` no quicker than the
configuration interval.'
| def run_forever(self, *args, **kwargs):
| self.logger.debug(_('Daemon started.'))
sleep((random.random() * self.interval))
while True:
begin = time()
self.run_once()
elapsed = (time() - begin)
if (elapsed < self.interval):
sleep((self.interval - elapsed))
|
'Main entry point when running the reaper in \'once\' mode, where it will
do a single pass over all accounts on the server. This is called
repeatedly by :func:`run_forever`. This will call :func:`reap_device`
once for each device on the server.'
| def run_once(self, *args, **kwargs):
| self.logger.debug(_('Begin devices pass: %s'), self.devices)
begin = time()
try:
for device in os.listdir(self.devices):
if (self.mount_check and (not os.path.ismount(os.path.join(self.devices, device)))):
self.logger.increment('errors')
self.logg... |
'Called once per pass for each device on the server. This will scan the
accounts directory for the device, looking for partitions this device
is the primary for, then looking for account databases that are marked
status=DELETED and still have containers and calling
:func:`reap_account`. Account databases marked status=... | def reap_device(self, device):
| datadir = os.path.join(self.devices, device, DATADIR)
if (not os.path.exists(datadir)):
return
for partition in os.listdir(datadir):
partition_path = os.path.join(datadir, partition)
if (not partition.isdigit()):
continue
nodes = self.get_account_ring().get_part_n... |
'Called once per pass for each account this server is the primary for
and attempts to delete the data for the given account. The reaper will
only delete one account at any given time. It will call
:func:`reap_container` up to sqrt(self.concurrency) times concurrently
while reaping the account.
If there is any exception... | def reap_account(self, broker, partition, nodes):
| begin = time()
info = broker.get_info()
if ((time() - float(info['delete_timestamp'])) <= self.delay_reaping):
return False
account = info['account']
self.logger.info(_('Beginning pass on account %s'), account)
self.stats_return_codes = {}
self.stats_containers_deleted = ... |
'Deletes the data and the container itself for the given container. This
will call :func:`reap_object` up to sqrt(self.concurrency) times
concurrently for the objects in the container.
If there is any exception while deleting a single object, the process
will continue for any other objects in the container and the fail... | def reap_container(self, account, account_partition, account_nodes, container):
| account_nodes = list(account_nodes)
(part, nodes) = self.get_container_ring().get_nodes(account, container)
node = nodes[(-1)]
pool = GreenPool(size=self.object_concurrency)
marker = ''
while True:
objects = None
try:
objects = direct_get_container(node, part, account... |
'Deletes the given object by issuing a delete request to each node for
the object. The format of the delete request is such that each object
server will update a corresponding container server, removing the
object from the container\'s listing.
This function returns nothing and should raise no exception but only
update... | def reap_object(self, account, container, container_partition, container_nodes, obj):
| container_nodes = list(container_nodes)
(part, nodes) = self.get_object_ring().get_nodes(account, container, obj)
successes = 0
failures = 0
for node in nodes:
cnode = container_nodes.pop()
try:
direct_delete_object(node, part, account, container, obj, conn_timeout=self.c... |
'Handle HTTP DELETE request.'
| @public
@timing_stats()
def DELETE(self, req):
| try:
(drive, part, account) = req.split_path(3)
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))):
return HTTPInsufficient... |
'Handle HTTP PUT request.'
| @public
@timing_stats()
def PUT(self, req):
| try:
(drive, part, account, container) = req.split_path(3, 4)
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))):
return HT... |
'Handle HTTP HEAD request.'
| @public
@timing_stats()
def HEAD(self, req):
| try:
(drive, part, account) = req.split_path(3)
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))):
return HTTPInsufficient... |
'Handle HTTP GET request.'
| @public
@timing_stats()
def GET(self, req):
| try:
(drive, part, account) = req.split_path(3)
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))):
return HTTPInsufficient... |
'Handle HTTP REPLICATE request.
Handler for RPC calls for account replication.'
| @public
@timing_stats()
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) = req.split_path(3)
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 account audit until stopped.'
| def run_forever(self, *args, **kwargs):
| reported = time.time()
time.sleep((random() * self.interval))
while True:
self.logger.info(_('Begin account audit pass.'))
begin = time.time()
try:
reported = self._one_audit_pass(reported)
except (Exception, Timeout):
self.logger.increment('e... |
'Run the account audit once.'
| def run_once(self, *args, **kwargs):
| self.logger.info(_('Begin account audit "once" mode'))
begin = reported = time.time()
self._one_audit_pass(reported)
elapsed = (time.time() - begin)
self.logger.info(_('Account audit "once" mode completed: %.02fs'), elapsed)
dump_recon_cache({'account_auditor_pass_comp... |
'Audits the given account path
:param path: the path to an account db'
| def account_audit(self, path):
| start_time = time.time()
try:
if (not path.endswith('.db')):
return
broker = AccountBroker(path)
if (not broker.is_deleted()):
broker.get_info()
self.logger.increment('passes')
self.account_passes += 1
self.logger.debug((_('Audi... |
'Runs a command in an out-of-process shell.
Returns the output of that command. Working directory is self.root.'
| def run_command_with_code(self, cmd, redirect_output=True, check_exit_code=True):
| if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if (check_exit_code and (proc.returncode != 0)):
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
... |
'Creates the virtual environment and installs PIP.
Creates the virtual environment and installs PIP only into the
virtual environment.'
| def create_virtualenv(self, no_site_packages=True):
| if (not os.path.isdir(self.venv)):
print 'Creating venv...',
if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages', self.venv])
else:
self.run_command(['virtualenv', '-q', self.venv])
print 'done.'
print 'Installing pip ... |
'Parses command-line arguments.'
| def parse_args(self, argv):
| parser = argparse.ArgumentParser()
parser.add_argument('-n', '--no-site-packages', action='store_true', help='Do not inherit packages from global Python install')
return parser.parse_args(argv[1:])
|
'Any distribution-specific post-processing gets done here.
In particular, this is useful for applying patches to code inside
the venv.'
| def post_process(self):
| pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.