本文整理汇总了Python中swift.common.storage_policy.POLICIES.get_by_index方法的典型用法代码示例。如果您正苦于以下问题:Python POLICIES.get_by_index方法的具体用法?Python POLICIES.get_by_index怎么用?Python POLICIES.get_by_index使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类swift.common.storage_policy.POLICIES
的用法示例。
在下文中一共展示了POLICIES.get_by_index方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DELETE
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def DELETE(self, req):
"""HTTP DELETE request handler."""
account_partition, accounts, container_count = \
self.account_info(self.account_name, req)
if not accounts:
return HTTPNotFound(request=req)
policy_index = self._convert_policy_to_index(req)
if policy_index is None:
policy_index = int(POLICIES.default)
cloud_ring = CloudRing(self.container_name, POLICIES.get_by_index(policy_index))
container_partition, containers = self.app.container_ring.get_nodes(
self.account_name, self.container_name)
headers = self._backend_requests(req, len(containers),
account_partition, accounts)
clear_info_cache(self.app, req.environ,
self.account_name, self.container_name)
resp = self.make_requests(
req, self.app.container_ring, container_partition, 'DELETE',
req.swift_entity_path, headers)
# Indicates no server had the container
if resp.status_int == HTTP_ACCEPTED:
return HTTPNotFound(request=req)
return_flag, _info = cloud_ring.delete_containers()
if not return_flag:
msg = 'Failed:' + str(_info)
raise DELETECloudContainerException(msg)
return resp
示例2: get_and_validate_policy_index
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def get_and_validate_policy_index(self, req):
"""
Validate that the index supplied maps to a policy.
:returns: policy index from request, or None if not present
:raises: HTTPBadRequest if the supplied index is bogus
"""
policy_index = req.headers.get('X-Backend-Storage-Policy-Index', None)
if policy_index is None:
return None
try:
policy_index = int(policy_index)
except ValueError:
raise HTTPBadRequest(
request=req, content_type="text/plain",
body=("Invalid X-Storage-Policy-Index %r" % policy_index))
policy = POLICIES.get_by_index(policy_index)
if policy is None:
raise HTTPBadRequest(
request=req, content_type="text/plain",
body=("Invalid X-Storage-Policy-Index %r" % policy_index))
return int(policy)
示例3: get_name_and_placement
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def get_name_and_placement(request, minsegs=1, maxsegs=None,
rest_with_last=False):
"""
Utility function to split and validate the request path and storage
policy. The storage policy index is extracted from the headers of
the request and converted to a StoragePolicy instance. The
remaining args are passed through to
:meth:`split_and_validate_path`.
:returns: a list, result of :meth:`split_and_validate_path` with
the BaseStoragePolicy instance appended on the end
:raises: HTTPServiceUnavailable if the path is invalid or no policy exists
with the extracted policy_index.
"""
policy_index = request.headers.get('X-Backend-Storage-Policy-Index')
policy = POLICIES.get_by_index(policy_index)
if not policy:
raise HTTPServiceUnavailable(
body=_("No policy with index %s") % policy_index,
request=request, content_type='text/plain')
results = split_and_validate_path(request, minsegs=minsegs,
maxsegs=maxsegs,
rest_with_last=rest_with_last)
results.append(policy)
return results
示例4: test_defaults
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def test_defaults(self):
self.assertTrue(len(POLICIES) > 0)
# test class functions
default_policy = POLICIES.default
self.assertTrue(default_policy.is_default)
zero_policy = POLICIES.get_by_index(0)
self.assertTrue(zero_policy.idx == 0)
zero_policy_by_name = POLICIES.get_by_name(zero_policy.name)
self.assertTrue(zero_policy_by_name.idx == 0)
示例5: PUT
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def PUT(self, req):
"""HTTP PUT request handler."""
error_response = \
self.clean_acls(req) or check_metadata(req, 'container')
if error_response:
return error_response
policy_index = self._convert_policy_to_index(req)
if policy_index is None:
policy_index = int(POLICIES.default)
if not req.environ.get('swift_owner'):
for key in self.app.swift_owner_headers:
req.headers.pop(key, None)
if len(self.container_name) > constraints.MAX_CONTAINER_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = 'Container name length of %d longer than %d' % \
(len(self.container_name),
constraints.MAX_CONTAINER_NAME_LENGTH)
return resp
account_partition, accounts, container_count = \
self.account_info(self.account_name, req)
if not accounts and self.app.account_autocreate:
self.autocreate_account(req, self.account_name)
account_partition, accounts, container_count = \
self.account_info(self.account_name, req)
if not accounts:
return HTTPNotFound(request=req)
if self.app.max_containers_per_account > 0 and \
container_count >= self.app.max_containers_per_account and \
self.account_name not in self.app.max_containers_whitelist:
container_info = \
self.container_info(self.account_name, self.container_name,
req)
if not is_success(container_info.get('status')):
resp = HTTPForbidden(request=req)
resp.body = 'Reached container limit of %s' % \
self.app.max_containers_per_account
return resp
container_partition, containers = self.app.container_ring.get_nodes(
self.account_name, self.container_name)
headers = self._backend_requests(req, len(containers),
account_partition, accounts,
policy_index)
clear_info_cache(self.app, req.environ,
self.account_name, self.container_name)
resp = self.make_requests(
req, self.app.container_ring,
container_partition, 'PUT', req.swift_entity_path, headers)
cloud_ring = CloudRing(self.container_name, POLICIES.get_by_index(policy_index))
return_flag, _info = cloud_ring.create_containers()
if not return_flag:
msg = 'Failed:' + str(_info)
raise PUTCloudContainerException(msg)
return resp
示例6: get_controller
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def get_controller(self, req):
"""
Get the controller to handle a request.
:param req: the request
:returns: tuple of (controller class, path dictionary)
:raises: ValueError (thrown by split_path) if given invalid path
"""
print 'req.path',req.path
if req.path == '/info':
d = dict(version=None,
expose_info=self.expose_info,
disallowed_sections=self.disallowed_sections,
admin_key=self.admin_key)
print 'd',d
return InfoController, d
version, account, container, obj = split_path(req.path, 1, 4, True)
d = dict(version=version,
account_name=account,
container_name=container,
object_name=obj)
print 'd',d
#print 'valid_api_version(version)',valid_api_version(version)
if account and not valid_api_version(version):
raise APIVersionError('Invalid path')
if obj and container and account:
info = get_container_info(req.environ, self)
print 'info of obj,Acc,Con',info
policy_index = req.headers.get('X-Backend-Storage-Policy-Index',
info['storage_policy'])
print 'policy_index',policy_index
policy = POLICIES.get_by_index(policy_index)
print 'policy',policy
if not policy:
# This indicates that a new policy has been created,
# with rings, deployed, released (i.e. deprecated =
# False), used by a client to create a container via
# another proxy that was restarted after the policy
# was released, and is now cached - all before this
# worker was HUPed to stop accepting new
# connections. There should never be an "unknown"
# index - but when there is - it's probably operator
# error and hopefully temporary.
raise HTTPServiceUnavailable('Unknown Storage Policy')
return self.obj_controller_router[policy], d
elif container and account:
print 'container & account, returning containercontroller',container,account
return ContainerController, d
elif account and not container and not obj:
print 'account, returning accountcontroller',account
return AccountController, d
return None, d
示例7: get_controller
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def get_controller(self, req):
"""
Get the controller to handle a request.
:param req: the request
:returns: tuple of (controller class, path dictionary)
:raises: ValueError (thrown by split_path) if given invalid path
"""
if req.path == '/info':
d = dict(version=None,
expose_info=self.expose_info,
disallowed_sections=self.disallowed_sections,
admin_key=self.admin_key)
return InfoController, d
#分割路径信息
version, account, container, obj = split_path(req.path, 1, 4, True)
#生成包含version、account、container、object的路径字典,用于返回
d = dict(version=version,
account_name=account,
container_name=container,
object_name=obj)
if account and not valid_api_version(version):
raise APIVersionError('Invalid path')
#如果是对象操作
if obj and container and account:
#获取container信息
info = get_container_info(req.environ, self)
policy_index = req.headers.get('X-Backend-Storage-Policy-Index',
info['storage_policy'])
#通过index获取存储策略对象
policy = POLICIES.get_by_index(policy_index)
if not policy:
# This indicates that a new policy has been created,
# with rings, deployed, released (i.e. deprecated =
# False), used by a client to create a container via
# another proxy that was restarted after the policy
# was released, and is now cached - all before this
# worker was HUPed to stop accepting new
# connections. There should never be an "unknown"
# index - but when there is - it's probably operator
# error and hopefully temporary.
raise HTTPServiceUnavailable('Unknown Storage Policy')
#返回对象操作的控制器对象,以及路径字典
return self.obj_controller_router[policy], d
#如果是container操作,返回container控制器,以及路径字典
elif container and account:
return ContainerController, d
#如果是account操作,返回account控制器,以及路径字典
elif account and not container and not obj:
return AccountController, d
return None, d
示例8: put_container
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def put_container(self, policy_index=None):
"""
put container with next storage policy
"""
policy = self.policies.next()
if policy_index is not None:
policy = POLICIES.get_by_index(int(policy_index))
if not policy:
raise ValueError('Unknown policy with index %s' % policy)
headers = {'X-Storage-Policy': policy.name}
client.put_container(self.url, self.token, self.container_name,
headers=headers)
示例9: check_config
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def check_config(self):
"""
Check the configuration for possible errors
"""
for policy_idx, options in self._override_options.items():
policy = (None if policy_idx is None
else POLICIES.get_by_index(policy_idx))
if options.read_affinity and options.sorting_method != 'affinity':
self.logger.warning(
_("sorting_method is set to '%(method)s', not 'affinity'; "
"%(label)s read_affinity setting will have no effect."),
{'label': _label_for_policy(policy),
'method': options.sorting_method})
示例10: _store_object
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def _store_object(self, req, data_source, nodes, partition,
outgoing_headers):
"""
Store a replicated object.
This method is responsible for establishing connection
with storage nodes and sending object to each one of those
nodes. After sending the data, the "best" reponse will be
returned based on statuses from all connections
"""
policy_idx = req.headers.get('X-Backend-Storage-Policy-Index')
policy = POLICIES.get_by_index(policy_idx)
if not nodes:
return HTTPNotFound()
# RFC2616:8.2.3 disallows 100-continue without a body
if (req.content_length > 0) or req.is_chunked:
expect = True
else:
expect = False
conns = self._get_put_connections(req, nodes, partition,
outgoing_headers, policy, expect)
try:
# check that a minimum number of connections were established and
# meet all the correct conditions set in the request
self._check_failure_put_connections(conns, req, nodes)
# transfer data
self._transfer_data(req, data_source, conns, nodes)
# get responses
statuses, reasons, bodies, etags = self._get_put_responses(
req, conns, nodes)
except HTTPException as resp:
return resp
finally:
for conn in conns:
conn.close()
if len(etags) > 1:
self.app.logger.error(
_('Object servers returned %s mismatched etags'), len(etags))
return HTTPServerError(request=req)
etag = etags.pop() if len(etags) else None
resp = self.best_response(req, statuses, reasons, bodies,
_('Object PUT'), etag=etag)
resp.last_modified = math.ceil(
float(Timestamp(req.headers['X-Timestamp'])))
return resp
示例11: test_obj_put_legacy_updates
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def test_obj_put_legacy_updates(self):
ts = (normalize_timestamp(t) for t in
itertools.count(int(time())))
policy = POLICIES.get_by_index(0)
# setup updater
conf = {
'devices': self.devices_dir,
'mount_check': 'false',
'swift_dir': self.testdir,
}
async_dir = os.path.join(self.sda1, get_async_dir(policy))
os.mkdir(async_dir)
account, container, obj = 'a', 'c', 'o'
# write an async
for op in ('PUT', 'DELETE'):
self.logger._clear()
daemon = object_updater.ObjectUpdater(conf, logger=self.logger)
dfmanager = DiskFileManager(conf, daemon.logger)
# don't include storage-policy-index in headers_out pickle
headers_out = swob.HeaderKeyDict({
'x-size': 0,
'x-content-type': 'text/plain',
'x-etag': 'd41d8cd98f00b204e9800998ecf8427e',
'x-timestamp': next(ts),
})
data = {'op': op, 'account': account, 'container': container,
'obj': obj, 'headers': headers_out}
dfmanager.pickle_async_update(self.sda1, account, container, obj,
data, next(ts), policy)
request_log = []
def capture(*args, **kwargs):
request_log.append((args, kwargs))
# run once
fake_status_codes = [200, 200, 200]
with mocked_http_conn(*fake_status_codes, give_connect=capture):
daemon.run_once()
self.assertEqual(len(fake_status_codes), len(request_log))
for request_args, request_kwargs in request_log:
ip, part, method, path, headers, qs, ssl = request_args
self.assertEqual(method, op)
self.assertEqual(headers['X-Backend-Storage-Policy-Index'],
str(int(policy)))
self.assertEqual(daemon.logger.get_increment_counts(),
{'successes': 1, 'unlinks': 1,
'async_pendings': 1})
示例12: statsd_metric_name_policy
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def statsd_metric_name_policy(self, req, status_int, method, policy_index):
if policy_index is None:
return None
stat_type = self.get_metric_name_type(req)
if stat_type == 'object':
stat_method = method if method in self.valid_methods \
else 'BAD_METHOD'
# The policy may not exist
policy = POLICIES.get_by_index(policy_index)
if policy:
return '.'.join((stat_type, 'policy', str(policy_index),
stat_method, str(status_int)))
else:
return None
else:
return None
示例13: __call__
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def __call__(self, env, start_response):
request = Request(env)
if request.method == 'PUT':
try:
version, account, container, obj = \
request.split_path(1, 4, True)
except ValueError:
return self.app(env, start_response)
# check container creation request
if account and container and not obj:
policy_name = request.headers.get('X-Storage-Policy', '')
default_policy = POLICIES.default.name
if (policy_name in self.policies) or \
(policy_name == '' and default_policy in self.policies):
container = unquote(container)
if len(container) > constraints. \
SOF_MAX_CONTAINER_NAME_LENGTH:
resp = HTTPBadRequest(request=request)
resp.body = \
'Container name length of %d longer than %d' % \
(len(container),
constraints.SOF_MAX_CONTAINER_NAME_LENGTH)
return resp(env, start_response)
elif account and container and obj:
# check object creation request
obj = unquote(obj)
container_info = get_container_info(
env, self.app)
policy = POLICIES.get_by_index(
container_info['storage_policy'])
if policy.name in self.policies:
error_response = sof_check_object_creation(request, obj)
if error_response:
self.logger.warn("returning error: %s", error_response)
return error_response(env, start_response)
return self.app(env, start_response)
示例14: test_obj_put_legacy_updates
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def test_obj_put_legacy_updates(self):
ts = (normalize_timestamp(t) for t in itertools.count(int(time())))
policy = POLICIES.get_by_index(0)
# setup updater
conf = {"devices": self.devices_dir, "mount_check": "false", "swift_dir": self.testdir}
async_dir = os.path.join(self.sda1, get_async_dir(policy.idx))
os.mkdir(async_dir)
account, container, obj = "a", "c", "o"
# write an async
for op in ("PUT", "DELETE"):
self.logger._clear()
daemon = object_updater.ObjectUpdater(conf, logger=self.logger)
dfmanager = DiskFileManager(conf, daemon.logger)
# don't include storage-policy-index in headers_out pickle
headers_out = swob.HeaderKeyDict(
{
"x-size": 0,
"x-content-type": "text/plain",
"x-etag": "d41d8cd98f00b204e9800998ecf8427e",
"x-timestamp": ts.next(),
}
)
data = {"op": op, "account": account, "container": container, "obj": obj, "headers": headers_out}
dfmanager.pickle_async_update(self.sda1, account, container, obj, data, ts.next(), policy.idx)
request_log = []
def capture(*args, **kwargs):
request_log.append((args, kwargs))
# run once
fake_status_codes = [200, 200, 200]
with mocked_http_conn(*fake_status_codes, give_connect=capture):
daemon.run_once()
self.assertEqual(len(fake_status_codes), len(request_log))
for request_args, request_kwargs in request_log:
ip, part, method, path, headers, qs, ssl = request_args
self.assertEqual(method, op)
self.assertEqual(headers["X-Backend-Storage-Policy-Index"], str(policy.idx))
self.assertEqual(daemon.logger.get_increment_counts(), {"successes": 1, "unlinks": 1, "async_pendings": 1})
示例15: get_response_headers
# 需要导入模块: from swift.common.storage_policy import POLICIES [as 别名]
# 或者: from swift.common.storage_policy.POLICIES import get_by_index [as 别名]
def get_response_headers(broker):
info = broker.get_info()
resp_headers = {
'X-Account-Container-Count': info['container_count'],
'X-Account-Object-Count': info['object_count'],
'X-Account-Bytes-Used': info['bytes_used'],
'X-Timestamp': Timestamp(info['created_at']).normal,
'X-PUT-Timestamp': Timestamp(info['put_timestamp']).normal}
policy_stats = broker.get_policy_stats()
for policy_idx, stats in policy_stats.items():
policy = POLICIES.get_by_index(policy_idx)
if not policy:
continue
header_prefix = 'X-Account-Storage-Policy-%s-%%s' % policy.name
for key, value in stats.items():
header_name = header_prefix % key.replace('_', '-')
resp_headers[header_name] = value
resp_headers.update((key, value)
for key, (value, timestamp) in
broker.metadata.items() if value != '')
return resp_headers