desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'If used, this should be the first middleware in pipeline.'
def __call__(self, env, start_response):
context = CatchErrorsContext(self.app, self.logger) return context.handle_request(env, start_response)
'Main hook into the WSGI paste.deploy filter/app pipeline. :param env: The WSGI environment dict. :param start_response: The WSGI start_response hook. :returns: Response as per WSGI.'
def __call__(self, env, start_response):
(temp_url_sig, temp_url_expires, filename) = self._get_temp_url_info(env) if ((temp_url_sig is None) and (temp_url_expires is None)): return self.app(env, start_response) if ((not temp_url_sig) or (not temp_url_expires)): return self._invalid(env, start_response) account = self._get_acco...
'Returns just the account for the request, if it\'s an object GET, PUT, or HEAD request; otherwise, None is returned. :param env: The WSGI environment for the request. :returns: Account str or None.'
def _get_account(self, env):
account = None if (env['REQUEST_METHOD'] in ('GET', 'PUT', 'HEAD')): parts = env['PATH_INFO'].split('/', 4) if ((len(parts) == 5) and (not parts[0]) and (parts[1] == 'v1') and parts[2] and parts[3] and parts[4].strip('/')): account = parts[2] return account
'Returns the provided temporary URL parameters (sig, expires), if given and syntactically valid. Either sig or expires could be None if not provided. If provided, expires is also converted to an int if possible or 0 if not, and checked for expiration (returns 0 if expired). :param env: The WSGI environment for the requ...
def _get_temp_url_info(self, env):
temp_url_sig = temp_url_expires = filename = None qs = parse_qs(env.get('QUERY_STRING', '')) if ('temp_url_sig' in qs): temp_url_sig = qs['temp_url_sig'][0] if ('temp_url_expires' in qs): try: temp_url_expires = int(qs['temp_url_expires'][0]) except ValueError: ...
'Returns the X-Account-Meta-Temp-URL-Key header value for the account, or None if none is set. :param env: The WSGI environment for the request. :param account: Account str. :returns: X-Account-Meta-Temp-URL-Key str value, or None.'
def _get_key(self, env, account):
key = None memcache = env.get('swift.cache') if memcache: key = memcache.get(('temp-url-key/%s' % account)) if (not key): newenv = make_pre_authed_env(env, 'HEAD', ('/v1/' + account), self.agent, swift_source='TU') newenv['CONTENT_LENGTH'] = '0' newenv['wsgi.input'] = Str...
'Returns the hexdigest string of the HMAC-SHA1 (RFC 2104) for the request. :param env: The WSGI environment for the request. :param expires: Unix timestamp as an int for when the URL expires. :param key: Key str, from the X-Account-Meta-Temp-URL-Key of the account. :param request_method: Optional override of the reques...
def _get_hmac(self, env, expires, key, request_method=None):
if (not request_method): request_method = env['REQUEST_METHOD'] return hmac.new(key, ('%s\n%s\n%s' % (request_method, expires, env['PATH_INFO'])), sha1).hexdigest()
'Performs the necessary steps to indicate a WSGI 401 Unauthorized response to the request. :param env: The WSGI environment for the request. :param start_response: The WSGI start_response hook. :returns: 401 response as per WSGI.'
def _invalid(self, env, start_response):
body = '401 Unauthorized: Temp URL invalid\n' start_response('401 Unauthorized', [('Content-Type', 'text/plain'), ('Content-Length', str(len(body)))]) if (env['REQUEST_METHOD'] == 'HEAD'): return [] return [body]
'Removes any headers from the WSGI environment as per the middleware configuration for incoming requests. :param env: The WSGI environment for the request.'
def _clean_incoming_headers(self, env):
for h in env.keys(): remove = (h in self.incoming_remove_headers) if (not remove): for p in self.incoming_remove_headers_startswith: if h.startswith(p): remove = True break if remove: if (h in self.incoming_allow...
'Removes any headers as per the middleware configuration for outgoing responses. :param headers: A WSGI start_response style list of headers, [(\'header1\', \'value), (\'header2\', \'value), :returns: The same headers list, but with some headers removed as per the middlware configuration for outgoing responses.'
def _clean_outgoing_headers(self, headers):
headers = dict(headers) for h in headers.keys(): remove = (h in self.outgoing_remove_headers) if (not remove): for p in self.outgoing_remove_headers_startswith: if h.startswith(p): remove = True break if remove: ...
'Returns a 200 response with "OK" in the body.'
def GET(self, req):
return Response(request=req, body='OK', content_type='text/plain')
'Returns a 503 response with "DISABLED BY FILE" in the body.'
def DISABLED(self, req):
return Response(request=req, status=503, body='DISABLED BY FILE', content_type='text/plain')
'Log a request. :param req: swob.Request object for the request :param status_int: integer code for the response status :param bytes_received: bytes successfully read from the request body :param bytes_sent: bytes yielded to the WSGI server :param request_time: time taken to satisfy the request, in seconds'
def log_request(self, req, status_int, bytes_received, bytes_sent, request_time):
if self.req_already_logged(req): return req_path = get_valid_utf8_str(req.path) the_request = quote(unquote(req_path)) if req.query_string: the_request = ((the_request + '?') + req.query_string) logged_headers = None if self.log_hdrs: logged_headers = '\n'.join((('%s: ...
'Will handle the PUT of a SLO manifest. Heads every object in manifest to check if is valid and if so will save a manifest generated from the user input. :params req: a swob.Request with an obj in path :raises: HttpException on errors'
def handle_multipart_put(self, req):
try: (vrs, account, container, obj) = req.split_path(1, 4, True) except ValueError: return self.app if (req.content_length > self.max_manifest_size): raise HTTPRequestEntityTooLarge(('Manifest File > %d bytes' % self.max_manifest_size)) if req.headers.get('X-Copy-From...
'Will delete all the segments in the SLO manifest and then, if successful, will delete the manifest file. :params req: a swob.Request with an obj in path :raises HTTPServerError: on invalid manifest :returns: swob.Response on failure, otherwise self.app'
def handle_multipart_delete(self, req):
new_env = req.environ.copy() new_env['REQUEST_METHOD'] = 'GET' del new_env['wsgi.input'] new_env['QUERY_STRING'] = 'multipart-manifest=get' new_env['CONTENT_LENGTH'] = 0 new_env['HTTP_USER_AGENT'] = ('%s MultipartDELETE' % req.environ.get('HTTP_USER_AGENT')) new_env['swift.source'] = 'SLO...
'WSGI entry point'
@wsgify def __call__(self, req):
try: (vrs, account, container, obj) = req.split_path(1, 4, True) except ValueError: return self.app if obj: if ((req.method == 'PUT') and (req.params.get('multipart-manifest') == 'put')): return self.handle_multipart_put(req) if ((req.method == 'DELETE') and (req....
'Extract the identity from the Keystone auth component.'
def _keystone_identity(self, environ):
if (environ.get('HTTP_X_IDENTITY_STATUS') != 'Confirmed'): return roles = [] if ('HTTP_X_ROLES' in environ): roles = environ['HTTP_X_ROLES'].split(',') identity = {'user': environ.get('HTTP_X_USER_NAME'), 'tenant': (environ.get('HTTP_X_TENANT_ID'), environ.get('HTTP_X_TENANT_NAME')), 'ro...
'Check reseller prefix.'
def _reseller_check(self, account, tenant_id):
return (account == self._get_account_for_tenant(tenant_id))
'Check cross-tenant ACLs Match tenant_id:user, tenant_name:user, and *:user. :param user: The user name from the identity token. :param tenant_id: The tenant ID from the identity token. :param tenant_name: The tenant name from the identity token. :param roles: The given container ACL. :returns: True if tenant_id:user, ...
def _authorize_cross_tenant(self, user, tenant_id, tenant_name, roles):
wildcard_tenant_match = ('*:%s' % user) tenant_id_user_match = ('%s:%s' % (tenant_id, user)) tenant_name_user_match = ('%s:%s' % (tenant_name, user)) return ((wildcard_tenant_match in roles) or (tenant_id_user_match in roles) or (tenant_name_user_match in roles))
'Authorize an anonymous request. :returns: None if authorization is granted, an error page otherwise.'
def authorize_anonymous(self, req):
try: part = req.split_path(1, 4, True) (version, account, container, obj) = part except ValueError: return HTTPNotFound(request=req) if (req.method == 'OPTIONS'): return is_authoritative_authz = (account and account.startswith(self.reseller_prefix)) if (not is_authori...
'Perform authorization for access that does not require a confirmed identity. :returns: A boolean if authorization is granted or denied. None if a determination could not be made.'
def _authorize_unconfirmed_identity(self, req, obj, referrers, roles):
if (req.environ.get('swift_sync_key') and (req.environ['swift_sync_key'] == req.headers.get('x-container-sync-key', None)) and ('x-timestamp' in req.headers)): log_msg = ('allowing proxy %s for container-sync' % req.remote_addr) self.logger.debug(log_msg) return True if swift...
'Deny WSGI Response. 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: return HTTPForbidden(request=req) else: return HTTPUnauthorized(request=req)
'Returns number of requests allowed per second for given container size.'
def get_container_maxrate(self, container_size):
last_func = None if container_size: container_size = int(container_size) for (size, rate, func) in self.container_ratelimits: if (container_size < size): break last_func = func if last_func: return last_func(container_size) return N...
'Returns a list of key (used in memcache), ratelimit tuples. Keys should be checked in order. :param req_method: HTTP method :param account_name: account name from path :param container_name: container name from path :param obj_name: object name from path'
def get_ratelimitable_key_tuples(self, req_method, account_name, container_name=None, obj_name=None):
keys = [] if (self.account_ratelimit and account_name and container_name and (not obj_name) and (req_method in ('PUT', 'DELETE'))): keys.append((('ratelimit/%s' % account_name), self.account_ratelimit)) if (account_name and container_name and obj_name and (req_method in ('PUT', 'DELETE', 'POST'))): ...
'Returns the amount of time (a float in seconds) that the app should sleep. :param key: a memcache key :param max_rate: maximum rate allowed in requests per second :raises: MaxSleepTimeHitError if max sleep time is exceeded.'
def _get_sleep_time(self, key, max_rate):
try: now_m = int(round((time.time() * self.clock_accuracy))) time_per_request_m = int(round((self.clock_accuracy / max_rate))) running_time_m = self.memcache_client.incr(key, delta=time_per_request_m) need_to_sleep_m = 0 if ((now_m - running_time_m) > (self.rate_buffer_second...
'Performs rate limiting and account white/black listing. Sleeps if necessary. If self.memcache_client is not set, immediately returns None. :param account_name: account name from path :param container_name: container name from path :param obj_name: object name from path'
def handle_ratelimit(self, req, account_name, container_name, obj_name):
if (not self.memcache_client): return None if (account_name in self.ratelimit_blacklist): self.logger.error(_('Returning 497 because of blacklisting: %s'), account_name) eventlet.sleep(self.BLACK_LIST_SLEEP) return Response(status='497 Blacklisted', body='Your ...
'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):
req = Request(env) if (self.memcache_client is None): self.memcache_client = cache_from_env(env) if (not self.memcache_client): self.logger.warning(_('Warning: Cannot ratelimit without a memcached client')) return self.app(env, start_response) try: (vers...
'retrieve values from a recon cache file :params cache_keys: list of cache items to retrieve :params cache_file: cache file to retrieve items from. :params openr: open to use [for unittests] :return: dict of cache items and their value or none if not found'
def _from_recon_cache(self, cache_keys, cache_file, openr=open):
try: with openr(cache_file, 'r') as f: recondata = json.load(f) return dict(((key, recondata.get(key)) for key in cache_keys)) except IOError: self.logger.exception(_('Error reading recon cache file')) except ValueError: self.logger.exception(_('Er...
'get ALL mounted fs from /proc/mounts'
def get_mounted(self, openr=open):
mounts = [] with openr('/proc/mounts', 'r') as procmounts: for line in procmounts: mount = {} (mount['device'], mount['path'], opt1, opt2, opt3, opt4) = line.rstrip().split() mounts.append(mount) return mounts
'get info from /proc/loadavg'
def get_load(self, openr=open):
loadavg = {} with openr('/proc/loadavg', 'r') as f: (onemin, fivemin, ftmin, tasks, procs) = f.read().rstrip().split() loadavg['1m'] = float(onemin) loadavg['5m'] = float(fivemin) loadavg['15m'] = float(ftmin) loadavg['tasks'] = tasks loadavg['processes'] = int(procs) return load...
'get info from /proc/meminfo'
def get_mem(self, openr=open):
meminfo = {} with openr('/proc/meminfo', 'r') as memlines: for i in memlines: entry = i.rstrip().split(':') meminfo[entry[0]] = entry[1].strip() return meminfo
'get # of async pendings'
def get_async_info(self):
return self._from_recon_cache(['async_pending'], self.object_recon_cache)
'get replication info'
def get_replication_info(self, recon_type):
if (recon_type == 'account'): return self._from_recon_cache(['replication_time', 'replication_stats', 'replication_last'], self.account_recon_cache) elif (recon_type == 'container'): return self._from_recon_cache(['replication_time', 'replication_stats', 'replication_last'], self.container_recon...
'get devices'
def get_device_info(self):
try: return {self.devices: os.listdir(self.devices)} except Exception: self.logger.exception(_('Error listing devices')) return {self.devices: None}
'get updater info'
def get_updater_info(self, recon_type):
if (recon_type == 'container'): return self._from_recon_cache(['container_updater_sweep'], self.container_recon_cache) elif (recon_type == 'object'): return self._from_recon_cache(['object_updater_sweep'], self.object_recon_cache) else: return None
'get expirer info'
def get_expirer_info(self, recon_type):
if (recon_type == 'object'): return self._from_recon_cache(['object_expiration_pass', 'expired_last_pass'], self.object_recon_cache)
'get auditor info'
def get_auditor_info(self, recon_type):
if (recon_type == 'account'): return self._from_recon_cache(['account_audits_passed', 'account_auditor_pass_completed', 'account_audits_since', 'account_audits_failed'], self.account_recon_cache) elif (recon_type == 'container'): return self._from_recon_cache(['container_audits_passed', 'contain...
'list unmounted (failed?) devices'
def get_unmounted(self):
mountlist = [] for entry in os.listdir(self.devices): mpoint = {'device': entry, 'mounted': check_mount(self.devices, entry)} if (not mpoint['mounted']): mountlist.append(mpoint) return mountlist
'get disk utilization statistics'
def get_diskusage(self):
devices = [] for entry in os.listdir(self.devices): if check_mount(self.devices, entry): path = os.path.join(self.devices, entry) disk = os.statvfs(path) capacity = (disk.f_bsize * disk.f_blocks) available = (disk.f_bsize * disk.f_bavail) used ...
'get all ring md5sum\'s'
def get_ring_md5(self, openr=open):
sums = {} for ringfile in self.rings: md5sum = md5() if os.path.exists(ringfile): try: with openr(ringfile, 'rb') as f: block = f.read(4096) while block: md5sum.update(block) block...
'get obj/container/account quarantine counts'
def get_quarantine_count(self):
qcounts = {'objects': 0, 'containers': 0, 'accounts': 0} qdir = 'quarantined' for device in os.listdir(self.devices): for qtype in qcounts: qtgt = os.path.join(self.devices, device, qdir, qtype) if os.path.exists(qtgt): linkcount = os.lstat(qtgt).st_nlink ...
'get info from /proc/net/sockstat and sockstat6 Note: The mem value is actually kernel pages, but we return bytes allocated based on the systems page size.'
def get_socket_info(self, openr=open):
sockstat = {} try: with openr('/proc/net/sockstat', 'r') as proc_sockstat: for entry in proc_sockstat: if entry.startswith('TCP: inuse'): tcpstats = entry.split() sockstat['tcp_in_use'] = int(tcpstats[2]) sockstat...
'Main hook into the WSGI paste.deploy filter/app pipeline. :param env: The WSGI environment dict. :param start_response: The WSGI start_response hook. :returns: Response as per WSGI.'
def __call__(self, env, start_response):
if (env['REQUEST_METHOD'] == 'POST'): try: (content_type, attrs) = _parse_attrs((env.get('CONTENT_TYPE') or '')) if ((content_type == 'multipart/form-data') and ('boundary' in attrs)): env['HTTP_USER_AGENT'] += ' FormPost' (status, headers, body) = ...
'Translates the form data into subrequests and issues a response. :param env: The WSGI environment dict. :param boundary: The MIME type boundary to look for. :returns: status_line, headers_list, body'
def _translate_form(self, env, boundary):
key = self._get_key(env) status = message = '' attributes = {} file_count = 0 for fp in _iter_requests(env['wsgi.input'], boundary): hdrs = rfc822.Message(fp, 0) (disp, attrs) = _parse_attrs(hdrs.getheader('Content-Disposition', '')) if ((disp == 'form-data') and attrs.get('f...
'Performs the subrequest and returns the response. :param orig_env: The WSGI environment dict; will only be used to form a new env for the subrequest. :param attributes: dict of the attributes of the form so far. :param fp: The file-like object containing the request body. :param key: The account key to validate the si...
def _perform_subrequest(self, orig_env, attributes, fp, key):
if (not key): return ('401 Unauthorized', 'invalid signature') try: max_file_size = int((attributes.get('max_file_size') or 0)) except ValueError: raise FormInvalid('max_file_size not an integer') subenv = make_pre_authed_env(orig_env, 'PUT', agent=None, swift_sour...
'Returns the X-Account-Meta-Temp-URL-Key header value for the account, or None if none is set. :param env: The WSGI environment for the request. :returns: X-Account-Meta-Temp-URL-Key str value, or None.'
def _get_key(self, env):
parts = env['PATH_INFO'].split('/', 4) if ((len(parts) < 4) or parts[0] or (parts[1] != 'v1') or (not parts[2]) or (not parts[3])): return None account = parts[2] key = None memcache = env.get('swift.cache') if memcache: key = memcache.get(('temp-url-key/%s' % account)) if (n...
'Makes a subrequest to create a new container. :params container_path: an unquoted path to a container to be created :returns: None on success :raises: CreateContainerError on creation error'
def create_container(self, req, container_path):
new_env = req.environ.copy() new_env['PATH_INFO'] = container_path new_env['swift.source'] = 'EA' create_cont_req = Request.blank(container_path, environ=new_env) resp = create_cont_req.get_response(self.app) if ((resp.status_int // 100) != 2): raise CreateContainerError(('Create Cont...
'Will populate objs_to_delete with data from request input. :params req: a Swob request :returns: a list of the contents of req.body when separated by newline. :raises: HTTPException on failures'
def get_objs_to_delete(self, req):
line = '' data_remaining = True objs_to_delete = [] if ((req.content_length is None) and (req.headers.get('transfer-encoding', '').lower() != 'chunked')): raise HTTPLengthRequired(request=req) while data_remaining: if ('\n' in line): (obj_to_delete, line) = line.split('\n...
':params req: a swob Request :raises HTTPException: on unhandled errors :returns: a swob Response'
def handle_delete(self, req, objs_to_delete=None, user_agent='BulkDelete', swift_source='BD'):
try: (vrs, account, _junk) = req.split_path(2, 3, True) except ValueError: return HTTPNotFound(request=req) incoming_format = req.headers.get('Content-Type') if (incoming_format and (not incoming_format.startswith('text/plain'))): return HTTPNotAcceptable(request=req) out_con...
':params req: a swob Request :params compress_type: specifying the compression type of the tar. Accepts \'\', \'gz, or \'bz2\' :raises HTTPException: on unhandled errors :returns: a swob response to request'
def handle_extract(self, req, compress_type):
success_count = 0 failed_files = [] existing_containers = set() out_content_type = req.accept.best_match(ACCEPTABLE_FORMATS) if (not out_content_type): return HTTPNotAcceptable(request=req) if ((req.content_length is None) and (req.headers.get('transfer-encoding', '').lower() != 'chunked...
'The length parameter must be a ctypes.c_uint64'
def __call__(self, fd, mode, offset, length):
if (FALLOCATE_RESERVE > 0): st = os.fstatvfs(fd) free = ((st.f_frsize * st.f_bavail) - length.value) if (free <= FALLOCATE_RESERVE): raise OSError(('FALLOCATE_RESERVE fail %s <= %s' % (free, FALLOCATE_RESERVE))) args = {'fallocate': (fd, mode, offset, length), 'po...
'Add extra info to message'
def process(self, msg, kwargs):
kwargs['extra'] = {'server': self.server, 'txn_id': self.txn_id, 'client_ip': self.client_ip} return (msg, kwargs)
'Convenience function for syslog priority LOG_NOTICE. The python logging lvl is set to 25, just above info. SysLogHandler is monkey patched to map this log lvl to the LOG_NOTICE syslog priority.'
def notice(self, msg, *args, **kwargs):
self.log(NOTICE, msg, *args, **kwargs)
'The StatsD client prefix defaults to the "name" of the logger. This method may override that default with a specific value. Currently used in the proxy-server to differentiate the Account, Container, and Object controllers.'
def set_statsd_prefix(self, prefix):
if self.logger.statsd_client: self.logger.statsd_client.set_prefix(prefix)
'Factory to create methods which delegate to methods on self.logger.statsd_client (an instance of StatsdClient). The created methods conditionally delegate to a method whose name is given in \'statsd_func_name\'. The created delegate methods are a no-op when StatsD logging is not configured. :param statsd_func_name: ...
def statsd_delegate(statsd_func_name):
func = getattr(StatsdClient, statsd_func_name) @functools.wraps(func) def wrapped(self, *a, **kw): if getattr(self.logger, 'statsd_client'): return func(self.logger.statsd_client, *a, **kw) return wrapped
':param wsgi_input: file-like object to wrap the functionality of'
def __init__(self, wsgi_input):
self.wsgi_input = wsgi_input self.bytes_received = 0 self.client_disconnect = False
'Pass read request to the underlying file-like object and add bytes read to total.'
def read(self, *args, **kwargs):
try: chunk = self.wsgi_input.read(*args, **kwargs) except Exception: self.client_disconnect = True raise self.bytes_received += len(chunk) return chunk
'Pass readline request to the underlying file-like object and add bytes read to total.'
def readline(self, *args, **kwargs):
try: line = self.wsgi_input.readline(*args, **kwargs) except Exception: self.client_disconnect = True raise self.bytes_received += len(line) return line
'Returns the weight of each partition as calculated from the total weight of all the devices.'
def weight_of_one_part(self):
try: return ((self.parts * self.replicas) / sum((d['weight'] for d in self._iter_devs()))) except ZeroDivisionError: raise exceptions.EmptyRingError('There are no devices in this ring, or all devices have been deleted')
'Reinitializes this RingBuilder instance from data obtained from the builder dict given. Code example:: b = RingBuilder(1, 1, 1) # Dummy values b.copy_from(builder) This is to restore a RingBuilder that has had its b.to_dict() previously saved.'
def copy_from(self, builder):
if hasattr(builder, 'devs'): self.part_power = builder.part_power self.replicas = builder.replicas self.min_part_hours = builder.min_part_hours self.parts = builder.parts self.devs = builder.devs self.devs_changed = builder.devs_changed self.version = builder....
'Returns a dict that can be used later with copy_from to restore a RingBuilder. swift-ring-builder uses this to pickle.dump the dict to a file and later load that dict into copy_from.'
def to_dict(self):
return {'part_power': self.part_power, 'replicas': self.replicas, 'min_part_hours': self.min_part_hours, 'parts': self.parts, 'devs': self.devs, 'devs_changed': self.devs_changed, 'version': self.version, '_replica2part2dev': self._replica2part2dev, '_last_part_moves_epoch': self._last_part_moves_epoch, '_last_part...
'Changes the value used to decide if a given partition can be moved again. This restriction is to give the overall system enough time to settle a partition to its new location before moving it to yet another location. While no data would be lost if a partition is moved several times quickly, it could make that data unr...
def change_min_part_hours(self, min_part_hours):
self.min_part_hours = min_part_hours
'Changes the number of replicas in this ring. If the new replica count is sufficiently different that self._replica2part2dev will change size, sets self.devs_changed. This is so tools like bin/swift-ring-builder can know to write out the new ring rather than bailing out due to lack of balance change.'
def set_replicas(self, new_replica_count):
old_slots_used = int((self.parts * self.replicas)) new_slots_used = int((self.parts * new_replica_count)) if (old_slots_used != new_slots_used): self.devs_changed = True self.replicas = new_replica_count
'Get the ring, or more specifically, the swift.common.ring.RingData. This ring data is the minimum required for use of the ring. The ring builder itself keeps additional data such as when partitions were last moved.'
def get_ring(self):
if (not self._ring): devs = ([None] * len(self.devs)) for dev in self._iter_devs(): devs[dev['id']] = dict(((k, v) for (k, v) in dev.items() if (k not in ('parts', 'parts_wanted')))) if (not self._replica2part2dev): self._ring = RingData([], devs, (32 - self.part_powe...
'Add a device to the ring. This device dict should have a minimum of the following keys: id unique integer identifier amongst devices. Defaults to the next id if the \'id\' key is not provided in the dict weight a float of the relative weight of this device as compared to others; this indicates how many partition...
def add_dev(self, dev):
if ('id' not in dev): dev['id'] = 0 if self.devs: dev['id'] = (max((d['id'] for d in self.devs if d)) + 1) if ((dev['id'] < len(self.devs)) and (self.devs[dev['id']] is not None)): raise exceptions.DuplicateDeviceError(('Duplicate device id: %d' % dev['id'])) whi...
'Set the weight of a device. This should be called rather than just altering the weight key in the device dict directly, as the builder will need to rebuild some internal state to reflect the change. .. note:: This will not rebalance the ring immediately as you may want to make multiple changes for a single rebalance. ...
def set_dev_weight(self, dev_id, weight):
self.devs[dev_id]['weight'] = weight self._set_parts_wanted() self.devs_changed = True self.version += 1
'Remove a device from the ring. .. note:: This will not rebalance the ring immediately as you may want to make multiple changes for a single rebalance. :param dev_id: device id'
def remove_dev(self, dev_id):
dev = self.devs[dev_id] dev['weight'] = 0 self._remove_devs.append(dev) self._set_parts_wanted() self.devs_changed = True self.version += 1
'Rebalance the ring. This is the main work function of the builder, as it will assign and reassign partitions to devices in the ring based on weights, distinct zones, recent reassignments, etc. The process doesn\'t always perfectly assign partitions (that\'d take a lot more analysis and therefore a lot more time -- I h...
def rebalance(self, seed=None):
if seed: random.seed(seed) self._ring = None if (self._last_part_moves_epoch is None): self._initial_balance() self.devs_changed = False return (self.parts, self.get_balance()) retval = 0 self._update_last_part_moves() last_balance = 0 (new_parts, removed_part...
'Validate the ring. This is a safety function to try to catch any bugs in the building process. It ensures partitions have been assigned to real devices, aren\'t doubly assigned, etc. It can also optionally check the even distribution of partitions across devices. :param stats: if True, check distribution of partitions...
def validate(self, stats=False):
dev_len = len(self.devs) parts_on_devs = sum((d['parts'] for d in self._iter_devs())) parts_in_map = sum((len(p2d) for p2d in self._replica2part2dev)) if (parts_on_devs != parts_in_map): raise exceptions.RingValidationError(('All partitions are not double accounted for: %d ...
'Get the balance of the ring. The balance value is the highest percentage off the desired amount of partitions a given device wants. For instance, if the "worst" device wants (based on its weight relative to the sum of all the devices\' weights) 123 partitions and it has 124 partitions, the balance value would be 0.83 ...
def get_balance(self):
balance = 0 weight_of_one_part = self.weight_of_one_part() for dev in self._iter_devs(): if (not dev['weight']): if dev['parts']: balance = 999.99 break continue dev_balance = abs((((100.0 * dev['parts']) / (dev['weight'] * weight_of_on...
'Override min_part_hours by marking all partitions as having been moved 255 hours ago. This can be used to force a full rebalance on the next call to rebalance.'
def pretend_min_part_hours_passed(self):
for part in xrange(self.parts): self._last_part_moves[part] = 255
'Get the devices that are responsible for the partition, filtering out duplicates. :param part: partition to get devices for :returns: list of device dicts'
def get_part_devices(self, part):
devices = [] for dev in self._devs_for_part(part): if (dev not in devices): devices.append(dev) return devices
'Returns an iterator all the non-None devices in the ring. Note that this means list(b._iter_devs())[some_id] may not equal b.devs[some_id]; you will have to check the \'id\' key of each device to obtain its dev_id.'
def _iter_devs(self):
for dev in self.devs: if (dev is not None): (yield dev)
'Sets the parts_wanted key for each of the devices to the number of partitions the device wants based on its relative weight. This key is used to sort the devices according to "most wanted" during rebalancing to best distribute partitions. A negative parts_wanted indicates the device is "overweight" and wishes to give ...
def _set_parts_wanted(self):
weight_of_one_part = self.weight_of_one_part() for dev in self._iter_devs(): if (not dev['weight']): dev['parts_wanted'] = ((- self.parts) * self.replicas) else: dev['parts_wanted'] = (int((weight_of_one_part * dev['weight'])) - dev['parts'])
'Make sure that the lengths of the arrays in _replica2part2dev are correct for the current value of self.replicas. Example: self.part_power = 8 self.replicas = 2.25 self._replica2part2dev will contain 3 arrays: the first 2 of length 256 (2**8), and the last of length 64 (0.25 * 2**8). Returns a 2-tuple: the first eleme...
def _adjust_replica2part2dev_size(self):
removed_replicas = 0 (fractional_replicas, whole_replicas) = math.modf(self.replicas) whole_replicas = int(whole_replicas) desired_lengths = ([self.parts] * whole_replicas) if fractional_replicas: desired_lengths.append(int((self.parts * fractional_replicas))) to_assign = defaultdict(lis...
'Initial partition assignment is the same as rebalancing an existing ring, but with some initial setup beforehand.'
def _initial_balance(self):
self._last_part_moves = array('B', (0 for _junk in xrange(self.parts))) self._last_part_moves_epoch = int(time()) self._reassign_parts(self._adjust_replica2part2dev_size()[0])
'Updates how many hours ago each partition was moved based on the current time. The builder won\'t move a partition that has been moved more recently than min_part_hours.'
def _update_last_part_moves(self):
elapsed_hours = (int((time() - self._last_part_moves_epoch)) / 3600) for part in xrange(self.parts): last_plus_elapsed = (self._last_part_moves[part] + elapsed_hours) if (last_plus_elapsed < 255): self._last_part_moves[part] = last_plus_elapsed else: self._last_pa...
'Returns a list of (partition, replicas) pairs to be reassigned by gathering from removed devices, insufficiently-far-apart replicas, and overweight drives.'
def _gather_reassign_parts(self):
tfd = {} removed_dev_parts = defaultdict(list) if self._remove_devs: dev_ids = [d['id'] for d in self._remove_devs if d['parts']] if dev_ids: for (part, replica) in self._each_part_replica(): dev_id = self._replica2part2dev[replica][part] if (dev_i...
'For an existing ring data set, partitions are reassigned similarly to the initial assignment. The devices are ordered by how many partitions they still want and kept in that order throughout the process. The gathered partitions are iterated through, assigning them to devices according to the "most wanted" while keepin...
def _reassign_parts(self, reassign_parts):
for dev in self._iter_devs(): dev['sort_key'] = self._sort_key_for(dev) available_devs = sorted((d for d in self._iter_devs() if d['weight']), key=(lambda x: x['sort_key'])) tier2devs = defaultdict(list) tier2sort_key = defaultdict(list) max_tier_depth = 0 for dev in available_devs: ...
'Returns a dict of (tier: replica_count) for all tiers in the ring. There will always be a () entry as the root of the structure, whose replica_count will equal the ring\'s replica_count. Then there will be (dev_id,) entries for each device, indicating the maximum number of replicas the device might have for any given ...
def _build_max_replicas_by_tier(self):
tier2children = build_tier_tree(self._iter_devs()) def walk_tree(tier, replica_count): mr = {tier: replica_count} if (tier in tier2children): subtiers = tier2children[tier] for subtier in subtiers: submax = math.ceil((float(replica_count) / len(subtiers)))...
'Returns a list of devices for a specified partition. Deliberately includes duplicates.'
def _devs_for_part(self, part):
if (self._replica2part2dev is None): return [] return [self.devs[part2dev[part]] for part2dev in self._replica2part2dev if (part < len(part2dev))]
'Returns a list of replicas for a specified partition. These can be used as indices into self._replica2part2dev without worrying about IndexErrors.'
def _replicas_for_part(self, part):
return [replica for (replica, part2dev) in enumerate(self._replica2part2dev) if (part < len(part2dev))]
'Generator yielding every (partition, replica) pair in the ring.'
def _each_part_replica(self):
for (replica, part2dev) in enumerate(self._replica2part2dev): for part in xrange(len(part2dev)): (yield (part, replica))
'Obtain RingBuilder instance of the provided builder file :param builder_file: path to builder file to load :return: RingBuilder instance'
@classmethod def load(cls, builder_file, open=open):
builder = pickle.load(open(builder_file, 'rb')) if (not hasattr(builder, 'devs')): builder_dict = builder builder = RingBuilder(1, 1, 1) builder.copy_from(builder_dict) for dev in builder.devs: if (dev and ('meta' not in dev)): dev['meta'] = '' return builder
'The <search-value> can be of the form:: d<device_id>r<region>z<zone>-<ip>:<port>/<device_name>_<meta> Any part is optional, but you must include at least one part. Examples:: d74 Matches the device id 74 r4 Matches devices in region 4 z1 Matches devices in zone 1 z1-1.2.3.4 ...
def search_devs(self, search_value):
orig_search_value = search_value match = [] if search_value.startswith('d'): i = 1 while ((i < len(search_value)) and search_value[i].isdigit()): i += 1 match.append(('id', int(search_value[1:i]))) search_value = search_value[i:] if search_value.startswith('r'...
'Load ring data from a file. :param filename: Path to a file serialized by the save() method. :returns: A RingData instance containing the loaded data.'
@classmethod def load(cls, filename):
gz_file = GzipFile(filename, 'rb') if hasattr(gz_file, '_checkReadable'): gz_file = BufferedReader(gz_file) magic = gz_file.read(4) if (magic == 'R1NG'): (version,) = struct.unpack('!H', gz_file.read(2)) if (version == 1): ring_data = cls.deserialize_v1(gz_file) ...
'Serialize this RingData instance to disk. :param filename: File into which this instance should be serialized.'
def save(self, filename):
try: gz_file = GzipFile(filename, 'wb', mtime=1300507380.0) except TypeError: gz_file = GzipFile(filename, 'wb') self.serialize_v1(gz_file) gz_file.close()
'Number of replicas (full or partial) used in the ring.'
@property def replica_count(self):
return len(self._replica2part2dev_id)
'Number of partitions in the ring.'
@property def partition_count(self):
return len(self._replica2part2dev_id[0])
'devices in the ring'
@property def devs(self):
if (time() > self._rtime): self._reload() return self._devs
'Check to see if the ring on disk is different than the current one in memory. :returns: True if the ring on disk has changed, False otherwise'
def has_changed(self):
return (getmtime(self.serialized_path) != self._mtime)
'Get the nodes that are responsible for the partition. If one node is responsible for more than one replica of the same partition, it will only appear in the output once. :param part: partition to get nodes for :returns: list of node dicts See :func:`get_nodes` for a description of the node dicts.'
def get_part_nodes(self, part):
if (time() > self._rtime): self._reload() return self._get_part_nodes(part)
'Get the partition and nodes for an account/container/object. If a node is responsible for more than one replica, it will only appear in the output once. :param account: account name :param container: container name :param obj: object name :returns: a tuple of (partition, list of node dicts) Each node dict will have at...
def get_nodes(self, account, container=None, obj=None):
key = hash_path(account, container, obj, raw_digest=True) if (time() > self._rtime): self._reload() part = (struct.unpack_from('>I', key)[0] >> self._part_shift) return (part, self._get_part_nodes(part))
'Generator to get extra nodes for a partition for hinted handoff. The handoff nodes will try to be in zones other than the primary zones, will take into account the device weights, and will usually keep the same sequences of handoffs even with ring changes. :param part: partition to get handoff nodes for :returns: gene...
def get_more_nodes(self, part):
if (time() > self._rtime): self._reload() primary_nodes = self._get_part_nodes(part) used = set((d['id'] for d in primary_nodes)) same_regions = set((d['region'] for d in primary_nodes)) same_zones = set(((d['region'], d['zone']) for d in primary_nodes)) parts = len(self._replica2part2de...
''
def __init__(self, node, partition, hash_, logger):
self.logger = logger self.node = node BufferedHTTPConnection.__init__(self, ('%(ip)s:%(port)s' % node)) self.path = ('/%s/%s/%s' % (node['device'], partition, hash_))
'Make an HTTP REPLICATE request :param args: list of json-encodable objects :returns: httplib response object'
def replicate(self, *args):
try: body = simplejson.dumps(args) self.request('REPLICATE', self.path, body, {'Content-Type': 'application/json'}) response = self.getresponse() response.data = response.read() return response except (Exception, Timeout): self.logger.exception(_('ERROR reading...
'Zero out the stats.'
def _zero_stats(self):
self.stats = {'attempted': 0, 'success': 0, 'failure': 0, 'ts_repl': 0, 'no_change': 0, 'hashmatch': 0, 'rsync': 0, 'diff': 0, 'remove': 0, 'empty': 0, 'remote_merge': 0, 'start': time.time(), 'diff_capped': 0}
'Report the current stats to the logs.'
def _report_stats(self):
self.logger.info(_('Attempted to replicate %(count)d dbs in %(time).5f seconds (%(rate).5f/s)'), {'count': self.stats['attempted'], 'time': (time.time() - self.stats['start']), 'rate': (self.stats['attempted'] / ((time.time() - self.stats['start']) + 1e-07))}) self.logger.info((_('Remove...
'Sync a single file using rsync. Used by _rsync_db to handle syncing. :param db_file: file to be synced :param remote_file: remote location to sync the DB file to :param whole-file: if True, uses rsync\'s --whole-file flag :returns: True if the sync was successful, False otherwise'
def _rsync_file(self, db_file, remote_file, whole_file=True):
popen_args = ['rsync', '--quiet', '--no-motd', ('--timeout=%s' % int(math.ceil(self.node_timeout))), ('--contimeout=%s' % int(math.ceil(self.conn_timeout)))] if whole_file: popen_args.append('--whole-file') popen_args.extend([db_file, remote_file]) proc = subprocess.Popen(popen_args) proc.co...
'Sync a whole db using rsync. :param broker: DB broker object of DB to be synced :param device: device to sync to :param http: ReplConnection object :param local_id: unique ID of the local database replica :param replicate_method: remote operation to perform after rsync :param replicate_timeout: timeout to wait in seco...
def _rsync_db(self, broker, device, http, local_id, replicate_method='complete_rsync', replicate_timeout=None):
device_ip = rsync_ip(device['ip']) if self.vm_test_mode: remote_file = ('%s::%s%s/%s/tmp/%s' % (device_ip, self.server_type, device['port'], device['device'], local_id)) else: remote_file = ('%s::%s/%s/tmp/%s' % (device_ip, self.server_type, device['device'], local_id)) mtime = os.path.g...
'Sync a db by sending all records since the last sync. :param point: synchronization high water mark between the replicas :param broker: database broker object :param http: ReplConnection object for the remote server :param remote_id: database id for the remote replica :param local_id: database id for the local replica...
def _usync_db(self, point, broker, http, remote_id, local_id):
self.stats['diff'] += 1 self.logger.increment('diffs') self.logger.debug(_('Syncing chunks with %s'), http.host) sync_table = broker.get_syncs() objects = broker.get_items_since(point, self.per_diff) diffs = 0 while (len(objects) and (diffs < self.max_diffs)): diffs += 1 ...