desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Register any configuration options used by this engine.'
def register_opts(self, conf):
conf.register_opts(self.OPTIONS)
'Return a Connection instance based on the configuration settings.'
def get_connection(self, conf):
return Connection(conf)
'Write the data to the backend storage system. :param data: a dictionary such as returned by ceilometer.meter.meter_message_from_counter'
def record_metering_data(self, data):
self.db.user.update({'_id': data['user_id']}, {'$addToSet': {'source': data['source']}}, upsert=True) self.db.project.update({'_id': data['project_id']}, {'$addToSet': {'source': data['source']}}, upsert=True) self.db.resource.update({'_id': data['resource_id']}, {'$set': {'project_id': data['project_id'], ...
'Return an iterable of user id strings. :param source: Optional source filter.'
def get_users(self, source=None):
q = {} if (source is not None): q['source'] = source return sorted(self.db.user.find(q).distinct('_id'))
'Return an iterable of project id strings. :param source: Optional source filter.'
def get_projects(self, source=None):
q = {} if (source is not None): q['source'] = source return sorted(self.db.project.find(q).distinct('_id'))
'Return an iterable of models.Resource instances :param user: Optional ID for user that owns the resource. :param project: Optional ID for project that owns the resource. :param source: Optional source filter. :param start_timestamp: Optional modified timestamp start range. :param end_timestamp: Optional modified times...
def get_resources(self, user=None, project=None, source=None, start_timestamp=None, end_timestamp=None, metaquery={}, resource=None):
q = {} if (user is not None): q['user_id'] = user if (project is not None): q['project_id'] = project if (source is not None): q['source'] = source if (resource is not None): q['resource_id'] = resource q.update(dict(((('resource_' + k), v) for (k, v) in metaquery...
'Return an iterable of models.Meter instances :param user: Optional ID for user that owns the resource. :param project: Optional ID for project that owns the resource. :param resource: Optional resource filter. :param source: Optional source filter. :param metaquery: Optional dict with metadata to match on.'
def get_meters(self, user=None, project=None, resource=None, source=None, metaquery={}):
q = {} if (user is not None): q['user_id'] = user if (project is not None): q['project_id'] = project if (resource is not None): q['_id'] = resource if (source is not None): q['source'] = source q.update(metaquery) for r in self.db.resource.find(q): fo...
'Return an iterable of model.Sample instances. :param sample_filter: Filter. :param limit: Maximum number of results to return.'
def get_samples(self, sample_filter, limit=None):
if (limit == 0): return q = make_query_from_filter(sample_filter, require_meter=False) samples = self.db.meter.find(q).limit((limit or 0)) for s in samples: del s['_id'] (yield models.Sample(**s))
'Return an iterable of models.Statistics instance containing meter statistics described by the query parameters. The filter must have a meter value set.'
def get_meter_statistics(self, sample_filter, period=None):
q = make_query_from_filter(sample_filter) if period: map_stats = (self.MAP_STATS_PERIOD % (period, (int(sample_filter.start.strftime('%s')) if sample_filter.start else 0))) else: map_stats = self.MAP_STATS results = self.db.meter.map_reduce(map_stats, self.REDUCE_STATS, {'inline': 1}, fi...
'Yields a lists of alarms that match filters'
def get_alarms(self, name=None, user=None, project=None, enabled=True, alarm_id=None):
q = {} if (user is not None): q['user_id'] = user if (project is not None): q['project_id'] = project if (name is not None): q['name'] = name if (enabled is not None): q['enabled'] = enabled if (alarm_id is not None): q['alarm_id'] = alarm_id for alarm...
'update alarm'
def update_alarm(self, alarm):
if (alarm.alarm_id is None): alarm.alarm_id = str(uuid.uuid1()) data = alarm.as_dict() self.db.alarm.update({'alarm_id': alarm.alarm_id}, {'$set': data}, upsert=True) stored_alarm = self.db.alarm.find({'alarm_id': alarm.alarm_id})[0] del stored_alarm['_id'] return models.Alarm(**stored_a...
'Delete a alarm'
def delete_alarm(self, alarm_id):
self.db.alarm.remove({'alarm_id': alarm_id})
'Write the events. :param events: a list of model.Event objects.'
@staticmethod def record_events(events):
raise NotImplementedError('Events not implemented.')
'Return an iterable of model.Event objects. :param event_filter: EventFilter instance'
@staticmethod def get_events(event_filter):
raise NotImplementedError('Events not implemented.')
'Register any configuration options used by this engine.'
def register_opts(self, conf):
conf.register_opts(self.OPTIONS)
'Return a Connection instance based on the configuration settings.'
@staticmethod def get_connection(conf):
return Connection(conf)
'Hbase Connection Initialization'
def __init__(self, conf):
opts = self._parse_connection_url(conf.database.connection) opts['table_prefix'] = conf.table_prefix if (opts['host'] == '__test__'): url = os.environ.get('CEILOMETER_TEST_HBASE_URL') if url: opts = self._parse_connection_url(url) else: self.conn = MConnection...
'Return a connection to the database. .. note:: The tests use a subclass to override this and return an in-memory connection.'
@staticmethod def _get_connection(conf):
LOG.debug('connecting to HBase on %s:%s', conf['host'], conf['port']) return happybase.Connection(host=conf['host'], port=conf['port'], table_prefix=conf['table_prefix'])
'Parse connection parameters from a database url. .. note:: HBase Thrift does not support authentication and there is no database name, so we are not looking for these in the url.'
@staticmethod def _parse_connection_url(url):
opts = {} result = urlparse(url) opts['dbtype'] = result.scheme if (':' in result.netloc): (opts['host'], port) = result.netloc.split(':') else: opts['host'] = result.netloc port = 9090 opts['port'] = ((port and int(port)) or 9090) return opts
'Write the data to the backend storage system. :param data: a dictionary such as returned by ceilometer.meter.meter_message_from_counter'
def record_metering_data(self, data):
if data['user_id']: user = self.user.row(data['user_id']) sources = _load_hbase_list(user, 's') if (data['source'] not in sources): user[('f:s_%s' % data['source'])] = '1' self.user.put(data['user_id'], user) project = self.project.row(data['project_id']) sour...
'Return an iterable of user id strings. :param source: Optional source filter.'
def get_users(self, source=None):
LOG.debug(('source: %s' % source)) scan_args = {} if source: scan_args['columns'] = [('f:s_%s' % source)] return sorted((key for (key, ignored) in self.user.scan(**scan_args)))
'Return an iterable of project id strings. :param source: Optional source filter.'
def get_projects(self, source=None):
LOG.debug(('source: %s' % source)) scan_args = {} if source: scan_args['columns'] = [('f:s_%s' % source)] return (key for (key, ignored) in self.project.scan(**scan_args))
'Return an iterable of models.Resource instances :param user: Optional ID for user that owns the resource. :param project: Optional ID for project that owns the resource. :param source: Optional source filter. :param start_timestamp: Optional modified timestamp start range. :param end_timestamp: Optional modified times...
def get_resources(self, user=None, project=None, source=None, start_timestamp=None, end_timestamp=None, metaquery={}):
def make_resource(data): 'Transform HBase fields to Resource model.' data['f:metadata'] = dict(((k[4:], v) for (k, v) in data.iteritems() if k.startswith('f:r_'))) return models.Resource(resource_id=data['f:resource_id'], project_id=data['f:project_id'], source=data['f:source'...
'Return an iterable of models.Meter instances :param user: Optional ID for user that owns the resource. :param project: Optional ID for project that owns the resource. :param resource: Optional resource filter. :param source: Optional source filter. :param metaquery: Optional dict with metadata to match on.'
def get_meters(self, user=None, project=None, resource=None, source=None, metaquery={}):
q = make_query(user=user, project=project, resource=resource, source=source, require_meter=False, query_only=True) LOG.debug(('Query Resource table: %s' % q)) if (len(metaquery) > 0): meta_q = [] for (k, v) in metaquery.iteritems(): meta_q.append(("SingleColumnValueFilte...
'Return an iterable of models.Sample instances. :param sample_filter: Filter. :param limit: Maximum number of results to return.'
def get_samples(self, sample_filter, limit=None):
def make_sample(data): 'Transform HBase fields to Sample model.' data = json.loads(data['f:message']) data['timestamp'] = timeutils.parse_strtime(data['timestamp']) return models.Sample(**data) (q, start, stop) = make_query_from_filter(sample_filter, require_meter=...
'Do the stats calculation on a requested time bucket in stats dict :param stats: dict where aggregated stats are kept :param index: time bucket index in stats :param meter: meter record as returned from HBase :param start_time: query start time :param period: length of the time bucket'
def _update_meter_stats(self, stat, meter):
vol = int(meter['f:counter_volume']) ts = timeutils.parse_strtime(meter['f:timestamp']) stat.min = min(vol, (stat.min or vol)) stat.max = max(vol, stat.max) stat.sum = (vol + (stat.sum or 0)) stat.count += 1 stat.avg = (stat.sum / float(stat.count)) stat.duration_start = min(ts, (stat.du...
'Return an iterable of models.Statistics instances containing meter statistics described by the query parameters. The filter must have a meter value set. .. note:: Due to HBase limitations the aggregations are implemented in the driver itself, therefore this method will be quite slow because of all the Thrift traffic i...
def get_meter_statistics(self, sample_filter, period=None):
(q, start, stop) = make_query_from_filter(sample_filter) meters = list((meter for (ignored, meter) in self.meter.scan(filter=q, row_start=start, row_stop=stop))) if sample_filter.start: start_time = sample_filter.start elif meters: start_time = timeutils.parse_strtime(meters[(-1)]['f:tim...
'Yields a lists of alarms that match filters raise NotImplementedError(\'metaquery not implemented\')'
def get_alarms(self, name=None, user=None, project=None, enabled=True, alarm_id=None):
raise NotImplementedError('Alarms not implemented')
'update alarm'
def update_alarm(self, alarm):
raise NotImplementedError('Alarms not implemented')
'Delete a alarm'
def delete_alarm(self, alarm_id):
raise NotImplementedError('Alarms not implemented')
'Write the events. :param events: a list of model.Event objects.'
def record_events(self, events):
raise NotImplementedError('Events not implemented.')
'Return an iterable of model.Event objects. :param event_filter: EventFilter instance'
def get_events(self, event_filter):
raise NotImplementedError('Events not implemented.')
'This method is called from scan() when \'SingleColumnValueFilter\' is found in the \'filter\' argument'
@staticmethod def SingleColumnValueFilter(args, rows):
op = args[2] column = ('%s:%s' % (args[0], args[1])) value = args[3] if value.startswith('binary:'): value = value[7:] r = {} for row in rows: data = rows[row] if (op == '='): if ((column in data) and (data[column] == value)): r[row] = data ...
'Return boolean indicating whether this plugin should be enabled and used by the caller.'
@staticmethod def is_enabled():
return True
'Transform a payload dict to a metadata dict.'
def notification_to_metadata(self, event):
metadata = dict([(k, event['payload'].get(k)) for k in self.metadata_keys]) metadata['event_type'] = event['event_type'] metadata['host'] = event['publisher_id'] return metadata
'Return a sequence of ExchangeTopics defining the exchange and topics to be connected for this plugin.'
@staticmethod def get_exchange_topics(conf):
return [plugin.ExchangeTopics(exchange=conf.cinder_control_exchange, topics=set(((topic + '.info') for topic in conf.notification_topics)))]
'For nova notifier usage.'
def setup_notifier_task(self):
task = PollingTask(self) for pollster in self.pollster_manager.extensions: task.add(pollster, self.pipeline_manager.pipelines) self.notifier_task = task
'Poll one instance.'
def poll_instance(self, context, instance):
self.notifier_task.poll_and_publish_instances([instance])
'Return a sequence of ExchangeTopics defining the exchange and topics to be connected for this plugin.'
@staticmethod def get_exchange_topics(conf):
return [plugin.ExchangeTopics(exchange=conf.nova_control_exchange, topics=set(((topic + '.info') for topic in conf.notification_topics)))]
'List the instances on the current host.'
def inspect_instances(self):
raise NotImplementedError()
'Inspect the CPU statistics for an instance. :param instance_name: the name of the target instance :return: the number of CPUs and cumulative CPU time'
def inspect_cpus(self, instance_name):
raise NotImplementedError()
'Inspect the vNIC statistics for an instance. :param instance_name: the name of the target instance :return: for each vNIC, the number of bytes & packets received and transmitted'
def inspect_vnics(self, instance_name):
raise NotImplementedError()
'Inspect the disk statistics for an instance. :param instance_name: the name of the target instance :return: for each disk, the number of bytes & operations read and written, and the error count'
def inspect_disks(self, instance_name):
raise NotImplementedError()
'Used with the extenaion manager map() method.'
def _get_counters_from_plugin(self, ext, instance, *args, **kwds):
return ext.obj.get_counters(self, instance)
'Bind the UDP socket and handle incoming data.'
def start(self):
super(UDPCollectorService, self).start() udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) udp.bind((cfg.CONF.collector.udp_address, cfg.CONF.collector.udp_port)) self.running = True while self.running: (data, source) = udp.r...
'Consumers must be declared before consume_thread start.'
def initialize_service_hook(self, service):
LOG.debug('initialize_service_hooks') self.pipeline_manager = pipeline.setup_pipeline(transformer.TransformerExtensionManager('ceilometer.transformer')) LOG.debug('loading notification handlers from %s', self.COLLECTOR_NAMESPACE) self.notification_manager = extension.ExtensionManager(namespa...
'Make a notification processed by an handler.'
def process_notification(self, notification):
LOG.debug('notification %r', notification.get('event_type')) self.notification_manager.map(self._process_notification_for_ext, notification=notification)
'This method is triggered when metering data is cast from an agent.'
def record_metering_data(self, context, data):
if (not isinstance(data, list)): data = [data] for meter in data: LOG.info('metering data %s for %s @ %s: %s', meter['counter_name'], meter['resource_id'], meter.get('timestamp', 'NO TIMESTAMP'), meter['counter_volume']) if publisher_rpc.verify_signature(meter, cf...
'Return a sequence of ExchangeTopics defining the exchange and topics to be connected for this plugin.'
@staticmethod def get_exchange_topics(conf):
return [plugin.ExchangeTopics(exchange=conf.quantum_control_exchange, topics=set(((topic + '.info') for topic in conf.notification_topics)))]
'Set up for testing swift.object_server.ObjectController'
def setUp(self):
self.testdir = os.path.join(mkdtemp(), 'tmp_test_object_server_ObjectController') mkdirs(self.testdir) rmtree(self.testdir) mkdirs(os.path.join(self.testdir, 'sda1')) mkdirs(os.path.join(self.testdir, 'sda1', 'tmp')) self.controller = container_server.ContainerController({'devices': self.testdir...
'Tear down for testing swift.object_server.ObjectController'
def tearDown(self):
rmtree(os.path.dirname(self.testdir), ignore_errors=1)
'Copied from swift.common.utils.split_path'
def test_split_path(self):
def _test_split_path(path, minsegs=1, maxsegs=None, rwl=False): req = swift.common.swob.Request.blank(path) return req.split_path(minsegs, maxsegs, rwl) self.assertRaises(ValueError, _test_split_path, '') self.assertRaises(ValueError, _test_split_path, '/') self.assertRaises(ValueError, ...
'The actual bug was a HEAD response coming out with a body because the Request object wasn\'t passed into the Response object\'s constructor. The Response object\'s __call__ method should be able to reify a Request object from the env it gets passed.'
def test_call_reifies_request_if_necessary(self):
def test_app(environ, start_response): start_response('200 OK', []) return ['hi'] req = swift.common.swob.Request.blank('/') req.method = 'HEAD' (status, headers, app_iter) = req.call_application(test_app) resp = swift.common.swob.Response(status=status, headers=dict(headers), app...
'log_request() should send timing and byte-count counters for GET requests. Also, __call__()\'s iter_response() function should statsd-log time to first byte (calling the passed-in start_response function), but only for GET requests.'
def test_log_request_stat_type_good(self):
stub_times = [] def stub_time(): return stub_times.pop(0) path_types = {'/v1/a': 'account', '/v1/a/': 'account', '/v1/a/c': 'container', '/v1/a/c/': 'container', '/v1/a/c/o': 'object', '/v1/a/c/o/': 'object', '/v1/a/c/o/p': 'object', '/v1/a/c/o/p/': 'object', '/v1/a/c/o/p/p2': 'object'} for (pat...
'Two identical rings should produce identical .gz files on disk. Only true on Python 2.7 or greater.'
def test_deterministic_serialization(self):
if ((sys.version_info[0] == 2) and (sys.version_info[1] < 7)): return os.mkdir(os.path.join(self.testdir, '1')) os.mkdir(os.path.join(self.testdir, '2')) ring_fname1 = os.path.join(self.testdir, '1', 'the.ring.gz') ring_fname2 = os.path.join(self.testdir, '2', 'the.ring.gz') rd = ring.Ri...
'Test for https://bugs.launchpad.net/swift/+bug/845952'
def test_add_rebalance_add_rebalance_delete_rebalance(self):
rb = ring.RingBuilder(8, 3, 0) rb.add_dev({'id': 0, 'region': 0, 'zone': 0, 'weight': 1, 'ip': '127.0.0.1', 'port': 10000, 'device': 'sda1'}) rb.add_dev({'id': 1, 'region': 0, 'zone': 1, 'weight': 1, 'ip': '127.0.0.1', 'port': 10001, 'device': 'sda1'}) rb.add_dev({'id': 2, 'region': 0, 'zone': 2, 'weigh...
'Test swift.common.db.ContainerBroker.__init__'
def test_creation(self):
broker = ContainerBroker(':memory:', account='a', container='c') self.assertEqual(broker.db_file, ':memory:') broker.initialize(normalize_timestamp('1')) with broker.get() as conn: curs = conn.cursor() curs.execute('SELECT 1') self.assertEqual(curs.fetchall()[0][0], 1)
'Test swift.common.db.ContainerBroker throwing a conn away after unhandled exception'
def test_exception(self):
first_conn = None broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) with broker.get() as conn: first_conn = conn try: with broker.get() as conn: self.assertEquals(first_conn, conn) raise Exception('OMG...
'Test swift.common.db.ContainerBroker.empty'
def test_empty(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) self.assert_(broker.empty()) broker.put_object('o', normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') self.assert_((not broker.empty())) sleep(1e-05) b...
'Test swift.common.db.ContainerBroker.delete_object'
def test_delete_object(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) broker.put_object('o', normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') with broker.get() as conn: self.assertEquals(conn.execute('SELECT count(*) F...
'Test swift.common.db.ContainerBroker.put_object'
def test_put_object(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) timestamp = normalize_timestamp(time()) broker.put_object('"{<object \'&\' name>}"', timestamp, 123, 'application/x-test', '5af83e3196bf99f440f31f2e1a6c9afe') with broker.get() as conn:...
'Test swift.common.db.ContainerBroker.get_info'
def test_get_info(self):
broker = ContainerBroker(':memory:', account='test1', container='test2') broker.initialize(normalize_timestamp('1')) info = broker.get_info() self.assertEquals(info['account'], 'test1') self.assertEquals(info['container'], 'test2') self.assertEquals(info['hash'], '0000000000000000000000000000000...
'Test swift.common.db.ContainerBroker.list_objects_iter'
def test_list_objects_iter(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) for obj1 in xrange(4): for obj2 in xrange(125): broker.put_object(('%d/%04d' % (obj1, obj2)), normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') ...
'Test swift.common.db.ContainerBroker.list_objects_iter'
def test_list_objects_iter_prefix_delim(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) broker.put_object('/pets/dogs/1', normalize_timestamp(0), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') broker.put_object('/pets/dogs/2', normalize_timestamp(0), 0, 'text/plain', 'd41d8cd9...
'Test swift.common.db.ContainerBroker.list_objects_iter for a container that has an odd file with a trailing delimiter'
def test_double_check_trailing_delimiter(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) broker.put_object('a', normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') broker.put_object('a/', normalize_timestamp(time()), 0, 'text/plain', 'd41d8cd98f00b204e98...
'test DatabaseBroker.newid'
def test_newid(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) id = broker.get_info()['id'] broker.newid('someid') self.assertNotEquals(id, broker.get_info()['id'])
'test DatabaseBroker.get_items_since'
def test_get_items_since(self):
broker = ContainerBroker(':memory:', account='a', container='c') broker.initialize(normalize_timestamp('1')) broker.put_object('a', normalize_timestamp(1), 0, 'text/plain', 'd41d8cd98f00b204e9800998ecf8427e') max_row = broker.get_replication_info()['max_row'] broker.put_object('b', normalize_timesta...
'exercise the DatabaseBroker sync functions a bit'
def test_sync_merging(self):
broker1 = ContainerBroker(':memory:', account='a', container='c') broker1.initialize(normalize_timestamp('1')) broker2 = ContainerBroker(':memory:', account='a', container='c') broker2.initialize(normalize_timestamp('1')) self.assertEquals(broker2.get_sync('12345'), (-1)) broker1.merge_syncs([{'...
'test DatabaseBroker.merge_items'
def test_merge_items_overwrite(self):
broker1 = ContainerBroker(':memory:', account='a', container='c') broker1.initialize(normalize_timestamp('1')) id = broker1.get_info()['id'] broker2 = ContainerBroker(':memory:', account='a', container='c') broker2.initialize(normalize_timestamp('1')) broker1.put_object('a', normalize_timestamp(...
'test DatabaseBroker.merge_items'
def test_merge_items_post_overwrite_out_of_order(self):
broker1 = ContainerBroker(':memory:', account='a', container='c') broker1.initialize(normalize_timestamp('1')) id = broker1.get_info()['id'] broker2 = ContainerBroker(':memory:', account='a', container='c') broker2.initialize(normalize_timestamp('1')) broker1.put_object('a', normalize_timestamp(...
'Test swift.common.db.AccountBroker.__init__'
def test_creation(self):
broker = AccountBroker(':memory:', account='a') self.assertEqual(broker.db_file, ':memory:') got_exc = False try: with broker.get() as conn: pass except Exception: got_exc = True self.assert_(got_exc) broker.initialize(normalize_timestamp('1')) with broker.get...
'Test swift.common.db.AccountBroker throwing a conn away after exception'
def test_exception(self):
first_conn = None broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) with broker.get() as conn: first_conn = conn try: with broker.get() as conn: self.assertEquals(first_conn, conn) raise Exception('OMG') except Exc...
'Test swift.common.db.AccountBroker.empty'
def test_empty(self):
broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) self.assert_(broker.empty()) broker.put_container('o', normalize_timestamp(time()), 0, 0, 0) self.assert_((not broker.empty())) sleep(1e-05) broker.put_container('o', 0, normalize_timestamp(time()), 0...
'Test swift.common.db.AccountBroker.delete_container'
def test_delete_container(self):
broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) broker.put_container('o', normalize_timestamp(time()), 0, 0, 0) with broker.get() as conn: self.assertEquals(conn.execute('SELECT count(*) FROM container WHERE deleted = 0').fetchone(...
'Test swift.common.db.AccountBroker.put_container'
def test_put_container(self):
broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) timestamp = normalize_timestamp(time()) broker.put_container('"{<container \'&\' name>}"', timestamp, 0, 0, 0) with broker.get() as conn: self.assertEquals(conn.execute('SELECT name FROM ...
'Test swift.common.db.AccountBroker.get_info'
def test_get_info(self):
broker = AccountBroker(':memory:', account='test1') broker.initialize(normalize_timestamp('1')) info = broker.get_info() self.assertEquals(info['account'], 'test1') self.assertEquals(info['hash'], '00000000000000000000000000000000') info = broker.get_info() self.assertEquals(info['container_...
'Test swift.common.db.AccountBroker.list_containers_iter'
def test_list_containers_iter(self):
broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) for cont1 in xrange(4): for cont2 in xrange(125): broker.put_container(('%d/%04d' % (cont1, cont2)), normalize_timestamp(time()), 0, 0, 0) for cont in xrange(125): broker.put_container...
'Test swift.common.db.AccountBroker.list_containers_iter for an account that has an odd file with a trailing delimiter'
def test_double_check_trailing_delimiter(self):
broker = AccountBroker(':memory:', account='a') broker.initialize(normalize_timestamp('1')) broker.put_container('a', normalize_timestamp(time()), 0, 0, 0) broker.put_container('a/', normalize_timestamp(time()), 0, 0, 0) broker.put_container('a/a', normalize_timestamp(time()), 0, 0, 0) broker.pu...
'Ensure that a non-clean canonical_version never happens'
def test_canonical_version_is_clean(self):
pattern = re.compile('^\\d+(\\.\\d+)*$') self.assertTrue((pattern.match(swift.__canonical_version__) is not None))
'Server.iter_pid_files is kinda boring, test the Server.pid_files stuff here as well'
def test_iter_pid_files(self):
pid_files = (('proxy-server.pid', 1), ('auth-server.pid', 'blah'), ('object-replicator/1.pid', 11), ('object-replicator/2.pid', 12)) (files, contents) = zip(*pid_files) with temptree(files, contents) as t: manager.RUN_DIR = t server = manager.Server('proxy', run_dir=t) iter = server....
'Pretend we are running as root.'
def geteuid(self):
return 0
'Test swift.common.utils.normalize_timestamp'
def test_normalize_timestamp(self):
self.assertEquals(utils.normalize_timestamp('1253327593.48174'), '1253327593.48174') self.assertEquals(utils.normalize_timestamp(1253327593.48174), '1253327593.48174') self.assertEquals(utils.normalize_timestamp('1253327593.48'), '1253327593.48000') self.assertEquals(utils.normalize_timestamp(1253327593...
'Test swift.common.utils.backward'
def test_backwards(self):
blocksize = 25 lines = ['123456789x12345678><123456789\n', '123456789x123>\n', '123423456789\n', '123456789x\n', '<123456789x123456789x123\n', '<6789x123\n', '6789x1234\n', '1234><234\n', '123456789x123456789\n'] with TemporaryFile('r+w') as f: for line in lines: f.write(line) co...
'Test swift.common.utils.split_account_path'
def test_split_path(self):
self.assertRaises(ValueError, utils.split_path, '') self.assertRaises(ValueError, utils.split_path, '/') self.assertRaises(ValueError, utils.split_path, '//') self.assertEquals(utils.split_path('/a'), ['a']) self.assertRaises(ValueError, utils.split_path, '//a') self.assertEquals(utils.split_pat...
'Test swift.common.utils.validate_device_partition'
def test_validate_device_partition(self):
utils.validate_device_partition('foo', 'bar') self.assertRaises(ValueError, utils.validate_device_partition, '', '') self.assertRaises(ValueError, utils.validate_device_partition, '', 'foo') self.assertRaises(ValueError, utils.validate_device_partition, 'foo', '') self.assertRaises(ValueError, utils...
'Test swift.common.utils.NullLogger'
def test_NullLogger(self):
sio = StringIO() nl = utils.NullLogger() nl.write('test') self.assertEquals(sio.getvalue(), '')
'Because the client library may not actually send a packet with sample_rate < 1, we keep trying until we get one through.'
def _send_and_get(self, sender_fn, *args, **kwargs):
got = None while (not got): sender_fn(*args, **kwargs) try: got = self.queue.get(timeout=0.5) except Empty: pass return got
'Set up for testing swift.object_server.ObjectController'
def setUp(self):
self.testdir = os.path.join(mkdtemp(), 'tmp_test_obj_server_DiskFile') mkdirs(os.path.join(self.testdir, 'sda1', 'tmp')) def fake_exe(*args, **kwargs): pass tpool.execute = fake_exe
'Tear down for testing swift.object_server.ObjectController'
def tearDown(self):
rmtree(os.path.dirname(self.testdir))
'This test case is to make sure that the disk file app_iter_ranges method all the paths being tested.'
def test_disk_file_large_app_iter_ranges(self):
long_str = ('01234567890' * 65536) target_strs = ['3456789', long_str[0:65590]] df = self._create_test_file(long_str) it = df.app_iter_ranges([(3, 10), (0, 65590)], 'plain/text', '5e816ff8b8b8e9a5d355497e5d9e0301', 655360) '\n the produced string actually m...
'This test case tests when empty value passed into app_iter_ranges When ranges passed into the method is either empty array or None, this method will yield empty string'
def test_disk_file_app_iter_ranges_empty(self):
df = self._create_test_file('012345678911234567892123456789') it = df.app_iter_ranges([], 'application/whatever', '\r\n--someheader\r\n', 100) self.assertEqual(''.join(it), '') df = object_server.DiskFile(self.testdir, 'sda1', '0', 'a', 'c', 'o', FakeLogger(), keep_data_fp=True) it = df.app_iter_ran...
'returns a DiskFile'
def _get_data_file(self, invalid_type=None, obj_name='o', fsize=1024, csize=8, extension='.data', ts=None, iter_hook=None):
df = object_server.DiskFile(self.testdir, 'sda1', '0', 'a', 'c', obj_name, FakeLogger()) data = ('0' * fsize) etag = md5() if ts: timestamp = ts else: timestamp = str(normalize_timestamp(time())) with df.mkstemp() as fd: os.write(fd, data) etag.update(data) ...
'Set up for testing swift.object_server.ObjectController'
def setUp(self):
utils.HASH_PATH_SUFFIX = 'endcap' utils.HASH_PATH_PREFIX = 'startcap' self.testdir = os.path.join(mkdtemp(), 'tmp_test_object_server_ObjectController') mkdirs(os.path.join(self.testdir, 'sda1', 'tmp')) conf = {'devices': self.testdir, 'mount_check': 'false'} self.object_controller = object_serve...
'Tear down for testing swift.object_server.ObjectController'
def tearDown(self):
rmtree(os.path.dirname(self.testdir))
'Test swift.object_server.ObjectController.POST'
def test_POST_update_meta(self):
original_headers = self.object_controller.allowed_headers test_headers = 'content-encoding foo bar'.split() self.object_controller.allowed_headers = set(test_headers) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Tim...
'Test swift.object_server.ObjectController.GET'
def test_POST_quarantine_zbyte(self):
timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = self.object_controller.PUT(req) self.assertEquals(resp.status_int, 201) file = obje...
'Test swift.object_server.ObjectController.HEAD'
def test_HEAD(self):
req = Request.blank('/sda1/p/a/c') resp = self.object_controller.HEAD(req) self.assertEquals(resp.status_int, 400) req = Request.blank('/sda1/p/a/c/o') resp = self.object_controller.HEAD(req) self.assertEquals(resp.status_int, 404) timestamp = normalize_timestamp(time()) req = Request.bl...
'Test swift.object_server.ObjectController.GET'
def test_HEAD_quarantine_zbyte(self):
timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = self.object_controller.PUT(req) self.assertEquals(resp.status_int, 201) file = obje...
'Test swift.object_server.ObjectController.GET'
def test_GET(self):
req = Request.blank('/sda1/p/a/c') resp = self.object_controller.GET(req) self.assertEquals(resp.status_int, 400) req = Request.blank('/sda1/p/a/c/o') resp = self.object_controller.GET(req) self.assertEquals(resp.status_int, 404) timestamp = normalize_timestamp(time()) req = Request.blan...
'Test swift.object_server.ObjectController.GET'
def test_GET_quarantine(self):
timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = self.object_controller.PUT(req) self.assertEquals(resp.status_int, 201) file = obje...