Rename cinder.flags to cinder.common.config

Replace FLAGS with cfg.CONF
Rename modules fake_flags to conf_fixture, test_flags to test_conf, declare_flags to declare_conf, runtime_flags to runtime_conf
Renamed cinder.flags, because exactly the same was done in the glance and nova

Fixes: bug #1182037
Change-Id: I3424d0a401b3ef7a3254d3e913263554361a52ff
This commit is contained in:
Sergey Vilgelm 2013-07-03 11:28:05 +04:00
parent 3b0921fbdc
commit 45a1a564c0
21 changed files with 285 additions and 209 deletions

View File

@ -27,12 +27,15 @@ continue attempting to launch the rest of the services.
""" """
import eventlet import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
import os import os
import sys import sys
from oslo.config import cfg
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir, os.pardir,
@ -43,14 +46,19 @@ if os.path.exists(os.path.join(possible_topdir, "cinder", "__init__.py")):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder import flags from cinder.common import config # Need to register global_opts
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import service from cinder import service
from cinder import utils from cinder import utils
from cinder import version
CONF = cfg.CONF
if __name__ == '__main__': if __name__ == '__main__':
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
LOG = logging.getLogger('cinder.all') LOG = logging.getLogger('cinder.all')

View File

@ -24,11 +24,13 @@
# eventlet is updated/released to fix the root issue # eventlet is updated/released to fix the root issue
import eventlet import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
import os import os
import sys import sys
from oslo.config import cfg
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir, os.pardir,
@ -39,13 +41,19 @@ if os.path.exists(os.path.join(possible_topdir, "cinder", "__init__.py")):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder import flags from cinder.common import config # Need to register global_opts
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import service from cinder import service
from cinder import utils from cinder import utils
from cinder import version
CONF = cfg.CONF
if __name__ == '__main__': if __name__ == '__main__':
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
utils.monkey_patch() utils.monkey_patch()
server = service.WSGIService('osapi_volume') server = service.WSGIService('osapi_volume')

View File

