Code cleanup

- Mark static methods
- Remove some useless code

Change-Id: I89f5829c75b874fdfe59bc88dad809e0d54b006a
Signed-off-by: Julien Danjou <julien@danjou.info>
This commit is contained in:
Julien Danjou 2013-06-13 15:07:41 +02:00
parent 8a86298bbd
commit 6af55da0df
14 changed files with 43 additions and 73 deletions

View File

@ -93,5 +93,6 @@ class AgentManager(object):
self.interval_task,
task=task)
def interval_task(self, task):
@staticmethod
def interval_task(task):
task.poll_and_publish()

View File

@ -54,18 +54,12 @@ cfg.CONF.register_opts(OPTS, group="collector")
LOG = log.getLogger(__name__)
def get_storage_connection(conf):
storage.register_opts(conf)
storage_engine = storage.get_engine(conf)
return storage_engine.get_connection(conf)
class UDPCollectorService(os_service.Service):
"""UDP listener for the collector service."""
def __init__(self):
super(UDPCollectorService, self).__init__()
self.storage_conn = get_storage_connection(cfg.CONF)
self.storage_conn = storage.get_connection(cfg.CONF)
def start(self):
"""Bind the UDP socket and handle incoming data."""
@ -113,7 +107,7 @@ class CollectorService(rpc_service.Service):
def __init__(self, host, topic, manager=None):
super(CollectorService, self).__init__(host, topic, manager)
self.storage_conn = get_storage_connection(cfg.CONF)
self.storage_conn = storage.get_connection(cfg.CONF)
def start(self):
super(CollectorService, self).start()

View File

@ -35,7 +35,8 @@ class PluginBase(object):
"""Base class for all plugins.
"""
def is_enabled(self):
@staticmethod
def is_enabled():
"""Return boolean indicating whether this plugin should
be enabled and used by the caller.
"""
@ -47,9 +48,6 @@ class NotificationBase(PluginBase):
__metaclass__ = abc.ABCMeta
def is_enabled(self):
return True
@abc.abstractmethod
def get_event_types(self):
"""Return a sequence of strings defining the event types to be

View File

@ -69,12 +69,6 @@ CLI_OPTIONS = [
cfg.CONF.register_cli_opts(CLI_OPTIONS, group="service_credentials")
def _sanitize_cmd_line(argv):
"""Remove non-nova CLI options from argv."""
cli_opt_names = ['--%s' % o.name for o in CLI_OPTIONS]
return [a for a in argv if a in cli_opt_names]
def prepare_service(argv=None):
eventlet.monkey_patch()
gettextutils.install('ceilometer')

View File

@ -621,7 +621,8 @@ class MTable(object):
for k in sorted(rows):
yield k, rows[k]
def SingleColumnValueFilter(self, args, rows):
@staticmethod
def SingleColumnValueFilter(args, rows):
"""This method is called from scan() when 'SingleColumnValueFilter'
is found in the 'filter' argument
"""
@ -659,7 +660,6 @@ class MConnection(object):
def open(self):
LOG.debug("Opening in-memory HBase connection")
return
def create_table(self, n, families={}):
if n in self.tables:

View File

@ -43,7 +43,7 @@ class Connection(base.Connection):
"""
def __init__(self, conf):
return
pass
def upgrade(self, version=None):
pass

View File

@ -248,7 +248,8 @@ class Connection(base.Connection):
('source', pymongo.ASCENDING),
], name='meter_idx')
def upgrade(self, version=None):
@staticmethod
def upgrade(version=None):
pass
def clear(self):
@ -260,7 +261,8 @@ class Connection(base.Connection):
else:
self.conn.drop_database(self.db)
def _parse_connection_url(self, url):
@staticmethod
def _parse_connection_url(url):
opts = {}
result = urlparse.urlparse(url)
opts['dbtype'] = result.scheme
@ -556,14 +558,16 @@ class Connection(base.Connection):
"""
self.db.alarm.remove({'alarm_id': alarm_id})
def record_events(self, events):
@staticmethod
def record_events(events):
"""Write the events.
:param events: a list of model.Event objects.
"""
raise NotImplementedError('Events not implemented.')
def get_events(self, event_filter):
@staticmethod
def get_events(event_filter):
"""Return an iterable of model.Event objects.
:param event_filter: EventFilter instance

View File

