python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
# Copyright 2020 NVIDIA Corporation # SPDX-License-Identifier: Apache-2.0 print('static const size_t nodeSizes[3][6] = {') for type in ['float', 'Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'sizeof(InternalNode<LeafNode<{type}>, {ld}>)', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('};') print('static const size_t leafSizes[3][6] = {') for type in ['float', 'Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'sizeof(LeafNode<{type}, Coord, Mask, {ld}>)', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('};') print('static const Node2RangeFunc rangeFunctions[3][6] = {') for type in ['float', 'Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'GetNode2Range<{type}, {ld}>', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('};') print('static const __device__ ProcessLeafFunc processLeafFuncs[3][6] = {') for type in ['float', 'nanovdb::Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'ProcessLeaf<{type}, {ld}>', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('};') print('static const __device__ NodeRangeFunc rangeFunctions[2][3][6] = {{') for type in ['float', 'nanovdb::Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'GetNodeRange<LeafNodeSmpl<{type}, {ld}>>', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('},{',) for type in ['float', 'nanovdb::Vec3f', 'int']: print('{', end='') for ld in range(2, 8): # Using 3 for the leaf node's LOG2DIM suffices here print(f'GetNodeRange<INodeSmpl<{type}, {ld}>>', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('}};') print('static const __device__ ProcessInternalNodeFunc processInternalNodeFuncs[3][6] = {') for type in ['float', 'nanovdb::Vec3f', 'int']: print('{', end='') for ld in range(2, 8): print(f'ProcessInternalNode<{type}, {ld}>', end='') if ld != 7: print(', ', end='') if(type == 'int'): print('}') else: print('},') print('};')
gvdb-voxels-master
source/gNanoVDB/generateNodeTables.py
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr'], pbr=True)
swift-master
setup.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import sys from contextlib import contextmanager import os from six import reraise from unittest.util import safe_repr import warnings warnings.filterwarnings('ignore', module='cryptography|OpenSSL', message=( 'Python 2 is no longer supported by the Python core team. ' 'Support for it is now deprecated in cryptography, ' 'and will be removed in a future release.')) warnings.filterwarnings('ignore', module='cryptography|OpenSSL', message=( 'Python 2 is no longer supported by the Python core team. ' 'Support for it is now deprecated in cryptography, ' 'and will be removed in the next release.')) warnings.filterwarnings('ignore', message=( 'Python 3.6 is no longer supported by the Python core team. ' 'Therefore, support for it is deprecated in cryptography ' 'and will be removed in a future release.')) import unittest if sys.version_info < (3, 2): unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp unittest.TestCase.assertRegex = unittest.TestCase.assertRegexpMatches from eventlet.green import socket from swift.common.utils import readconf # Work around what seems to be a Python bug. # c.f. https://bugs.launchpad.net/swift/+bug/820185. import logging logging.raiseExceptions = False def get_config(section_name=None, defaults=None): """ Attempt to get a test config dictionary. :param section_name: the section to read (all sections if not defined) :param defaults: an optional dictionary namespace of defaults """ config = {} if defaults is not None: config.update(defaults) config_file = os.environ.get('SWIFT_TEST_CONFIG_FILE', '/etc/swift/test.conf') try: config = readconf(config_file, section_name) except IOError: if not os.path.exists(config_file): print('Unable to read test config %s - file not found' % config_file, file=sys.stderr) elif not os.access(config_file, os.R_OK): print('Unable to read test config %s - permission denied' % config_file, file=sys.stderr) except ValueError as e: print(e) return config def listen_zero(): """ The eventlet.listen() always sets SO_REUSEPORT, so when called with ("localhost",0), instead of returning unique ports it can return the same port twice. That causes our tests to fail, so open-code it here without SO_REUSEPORT. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 0)) sock.listen(50) return sock @contextmanager def annotate_failure(msg): """ Catch AssertionError and annotate it with a message. Useful when making assertions in a loop where the message can indicate the loop index or richer context about the failure. :param msg: A message to be prefixed to the AssertionError message. """ try: yield except AssertionError as err: err_typ, err_val, err_tb = sys.exc_info() if err_val.args: msg = '%s Failed with %s' % (msg, err_val.args[0]) err_val.args = (msg, ) + err_val.args[1:] else: # workaround for some IDE's raising custom AssertionErrors err_val = '%s Failed with %s' % (msg, err) err_typ = AssertionError reraise(err_typ, err_val, err_tb) class BaseTestCase(unittest.TestCase): def _assertDictContainsSubset(self, subset, dictionary, msg=None): """Checks whether dictionary is a superset of subset.""" # This is almost identical to the method in python3.4 version of # unitest.case.TestCase.assertDictContainsSubset, reproduced here to # avoid the deprecation warning in the original when using python3. missing = [] mismatched = [] for key, value in subset.items(): if key not in dictionary: missing.append(key) elif value != dictionary[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(dictionary[key]))) if not (missing or mismatched): return standardMsg = '' if missing: standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += 'Mismatched values: %s' % ','.join(mismatched) self.fail(self._formatMessage(msg, standardMsg))
swift-master
test/__init__.py
# Copyright (c) 2010-2021 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import logging import mock import sys from collections import defaultdict from swift.common import utils from swift.common.utils import NOTICE class WARN_DEPRECATED(Exception): def __init__(self, msg): self.msg = msg print(self.msg) class FakeStatsdClient(utils.StatsdClient): def __init__(self, host, port, base_prefix='', tail_prefix='', default_sample_rate=1, sample_rate_factor=1, logger=None): super(FakeStatsdClient, self).__init__( host, port, base_prefix, tail_prefix, default_sample_rate, sample_rate_factor, logger) self.clear() # Capture then call parent pubic stat functions self.update_stats = self._capture("update_stats") self.increment = self._capture("increment") self.decrement = self._capture("decrement") self.timing = self._capture("timing") self.timing_since = self._capture("timing_since") self.transfer_rate = self._capture("transfer_rate") def _capture(self, func_name): func = getattr(super(FakeStatsdClient, self), func_name) def wrapper(*args, **kwargs): self.calls[func_name].append((args, kwargs)) return func(*args, **kwargs) return wrapper def _determine_sock_family(self, host, port): return None, None def _open_socket(self): return self # sendto and close are mimicing the socket calls. def sendto(self, msg, target): self.sendto_calls.append((msg, target)) def close(self): pass def _send(self, *args, **kwargs): self.send_calls.append((args, kwargs)) super(FakeStatsdClient, self)._send(*args, **kwargs) def clear(self): self.send_calls = [] self.calls = defaultdict(list) self.sendto_calls = [] def get_increments(self): return [call[0][0] for call in self.calls['increment']] def get_increment_counts(self): # note: this method reports the sum of stats sent via the increment # method only; consider using get_stats_counts instead to get the sum # of stats sent via both the increment and update_stats methods counts = defaultdict(int) for metric in self.get_increments(): counts[metric] += 1 return counts def get_update_stats(self): return [call[0][:2] for call in self.calls['update_stats']] def get_stats_counts(self): counts = defaultdict(int) for metric, step in self.get_update_stats(): counts[metric] += step return counts class CaptureLog(object): """ Captures log records passed to the ``handle`` method and provides accessor functions to the captured logs. """ def __init__(self): self.clear() def _clear(self): self.log_dict = defaultdict(list) self.lines_dict = {'critical': [], 'error': [], 'info': [], 'warning': [], 'debug': [], 'notice': []} clear = _clear # this is a public interface def get_lines_for_level(self, level): if level not in self.lines_dict: raise KeyError( "Invalid log level '%s'; valid levels are %s" % (level, ', '.join("'%s'" % lvl for lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return dict((level, msgs) for level, msgs in self.lines_dict.items() if len(msgs) > 0) def _handle(self, record): try: line = record.getMessage() except TypeError: print('WARNING: unable to format log message %r %% %r' % ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) return 0 def handle(self, record): return self._handle(record) class FakeLogger(logging.Logger, CaptureLog): # a thread safe fake logger def __init__(self, *args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility' in kwargs: self.facility = kwargs['facility'] self.statsd_client = FakeStatsdClient("host", 8125) self.thread_locals = None self.parent = None # ensure the NOTICE level has been named, in case it has not already # been set logging.addLevelName(NOTICE, 'NOTICE') store_in = { logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', } def clear(self): self._clear() self.statsd_client.clear() def close(self): self.clear() def warn(self, *args, **kwargs): raise WARN_DEPRECATED("Deprecated Method warn use warning instead") def notice(self, msg, *args, **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. """ self.log(NOTICE, msg, *args, **kwargs) def _log(self, level, msg, *args, **kwargs): store_name = self.store_in[level] cargs = [msg] if any(args): cargs.extend(args) captured = dict(kwargs) if 'exc_info' in kwargs and \ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs) def setFormatter(self, obj): self.formatter = obj def set_name(self, name): # don't touch _handlers self._name = name def acquire(self): pass def release(self): pass def createLock(self): pass def emit(self, record): pass def flush(self): pass def handleError(self, record): pass def isEnabledFor(self, level): return True class DebugSwiftLogFormatter(utils.SwiftLogFormatter): def format(self, record): msg = super(DebugSwiftLogFormatter, self).format(record) return msg.replace('#012', '\n') class DebugLogger(FakeLogger): """A simple stdout logging version of FakeLogger""" def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter = DebugSwiftLogFormatter( "%(server)s %(levelname)s: %(message)s") self.records = defaultdict(list) def handle(self, record): self._handle(record) formatted = self.formatter.format(record) print(formatted) self.records[record.levelname].append(formatted) class DebugLogAdapter(utils.LogAdapter): def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): """get a named adapted debug logger""" return DebugLogAdapter(DebugLogger(), name) class ForwardingLogHandler(logging.NullHandler): """ Provides a LogHandler implementation that simply forwards filtered records to a given handler function. This can be useful to forward records to a handler without the handler itself needing to subclass LogHandler. """ def __init__(self, handler_fn): super(ForwardingLogHandler, self).__init__() self.handler_fn = handler_fn def handle(self, record): return self.handler_fn(record) class CaptureLogAdapter(utils.LogAdapter, CaptureLog): """ A LogAdapter that is capable of capturing logs for inspection via accessor methods. """ def __init__(self, logger, name): super(CaptureLogAdapter, self).__init__(logger, name) self.clear() self.handler = ForwardingLogHandler(self.handle) def start_capture(self): """ Attaches the adapter's handler to the adapted logger in order to start capturing log messages. """ self.logger.addHandler(self.handler) def stop_capture(self): """ Detaches the adapter's handler from the adapted logger. This should be called to prevent further logging to the adapted logger (possibly via other log adapter instances) being captured by this instance. """ self.logger.removeHandler(self.handler) @contextlib.contextmanager def capture_logger(conf, *args, **kwargs): """ Yields an adapted system logger based on the conf options. The log adapter captures logs in order to support the pattern of tests calling the log accessor methods (e.g. get_lines_for_level) directly on the logger instance. """ with mock.patch('swift.common.utils.LogAdapter', CaptureLogAdapter): log_adapter = utils.get_logger(conf, *args, **kwargs) log_adapter.start_capture() try: yield log_adapter finally: log_adapter.stop_capture()
swift-master
test/debug_logger.py
# Copyright (c) 2022 Nvidia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest import SkipTest from test.s3api import BaseS3TestCase class AlwaysAbsoluteURLProxyConfig(object): def __init__(self): self.settings = {'proxy_use_forwarding_for_https': True} def proxy_url_for(self, request_url): return request_url def proxy_headers_for(self, proxy_url): return {} class TestRequestTargetStyle(BaseS3TestCase): def setUp(self): self.client = self.get_s3_client(1) if not self.client._endpoint.host.startswith('https:'): raise SkipTest('Absolute URL test requires https') self.bucket_name = self.create_name('test-address-style') resp = self.client.create_bucket(Bucket=self.bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) def tearDown(self): self.clear_bucket(self.client, self.bucket_name) super(TestRequestTargetStyle, self).tearDown() def test_absolute_url(self): sess = self.client._endpoint.http_session sess._proxy_config = AlwaysAbsoluteURLProxyConfig() self.assertEqual({'use_forwarding_for_https': True}, sess._proxies_kwargs()) resp = self.client.list_buckets() self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertIn(self.bucket_name, { info['Name'] for info in resp['Buckets']})
swift-master
test/s3api/test_request_target_style.py
# Copyright (c) 2019 SwiftStack, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from test.s3api import BaseS3TestCase, ConfigError class TestGetServiceSigV4(BaseS3TestCase): def test_empty_service(self): def do_test(client): access_key = client._request_signer._credentials.access_key resp = client.list_buckets() self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual([], resp['Buckets']) self.assertIn('x-amz-request-id', resp['ResponseMetadata']['HTTPHeaders']) self.assertIn('DisplayName', resp['Owner']) self.assertEqual(access_key, resp['Owner']['DisplayName']) self.assertIn('ID', resp['Owner']) client = self.get_s3_client(1) do_test(client) try: client = self.get_s3_client(3) except ConfigError: pass else: do_test(client) def test_service_with_buckets(self): c = self.get_s3_client(1) buckets = [self.create_name('bucket%s' % i) for i in range(5)] for bucket in buckets: c.create_bucket(Bucket=bucket) resp = c.list_buckets() self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual(sorted(buckets), [ bucket['Name'] for bucket in resp['Buckets']]) self.assertTrue(all('CreationDate' in bucket for bucket in resp['Buckets'])) self.assertIn('x-amz-request-id', resp['ResponseMetadata']['HTTPHeaders']) self.assertIn('DisplayName', resp['Owner']) access_key = c._request_signer._credentials.access_key self.assertEqual(access_key, resp['Owner']['DisplayName']) self.assertIn('ID', resp['Owner']) # Second user can only see its own buckets try: c2 = self.get_s3_client(2) except ConfigError as err: raise unittest.SkipTest(str(err)) buckets2 = [self.create_name('bucket%s' % i) for i in range(2)] for bucket in buckets2: c2.create_bucket(Bucket=bucket) self.assertEqual(sorted(buckets2), [ bucket['Name'] for bucket in c2.list_buckets()['Buckets']]) # Unprivileged user can't see anything try: c3 = self.get_s3_client(3) except ConfigError as err: raise unittest.SkipTest(str(err)) self.assertEqual([], c3.list_buckets()['Buckets']) class TestGetServiceSigV2(TestGetServiceSigV4): signature_version = 's3' class TestGetServicePresignedV2(TestGetServiceSigV4): signature_version = 's3-query' class TestGetServicePresignedV4(TestGetServiceSigV4): signature_version = 's3v4-query'
swift-master
test/s3api/test_service.py
# Copyright (c) 2019 SwiftStack, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import unittest import uuid import time import boto3 from botocore.exceptions import ClientError from six.moves import urllib from swift.common.utils import config_true_value, readconf from test import get_config _CONFIG = None # boto's loggign can get pretty noisy; require opt-in to see it all if not config_true_value(os.environ.get('BOTO3_DEBUG')): logging.getLogger('boto3').setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.INFO) class ConfigError(Exception): '''Error test conf misconfigurations''' def load_aws_config(conf_file): """ Read user credentials from an AWS CLI style credentials file and translate to a swift test config. Currently only supports a single user. :param conf_file: path to AWS credentials file """ conf = readconf(conf_file, 'default') global _CONFIG _CONFIG = { 'endpoint': 'https://s3.amazonaws.com', 'region': 'us-east-1', 'access_key1': conf.get('aws_access_key_id'), 'secret_key1': conf.get('aws_secret_access_key'), 'session_token1': conf.get('aws_session_token') } aws_config_file = os.environ.get('SWIFT_TEST_AWS_CONFIG_FILE') if aws_config_file: load_aws_config(aws_config_file) print('Loaded test config from %s' % aws_config_file) def get_opt_or_error(option): global _CONFIG if _CONFIG is None: _CONFIG = get_config('s3api_test') value = _CONFIG.get(option) if not value: raise ConfigError('must supply [s3api_test]%s' % option) return value def get_opt(option, default=None): try: return get_opt_or_error(option) except ConfigError: return default def get_s3_client(user=1, signature_version='s3v4', addressing_style='path'): ''' Get a boto3 client to talk to an S3 endpoint. :param user: user number to use. Should be one of: 1 -- primary user 2 -- secondary user 3 -- unprivileged user :param signature_version: S3 signing method. Should be one of: s3 -- v2 signatures; produces Authorization headers like ``AWS access_key:signature`` s3-query -- v2 pre-signed URLs; produces query strings like ``?AWSAccessKeyId=access_key&Signature=signature`` s3v4 -- v4 signatures; produces Authorization headers like ``AWS4-HMAC-SHA256 Credential=access_key/date/region/s3/aws4_request, Signature=signature`` s3v4-query -- v4 pre-signed URLs; produces query strings like ``?X-Amz-Algorithm=AWS4-HMAC-SHA256& X-Amz-Credential=access_key/date/region/s3/aws4_request& X-Amz-Signature=signature`` :param addressing_style: One of: path -- produces URLs like ``http(s)://host.domain/bucket/key`` virtual -- produces URLs like ``http(s)://bucket.host.domain/key`` ''' endpoint = get_opt('endpoint', None) if endpoint: scheme = urllib.parse.urlsplit(endpoint).scheme if scheme not in ('http', 'https'): raise ConfigError('unexpected scheme in endpoint: %r; ' 'expected http or https' % scheme) else: scheme = None region = get_opt('region', 'us-east-1') access_key = get_opt_or_error('access_key%d' % user) secret_key = get_opt_or_error('secret_key%d' % user) session_token = get_opt('session_token%d' % user) ca_cert = get_opt('ca_cert') if ca_cert is not None: try: # do a quick check now; it's more expensive to have boto check os.stat(ca_cert) except OSError as e: raise ConfigError(str(e)) return boto3.client( 's3', endpoint_url=endpoint, region_name=region, use_ssl=(scheme == 'https'), verify=ca_cert, config=boto3.session.Config(s3={ 'signature_version': signature_version, 'addressing_style': addressing_style, }), aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token ) TEST_PREFIX = 's3api-test-' class BaseS3TestCase(unittest.TestCase): # Default to v4 signatures (as aws-cli does), but subclasses can override signature_version = 's3v4' @classmethod def get_s3_client(cls, user): return get_s3_client(user, cls.signature_version) @classmethod def _remove_all_object_versions_from_bucket(cls, client, bucket_name): resp = client.list_object_versions(Bucket=bucket_name) objs_to_delete = (resp.get('Versions', []) + resp.get('DeleteMarkers', [])) while objs_to_delete: multi_delete_body = { 'Objects': [ {'Key': obj['Key'], 'VersionId': obj['VersionId']} for obj in objs_to_delete ], 'Quiet': False, } del_resp = client.delete_objects(Bucket=bucket_name, Delete=multi_delete_body) if any(del_resp.get('Errors', [])): raise Exception('Unable to delete %r' % del_resp['Errors']) if not resp['IsTruncated']: break key_marker = resp['NextKeyMarker'] version_id_marker = resp['NextVersionIdMarker'] resp = client.list_object_versions( Bucket=bucket_name, KeyMarker=key_marker, VersionIdMarker=version_id_marker) objs_to_delete = (resp.get('Versions', []) + resp.get('DeleteMarkers', [])) @classmethod def clear_bucket(cls, client, bucket_name): timeout = time.time() + 10 backoff = 0.1 cls._remove_all_object_versions_from_bucket(client, bucket_name) try: client.delete_bucket(Bucket=bucket_name) except ClientError as e: if 'NoSuchBucket' in str(e): return if 'BucketNotEmpty' not in str(e): raise # Something's gone sideways. Try harder client.put_bucket_versioning( Bucket=bucket_name, VersioningConfiguration={'Status': 'Suspended'}) while True: cls._remove_all_object_versions_from_bucket( client, bucket_name) # also try some version-unaware operations... for key in client.list_objects(Bucket=bucket_name).get( 'Contents', []): client.delete_object(Bucket=bucket_name, Key=key['Key']) # *then* try again try: client.delete_bucket(Bucket=bucket_name) except ClientError as e: if 'NoSuchBucket' in str(e): return if 'BucketNotEmpty' not in str(e): raise if time.time() > timeout: raise Exception('Timeout clearing %r' % bucket_name) time.sleep(backoff) backoff *= 2 else: break def create_name(self, slug): return '%s%s-%s' % (TEST_PREFIX, slug, uuid.uuid4().hex) @classmethod def clear_account(cls, client): for bucket in client.list_buckets()['Buckets']: if not bucket['Name'].startswith(TEST_PREFIX): # these tests run against real s3 accounts continue cls.clear_bucket(client, bucket['Name']) def tearDown(self): client = self.get_s3_client(1) self.clear_account(client) try: client = self.get_s3_client(2) except ConfigError: pass else: self.clear_account(client)
swift-master
test/s3api/__init__.py
# Copyright (c) 2019 SwiftStack, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import time from collections import defaultdict from botocore.exceptions import ClientError import six from swift.common.header_key_dict import HeaderKeyDict from swift.common.utils import md5 from test.s3api import BaseS3TestCase def retry(f, timeout=10): timelimit = time.time() + timeout while True: try: f() except (ClientError, AssertionError): if time.time() > timelimit: raise continue else: break class TestObjectVersioning(BaseS3TestCase): maxDiff = None def setUp(self): self.client = self.get_s3_client(1) self.bucket_name = self.create_name('versioning') resp = self.client.create_bucket(Bucket=self.bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) def enable_versioning(): resp = self.client.put_bucket_versioning( Bucket=self.bucket_name, VersioningConfiguration={'Status': 'Enabled'}) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) retry(enable_versioning) def tearDown(self): resp = self.client.put_bucket_versioning( Bucket=self.bucket_name, VersioningConfiguration={'Status': 'Suspended'}) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.clear_bucket(self.client, self.bucket_name) super(TestObjectVersioning, self).tearDown() def test_setup(self): bucket_name = self.create_name('new-bucket') resp = self.client.create_bucket(Bucket=bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) expected_location = '/%s' % bucket_name self.assertEqual(expected_location, resp['Location']) headers = HeaderKeyDict(resp['ResponseMetadata']['HTTPHeaders']) self.assertEqual('0', headers['content-length']) self.assertEqual(expected_location, headers['location']) # get versioning resp = self.client.get_bucket_versioning(Bucket=bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertNotIn('Status', resp) # put versioning versioning_config = { 'Status': 'Enabled', } resp = self.client.put_bucket_versioning( Bucket=bucket_name, VersioningConfiguration=versioning_config) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) # ... now it's enabled def check_status(): resp = self.client.get_bucket_versioning(Bucket=bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) try: self.assertEqual('Enabled', resp['Status']) except KeyError: self.fail('Status was not in %r' % resp) retry(check_status) # send over some bogus junk versioning_config['Status'] = 'Disabled' with self.assertRaises(ClientError) as ctx: self.client.put_bucket_versioning( Bucket=bucket_name, VersioningConfiguration=versioning_config) expected_err = 'An error occurred (MalformedXML) when calling the ' \ 'PutBucketVersioning operation: The XML you provided was ' \ 'not well-formed or did not validate against our published schema' self.assertEqual(expected_err, str(ctx.exception)) # disable it versioning_config['Status'] = 'Suspended' resp = self.client.put_bucket_versioning( Bucket=bucket_name, VersioningConfiguration=versioning_config) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) # ... now it's disabled again def check_status(): resp = self.client.get_bucket_versioning(Bucket=bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('Suspended', resp['Status']) retry(check_status) def test_upload_fileobj_versioned(self): obj_data = self.create_name('some-data').encode('ascii') obj_etag = md5(obj_data, usedforsecurity=False).hexdigest() obj_name = self.create_name('versioned-obj') self.client.upload_fileobj(six.BytesIO(obj_data), self.bucket_name, obj_name) # object is in the listing resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual([{ 'ETag': '"%s"' % obj_etag, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # object version listing resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) for obj in objs: obj.pop('LastModified') obj.pop('Owner') obj.pop('VersionId') self.assertEqual([{ 'ETag': '"%s"' % obj_etag, 'IsLatest': True, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # overwrite the object new_obj_data = self.create_name('some-new-data').encode('ascii') new_obj_etag = md5(new_obj_data, usedforsecurity=False).hexdigest() self.client.upload_fileobj(six.BytesIO(new_obj_data), self.bucket_name, obj_name) # new object is in the listing resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual([{ 'ETag': '"%s"' % new_obj_etag, 'Key': obj_name, 'Size': len(new_obj_data), 'StorageClass': 'STANDARD', }], objs) # both object versions in the versions listing resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) for obj in objs: obj.pop('LastModified') obj.pop('Owner') obj.pop('VersionId') self.assertEqual([{ 'ETag': '"%s"' % new_obj_etag, 'IsLatest': True, 'Key': obj_name, 'Size': len(new_obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % obj_etag, 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) def test_delete_versioned_objects(self): etags = [] obj_name = self.create_name('versioned-obj') for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags.insert(0, md5(obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj(six.BytesIO(obj_data), self.bucket_name, obj_name) # only one object appears in the listing resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual([{ 'ETag': '"%s"' % etags[0], 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # but everything is layed out in the object versions listing resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: obj.pop('LastModified') obj.pop('Owner') versions.append(obj.pop('VersionId')) self.assertEqual([{ 'ETag': '"%s"' % etags[0], 'IsLatest': True, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % etags[1], 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % etags[2], 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # we can delete a specific version resp = self.client.delete_object(Bucket=self.bucket_name, Key=obj_name, VersionId=versions[1]) # and that just pulls it out of the versions listing resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) for obj in objs: obj.pop('LastModified') obj.pop('Owner') obj.pop('VersionId') self.assertEqual([{ 'ETag': '"%s"' % etags[0], 'IsLatest': True, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % etags[2], 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # ... but the current listing is unaffected resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual([{ 'ETag': '"%s"' % etags[0], 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # OTOH, if you delete specifically the latest version # we can delete a specific version resp = self.client.delete_object(Bucket=self.bucket_name, Key=obj_name, VersionId=versions[0]) # the versions listing has a new IsLatest resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) for obj in objs: obj.pop('LastModified') obj.pop('Owner') obj.pop('VersionId') self.assertEqual([{ 'ETag': '"%s"' % etags[2], 'IsLatest': True, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # and the stack pops resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual([{ 'ETag': '"%s"' % etags[2], 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) def test_delete_versioned_deletes(self): etags = [] obj_name = self.create_name('versioned-obj') for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags.insert(0, md5(obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj(six.BytesIO(obj_data), self.bucket_name, obj_name) # and make a delete marker self.client.delete_object(Bucket=self.bucket_name, Key=obj_name) # current listing is empty resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) self.assertEqual([], objs) # but everything is in layed out in the versions listing resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: obj.pop('LastModified') obj.pop('Owner') versions.append(obj.pop('VersionId')) self.assertEqual([{ 'ETag': '"%s"' % etag, 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', } for etag in etags], objs) # ... plus the delete markers delete_markers = resp.get('DeleteMarkers', []) marker_versions = [] for marker in delete_markers: marker.pop('LastModified') marker.pop('Owner') marker_versions.append(marker.pop('VersionId')) self.assertEqual([{ 'Key': obj_name, 'IsLatest': is_latest, } for is_latest in (True, False, False)], delete_markers) # delete an old delete markers resp = self.client.delete_object(Bucket=self.bucket_name, Key=obj_name, VersionId=marker_versions[2]) # since IsLatest is still marker we'll raise NoSuchKey with self.assertRaises(ClientError) as caught: resp = self.client.get_object(Bucket=self.bucket_name, Key=obj_name) expected_err = 'An error occurred (NoSuchKey) when calling the ' \ 'GetObject operation: The specified key does not exist.' self.assertEqual(expected_err, str(caught.exception)) # now delete the delete marker (IsLatest) resp = self.client.delete_object(Bucket=self.bucket_name, Key=obj_name, VersionId=marker_versions[0]) # most recent version is now latest resp = self.client.get_object(Bucket=self.bucket_name, Key=obj_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[0], resp['ETag']) # now delete the IsLatest object version resp = self.client.delete_object(Bucket=self.bucket_name, Key=obj_name, VersionId=versions[0]) # and object is deleted again with self.assertRaises(ClientError) as caught: resp = self.client.get_object(Bucket=self.bucket_name, Key=obj_name) expected_err = 'An error occurred (NoSuchKey) when calling the ' \ 'GetObject operation: The specified key does not exist.' self.assertEqual(expected_err, str(caught.exception)) # delete marker IsLatest resp = self.client.list_object_versions(Bucket=self.bucket_name) delete_markers = resp.get('DeleteMarkers', []) for marker in delete_markers: marker.pop('LastModified') marker.pop('Owner') self.assertEqual([{ 'Key': obj_name, 'IsLatest': True, 'VersionId': marker_versions[1], }], delete_markers) def test_multipart_upload(self): obj_name = self.create_name('versioned-obj') obj_data = b'data' mu = self.client.create_multipart_upload( Bucket=self.bucket_name, Key=obj_name) part_md5 = self.client.upload_part( Bucket=self.bucket_name, Key=obj_name, UploadId=mu['UploadId'], PartNumber=1, Body=obj_data)['ETag'] complete_response = self.client.complete_multipart_upload( Bucket=self.bucket_name, Key=obj_name, UploadId=mu['UploadId'], MultipartUpload={'Parts': [ {'PartNumber': 1, 'ETag': part_md5}, ]}) obj_etag = complete_response['ETag'] delete_response = self.client.delete_object( Bucket=self.bucket_name, Key=obj_name) marker_version_id = delete_response['VersionId'] resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: obj.pop('LastModified') obj.pop('Owner') versions.append(obj.pop('VersionId')) self.assertEqual([{ 'ETag': obj_etag, 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) markers = resp.get('DeleteMarkers', []) for marker in markers: marker.pop('LastModified') marker.pop('Owner') self.assertEqual([{ 'IsLatest': True, 'Key': obj_name, 'VersionId': marker_version_id, }], markers) # Can still get the old version resp = self.client.get_object( Bucket=self.bucket_name, Key=obj_name, VersionId=versions[0]) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual(obj_etag, resp['ETag']) delete_response = self.client.delete_object( Bucket=self.bucket_name, Key=obj_name, VersionId=versions[0]) resp = self.client.list_object_versions(Bucket=self.bucket_name) self.assertEqual([], resp.get('Versions', [])) markers = resp.get('DeleteMarkers', []) for marker in markers: marker.pop('LastModified') marker.pop('Owner') self.assertEqual([{ 'IsLatest': True, 'Key': obj_name, 'VersionId': marker_version_id, }], markers) def test_get_versioned_object(self): etags = [] obj_name = self.create_name('versioned-obj') for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') # TODO: pull etag from response instead etags.insert(0, md5(obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj( six.BytesIO(obj_data), self.bucket_name, obj_name) resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: obj.pop('LastModified') obj.pop('Owner') versions.append(obj.pop('VersionId')) self.assertEqual([{ 'ETag': '"%s"' % etags[0], 'IsLatest': True, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % etags[1], 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }, { 'ETag': '"%s"' % etags[2], 'IsLatest': False, 'Key': obj_name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }], objs) # un-versioned get_object returns IsLatest resp = self.client.get_object(Bucket=self.bucket_name, Key=obj_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[0], resp['ETag']) # but you can get any object by version for i, version in enumerate(versions): resp = self.client.get_object( Bucket=self.bucket_name, Key=obj_name, VersionId=version) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[i], resp['ETag']) # and head_object works about the same resp = self.client.head_object(Bucket=self.bucket_name, Key=obj_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[0], resp['ETag']) self.assertEqual(versions[0], resp['VersionId']) for version, etag in zip(versions, etags): resp = self.client.head_object( Bucket=self.bucket_name, Key=obj_name, VersionId=version) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual(version, resp['VersionId']) self.assertEqual('"%s"' % etag, resp['ETag']) def test_get_versioned_object_invalid_params(self): with self.assertRaises(ClientError) as ctx: self.client.list_object_versions(Bucket=self.bucket_name, KeyMarker='', VersionIdMarker='bogus') expected_err = 'An error occurred (InvalidArgument) when calling ' \ 'the ListObjectVersions operation: Invalid version id specified' self.assertEqual(expected_err, str(ctx.exception)) with self.assertRaises(ClientError) as ctx: self.client.list_object_versions( Bucket=self.bucket_name, VersionIdMarker='a' * 32) expected_err = 'An error occurred (InvalidArgument) when calling ' \ 'the ListObjectVersions operation: A version-id marker cannot ' \ 'be specified without a key marker.' self.assertEqual(expected_err, str(ctx.exception)) def test_get_versioned_object_key_marker(self): obj00_name = self.create_name('00-versioned-obj') obj01_name = self.create_name('01-versioned-obj') names = [obj00_name] * 3 + [obj01_name] * 3 latest = [True, False, False, True, False, False] etags = [] for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags.insert(0, '"%s"' % md5( obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj( six.BytesIO(obj_data), self.bucket_name, obj01_name) for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags.insert(0, '"%s"' % md5( obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj( six.BytesIO(obj_data), self.bucket_name, obj00_name) resp = self.client.list_object_versions(Bucket=self.bucket_name) versions = [] objs = [] for o in resp.get('Versions', []): versions.append(o['VersionId']) objs.append({ 'Key': o['Key'], 'VersionId': o['VersionId'], 'IsLatest': o['IsLatest'], 'ETag': o['ETag'], }) expected = [{ 'Key': name, 'VersionId': version, 'IsLatest': is_latest, 'ETag': etag, } for name, etag, version, is_latest in zip( names, etags, versions, latest)] self.assertEqual(expected, objs) # on s3 this makes expected[0]['IsLatest'] magicaly change to False? # resp = self.client.list_object_versions(Bucket=self.bucket_name, # KeyMarker='', # VersionIdMarker=versions[0]) # objs = [{ # 'Key': o['Key'], # 'VersionId': o['VersionId'], # 'IsLatest': o['IsLatest'], # 'ETag': o['ETag'], # } for o in resp.get('Versions', [])] # self.assertEqual(expected, objs) # KeyMarker skips past that key resp = self.client.list_object_versions(Bucket=self.bucket_name, KeyMarker=obj00_name) objs = [{ 'Key': o['Key'], 'VersionId': o['VersionId'], 'IsLatest': o['IsLatest'], 'ETag': o['ETag'], } for o in resp.get('Versions', [])] self.assertEqual(expected[3:], objs) # KeyMarker with VersionIdMarker skips past that version resp = self.client.list_object_versions(Bucket=self.bucket_name, KeyMarker=obj00_name, VersionIdMarker=versions[0]) objs = [{ 'Key': o['Key'], 'VersionId': o['VersionId'], 'IsLatest': o['IsLatest'], 'ETag': o['ETag'], } for o in resp.get('Versions', [])] self.assertEqual(expected[1:], objs) # KeyMarker with bogus version skips past that key resp = self.client.list_object_versions( Bucket=self.bucket_name, KeyMarker=obj00_name, VersionIdMarker=versions[4]) objs = [{ 'Key': o['Key'], 'VersionId': o['VersionId'], 'IsLatest': o['IsLatest'], 'ETag': o['ETag'], } for o in resp.get('Versions', [])] self.assertEqual(expected[3:], objs) def test_list_objects(self): etags = defaultdict(list) for i in range(3): obj_name = self.create_name('versioned-obj') for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags[obj_name].insert(0, md5( obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj( six.BytesIO(obj_data), self.bucket_name, obj_name) # both unversioned list_objects responses are similar expected = [] for name, obj_etags in sorted(etags.items()): expected.append({ 'ETag': '"%s"' % obj_etags[0], 'Key': name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }) resp = self.client.list_objects(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') # one difference seems to be the Owner key self.assertEqual({'DisplayName', 'ID'}, set(obj.pop('Owner').keys())) self.assertEqual(expected, objs) resp = self.client.list_objects_v2(Bucket=self.bucket_name) objs = resp.get('Contents', []) for obj in objs: obj.pop('LastModified') self.assertEqual(expected, objs) # versioned listings has something for everyone expected = [] for name, obj_etags in sorted(etags.items()): is_latest = True for etag in obj_etags: expected.append({ 'ETag': '"%s"' % etag, 'IsLatest': is_latest, 'Key': name, 'Size': len(obj_data), 'StorageClass': 'STANDARD', }) is_latest = False resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: obj.pop('LastModified') obj.pop('Owner') versions.append(obj.pop('VersionId')) self.assertEqual(expected, objs) def test_copy_object(self): etags = [] obj_name = self.create_name('versioned-obj') for i in range(3): obj_data = self.create_name('some-data-%s' % i).encode('ascii') etags.insert(0, md5( obj_data, usedforsecurity=False).hexdigest()) self.client.upload_fileobj( six.BytesIO(obj_data), self.bucket_name, obj_name) resp = self.client.list_object_versions(Bucket=self.bucket_name) objs = resp.get('Versions', []) versions = [] for obj in objs: versions.append(obj.pop('VersionId')) # CopySource can just be Bucket/Key string first_target = self.create_name('target-obj1') copy_resp = self.client.copy_object( Bucket=self.bucket_name, Key=first_target, CopySource='%s/%s' % (self.bucket_name, obj_name)) self.assertEqual(versions[0], copy_resp['CopySourceVersionId']) # and you'll just get the most recent version resp = self.client.head_object(Bucket=self.bucket_name, Key=first_target) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[0], resp['ETag']) # or you can be more explicit explicit_target = self.create_name('target-%s' % versions[0]) copy_source = {'Bucket': self.bucket_name, 'Key': obj_name, 'VersionId': versions[0]} copy_resp = self.client.copy_object( Bucket=self.bucket_name, Key=explicit_target, CopySource=copy_source) self.assertEqual(versions[0], copy_resp['CopySourceVersionId']) # and you still get the same thing resp = self.client.head_object(Bucket=self.bucket_name, Key=explicit_target) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[0], resp['ETag']) # but you can also copy from a specific version version_target = self.create_name('target-%s' % versions[2]) copy_source['VersionId'] = versions[2] copy_resp = self.client.copy_object( Bucket=self.bucket_name, Key=version_target, CopySource=copy_source) self.assertEqual(versions[2], copy_resp['CopySourceVersionId']) resp = self.client.head_object(Bucket=self.bucket_name, Key=version_target) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) self.assertEqual('"%s"' % etags[2], resp['ETag'])
swift-master
test/s3api/test_versioning.py
# Copyright (c) 2021 Nvidia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from test.s3api import BaseS3TestCase from botocore.exceptions import ClientError class TestMultiPartUploads(BaseS3TestCase): maxDiff = None def setUp(self): self.client = self.get_s3_client(1) self.bucket_name = self.create_name('test-mpu') resp = self.client.create_bucket(Bucket=self.bucket_name) self.assertEqual(200, resp['ResponseMetadata']['HTTPStatusCode']) def tearDown(self): self.clear_bucket(self.client, self.bucket_name) super(TestMultiPartUploads, self).tearDown() def test_basic_upload(self): key_name = self.create_name('key') create_mpu_resp = self.client.create_multipart_upload( Bucket=self.bucket_name, Key=key_name) self.assertEqual(200, create_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) upload_id = create_mpu_resp['UploadId'] parts = [] for i in range(1, 3): body = ('%d' % i) * 5 * (2 ** 20) part_resp = self.client.upload_part( Body=body, Bucket=self.bucket_name, Key=key_name, PartNumber=i, UploadId=upload_id) self.assertEqual(200, part_resp[ 'ResponseMetadata']['HTTPStatusCode']) parts.append({ 'ETag': part_resp['ETag'], 'PartNumber': i, }) list_parts_resp = self.client.list_parts( Bucket=self.bucket_name, Key=key_name, UploadId=upload_id, ) self.assertEqual(200, list_parts_resp[ 'ResponseMetadata']['HTTPStatusCode']) self.assertEqual(parts, [{k: p[k] for k in ('ETag', 'PartNumber')} for p in list_parts_resp['Parts']]) complete_mpu_resp = self.client.complete_multipart_upload( Bucket=self.bucket_name, Key=key_name, MultipartUpload={ 'Parts': parts, }, UploadId=upload_id, ) self.assertEqual(200, complete_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) def test_create_list_abort_multipart_uploads(self): key_name = self.create_name('key') create_mpu_resp = self.client.create_multipart_upload( Bucket=self.bucket_name, Key=key_name) self.assertEqual(200, create_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) upload_id = create_mpu_resp['UploadId'] # our upload is in progress list_mpu_resp = self.client.list_multipart_uploads( Bucket=self.bucket_name) self.assertEqual(200, list_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) found_uploads = list_mpu_resp.get('Uploads', []) self.assertEqual(1, len(found_uploads), found_uploads) self.assertEqual(upload_id, found_uploads[0]['UploadId']) abort_resp = self.client.abort_multipart_upload( Bucket=self.bucket_name, Key=key_name, UploadId=upload_id, ) self.assertEqual(204, abort_resp[ 'ResponseMetadata']['HTTPStatusCode']) # no more inprogress uploads list_mpu_resp = self.client.list_multipart_uploads( Bucket=self.bucket_name) self.assertEqual(200, list_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) self.assertEqual([], list_mpu_resp.get('Uploads', [])) def test_complete_multipart_upload_malformed_request(self): key_name = self.create_name('key') create_mpu_resp = self.client.create_multipart_upload( Bucket=self.bucket_name, Key=key_name) self.assertEqual(200, create_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) upload_id = create_mpu_resp['UploadId'] parts = [] for i in range(1, 3): body = ('%d' % i) * 5 * (2 ** 20) part_resp = self.client.upload_part( Body=body, Bucket=self.bucket_name, Key=key_name, PartNumber=i, UploadId=upload_id) self.assertEqual(200, part_resp[ 'ResponseMetadata']['HTTPStatusCode']) parts.append({ 'PartNumber': i, 'ETag': '', }) with self.assertRaises(ClientError) as caught: self.client.complete_multipart_upload( Bucket=self.bucket_name, Key=key_name, MultipartUpload={ 'Parts': parts, }, UploadId=upload_id, ) complete_mpu_resp = caught.exception.response self.assertEqual(400, complete_mpu_resp[ 'ResponseMetadata']['HTTPStatusCode']) self.assertEqual('InvalidPart', complete_mpu_resp[ 'Error']['Code']) self.assertTrue(complete_mpu_resp['Error']['Message'].startswith( 'One or more of the specified parts could not be found.' ), complete_mpu_resp['Error']['Message']) self.assertEqual(complete_mpu_resp['Error']['UploadId'], upload_id) self.assertIn(complete_mpu_resp['Error']['PartNumber'], ('1', '2')) self.assertEqual(complete_mpu_resp['Error']['ETag'], None)
swift-master
test/s3api/test_mpu.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Swift tests """ from __future__ import print_function import os import copy import logging import logging.handlers import sys from contextlib import contextmanager, closing from collections import defaultdict try: from collections.abc import Iterable except ImportError: from collections import Iterable # py2 import itertools from numbers import Number from tempfile import NamedTemporaryFile import time import eventlet from eventlet import greenpool, debug as eventlet_debug from eventlet.green import socket from tempfile import mkdtemp, mkstemp, gettempdir from shutil import rmtree import signal import json import random import errno import xattr from io import BytesIO from uuid import uuid4 import six import six.moves.cPickle as pickle from six.moves import range from six.moves.http_client import HTTPException from swift.common import storage_policy, swob, utils, exceptions from swift.common.memcached import MemcacheConnectionError from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) from swift.common.utils import Timestamp, md5 from test import get_config from test.debug_logger import FakeLogger from swift.common.header_key_dict import HeaderKeyDict from swift.common.ring import Ring, RingData, RingBuilder from swift.obj import server import functools from gzip import GzipFile import mock as mocklib import inspect from unittest import SkipTest EMPTY_ETAG = md5(usedforsecurity=False).hexdigest() # try not to import this module from swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = b'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable to find suitable PyECLib type' ' (none of %r found in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies = [ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args = [{}] elif with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas': 14}, {}] else: default_policies = [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args = [{}, {}] fake_ring_args = fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator else: # it's a thing, we return the wrapped thing instead of the decorator return decorator(thing_or_policies) class PatchPolicies(object): """ Why not mock.patch? In my case, when used as a decorator on the class it seemed to patch setUp at the wrong time (i.e. in setUp the global wasn't patched yet) """ def __init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None] * len(self.policies) def _setup_rings(self): """ Our tests tend to use the policies rings like their own personal playground - which can be a problem in the particular case of a patched TestCase class where the FakeRing objects are scoped in the call to the patch_policies wrapper outside of the TestCase instance which can lead to some bled state. To help tests get better isolation without having to think about it, here we're capturing the args required to *build* a new FakeRing instances so we can ensure each test method gets a clean ring setup. The TestCase can always "tweak" these fresh rings in setUp - or if they'd prefer to get the same "reset" behavior with custom FakeRing's they can pass in their own fake_ring_args to patch_policies instead of setting the object_ring on the policy definitions. """ for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg is not None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing, type): return self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self, cls): """ Creating a new class that inherits from decorated class is the more common way I've seen class decorators done - but it seems to cause infinite recursion when super is called from inside methods in the decorated class. """ orig_setUp = cls.setUp def unpatch_cleanup(cls_self): if cls_self._policies_patched: self.__exit__(None, None, None) cls_self._policies_patched = False def setUp(cls_self): if not getattr(cls_self, '_policies_patched', False): self.__enter__() cls_self._policies_patched = True cls_self.addCleanup(unpatch_cleanup, cls_self) orig_setUp(cls_self) cls.setUp = setUp return cls def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs): with self: return f(*args, **kwargs) return mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies try: self._setup_rings() except: # noqa self.__exit__(None, None, None) raise def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000, separate_replication=False, next_part_power=None, reload_time=15): self.serialized_path = '/foo/bar/object.ring.gz' self._base_port = base_port self.max_more_nodes = max_more_nodes self._part_shift = 32 - part_power self._init_device_char() self.separate_replication = separate_replication # 9 total nodes (6 more past the initial 3) is the cap, no matter if # this is set higher, or R^2 for R replicas self.reload_time = reload_time self.set_replicas(replicas) self._next_part_power = next_part_power self._reload() def has_changed(self): """ The real implementation uses getmtime on the serialized_path attribute, which doesn't exist on our fake and relies on the implementation of _reload which we override. So ... just NOOPE. """ return False def _reload(self): self._rtime = time.time() @property def device_char(self): return next(self._device_char_iter) def _init_device_char(self): self._device_char_iter = itertools.cycle( ['sd%s' % chr(ord('a') + x) for x in range(26)]) def add_node(self, dev): # round trip through json to ensure unicode like real rings self._devs.append(json.loads(json.dumps(dev))) def set_replicas(self, replicas): self.replicas = replicas self._devs = [] self._init_device_char() for x in range(self.replicas): ip = '10.0.0.%s' % x port = self._base_port + x if self.separate_replication: repl_ip = '10.0.1.%s' % x repl_port = port + 100 else: repl_ip, repl_port = ip, port dev = { 'ip': ip, 'replication_ip': repl_ip, 'port': port, 'replication_port': repl_port, 'device': self.device_char, 'zone': x % 3, 'region': x % 2, 'id': x, 'weight': 1, } self.add_node(dev) @property def replica_count(self): return self.replicas def _get_part_nodes(self, part): return [dict(node, index=i) for i, node in enumerate(list(self._devs))] def get_more_nodes(self, part): index_counter = itertools.count() for x in range(self.replicas, (self.replicas + self.max_more_nodes)): ip = '10.0.0.%s' % x port = self._base_port + x if self.separate_replication: repl_ip = '10.0.1.%s' % x repl_port = port + 100 else: repl_ip, repl_port = ip, port yield {'ip': ip, 'replication_ip': repl_ip, 'port': port, 'replication_port': repl_port, 'device': 'sda', 'zone': x % 3, 'region': x % 2, 'id': x, 'handoff_index': next(index_counter)} def write_fake_ring(path, *devs): """ Pretty much just a two node, two replica, 2 part power ring... """ dev1 = {'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': 6200} dev2 = {'id': 1, 'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6200} dev1_updates, dev2_updates = devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0, 1], [1, 0, 1, 0]] devs = [dev1, dev2] part_shift = 30 with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) def write_stub_builder(tmpdir, region=1, name=''): """ Pretty much just a three node, three replica, 8 part power builder... :param tmpdir: a place to write the builder, be sure to clean it up! :param region: an integer, fills in region and ip :param name: the name of the builder (i.e. <name>.builder) """ name = name or str(region) replicas = 3 builder = RingBuilder(8, replicas, 1) for i in range(replicas): dev = {'weight': 100, 'region': '%d' % region, 'zone': '1', 'ip': '10.0.0.%d' % region, 'port': '3600', 'device': 'sdb%d' % i} builder.add_dev(dev) builder.rebalance() builder_file = os.path.join(tmpdir, '%s.builder' % name) builder.save(builder_file) return builder, builder_file class FabricatedRing(Ring): """ When a FakeRing just won't do - you can fabricate one to meet your tests needs. """ def __init__(self, replicas=6, devices=8, nodes=4, port=6200, part_power=4): self.devices = devices self.nodes = nodes self.port = port self.replicas = replicas self._part_shift = 32 - part_power self._reload() def has_changed(self): return False def _reload(self, *args, **kwargs): self._rtime = time.time() * 2 if hasattr(self, '_replica2part2dev_id'): return self._devs = [{ 'region': 1, 'zone': 1, 'weight': 1.0, 'id': i, 'device': 'sda%d' % i, 'ip': '10.0.0.%d' % (i % self.nodes), 'replication_ip': '10.0.0.%d' % (i % self.nodes), 'port': self.port, 'replication_port': self.port, } for i in range(self.devices)] self._replica2part2dev_id = [ [None] * 2 ** self.part_power for i in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for p in range(2 ** self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) self._update_bookkeeping() def track(f): def wrapper(self, *a, **kw): self.calls.append(getattr(mocklib.call, f.__name__)(*a, **kw)) return f(self, *a, **kw) return wrapper class FakeMemcache(object): def __init__(self, error_on_set=None, error_on_get=None): self.store = {} self.calls = [] self.error_on_incr = False self.error_on_get = error_on_get or [] self.error_on_set = error_on_set or [] self.init_incr_return_neg = False def clear_calls(self): del self.calls[:] @track def get(self, key, raise_on_error=False): if self.error_on_get and self.error_on_get.pop(0): if raise_on_error: raise MemcacheConnectionError() return self.store.get(key) @property def keys(self): return self.store.keys @track def set(self, key, value, serialize=True, time=0, raise_on_error=False): if self.error_on_set and self.error_on_set.pop(0): if raise_on_error: raise MemcacheConnectionError() if serialize: value = json.loads(json.dumps(value)) else: assert isinstance(value, (str, bytes)) self.store[key] = value return True @track def incr(self, key, delta=1, time=0): if self.error_on_incr: raise MemcacheConnectionError('Memcache restarting') if self.init_incr_return_neg: # simulate initial hit, force reset of memcache self.init_incr_return_neg = False return -10000000 self.store[key] = int(self.store.setdefault(key, 0)) + delta if self.store[key] < 0: self.store[key] = 0 return self.store[key] # tracked via incr() def decr(self, key, delta=1, time=0): return self.incr(key, delta=-delta, time=time) @track def delete(self, key): try: del self.store[key] except Exception: pass return True def delete_all(self): self.store.clear() # This decorator only makes sense in the context of FakeMemcache; # may as well clean it up now del track class FakeIterable(object): def __init__(self, values): self.next_call_count = 0 self.close_call_count = 0 self.values = iter(values) def __iter__(self): return self def __next__(self): self.next_call_count += 1 return next(self.values) next = __next__ # py2 def close(self): self.close_call_count += 1 def readuntil2crlfs(fd): rv = b'' lc = b'' crlfs = 0 while crlfs < 2: c = fd.read(1) if not c: raise ValueError("didn't get two CRLFs; just got %r" % rv) rv = rv + c if c == b'\r' and lc != b'\n': crlfs = 0 if lc == b'\r' and c == b'\n': crlfs += 1 lc = c return rv def readlength(fd, size, timeout=1.0): buf = b'' with eventlet.Timeout(timeout): while len(buf) < size: chunk = fd.read(min(64, size - len(buf))) buf += chunk if len(buf) >= size: break return buf def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False) as f: file_name = f.name f.write(str(content)) try: yield file_name finally: os.unlink(file_name) @contextmanager def temptree(files, contents=''): # generate enough contents to fill the files c = len(files) contents = (list(contents) + [''] * c)[:c] tempdir = mkdtemp() for path, content in zip(files, contents): if os.path.isabs(path): path = '.' + path new_path = os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as f: f.write(str(content)) try: yield tempdir finally: rmtree(tempdir) def with_tempdir(f): """ Decorator to give a single test a tempdir as argument to test method. """ @functools.wraps(f) def wrapped(*args, **kwargs): tempdir = mkdtemp() args = list(args) args.append(tempdir) try: return f(*args, **kwargs) finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def emit(self, record): pass class UnmockTimeModule(object): """ Even if a test mocks time.time - you can restore unmolested behavior in a another module who imports time directly by monkey patching it's imported reference to the module with an instance of this class """ _orig_time = time.time def __getattribute__(self, name): if name == 'time': return UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule() original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() @contextmanager def quiet_eventlet_exceptions(): orig_state = greenpool.DEBUG eventlet_debug.hub_exceptions(False) try: yield finally: eventlet_debug.hub_exceptions(orig_state) @contextmanager def mock_check_drive(isdir=False, ismount=False): """ All device/drive/mount checking should be done through the constraints module. If we keep the mocking consistently within that module, we can keep our tests robust to further rework on that interface. Replace the constraint modules underlying os calls with mocks. :param isdir: return value of constraints isdir calls, default False :param ismount: return value of constraints ismount calls, default False :returns: a dict of constraint module mocks """ mock_base = 'swift.common.constraints.' with mocklib.patch(mock_base + 'isdir') as mock_isdir, \ mocklib.patch(mock_base + 'utils.ismount') as mock_ismount: mock_isdir.return_value = isdir mock_ismount.return_value = ismount yield { 'isdir': mock_isdir, 'ismount': mock_ismount, } @contextmanager def mock(update): returns = [] deletes = [] for key, value in update.items(): imports = key.split('.') attr = imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]: module = getattr(module, modname) if hasattr(module, attr): returns.append((module, attr, getattr(module, attr))) else: deletes.append((module, attr)) setattr(module, attr, value) try: yield True finally: for module, attr, value in returns: setattr(module, attr, value) for module, attr in deletes: delattr(module, attr) class FakeStatus(object): """ This will work with our fake_http_connect, if you hand in one of these instead of a status int or status int tuple to the "codes" iter you can add some eventlet sleep to the expect and response stages of the connection. """ def __init__(self, status, expect_sleep=None, response_sleep=None): """ :param status: the response status int, or a tuple of ([expect_status, ...], response_status) :param expect_sleep: float, time to eventlet sleep during expect, can be a iter of floats :param response_sleep: float, time to eventlet sleep during response """ # connect exception if inspect.isclass(status) and issubclass(status, Exception): raise status('FakeStatus Error') if isinstance(status, (Exception, eventlet.Timeout)): raise status if isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status = status[-1] self.explicit_expect_list = True else: self.expect_status, self.status = ([], status) self.explicit_expect_list = False if not self.expect_status: # when a swift backend service returns a status before reading # from the body (mostly an error response) eventlet.wsgi will # respond with that status line immediately instead of 100 # Continue, even if the client sent the Expect 100 header. # BufferedHttp and the proxy both see these error statuses # when they call getexpect, so our FakeConn tries to act like # our backend services and return certain types of responses # as expect statuses just like a real backend server would do. if self.status in (507, 412, 409): self.expect_status = [status] else: self.expect_status = [100, 100] # setup sleep attributes if not isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def __repr__(self): return '%s(%s, expect_status=%r, response_sleep=%s)' % ( self.__class__.__name__, self.status, self.expect_status, self.response_sleep) def get_response_status(self): if self.response_sleep is not None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise Exception('Test did not consume all fake ' 'expect status: %r' % (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return expect_status class SlowBody(object): """ This will work with our fake_http_connect, if you hand in these instead of strings it will make reads take longer by the given amount. It should be a little bit easier to extend than the current slow kwarg - which inserts whitespace in the response. Also it should be easy to detect if you have one of these (or a subclass) for the body inside of FakeConn if we wanted to do something smarter than just duck-type the str/buffer api enough to get by. """ def __init__(self, body, slowness): self.body = body self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body) def __radd__(self, other): self.slowdown() return other + self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): SLOW_READS = 4 SLOW_WRITES = 4 def __init__(self, status, etag=None, body=b'', timestamp=-1, headers=None, expect_headers=None, connection_id=None, give_send=None, give_expect=None): if not isinstance(status, FakeStatus): status = FakeStatus(status) self._status = status self.reason = 'Fake' self.host = '1.2.3.4' self.port = '1234' self.sent = 0 self.received = 0 self.etag = etag self.body = body self.headers = headers or {} self.expect_headers = expect_headers or {} if timestamp == -1: # -1 is reserved to mean "magic default" if status.status != 404: self.timestamp = '1' else: self.timestamp = '0' else: # tests may specify int, string, Timestamp or None self.timestamp = timestamp self.connection_id = connection_id self.give_send = give_send self.give_expect = give_expect self.closed = False if 'slow' in kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep = None # if we're going to be slow, we need a body to send slowly am_slow, _junk = self.get_slow() if am_slow and len(self.body) < self.SLOW_READS: self.body += b" " * (self.SLOW_READS - len(self.body)) # be nice to trixy bits with node_iter's eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status() return self def getexpect(self): if self.give_expect: self.give_expect(self) expect_status = self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status return response def getheaders(self): etag = self.etag if not etag: if isinstance(self.body, bytes): etag = ('"' + md5( self.body, usedforsecurity=False).hexdigest() + '"') else: etag = '"68b329da9893e34099c7d8ad5cb9c940"' am_slow, _junk = self.get_slow() headers = HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes', }) if self.status // 100 == 2: headers['x-account-container-count'] = \ kwargs.get('count', 12345) if not self.timestamp: # when timestamp is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter) is False: headers['x-container-timestamp'] = '1' except StopIteration: pass headers.update(self.headers) return headers.items() def get_slow(self): if 'slow' in kwargs and isinstance(kwargs['slow'], list): if self._next_sleep is not None: return True, self._next_sleep else: return False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow, value = self.get_slow() if am_slow: if self.sent < self.SLOW_READS: slowly_read_byte = self.body[self.sent:self.sent + 1] self.sent += 1 eventlet.sleep(value) return slowly_read_byte if amt is None: rv = self.body[self.sent:] else: rv = self.body[self.sent:self.sent + amt] self.sent += len(rv) return rv def send(self, data=None): if self.give_send: self.give_send(self, data) am_slow, value = self.get_slow() if am_slow: if self.received < self.SLOW_WRITES: self.received += 1 eventlet.sleep(value) def getheader(self, name, default=None): return HeaderKeyDict(self.getheaders()).get(name, default) def nuke_from_orbit(self): # wrapped connections from buffered_http have this helper self.close() def close(self): self.closed = True # unless tests provide timestamps we use the "magic default" timestamps_iter = iter(kwargs.get('timestamps') or [-1] * len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter)) x = kwargs.get('missing_container', [False] * len(code_iter)) if not isinstance(x, (tuple, list)): x = [x] * len(code_iter) container_ts_iter = iter(x) code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body', None) body_iter = kwargs.get('body_iter', None) if body_iter: body_iter = iter(body_iter) unexpected_requests = [] def connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in kwargs: if len(args) >= 7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') try: i, status = next(conn_id_and_code_iter) except StopIteration: # the code under test may swallow the StopIteration, so by logging # unexpected requests here we allow the test framework to check for # them after the connect function has been used. unexpected_requests.append((args, ckwargs)) raise if 'give_connect' in kwargs: give_conn_fn = kwargs['give_connect'] if six.PY2: argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id'] = i else: argspec = inspect.getfullargspec(give_conn_fn) if argspec.varkw or 'connection_id' in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers = next(headers_iter) expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter) if isinstance(status, int) and status <= 0: raise HTTPException() if body_iter is None: body = static_body or b'' else: body = next(body_iter) conn = FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send'), give_expect=kwargs.get('give_expect')) if 'capture_connections' in kwargs: kwargs['capture_connections'].append(conn) return conn connect.unexpected_requests = unexpected_requests connect.code_iter = code_iter return connect @contextmanager def mocked_http_conn(*args, **kwargs): requests = [] responses = [] def capture_requests(ip, port, method, path, headers, qs, ssl): if six.PY2 and not isinstance(ip, bytes): ip = ip.encode('ascii') req = { 'ip': ip, 'port': port, 'method': method, 'path': path, 'headers': headers, 'qs': qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) kwargs['capture_connections'] = responses fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests = requests fake_conn.responses = responses with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over status %r' % left_over_status) if fake_conn.unexpected_requests: raise AssertionError('unexpected requests:\n%s' % '\n '.join( '%r' % (req,) for req in fake_conn.unexpected_requests)) def make_timestamp_iter(offset=0): return iter(Timestamp(t) for t in itertools.count(int(time.time()) + offset)) @contextmanager def mock_timestamp_now(now=None, klass=Timestamp): if now is None: now = klass.now() with mocklib.patch('swift.common.utils.Timestamp.now', classmethod(lambda c: now)): yield now @contextmanager def mock_timestamp_now_with_iter(ts_iter): with mocklib.patch('swift.common.utils.Timestamp.now', side_effect=ts_iter): yield class Timeout(object): def __init__(self, seconds): self.seconds = seconds def __enter__(self): signal.signal(signal.SIGALRM, self._exit) signal.alarm(self.seconds) def __exit__(self, type, value, traceback): signal.alarm(0) def _exit(self, signum, frame): class TimeoutException(Exception): pass raise TimeoutException def requires_o_tmpfile_support_in_tmp(func): @functools.wraps(func) def wrapper(*args, **kwargs): if not utils.o_tmpfile_in_tmpdir_supported(): raise SkipTest('Requires O_TMPFILE support in TMPDIR') return func(*args, **kwargs) return wrapper class StubResponse(object): def __init__(self, status, body=b'', headers=None, frag_index=None, slowdown=None): self.status = status self.body = body self.readable = BytesIO(body) try: self._slowdown = iter(slowdown) except TypeError: self._slowdown = iter([slowdown]) self.headers = HeaderKeyDict(headers) if frag_index is not None: self.headers['X-Object-Sysmeta-Ec-Frag-Index'] = frag_index fake_reason = ('Fake', 'This response is a lie.') self.reason = swob.RESPONSE_REASONS.get(status, fake_reason)[0] def slowdown(self): try: wait = next(self._slowdown) except StopIteration: wait = None if wait is not None: eventlet.sleep(wait) def nuke_from_orbit(self): if hasattr(self, 'swift_conn'): self.swift_conn.close() def getheader(self, header_name, default=None): return self.headers.get(header_name, default) def getheaders(self): if 'Content-Length' not in self.headers: self.headers['Content-Length'] = len(self.body) return self.headers.items() def read(self, amt=0): self.slowdown() return self.readable.read(amt) def readline(self, size=-1): self.slowdown() return self.readable.readline(size) def __repr__(self): info = ['Status: %s' % self.status] if self.headers: info.append('Headers: %r' % dict(self.headers)) if self.body: info.append('Body: %r' % self.body) return '<StubResponse %s>' % ', '.join(info) def encode_frag_archive_bodies(policy, body): """ Given a stub body produce a list of complete frag_archive bodies as strings in frag_index order. :param policy: a StoragePolicy instance, with policy_type EC_POLICY :param body: a string, the body to encode into frag archives :returns: list of strings, the complete frag_archive bodies for the given plaintext """ segment_size = policy.ec_segment_size # split up the body into buffers chunks = [body[x:x + segment_size] for x in range(0, len(body), segment_size)] # encode the buffers into fragment payloads fragment_payloads = [] for chunk in chunks: fragments = policy.pyeclib_driver.encode(chunk) \ * policy.ec_duplication_factor if not fragments: break fragment_payloads.append(fragments) # join up the fragment payloads per node ec_archive_bodies = [b''.join(frags) for frags in zip(*fragment_payloads)] return ec_archive_bodies def make_ec_object_stub(test_body, policy, timestamp): segment_size = policy.ec_segment_size test_body = test_body or ( b'test' * segment_size)[:-random.randint(1, 1000)] timestamp = timestamp or utils.Timestamp.now() etag = md5(test_body, usedforsecurity=False).hexdigest() ec_archive_bodies = encode_frag_archive_bodies(policy, test_body) return { 'body': test_body, 'etag': etag, 'frags': ec_archive_bodies, 'timestamp': timestamp } def fake_ec_node_response(node_frags, policy): """ Given a list of entries for each node in ring order, where the entries are a dict (or list of dicts) which describes the fragment (or fragments) that are on the node; create a function suitable for use with capture_http_requests that will accept a req object and return a response that will suitably fake the behavior of an object server who had the given fragments on disk at the time. :param node_frags: a list. Each item in the list describes the fragments that are on a node; each item is a dict or list of dicts, each dict describing a single fragment; where the item is a list, repeated calls to get_response will return fragments in the order of the list; each dict has keys: - obj: an object stub, as generated by _make_ec_object_stub, that defines all of the fragments that compose an object at a specific timestamp. - frag: the index of a fragment to be selected from the object stub - durable (optional): True if the selected fragment is durable :param policy: storage policy to return """ node_map = {} # maps node ip and port to node index all_nodes = [] call_count = {} # maps node index to get_response call count for node def _build_node_map(req, policy): part = utils.split_path(req['path'], 5, 5, True)[1] all_nodes.extend(policy.object_ring.get_part_nodes(part)) all_nodes.extend(policy.object_ring.get_more_nodes(part)) for i, node in enumerate(all_nodes): node_map[(node['ip'], node['port'])] = i call_count[i] = 0 # normalize node_frags to a list of fragments for each node even # if there's only one fragment in the dataset provided. for i, frags in enumerate(node_frags): if isinstance(frags, dict): node_frags[i] = [frags] def get_response(req): requested_policy = int( req['headers']['X-Backend-Storage-Policy-Index']) if int(policy) != requested_policy: AssertionError( "Requested polciy doesn't fit the fake response policy") if not node_map: _build_node_map(req, policy) try: node_index = node_map[(req['ip'], req['port'])] except KeyError: raise Exception("Couldn't find node %s:%s in %r" % ( req['ip'], req['port'], all_nodes)) try: frags = node_frags[node_index] except IndexError: raise Exception('Found node %r:%r at index %s - ' 'but only got %s stub response nodes' % ( req['ip'], req['port'], node_index, len(node_frags))) if not frags: return StubResponse(404) # determine response fragment (if any) for this call resp_frag = frags[call_count[node_index]] call_count[node_index] += 1 frag_prefs = req['headers'].get('X-Backend-Fragment-Preferences') if not (frag_prefs or resp_frag.get('durable', True)): return StubResponse(404) # prepare durable timestamp and backend frags header for this node obj_stub = resp_frag['obj'] ts2frags = defaultdict(list) durable_timestamp = None for frag in frags: ts_frag = frag['obj']['timestamp'] if frag.get('durable', True): durable_timestamp = ts_frag.internal ts2frags[ts_frag].append(frag['frag']) try: body = obj_stub['frags'][resp_frag['frag']] except IndexError as err: raise Exception( 'Frag index %s not defined: node index %s, frags %r\n%s' % (resp_frag['frag'], node_index, [f['frag'] for f in frags], err)) headers = { 'X-Object-Sysmeta-Ec-Content-Length': len(obj_stub['body']), 'X-Object-Sysmeta-Ec-Etag': obj_stub['etag'], 'X-Object-Sysmeta-Ec-Frag-Index': policy.get_backend_index(resp_frag['frag']), 'X-Backend-Timestamp': obj_stub['timestamp'].internal, 'X-Timestamp': obj_stub['timestamp'].normal, 'X-Backend-Data-Timestamp': obj_stub['timestamp'].internal, 'X-Backend-Fragments': server._make_backend_fragments_header(ts2frags) } if durable_timestamp: headers['X-Backend-Durable-Timestamp'] = durable_timestamp return StubResponse(200, body, headers) return get_response supports_xattr_cached_val = None def xattr_supported_check(): """ This check simply sets more than 4k of metadata on a tempfile and returns True if it worked and False if not. We want to use *more* than 4k of metadata in this check because some filesystems (eg ext4) only allow one blocksize worth of metadata. The XFS filesystem doesn't have this limit, and so this check returns True when TMPDIR is XFS. This check will return False under ext4 (which supports xattrs <= 4k) and tmpfs (which doesn't support xattrs at all). """ global supports_xattr_cached_val if supports_xattr_cached_val is not None: return supports_xattr_cached_val # assume the worst -- xattrs aren't supported supports_xattr_cached_val = False big_val = b'x' * (4096 + 1) # more than 4k of metadata try: fd, tmppath = mkstemp() xattr.setxattr(fd, 'user.swift.testing_key', big_val) except IOError as e: if errno.errorcode.get(e.errno) in ('ENOSPC', 'ENOTSUP', 'EOPNOTSUPP', 'ERANGE'): # filesystem does not support xattr of this size return False raise else: supports_xattr_cached_val = True return True finally: # clean up the tmpfile os.close(fd) os.unlink(tmppath) def skip_if_no_xattrs(): if not xattr_supported_check(): raise SkipTest('Large xattrs not supported in `%s`. Skipping test' % gettempdir()) def unlink_files(paths): for path in paths: try: os.unlink(path) except OSError as err: if err.errno != errno.ENOENT: raise class FakeHTTPResponse(object): def __init__(self, resp): self.resp = resp @property def status(self): return self.resp.status_int @property def data(self): return self.resp.body def attach_fake_replication_rpc(rpc, replicate_hook=None, errors=None): class FakeReplConnection(object): def __init__(self, node, partition, hash_, logger): self.logger = logger self.node = node self.partition = partition self.path = '/%s/%s/%s' % (node['device'], partition, hash_) self.host = node['replication_ip'] def replicate(self, op, *sync_args): print('REPLICATE: %s, %s, %r' % (self.path, op, sync_args)) resp = None if errors and op in errors and errors[op]: resp = errors[op].pop(0) if not resp: replicate_args = self.path.lstrip('/').split('/') args = [op] + copy.deepcopy(list(sync_args)) with mock_check_drive(isdir=not rpc.mount_check, ismount=rpc.mount_check): swob_response = rpc.dispatch(replicate_args, args) resp = FakeHTTPResponse(swob_response) if replicate_hook: replicate_hook(op, *sync_args) return resp return FakeReplConnection def group_by_byte(contents): # This looks a little funny, but iterating through a byte string on py3 # yields a sequence of ints, not a sequence of single-byte byte strings # as it did on py2. byte_iter = (contents[i:i + 1] for i in range(len(contents))) return [ (char, sum(1 for _ in grp)) for char, grp in itertools.groupby(byte_iter)] def generate_db_path(tempdir, server_type): return os.path.join( tempdir, '%ss' % server_type, 'part', 'suffix', 'hash', '%s-%s.db' % (server_type, uuid4())) class ConfigAssertMixin(object): """ Use this with a TestCase to get py2/3 compatible assert for DuplicateOption """ def assertDuplicateOption(self, app_config, option_name, option_value): """ PY3 added a DuplicateOptionError, PY2 didn't seem to care """ if six.PY3: self.assertDuplicateOptionError(app_config, option_name) else: self.assertDuplicateOptionOK(app_config, option_name, option_value) def assertDuplicateOptionError(self, app_config, option_name): with self.assertRaises( utils.configparser.DuplicateOptionError) as ctx: app_config() msg = str(ctx.exception) self.assertIn(option_name, msg) self.assertIn('already exists', msg) def assertDuplicateOptionOK(self, app_config, option_name, option_value): app = app_config() if hasattr(app, 'conf'): found_value = app.conf[option_name] else: if hasattr(app, '_pipeline_final_app'): # special case for proxy app! app = app._pipeline_final_app found_value = getattr(app, option_name) self.assertEqual(found_value, option_value) class FakeSource(object): def __init__(self, chunks, headers=None, body=b''): self.chunks = list(chunks) self.headers = headers or {} self.status = 200 self.swift_conn = None self.body = body def read(self, _read_size): if self.chunks: chunk = self.chunks.pop(0) if chunk is None: raise exceptions.ChunkReadTimeout() else: return chunk else: return self.body def getheader(self, header): # content-length for the whole object is generated dynamically # by summing non-None chunks if header.lower() == "content-length": if self.chunks: return str(sum(len(c) for c in self.chunks if c is not None)) return len(self.read(-1)) return self.headers.get(header.lower()) def getheaders(self): return [('content-length', self.getheader('content-length'))] + \ [(k, v) for k, v in self.headers.items()]
swift-master
test/unit/__init__.py
# Copyright (c) 2010-2016 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Provides helper functions for unit tests. This cannot be in test/unit/__init__.py because that module is imported by the py34 unit test job and there are imports here that end up importing modules that are not yet ported to py34, such wsgi.py which import mimetools. """ import os from contextlib import closing from gzip import GzipFile from tempfile import mkdtemp import time import warnings from eventlet import spawn, wsgi import mock from shutil import rmtree import six.moves.cPickle as pickle import swift from swift.account import server as account_server from swift.common import storage_policy from swift.common.ring import RingData from swift.common.storage_policy import StoragePolicy, ECStoragePolicy from swift.common.middleware import listing_formats, proxy_logging from swift.common import utils from swift.common.utils import mkdirs, normalize_timestamp, NullLogger from swift.common.http_protocol import SwiftHttpProtocol from swift.container import server as container_server from swift.obj import server as object_server from swift.proxy import server as proxy_server import swift.proxy.controllers.obj from test import listen_zero from test.debug_logger import debug_logger from test.unit import write_fake_ring, DEFAULT_TEST_EC_TYPE, connect_tcp, \ readuntil2crlfs def setup_servers(the_object_server=object_server, extra_conf=None): """ Setup proxy, account, container and object servers using a set of fake rings and policies. :param the_object_server: The object server module to use (optional, defaults to swift.obj.server) :param extra_conf: A dict of config options that will update the basic config passed to all server instances. :returns: A dict containing the following entries: orig_POLICIES: the value of storage_policy.POLICIES prior to it being patched with fake policies orig_SysLogHandler: the value of utils.SysLogHandler prior to it being patched testdir: root directory used for test files test_POLICIES: a StoragePolicyCollection of fake policies test_servers: a tuple of test server instances test_sockets: a tuple of sockets used by test servers test_coros: a tuple of greenthreads in which test servers are running """ context = { "orig_POLICIES": storage_policy._POLICIES, "orig_SysLogHandler": utils.SysLogHandler} utils.HASH_PATH_SUFFIX = b'endcap' utils.SysLogHandler = mock.MagicMock() # Since we're starting up a lot here, we're going to test more than # just chunked puts; we're also going to test parts of # proxy_server.Application we couldn't get to easily otherwise. context["testdir"] = _testdir = \ os.path.join(mkdtemp(), 'tmp_test_proxy_server_chunked') mkdirs(_testdir) rmtree(_testdir) for drive in ('sda1', 'sdb1', 'sdc1', 'sdd1', 'sde1', 'sdf1', 'sdg1', 'sdh1', 'sdi1', 'sdj1', 'sdk1', 'sdl1'): mkdirs(os.path.join(_testdir, drive, 'tmp')) conf = {'devices': _testdir, 'swift_dir': _testdir, 'mount_check': 'false', 'allowed_headers': 'content-encoding, x-object-manifest, content-disposition, foo', 'allow_versions': 't', 'node_timeout': 20} if extra_conf: conf.update(extra_conf) context['conf'] = conf prolis = listen_zero() acc1lis = listen_zero() acc2lis = listen_zero() con1lis = listen_zero() con2lis = listen_zero() obj1lis = listen_zero() obj2lis = listen_zero() obj3lis = listen_zero() obj4lis = listen_zero() obj5lis = listen_zero() obj6lis = listen_zero() objsocks = [obj1lis, obj2lis, obj3lis, obj4lis, obj5lis, obj6lis] context["test_sockets"] = \ (prolis, acc1lis, acc2lis, con1lis, con2lis, obj1lis, obj2lis, obj3lis, obj4lis, obj5lis, obj6lis) account_ring_path = os.path.join(_testdir, 'account.ring.gz') account_devs = [ {'port': acc1lis.getsockname()[1]}, {'port': acc2lis.getsockname()[1]}, ] write_fake_ring(account_ring_path, *account_devs) container_ring_path = os.path.join(_testdir, 'container.ring.gz') container_devs = [ {'port': con1lis.getsockname()[1]}, {'port': con2lis.getsockname()[1]}, ] write_fake_ring(container_ring_path, *container_devs) storage_policy._POLICIES = storage_policy.StoragePolicyCollection([ StoragePolicy(0, 'zero', True), StoragePolicy(1, 'one', False), StoragePolicy(2, 'two', False), ECStoragePolicy(3, 'ec', ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=2, ec_nparity=1, ec_segment_size=4096), ECStoragePolicy(4, 'ec-dup', ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=2, ec_nparity=1, ec_segment_size=4096, ec_duplication_factor=2)]) obj_rings = { 0: ('sda1', 'sdb1'), 1: ('sdc1', 'sdd1'), 2: ('sde1', 'sdf1'), # sdg1, sdh1, sdi1 taken by policy 3 (see below) } for policy_index, devices in obj_rings.items(): policy = storage_policy.POLICIES[policy_index] obj_ring_path = os.path.join(_testdir, policy.ring_name + '.ring.gz') obj_devs = [ {'port': objsock.getsockname()[1], 'device': dev} for objsock, dev in zip(objsocks, devices)] write_fake_ring(obj_ring_path, *obj_devs) # write_fake_ring can't handle a 3-element ring, and the EC policy needs # at least 6 devs to work with (ec_k=2, ec_m=1, duplication_factor=2), # so we do it manually devs = [{'id': 0, 'zone': 0, 'device': 'sdg1', 'ip': '127.0.0.1', 'port': obj1lis.getsockname()[1]}, {'id': 1, 'zone': 0, 'device': 'sdh1', 'ip': '127.0.0.1', 'port': obj2lis.getsockname()[1]}, {'id': 2, 'zone': 0, 'device': 'sdi1', 'ip': '127.0.0.1', 'port': obj3lis.getsockname()[1]}, {'id': 3, 'zone': 0, 'device': 'sdj1', 'ip': '127.0.0.1', 'port': obj4lis.getsockname()[1]}, {'id': 4, 'zone': 0, 'device': 'sdk1', 'ip': '127.0.0.1', 'port': obj5lis.getsockname()[1]}, {'id': 5, 'zone': 0, 'device': 'sdl1', 'ip': '127.0.0.1', 'port': obj6lis.getsockname()[1]}] pol3_replica2part2dev_id = [[0, 1, 2, 0], [1, 2, 0, 1], [2, 0, 1, 2]] pol4_replica2part2dev_id = [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 0], [4, 5, 0, 1], [5, 0, 1, 2]] obj3_ring_path = os.path.join( _testdir, storage_policy.POLICIES[3].ring_name + '.ring.gz') part_shift = 30 with closing(GzipFile(obj3_ring_path, 'wb')) as fh: pickle.dump(RingData(pol3_replica2part2dev_id, devs, part_shift), fh) obj4_ring_path = os.path.join( _testdir, storage_policy.POLICIES[4].ring_name + '.ring.gz') part_shift = 30 with closing(GzipFile(obj4_ring_path, 'wb')) as fh: pickle.dump(RingData(pol4_replica2part2dev_id, devs, part_shift), fh) prosrv = proxy_server.Application(conf, logger=debug_logger('proxy')) for policy in storage_policy.POLICIES: # make sure all the rings are loaded prosrv.get_object_ring(policy.idx) # don't lose this one! context["test_POLICIES"] = storage_policy._POLICIES acc1srv = account_server.AccountController( conf, logger=debug_logger('acct1')) acc2srv = account_server.AccountController( conf, logger=debug_logger('acct2')) con1srv = container_server.ContainerController( conf, logger=debug_logger('cont1')) con2srv = container_server.ContainerController( conf, logger=debug_logger('cont2')) obj1srv = the_object_server.ObjectController( conf, logger=debug_logger('obj1')) obj2srv = the_object_server.ObjectController( conf, logger=debug_logger('obj2')) obj3srv = the_object_server.ObjectController( conf, logger=debug_logger('obj3')) obj4srv = the_object_server.ObjectController( conf, logger=debug_logger('obj4')) obj5srv = the_object_server.ObjectController( conf, logger=debug_logger('obj5')) obj6srv = the_object_server.ObjectController( conf, logger=debug_logger('obj6')) context["test_servers"] = \ (prosrv, acc1srv, acc2srv, con1srv, con2srv, obj1srv, obj2srv, obj3srv, obj4srv, obj5srv, obj6srv) nl = NullLogger() logging_prosv = proxy_logging.ProxyLoggingMiddleware( listing_formats.ListingFilter(prosrv, {}, logger=prosrv.logger), conf, logger=prosrv.logger) # Yes, eventlet, we know -- we have to support bad clients, though warnings.filterwarnings( 'ignore', module='eventlet', message='capitalize_response_headers is disabled') prospa = spawn(wsgi.server, prolis, logging_prosv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) acc1spa = spawn(wsgi.server, acc1lis, acc1srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) acc2spa = spawn(wsgi.server, acc2lis, acc2srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) con1spa = spawn(wsgi.server, con1lis, con1srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) con2spa = spawn(wsgi.server, con2lis, con2srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj1spa = spawn(wsgi.server, obj1lis, obj1srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj2spa = spawn(wsgi.server, obj2lis, obj2srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj3spa = spawn(wsgi.server, obj3lis, obj3srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj4spa = spawn(wsgi.server, obj4lis, obj4srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj5spa = spawn(wsgi.server, obj5lis, obj5srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) obj6spa = spawn(wsgi.server, obj6lis, obj6srv, nl, protocol=SwiftHttpProtocol, capitalize_response_headers=False) context["test_coros"] = \ (prospa, acc1spa, acc2spa, con1spa, con2spa, obj1spa, obj2spa, obj3spa, obj4spa, obj5spa, obj6spa) # Create account ts = normalize_timestamp(time.time()) partition, nodes = prosrv.account_ring.get_nodes('a') for node in nodes: conn = swift.proxy.controllers.obj.http_connect(node['ip'], node['port'], node['device'], partition, 'PUT', '/a', {'X-Timestamp': ts, 'x-trans-id': 'test'}) resp = conn.getresponse() assert(resp.status == 201) # Create another account # used for account-to-account tests ts = normalize_timestamp(time.time()) partition, nodes = prosrv.account_ring.get_nodes('a1') for node in nodes: conn = swift.proxy.controllers.obj.http_connect(node['ip'], node['port'], node['device'], partition, 'PUT', '/a1', {'X-Timestamp': ts, 'x-trans-id': 'test'}) resp = conn.getresponse() assert(resp.status == 201) # Create containers, 1 per test policy sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile('rwb') fd.write(b'PUT /v1/a/c HTTP/1.1\r\nHost: localhost\r\n' b'Connection: close\r\nX-Auth-Token: t\r\n' b'Content-Length: 0\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = b'HTTP/1.1 201' assert headers[:len(exp)] == exp, "Expected '%s', encountered '%s'" % ( exp, headers[:len(exp)]) # Create container in other account # used for account-to-account tests sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile('rwb') fd.write(b'PUT /v1/a1/c1 HTTP/1.1\r\nHost: localhost\r\n' b'Connection: close\r\nX-Auth-Token: t\r\n' b'Content-Length: 0\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = b'HTTP/1.1 201' assert headers[:len(exp)] == exp, "Expected '%s', encountered '%s'" % ( exp, headers[:len(exp)]) sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile('rwb') fd.write( b'PUT /v1/a/c1 HTTP/1.1\r\nHost: localhost\r\n' b'Connection: close\r\nX-Auth-Token: t\r\nX-Storage-Policy: one\r\n' b'Content-Length: 0\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = b'HTTP/1.1 201' assert headers[:len(exp)] == exp, \ "Expected %r, encountered %r" % (exp, headers[:len(exp)]) sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile('rwb') fd.write( b'PUT /v1/a/c2 HTTP/1.1\r\nHost: localhost\r\n' b'Connection: close\r\nX-Auth-Token: t\r\nX-Storage-Policy: two\r\n' b'Content-Length: 0\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = b'HTTP/1.1 201' assert headers[:len(exp)] == exp, \ "Expected '%s', encountered '%s'" % (exp, headers[:len(exp)]) return context def teardown_servers(context): for server in context["test_coros"]: server.kill() rmtree(os.path.dirname(context["testdir"])) utils.SysLogHandler = context["orig_SysLogHandler"] storage_policy._POLICIES = context["orig_POLICIES"]
swift-master
test/unit/helpers.py
README.md exists but content is empty.
Downloads last month
38