@ -17,6 +17,7 @@
"""Starter script for Cinder Volume Backup.""" """Starter script for Cinder Volume Backup."""
import os import os
import sys import sys
@ -24,6 +25,8 @@ import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
from oslo.config import cfg
# If ../cinder/__init__.py exists, add ../ to Python search path, so that # If ../cinder/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python... # it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
@ -35,13 +38,19 @@ if os.path.exists(os.path.join(possible_topdir, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder import flags from cinder.common import config # Need to register global_opts
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import service from cinder import service
from cinder import utils from cinder import utils
from cinder import version
CONF = cfg.CONF
if __name__ == '__main__': if __name__ == '__main__':
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
utils.monkey_patch() utils.monkey_patch()
launcher = service.ProcessLauncher() launcher = service.ProcessLauncher()

View File

@ -28,6 +28,8 @@ import os
import sys import sys
import time import time
from oslo.config import cfg
# If ../cinder/__init__.py exists, add ../ to Python search path, so that # If ../cinder/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python... # it will override what happens to be installed in /usr/(local/)lib/python...
POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
@ -39,21 +41,21 @@ if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from oslo.config import cfg from cinder.common import config # Need to register global_opts
from cinder import context from cinder import context
from cinder import exception from cinder import exception
from cinder import flags
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder.openstack.common import rpc from cinder.openstack.common import rpc
from cinder import version
delete_exchange_opt = \ delete_exchange_opt = \
cfg.BoolOpt('delete_exchange', cfg.BoolOpt('delete_exchange',
default=False, default=False,
help='delete cinder exchange too.') help='delete cinder exchange too.')
FLAGS = flags.FLAGS CONF = cfg.CONF
FLAGS.register_cli_opt(delete_exchange_opt) CONF.register_cli_opt(delete_exchange_opt)
def delete_exchange(exch): def delete_exchange(exch):
@ -69,8 +71,9 @@ def delete_queues(queues):
x.queue_delete(q) x.queue_delete(q)
if __name__ == '__main__': if __name__ == '__main__':
args = flags.parse_args(sys.argv) args = CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
delete_queues(args[1:]) delete_queues(args[1:])
if FLAGS.delete_exchange: if CONF.delete_exchange:
delete_exchange(FLAGS.control_exchange) delete_exchange(CONF.control_exchange)

View File

@ -54,10 +54,12 @@
CLI interface for cinder management. CLI interface for cinder management.
""" """
import os import os
import sys import sys
import uuid import uuid
from oslo.config import cfg
from sqlalchemy import create_engine, MetaData, Table from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
@ -74,20 +76,19 @@ if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from oslo.config import cfg from cinder.common import config # Need to register global_opts
from cinder import context from cinder import context
from cinder import db from cinder import db
from cinder.db import migration from cinder.db import migration
from cinder import exception from cinder import exception
from cinder import flags
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder.openstack.common import rpc from cinder.openstack.common import rpc
from cinder.openstack.common import uuidutils from cinder.openstack.common import uuidutils
from cinder import utils from cinder import utils
from cinder import version from cinder import version
FLAGS = flags.FLAGS
CONF = cfg.CONF
# Decorators for actions # Decorators for actions
@ -269,7 +270,7 @@ class VolumeCommands(object):
return return
rpc.cast(ctxt, rpc.cast(ctxt,
rpc.queue_get_for(ctxt, FLAGS.volume_topic, host), rpc.queue_get_for(ctxt, CONF.volume_topic, host),
{"method": "delete_volume", {"method": "delete_volume",
"args": {"volume_id": volume['id']}}) "args": {"volume_id": volume['id']}})
@ -288,7 +289,7 @@ class VolumeCommands(object):
instance = db.instance_get(ctxt, volume['instance_id']) instance = db.instance_get(ctxt, volume['instance_id'])
host = instance['host'] host = instance['host']
rpc.cast(ctxt, rpc.cast(ctxt,
rpc.queue_get_for(ctxt, FLAGS.compute_topic, host), rpc.queue_get_for(ctxt, CONF.compute_topic, host),
{"method": "attach_volume", {"method": "attach_volume",
"args": {"instance_id": instance['id'], "args": {"instance_id": instance['id'],
"volume_id": volume['id'], "volume_id": volume['id'],
@ -450,7 +451,7 @@ class ConfigCommands(object):
pass pass
def list(self): def list(self):
for key, value in FLAGS.iteritems(): for key, value in CONF.iteritems():
if value is not None: if value is not None:
print '%s = %s' % (key, value) print '%s = %s' % (key, value)
@ -461,10 +462,10 @@ class GetLogCommands(object):
def errors(self): def errors(self):
"""Get all of the errors from the log files.""" """Get all of the errors from the log files."""
error_found = 0 error_found = 0
if FLAGS.log_dir: if CONF.log_dir:
logs = [x for x in os.listdir(FLAGS.log_dir) if x.endswith('.log')] logs = [x for x in os.listdir(CONF.log_dir) if x.endswith('.log')]
for file in logs: for file in logs:
log_file = os.path.join(FLAGS.log_dir, file) log_file = os.path.join(CONF.log_dir, file)
lines = [line.strip() for line in open(log_file, "r")] lines = [line.strip() for line in open(log_file, "r")]
lines.reverse() lines.reverse()
print_name = 0 print_name = 0
@ -638,14 +639,14 @@ def fetch_func_args(func):
fn_args = [] fn_args = []
for args, kwargs in getattr(func, 'args', []): for args, kwargs in getattr(func, 'args', []):
arg = get_arg_string(args[0]) arg = get_arg_string(args[0])
fn_args.append(getattr(FLAGS.category, arg)) fn_args.append(getattr(CONF.category, arg))
return fn_args return fn_args
def main(): def main():
"""Parse options and call the appropriate class/method.""" """Parse options and call the appropriate class/method."""
FLAGS.register_cli_opt(category_opt) CONF.register_cli_opt(category_opt)
script_name = sys.argv[0] script_name = sys.argv[0]
if len(sys.argv) < 2: if len(sys.argv) < 2:
print(_("\nOpenStack Cinder version: %(version)s\n") % print(_("\nOpenStack Cinder version: %(version)s\n") %
@ -657,10 +658,11 @@ def main():
sys.exit(2) sys.exit(2)
try: try:
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
except cfg.ConfigFilesNotFoundError: except cfg.ConfigFilesNotFoundError:
cfgfile = FLAGS.config_file[-1] if FLAGS.config_file else None cfgfile = CONF.config_file[-1] if CONF.config_file else None
if cfgfile and not os.access(cfgfile, os.R_OK): if cfgfile and not os.access(cfgfile, os.R_OK):
st = os.stat(cfgfile) st = os.stat(cfgfile)
print _("Could not read %s. Re-running with sudo") % cfgfile print _("Could not read %s. Re-running with sudo") % cfgfile
@ -672,7 +674,7 @@ def main():
print _('Please re-run cinder-manage as root.') print _('Please re-run cinder-manage as root.')
sys.exit(2) sys.exit(2)
fn = FLAGS.category.action_fn fn = CONF.category.action_fn
fn_args = fetch_func_args(fn) fn_args = fetch_func_args(fn)
fn(*fn_args) fn(*fn_args)

View File

@ -19,12 +19,16 @@
"""Starter script for Cinder Scheduler.""" """Starter script for Cinder Scheduler."""
import eventlet import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
import os import os
import sys import sys
from oslo.config import cfg
# If ../cinder/__init__.py exists, add ../ to Python search path, so that # If ../cinder/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python... # it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
@ -36,13 +40,19 @@ if os.path.exists(os.path.join(possible_topdir, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder import flags from cinder.common import config # Need to register global_opts
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import service from cinder import service
from cinder import utils from cinder import utils
from cinder import version
CONF = cfg.CONF
if __name__ == '__main__': if __name__ == '__main__':
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
utils.monkey_patch() utils.monkey_patch()
server = service.Service.create(binary='cinder-scheduler') server = service.Service.create(binary='cinder-scheduler')

View File

@ -20,11 +20,14 @@
"""Starter script for Cinder Volume.""" """Starter script for Cinder Volume."""
import eventlet import eventlet
eventlet.monkey_patch() eventlet.monkey_patch()
import os import os
import sys import sys
from oslo.config import cfg
# If ../cinder/__init__.py exists, add ../ to Python search path, so that # If ../cinder/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python... # it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
@ -36,21 +39,25 @@ if os.path.exists(os.path.join(possible_topdir, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder import flags from cinder.common import config # Need to register global_opts
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import service from cinder import service
from cinder import utils from cinder import utils
from cinder import version
CONF = cfg.CONF
FLAGS = flags.FLAGS
if __name__ == '__main__': if __name__ == '__main__':
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
utils.monkey_patch() utils.monkey_patch()
launcher = service.ProcessLauncher() launcher = service.ProcessLauncher()
if FLAGS.enabled_backends: if CONF.enabled_backends:
for backend in FLAGS.enabled_backends: for backend in CONF.enabled_backends:
host = "%s@%s" % (FLAGS.host, backend) host = "%s@%s" % (CONF.host, backend)
server = service.Service.create(host=host, server = service.Service.create(host=host,
service_name=backend) service_name=backend)
launcher.launch_server(server) launcher.launch_server(server)

View File

@ -34,10 +34,13 @@
Jan 1 through Dec 31 of the previous year. Jan 1 through Dec 31 of the previous year.
""" """
import os import os
import sys import sys
import traceback import traceback
from oslo.config import cfg
# If ../cinder/__init__.py exists, add ../ to Python search path, so that # If ../cinder/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python... # it will override what happens to be installed in /usr/(local/)lib/python...
POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
@ -49,20 +52,23 @@ if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'cinder', '__init__.py')):
from cinder.openstack.common import gettextutils from cinder.openstack.common import gettextutils
gettextutils.install('cinder') gettextutils.install('cinder')
from cinder.common import config # Need to register global_opts
from cinder import context from cinder import context
from cinder import db from cinder import db
from cinder import flags
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder.openstack.common import rpc from cinder.openstack.common import rpc
from cinder import utils from cinder import utils
from cinder import version
import cinder.volume.utils import cinder.volume.utils
FLAGS = flags.FLAGS CONF = cfg.CONF
if __name__ == '__main__': if __name__ == '__main__':
admin_context = context.get_admin_context() admin_context = context.get_admin_context()
flags.parse_args(sys.argv) CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup("cinder") logging.setup("cinder")
begin, end = utils.last_completed_audit_period() begin, end = utils.last_completed_audit_period()
print _("Starting volume usage audit") print _("Starting volume usage audit")

View File

@ -28,30 +28,11 @@ stepping stone.
import os import os
import socket import socket
import sys
from oslo.config import cfg from oslo.config import cfg
from cinder import version
FLAGS = cfg.CONF CONF = cfg.CONF
def parse_args(argv, default_config_files=None):
FLAGS(argv[1:], project='cinder',
version=version.version_string(),
default_config_files=default_config_files)
class UnrecognizedFlag(Exception):
pass
def DECLARE(name, module_string, flag_values=FLAGS):
if module_string not in sys.modules:
__import__(module_string, globals(), locals())
if name not in flag_values:
raise UnrecognizedFlag('%s not defined by %s' % (name, module_string))
def _get_my_ip(): def _get_my_ip():
@ -83,7 +64,8 @@ core_opts = [
help='File name for the paste.deploy config for cinder-api'), help='File name for the paste.deploy config for cinder-api'),
cfg.StrOpt('pybasedir', cfg.StrOpt('pybasedir',
default=os.path.abspath(os.path.join(os.path.dirname(__file__), default=os.path.abspath(os.path.join(os.path.dirname(__file__),
'../')), '..',
'..')),
help='Directory where the cinder python module is installed'), help='Directory where the cinder python module is installed'),
cfg.StrOpt('bindir', cfg.StrOpt('bindir',
default='$pybasedir/bin', default='$pybasedir/bin',
@ -95,8 +77,8 @@ core_opts = [
debug_opts = [ debug_opts = [
] ]
FLAGS.register_cli_opts(core_opts) CONF.register_cli_opts(core_opts)
FLAGS.register_cli_opts(debug_opts) CONF.register_cli_opts(debug_opts)
global_opts = [ global_opts = [
cfg.StrOpt('my_ip', cfg.StrOpt('my_ip',
@ -230,4 +212,4 @@ global_opts = [
default='cinder.transfer.api.API', default='cinder.transfer.api.API',
help='The full class name of the volume transfer API class'), ] help='The full class name of the volume transfer API class'), ]
FLAGS.register_opts(global_opts) CONF.register_opts(global_opts)

View File

@ -18,11 +18,12 @@
"""Base classes for our unit tests. """Base classes for our unit tests.
Allows overriding of flags for use of fakes, and some black magic for Allows overriding of CONF for use of fakes, and some black magic for
inline callbacks. inline callbacks.
""" """
import functools import functools
import os import os
import shutil import shutil
@ -34,13 +35,14 @@ from oslo.config import cfg
import stubout import stubout
import testtools import testtools
from cinder.common import config # Need to register global_opts
from cinder.db import migration from cinder.db import migration
from cinder import flags
from cinder.openstack.common.db.sqlalchemy import session from cinder.openstack.common.db.sqlalchemy import session
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder.openstack.common import timeutils from cinder.openstack.common import timeutils
from cinder import service from cinder import service
from cinder.tests import fake_flags from cinder.tests import conf_fixture
test_opts = [ test_opts = [
cfg.StrOpt('sqlite_clean_db', cfg.StrOpt('sqlite_clean_db',
@ -50,8 +52,8 @@ test_opts = [
default=True, default=True,
help='should we use everything for testing'), ] help='should we use everything for testing'), ]
FLAGS = flags.FLAGS CONF = cfg.CONF
FLAGS.register_opts(test_opts) CONF.register_opts(test_opts)
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -77,7 +79,7 @@ class Database(fixtures.Fixture):
if db_migrate.db_version() > db_migrate.INIT_VERSION: if db_migrate.db_version() > db_migrate.INIT_VERSION:
return return
else: else:
testdb = os.path.join(FLAGS.state_path, sqlite_db) testdb = os.path.join(CONF.state_path, sqlite_db)
if os.path.exists(testdb): if os.path.exists(testdb):
return return
db_migrate.db_sync() db_migrate.db_sync()
@ -87,7 +89,7 @@ class Database(fixtures.Fixture):
self._DB = "".join(line for line in conn.connection.iterdump()) self._DB = "".join(line for line in conn.connection.iterdump())
self.engine.dispose() self.engine.dispose()
else: else:
cleandb = os.path.join(FLAGS.state_path, sqlite_clean_db) cleandb = os.path.join(CONF.state_path, sqlite_clean_db)
shutil.copyfile(testdb, cleandb) shutil.copyfile(testdb, cleandb)
def setUp(self): def setUp(self):
@ -99,8 +101,8 @@ class Database(fixtures.Fixture):
self.addCleanup(self.engine.dispose) self.addCleanup(self.engine.dispose)
else: else:
shutil.copyfile( shutil.copyfile(
os.path.join(FLAGS.state_path, self.sqlite_clean_db), os.path.join(CONF.state_path, self.sqlite_clean_db),
os.path.join(FLAGS.state_path, self.sqlite_db)) os.path.join(CONF.state_path, self.sqlite_db))
class TestCase(testtools.TestCase): class TestCase(testtools.TestCase):
@ -132,32 +134,32 @@ class TestCase(testtools.TestCase):
self.log_fixture = self.useFixture(fixtures.FakeLogger()) self.log_fixture = self.useFixture(fixtures.FakeLogger())
fake_flags.set_defaults(FLAGS) conf_fixture.set_defaults(CONF)
flags.parse_args([], default_config_files=[]) CONF([], default_config_files=[])
# NOTE(vish): We need a better method for creating fixtures for tests # NOTE(vish): We need a better method for creating fixtures for tests
# now that we have some required db setup for the system # now that we have some required db setup for the system
# to work properly. # to work properly.
self.start = timeutils.utcnow() self.start = timeutils.utcnow()
FLAGS.set_default('connection', 'sqlite://', 'database') CONF.set_default('connection', 'sqlite://', 'database')
FLAGS.set_default('sqlite_synchronous', False) CONF.set_default('sqlite_synchronous', False)
self.log_fixture = self.useFixture(fixtures.FakeLogger()) self.log_fixture = self.useFixture(fixtures.FakeLogger())
global _DB_CACHE global _DB_CACHE
if not _DB_CACHE: if not _DB_CACHE:
_DB_CACHE = Database(session, migration, _DB_CACHE = Database(session, migration,
sql_connection=FLAGS.database.connection, sql_connection=CONF.database.connection,
sqlite_db=FLAGS.sqlite_db, sqlite_db=CONF.sqlite_db,
sqlite_clean_db=FLAGS.sqlite_clean_db) sqlite_clean_db=CONF.sqlite_clean_db)
self.useFixture(_DB_CACHE) self.useFixture(_DB_CACHE)
# emulate some of the mox stuff, we can't use the metaclass # emulate some of the mox stuff, we can't use the metaclass
# because it screws with our generators # because it screws with our generators
self.mox = mox.Mox() self.mox = mox.Mox()
self.stubs = stubout.StubOutForTesting() self.stubs = stubout.StubOutForTesting()
self.addCleanup(FLAGS.reset) self.addCleanup(CONF.reset)
self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.mox.UnsetStubs)
self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.UnsetAll)
self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.stubs.SmartUnsetAll)
@ -165,7 +167,7 @@ class TestCase(testtools.TestCase):
self.injected = [] self.injected = []
self._services = [] self._services = []
FLAGS.set_override('fatal_exception_format_errors', True) CONF.set_override('fatal_exception_format_errors', True)
def tearDown(self): def tearDown(self):
"""Runs after each test method to tear down test environment.""" """Runs after each test method to tear down test environment."""
@ -192,9 +194,9 @@ class TestCase(testtools.TestCase):
super(TestCase, self).tearDown() super(TestCase, self).tearDown()
def flags(self, **kw): def flags(self, **kw):
"""Override flag variables for a test.""" """Override CONF variables for a test."""
for k, v in kw.iteritems(): for k, v in kw.iteritems():
FLAGS.set_override(k, v) CONF.set_override(k, v)
def start_service(self, name, host=None, **kwargs): def start_service(self, name, host=None, **kwargs):
host = host and host or uuid.uuid4().hex host = host and host or uuid.uuid4().hex

View File

@ -0,0 +1,48 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# 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 oslo.config import cfg
CONF = cfg.CONF
CONF.import_opt('iscsi_num_targets', 'cinder.volume.drivers.lvm')
CONF.import_opt('policy_file', 'cinder.policy')
CONF.import_opt('volume_driver', 'cinder.volume.manager')
CONF.import_opt('xiv_proxy', 'cinder.volume.drivers.xiv')
CONF.import_opt('backup_service', 'cinder.backup.manager')
def_vol_type = 'fake_vol_type'
def set_defaults(conf):
conf.set_default('default_volume_type', def_vol_type)
conf.set_default('volume_driver',
'cinder.tests.fake_driver.FakeISCSIDriver')
conf.set_default('iscsi_helper', 'fake')
conf.set_default('connection_type', 'fake')
conf.set_default('fake_rabbit', True)
conf.set_default('rpc_backend', 'cinder.openstack.common.rpc.impl_fake')
conf.set_default('iscsi_num_targets', 8)
conf.set_default('verbose', True)
conf.set_default('connection', 'sqlite://', group='database')
conf.set_default('sqlite_synchronous', False)
conf.set_default('policy_file', 'cinder/tests/policy.json')
conf.set_default('xiv_proxy', 'cinder.tests.test_xiv.XIVFakeProxyDriver')
conf.set_default('backup_service', 'cinder.tests.backup.fake_service')

View File

@ -21,4 +21,4 @@ from oslo.config import cfg
CONF = cfg.CONF CONF = cfg.CONF
CONF.register_opt(cfg.IntOpt('answer', default=42, help='test flag')) CONF.register_opt(cfg.IntOpt('answer', default=42, help='test conf'))

View File

@ -21,4 +21,4 @@ from oslo.config import cfg
CONF = cfg.CONF CONF = cfg.CONF
CONF.register_opt(cfg.IntOpt('runtime_answer', default=54, help='test flag')) CONF.register_opt(cfg.IntOpt('runtime_answer', default=54, help='test conf'))

84
cinder/tests/test_conf.py Normal file
View File

@ -0,0 +1,84 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2011 Red Hat, 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.
from oslo.config import cfg
from cinder import test
CONF = cfg.CONF
CONF.register_opt(cfg.StrOpt('conf_unittest',
default='foo',
help='for testing purposes only'))
class ConfigTestCase(test.TestCase):
def setUp(self):
super(ConfigTestCase, self).setUp()
def test_declare(self):
self.assert_('answer' not in CONF)
CONF.import_opt('answer', 'cinder.tests.declare_conf')
self.assert_('answer' in CONF)
self.assertEqual(CONF.answer, 42)
# Make sure we don't overwrite anything
CONF.set_override('answer', 256)
self.assertEqual(CONF.answer, 256)
CONF.import_opt('answer', 'cinder.tests.declare_conf')
self.assertEqual(CONF.answer, 256)
def test_runtime_and_unknown_conf(self):
self.assert_('runtime_answer' not in CONF)
import cinder.tests.runtime_conf
self.assert_('runtime_answer' in CONF)
self.assertEqual(CONF.runtime_answer, 54)
def test_long_vs_short_conf(self):
CONF.clear()
CONF.register_cli_opt(cfg.StrOpt('duplicate_answer_long',
default='val',
help='desc'))
CONF.register_cli_opt(cfg.IntOpt('duplicate_answer',
default=50,
help='desc'))
argv = ['--duplicate_answer=60']
CONF(argv, default_config_files=[])
self.assertEqual(CONF.duplicate_answer, 60)
self.assertEqual(CONF.duplicate_answer_long, 'val')
def test_conf_leak_left(self):
self.assertEqual(CONF.conf_unittest, 'foo')
self.flags(conf_unittest='bar')
self.assertEqual(CONF.conf_unittest, 'bar')
def test_conf_leak_right(self):
self.assertEqual(CONF.conf_unittest, 'foo')
self.flags(conf_unittest='bar')
self.assertEqual(CONF.conf_unittest, 'bar')
def test_conf_overrides(self):
self.assertEqual(CONF.conf_unittest, 'foo')
self.flags(conf_unittest='bar')
self.assertEqual(CONF.conf_unittest, 'bar')
CONF.reset()
self.assertEqual(CONF.conf_unittest, 'foo')

View File

@ -1,83 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2011 Red Hat, 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.
from oslo.config import cfg
from cinder import flags
from cinder import test
FLAGS = flags.FLAGS
FLAGS.register_opt(cfg.StrOpt('flags_unittest',
default='foo',
help='for testing purposes only'))
class FlagsTestCase(test.TestCase):
def setUp(self):
super(FlagsTestCase, self).setUp()
def test_declare(self):
self.assert_('answer' not in FLAGS)
flags.DECLARE('answer', 'cinder.tests.declare_flags')
self.assert_('answer' in FLAGS)
self.assertEqual(FLAGS.answer, 42)
# Make sure we don't overwrite anything
FLAGS.set_override('answer', 256)
self.assertEqual(FLAGS.answer, 256)
flags.DECLARE('answer', 'cinder.tests.declare_flags')
self.assertEqual(FLAGS.answer, 256)
def test_runtime_and_unknown_flags(self):
self.assert_('runtime_answer' not in FLAGS)
import cinder.tests.runtime_flags
self.assert_('runtime_answer' in FLAGS)
self.assertEqual(FLAGS.runtime_answer, 54)
def test_long_vs_short_flags(self):
FLAGS.clear()
FLAGS.register_cli_opt(cfg.StrOpt('duplicate_answer_long',
default='val',
help='desc'))
FLAGS.register_cli_opt(cfg.IntOpt('duplicate_answer',
default=50,
help='desc'))
argv = ['flags_test', '--duplicate_answer=60']
flags.parse_args(argv, default_config_files=[])
self.assertEqual(FLAGS.duplicate_answer, 60)
self.assertEqual(FLAGS.duplicate_answer_long, 'val')
def test_flag_leak_left(self):
self.assertEqual(FLAGS.flags_unittest, 'foo')
self.flags(flags_unittest='bar')
self.assertEqual(FLAGS.flags_unittest, 'bar')
def test_flag_leak_right(self):
self.assertEqual(FLAGS.flags_unittest, 'foo')
self.flags(flags_unittest='bar')
self.assertEqual(FLAGS.flags_unittest, 'bar')
def test_flag_overrides(self):
self.assertEqual(FLAGS.flags_unittest, 'foo')
self.flags(flags_unittest='bar')
self.assertEqual(FLAGS.flags_unittest, 'bar')
FLAGS.reset()
self.assertEqual(FLAGS.flags_unittest, 'foo')

View File

@ -41,7 +41,7 @@ from cinder.openstack.common import rpc
import cinder.policy import cinder.policy
from cinder import quota from cinder import quota
from cinder import test from cinder import test
from cinder.tests import fake_flags from cinder.tests import conf_fixture
from cinder.tests.image import fake as fake_image from cinder.tests.image import fake as fake_image
from cinder.volume import configuration as conf from cinder.volume import configuration as conf
from cinder.volume import driver from cinder.volume import driver
@ -266,7 +266,7 @@ class VolumeTestCase(test.TestCase):
self.assertEquals(volume['volume_type_id'], None) self.assertEquals(volume['volume_type_id'], None)
# Create default volume type # Create default volume type
vol_type = fake_flags.def_vol_type vol_type = conf_fixture.def_vol_type
db.volume_type_create(context.get_admin_context(), db.volume_type_create(context.get_admin_context(),
dict(name=vol_type, extra_specs={})) dict(name=vol_type, extra_specs={}))

View File

@ -26,7 +26,7 @@ from cinder.db.sqlalchemy import models
from cinder import exception from cinder import exception
from cinder.openstack.common import log as logging from cinder.openstack.common import log as logging
from cinder import test from cinder import test
from cinder.tests import fake_flags from cinder.tests import conf_fixture
from cinder.volume import volume_types from cinder.volume import volume_types
@ -84,11 +84,11 @@ class VolumeTypeTestCase(test.TestCase):
def test_get_default_volume_type(self): def test_get_default_volume_type(self):
"""Ensures default volume type can be retrieved.""" """Ensures default volume type can be retrieved."""
type_ref = volume_types.create(self.ctxt, type_ref = volume_types.create(self.ctxt,
fake_flags.def_vol_type, conf_fixture.def_vol_type,
{}) {})
default_vol_type = volume_types.get_default_volume_type() default_vol_type = volume_types.get_default_volume_type()
self.assertEqual(default_vol_type.get('name'), self.assertEqual(default_vol_type.get('name'),
fake_flags.def_vol_type) conf_fixture.def_vol_type)
def test_default_volume_type_missing_in_db(self): def test_default_volume_type_missing_in_db(self):
"""Ensures proper exception raised if default volume type """Ensures proper exception raised if default volume type

View File

@ -16,8 +16,12 @@
# Importing full names to not pollute the namespace and cause possible # Importing full names to not pollute the namespace and cause possible
# collisions with use of 'from cinder.transfer import <foo>' elsewhere. # collisions with use of 'from cinder.transfer import <foo>' elsewhere.
import cinder.flags
from oslo.config import cfg
import cinder.openstack.common.importutils import cinder.openstack.common.importutils
API = cinder.openstack.common.importutils.import_class(
cinder.flags.FLAGS.transfer_api_class) CONF = cfg.CONF
API = cinder.openstack.common.importutils.import_class(CONF.transfer_api_class)

View File

@ -18,7 +18,13 @@
# Importing full names to not pollute the namespace and cause possible # Importing full names to not pollute the namespace and cause possible
# collisions with use of 'from cinder.volume import <foo>' elsewhere. # collisions with use of 'from cinder.volume import <foo>' elsewhere.
import cinder.flags as flags
from oslo.config import cfg
import cinder.openstack.common.importutils as import_utils import cinder.openstack.common.importutils as import_utils
API = import_utils.import_class(flags.FLAGS.volume_api_class)
CONF = cfg.CONF
API = import_utils.import_class(CONF.volume_api_class)

View File

@ -52,10 +52,10 @@ The :mod:`cinder.exception` Module
:show-inheritance: :show-inheritance:
The :mod:`cinder.flags` Module The :mod:`cinder.common.config` Module
------------------------------ ------------------------------
.. automodule:: cinder.flags .. automodule:: cinder.common.config
:noindex: :noindex:
:members: :members:
:undoc-members: :undoc-members:
@ -135,30 +135,20 @@ The :mod:`cinder.wsgi` Module
Tests Tests
----- -----
The :mod:`declare_flags` Module The :mod:`declare_conf` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: cinder.tests.declare_flags .. automodule:: cinder.tests.declare_conf
:noindex: :noindex:
:members: :members:
:undoc-members: :undoc-members:
:show-inheritance: :show-inheritance:
The :mod:`fake_flags` Module The :mod:`conf_fixture` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: cinder.tests.fake_flags .. automodule:: cinder.tests.conf_fixture
:noindex:
:members:
:undoc-members:
:show-inheritance:
The :mod:`flags_unittest` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: cinder.tests.flags_unittest
:noindex: :noindex:
:members: :members:
:undoc-members: :undoc-members:
@ -175,16 +165,6 @@ The :mod:`process_unittest` Module
:show-inheritance: :show-inheritance:
The :mod:`real_flags` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: cinder.tests.real_flags
:noindex:
:members:
:undoc-members:
:show-inheritance:
The :mod:`rpc_unittest` Module The :mod:`rpc_unittest` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -195,10 +175,10 @@ The :mod:`rpc_unittest` Module
:show-inheritance: :show-inheritance:
The :mod:`runtime_flags` Module The :mod:`runtime_conf` Module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: cinder.tests.runtime_flags .. automodule:: cinder.tests.runtime_conf
:noindex: :noindex:
:members: :members:
:undoc-members: :undoc-members:

View File

@ -139,9 +139,9 @@ Gotchas
If you are running the unit tests from a shared folder, you may see tests start If you are running the unit tests from a shared folder, you may see tests start
to fail or stop completely as a result of Python lockfile issues [#f4]_. You to fail or stop completely as a result of Python lockfile issues [#f4]_. You
can get around this by manually setting or updating the following line in can get around this by manually setting or updating the following line in
``cinder/tests/fake_flags.py``:: ``cinder/tests/conf_fixture.py``::
FLAGS['lock_path'].SetDefault('/tmp') CONF['lock_path'].SetDefault('/tmp')
Note that you may use any location (not just ``/tmp``!) as long as it is not Note that you may use any location (not just ``/tmp``!) as long as it is not
a shared folder. a shared folder.