@ -154,7 +154,8 @@ class Connection(base.Connection):
for table in reversed(Base.metadata.sorted_tables):
engine.execute(table.delete())
def record_metering_data(self, data):
@staticmethod
def record_metering_data(data):
"""Write the data to the backend storage system.
:param data: a dictionary such as returned by
@ -212,7 +213,8 @@ class Connection(base.Connection):
meter.message_id = data['message_id']
session.flush()
def get_users(self, source=None):
@staticmethod
def get_users(source=None):
"""Return an iterable of user id strings.
:param source: Optional source filter.
@ -223,7 +225,8 @@ class Connection(base.Connection):
query = query.filter(User.sources.any(id=source))
return (x[0] for x in query.all())
def get_projects(self, source=None):
@staticmethod
def get_projects(source=None):
"""Return an iterable of project id strings.
:param source: Optional source filter.
@ -234,7 +237,8 @@ class Connection(base.Connection):
query = query.filter(Project.sources.any(id=source))
return (x[0] for x in query.all())
def get_resources(self, user=None, project=None, source=None,
@staticmethod
def get_resources(user=None, project=None, source=None,
start_timestamp=None, end_timestamp=None,
metaquery={}, resource=None):
"""Return an iterable of api_models.Resource instances
@ -281,7 +285,8 @@ class Connection(base.Connection):
],
)
def get_meters(self, user=None, project=None, resource=None, source=None,
@staticmethod
def get_meters(user=None, project=None, resource=None, source=None,
metaquery={}):
"""Return an iterable of api_models.Meter instances
@ -322,7 +327,8 @@ class Connection(base.Connection):
user_id=resource.user_id,
)
def get_samples(self, sample_filter, limit=None):
@staticmethod
def get_samples(sample_filter, limit=None):
"""Return an iterable of api_models.Samples.
:param sample_filter: Filter.
@ -361,7 +367,8 @@ class Connection(base.Connection):
message_signature=s.message_signature,
)
def _make_volume_query(self, sample_filter, counter_volume_func):
@staticmethod
def _make_volume_query(sample_filter, counter_volume_func):
"""Returns complex Meter counter_volume query for max and sum."""
session = sqlalchemy_session.get_session()
subq = session.query(Meter.id)
@ -371,7 +378,8 @@ class Connection(base.Connection):
mainq = mainq.join(Meter).group_by(Resource.id)
return mainq.filter(Meter.id.in_(subq))
def _make_stats_query(self, sample_filter):
@staticmethod
def _make_stats_query(sample_filter):
session = sqlalchemy_session.get_session()
query = session.query(
func.min(Meter.timestamp).label('tsmin'),
@ -440,7 +448,8 @@ class Connection(base.Connection):
period_end=period_end,
)
def _row_to_alarm_model(self, row):
@staticmethod
def _row_to_alarm_model(row):
return api_models.Alarm(alarm_id=row.id,
enabled=row.enabled,
name=row.name,
@ -462,7 +471,8 @@ class Connection(base.Connection):
row.insufficient_data_actions,
matching_metadata=row.matching_metadata)
def _alarm_model_to_row(self, alarm, row=None):
@staticmethod
def _alarm_model_to_row(alarm, row=None):
if row is None:
row = Alarm(id=str(uuid.uuid1()))
row.update(alarm.as_dict())
@ -511,7 +521,8 @@ class Connection(base.Connection):
session.flush()
return self._row_to_alarm_model(alarm_row)
def delete_alarm(self, alarm_id):
@staticmethod
def delete_alarm(alarm_id):
"""Delete a alarm
:param alarm_id: ID of the alarm to delete
@ -521,7 +532,8 @@ class Connection(base.Connection):
session.query(Alarm).filter(Alarm.id == alarm_id).delete()
session.flush()
def _get_unique(self, session, key):
@staticmethod
def _get_unique(session, key):
return session.query(UniqueName).filter(UniqueName.key == key).first()
def _get_or_create_unique_name(self, key, session=None):

View File

@ -26,17 +26,7 @@ from ceilometer import storage
from ceilometer.tests import base as test_base
class BaseException(Exception):
"""A base exception for avoiding false positives."""
class TestBase(test_base.TestCase):
# Default tests use mongodb://__test__ (MIM)
# TODO(jd) remove it, so we're sure we run test on the backend we want,
# not this default one by mistake
database_connection = 'mongodb://__test__'
def setUp(self):
super(TestBase, self).setUp()
cfg.CONF.set_override('connection', self.database_connection,

View File

@ -23,31 +23,10 @@
import calendar
import datetime
import decimal
import os
from ceilometer.openstack.common import timeutils
def read_cached_file(filename, cache_info, reload_func=None):
"""Read from a file if it has been modified.
:param cache_info: dictionary to hold opaque cache.
:param reload_func: optional function to be called with data when
file is reloaded due to a modification.
:returns: data from file
"""
mtime = os.path.getmtime(filename)
if not cache_info or mtime != cache_info.get('mtime'):
with open(filename) as fap:
cache_info['data'] = fap.read()
cache_info['mtime'] = mtime
if reload_func:
reload_func(cache_info['data'])
return cache_info['data']
def recursive_keypairs(d):
"""Generator that produces sequence of keypairs for nested dictionaries.
"""

View File

@ -21,4 +21,6 @@ from ceilometer.tests import api
class FunctionalTest(api.FunctionalTest):
database_connection = 'mongodb://__test__'
PATH_PREFIX = '/v2'

View File

@ -30,7 +30,6 @@ from tests import agentbase
def test_load_plugins():
mgr = manager.AgentManager()
assert list(mgr.pollster_manager), 'Failed to load any plugins'
return
class TestRunTasks(agentbase.BaseAgentManagerTestCase):

View File

@ -29,7 +29,6 @@ from tests import agentbase
def test_load_plugins():
mgr = manager.AgentManager()
assert list(mgr.pollster_manager), 'Failed to load any plugins'
return
class TestRunTasks(agentbase.BaseAgentManagerTestCase):

View File

@ -26,7 +26,6 @@ def test_send_messages():
mox.Replay(conn)
notificationclient.send_messages(conn, 'notifications.info', input)
mox.Verify(conn)
return
def test_record_messages():
@ -37,4 +36,3 @@ def test_record_messages():
mox.Replay(conn)
notificationclient.record_messages(conn, 'notifications.info', StringIO())
mox.Verify(conn)
return