From 3f24fee2188e0a54bab6f710a8c223babfff2b21 Mon Sep 17 00:00:00 2001 From: "Andrei V. Ostapenko" Date: Sat, 5 Oct 2013 13:58:24 +0300 Subject: [PATCH] Removing deprecated using of flags module from project Moving file flags.py to manila/common/config.py, replacing FLAGS by CONF. Rename modules fake_flags to conf_fixture, test_flags to test_conf, declare_flags to declare_conf, runtime_flags to runtime_conf like it was done in cinder, nova, glance etc. Implement bp: use-oslo-conf Change-Id: I38d869123e5e706d3b06f1844b97ead05e22668f --- bin/manila-all | 9 +- bin/manila-api | 9 +- bin/manila-clear-rabbit-queues | 17 ++-- bin/manila-manage | 25 +++--- bin/manila-scheduler | 10 ++- bin/manila-share | 16 ++-- doc/source/devref/manila.rst | 12 +-- doc/source/devref/unit_tests.rst | 2 +- etc/manila/manila.conf.sample | 2 +- manila/api/__init__.py | 10 +-- manila/api/common.py | 14 ++-- manila/api/contrib/__init__.py | 7 +- manila/api/extensions.py | 7 +- manila/api/middleware/auth.py | 16 ++-- manila/api/middleware/sizelimit.py | 10 +-- manila/api/versions.py | 9 +- manila/{flags.py => common/config.py} | 30 ++----- manila/db/api.py | 6 +- manila/db/base.py | 8 +- manila/db/sqlalchemy/api.py | 8 +- .../migrate_repo/versions/001_manila_init.py | 5 +- manila/db/sqlalchemy/migration.py | 6 +- manila/db/sqlalchemy/models.py | 13 +-- manila/db/sqlalchemy/session.py | 22 ++--- manila/exception.py | 8 +- manila/image/glance.py | 21 ++--- manila/image/image_utils.py | 14 ++-- manila/manager.py | 11 +-- manila/policy.py | 10 +-- manila/quota.py | 15 ++-- manila/scheduler/chance.py | 7 +- manila/scheduler/driver.py | 8 +- manila/scheduler/filter_scheduler.py | 7 +- manila/scheduler/host_manager.py | 12 +-- manila/scheduler/manager.py | 8 +- manila/scheduler/rpcapi.py | 7 +- manila/scheduler/scheduler_options.py | 8 +- manila/scheduler/simple.py | 10 +-- manila/scheduler/weights/capacity.py | 8 +- manila/service.py | 44 +++++----- manila/share/__init__.py | 9 +- manila/share/api.py | 7 +- manila/share/configuration.py | 11 ++- manila/share/driver.py | 5 +- manila/share/drivers/lvm.py | 5 +- manila/share/drivers/netapp.py | 5 +- manila/share/manager.py | 5 +- manila/share/rpcapi.py | 6 +- manila/test.py | 20 ++--- manila/tests/__init__.py | 25 +++--- .../tests/api/contrib/test_share_actions.py | 5 +- manila/tests/api/middleware/test_sizelimit.py | 8 +- manila/tests/api/test_extensions.py | 7 +- manila/tests/api/test_router.py | 5 +- .../tests/{fake_flags.py => conf_fixture.py} | 6 +- .../{declare_flags.py => declare_conf.py} | 5 +- manila/tests/fake_utils.py | 1 - manila/tests/image/fake.py | 5 +- manila/tests/image/test_glance.py | 7 +- manila/tests/integrated/integrated_helpers.py | 6 +- manila/tests/integrated/test_extensions.py | 7 +- .../{runtime_flags.py => runtime_conf.py} | 5 +- manila/tests/scheduler/test_host_manager.py | 7 +- manila/tests/scheduler/test_rpcapi.py | 7 +- manila/tests/scheduler/test_scheduler.py | 5 +- manila/tests/test_conf.py | 83 +++++++++++++++++++ manila/tests/test_flags.py | 83 ------------------- manila/tests/test_policy.py | 9 +- manila/tests/test_quota.py | 7 +- manila/tests/test_service.py | 5 +- manila/tests/test_share.py | 13 +-- manila/tests/test_share_lvm.py | 37 +++++---- manila/tests/test_share_netapp.py | 6 +- manila/tests/test_share_rpcapi.py | 9 +- manila/tests/test_utils.py | 7 +- manila/tests/utils.py | 2 - manila/tests/windows/windowsutils.py | 5 +- manila/utils.py | 35 ++++---- manila/wsgi.py | 6 +- 79 files changed, 494 insertions(+), 468 deletions(-) rename manila/{flags.py => common/config.py} (92%) rename manila/tests/{fake_flags.py => conf_fixture.py} (93%) rename manila/tests/{declare_flags.py => declare_conf.py} (87%) rename manila/tests/{runtime_flags.py => runtime_conf.py} (86%) create mode 100644 manila/tests/test_conf.py delete mode 100644 manila/tests/test_flags.py diff --git a/bin/manila-all b/bin/manila-all index 9bcb8a9584..923473b81b 100755 --- a/bin/manila-all +++ b/bin/manila-all @@ -33,7 +33,7 @@ eventlet.monkey_patch() import os import sys - +from oslo.config import cfg possible_topdir = os.path.normpath(os.path.join(os.path.abspath( sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, "manila", "__init__.py")): @@ -42,14 +42,17 @@ if os.path.exists(os.path.join(possible_topdir, "manila", "__init__.py")): from manila.openstack.common import gettextutils gettextutils.install('manila') -from manila import flags +from manila.common import config # Need to register global_opts from manila.openstack.common import log as logging from manila import service from manila import utils +from manila import version +CONF = cfg.CONF if __name__ == '__main__': - flags.parse_args(sys.argv) + CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") LOG = logging.getLogger('manila.all') diff --git a/bin/manila-api b/bin/manila-api index 4b0538267f..172b18b60c 100755 --- a/bin/manila-api +++ b/bin/manila-api @@ -29,6 +29,7 @@ eventlet.monkey_patch() import os import sys +from oslo.config import cfg possible_topdir = os.path.normpath(os.path.join(os.path.abspath( sys.argv[0]), os.pardir, os.pardir)) @@ -38,13 +39,17 @@ if os.path.exists(os.path.join(possible_topdir, "manila", "__init__.py")): from manila.openstack.common import gettextutils gettextutils.install('manila') -from manila import flags +from manila.common import config # Need to register global_opts from manila.openstack.common import log as logging from manila import service from manila import utils +from manila import version + +CONF = cfg.CONF if __name__ == '__main__': - flags.parse_args(sys.argv) + CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") utils.monkey_patch() server = service.WSGIService('osapi_share') diff --git a/bin/manila-clear-rabbit-queues b/bin/manila-clear-rabbit-queues index 31fd383205..4d3cab1352 100755 --- a/bin/manila-clear-rabbit-queues +++ b/bin/manila-clear-rabbit-queues @@ -28,6 +28,7 @@ import os import sys import time +from oslo.config import cfg # If ../manila/__init__.py exists, add ../ to Python search path, so that # 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]), @@ -39,21 +40,20 @@ if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'manila', '__init__.py')): from manila.openstack.common import gettextutils gettextutils.install('manila') -from oslo.config import cfg - +from manila.common import config # Need to register global_opts from manila import context from manila import exception -from manila import flags from manila.openstack.common import log as logging from manila.openstack.common import rpc +from manila import version delete_exchange_opt = \ cfg.BoolOpt('delete_exchange', default=False, help='delete manila exchange too.') -FLAGS = flags.FLAGS -FLAGS.register_cli_opt(delete_exchange_opt) +CONF = cfg.CONF +CONF.register_cli_opt(delete_exchange_opt) def delete_exchange(exch): @@ -69,8 +69,9 @@ def delete_queues(queues): x.queue_delete(q) if __name__ == '__main__': - args = flags.parse_args(sys.argv) + args = CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") delete_queues(args[1:]) - if FLAGS.delete_exchange: - delete_exchange(FLAGS.control_exchange) + if CONF.delete_exchange: + delete_exchange(CONF.control_exchange) diff --git a/bin/manila-manage b/bin/manila-manage index f89cceab8e..1e9e7ff963 100755 --- a/bin/manila-manage +++ b/bin/manila-manage @@ -76,18 +76,18 @@ gettextutils.install('manila') from oslo.config import cfg +from manila.common import config # Need to register global_opts from manila import context from manila import db from manila.db import migration from manila import exception -from manila import flags from manila.openstack.common import log as logging from manila.openstack.common import rpc from manila.openstack.common import uuidutils from manila import utils from manila import version -FLAGS = flags.FLAGS +CONF = cfg.CONF # Decorators for actions @@ -243,7 +243,7 @@ class ConfigCommands(object): pass def list(self): - for key, value in FLAGS.iteritems(): + for key, value in CONF.iteritems(): if value is not None: print '%s = %s' % (key, value) @@ -254,10 +254,10 @@ class GetLogCommands(object): def errors(self): """Get all of the errors from the log files.""" error_found = 0 - if FLAGS.log_dir: - logs = [x for x in os.listdir(FLAGS.log_dir) if x.endswith('.log')] + if CONF.log_dir: + logs = [x for x in os.listdir(CONF.log_dir) if x.endswith('.log')] 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.reverse() print_name = 0 @@ -373,7 +373,7 @@ category_opt = cfg.SubCommandOpt('category', def get_arg_string(args): arg = None if args[0] == '-': - # (Note)zhiteng: args starts with FLAGS.oparser.prefix_chars + # (Note)zhiteng: args starts with CONF.oparser.prefix_chars # is optional args. Notice that cfg module takes care of # actual ArgParser so prefix_chars is always '-'. if args[1] == '-': @@ -391,14 +391,14 @@ def fetch_func_args(func): fn_args = [] for args, kwargs in getattr(func, 'args', []): arg = get_arg_string(args[0]) - fn_args.append(getattr(FLAGS.category, arg)) + fn_args.append(getattr(CONF.category, arg)) return fn_args def main(): """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] if len(sys.argv) < 2: print(_("\nOpenStack manila version: %(version)s\n") % @@ -410,10 +410,11 @@ def main(): sys.exit(2) try: - flags.parse_args(sys.argv) + CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") 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): st = os.stat(cfgfile) print _("Could not read %s. Re-running with sudo") % cfgfile @@ -425,7 +426,7 @@ def main(): print _('Please re-run manila-manage as root.') sys.exit(2) - fn = FLAGS.category.action_fn + fn = CONF.category.action_fn fn_args = fetch_func_args(fn) fn(*fn_args) diff --git a/bin/manila-scheduler b/bin/manila-scheduler index 1a15ff7633..0ae1136ff6 100755 --- a/bin/manila-scheduler +++ b/bin/manila-scheduler @@ -25,6 +25,8 @@ eventlet.monkey_patch() import os import sys +from oslo.config import cfg + # If ../manila/__init__.py exists, add ../ to Python search path, so that # 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]), @@ -36,13 +38,17 @@ if os.path.exists(os.path.join(possible_topdir, 'manila', '__init__.py')): from manila.openstack.common import gettextutils gettextutils.install('manila') -from manila import flags +from manila.common import config # Need to register global_opts from manila.openstack.common import log as logging from manila import service from manila import utils +from manila import version + +CONF = cfg.CONF if __name__ == '__main__': - flags.parse_args(sys.argv) + CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") utils.monkey_patch() server = service.Service.create(binary='manila-scheduler') diff --git a/bin/manila-share b/bin/manila-share index 2f73b0b340..647f38b6f1 100755 --- a/bin/manila-share +++ b/bin/manila-share @@ -24,6 +24,8 @@ eventlet.monkey_patch() import os import sys +from oslo.config import cfg + # If ../manila/__init__.py exists, add ../ to Python search path, so that # 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]), @@ -35,21 +37,23 @@ if os.path.exists(os.path.join(possible_topdir, 'manila', '__init__.py')): from manila.openstack.common import gettextutils gettextutils.install('manila') -from manila import flags +from manila.common import config # Need to register global_opts from manila.openstack.common import log as logging from manila import service from manila import utils +from manila import version -FLAGS = flags.FLAGS +CONF = cfg.CONF if __name__ == '__main__': - flags.parse_args(sys.argv) + args = CONF(sys.argv[1:], project='manila', + version=version.version_string()) logging.setup("manila") utils.monkey_patch() launcher = service.ProcessLauncher() - if FLAGS.enabled_share_backends: - for backend in FLAGS.enabled_share_backends: - host = "%s@%s" % (FLAGS.host, backend) + if CONF.enabled_share_backends: + for backend in CONF.enabled_share_backends: + host = "%s@%s" % (CONF.host, backend) server = service.Service.create( host=host, service_name=backend) diff --git a/doc/source/devref/manila.rst b/doc/source/devref/manila.rst index 2c3bed1e36..941b0bb407 100644 --- a/doc/source/devref/manila.rst +++ b/doc/source/devref/manila.rst @@ -135,20 +135,20 @@ The :mod:`manila.wsgi` Module Tests ----- -The :mod:`declare_flags` Module +The :mod:`declare_conf` Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. automodule:: manila.tests.declare_flags +.. automodule:: manila.tests.declare_conf :noindex: :members: :undoc-members: :show-inheritance: -The :mod:`fake_flags` Module +The :mod:`conf_fixture` Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. automodule:: manila.tests.fake_flags +.. automodule:: manila.tests.conf_fixture :noindex: :members: :undoc-members: @@ -195,10 +195,10 @@ The :mod:`rpc_unittest` Module :show-inheritance: -The :mod:`runtime_flags` Module +The :mod:`runtime_conf` Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. automodule:: manila.tests.runtime_flags +.. automodule:: manila.tests.runtime_conf :noindex: :members: :undoc-members: diff --git a/doc/source/devref/unit_tests.rst b/doc/source/devref/unit_tests.rst index 8380f9463f..e287fcb4a4 100644 --- a/doc/source/devref/unit_tests.rst +++ b/doc/source/devref/unit_tests.rst @@ -139,7 +139,7 @@ Gotchas 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 can get around this by manually setting or updating the following line in -``manila/tests/fake_flags.py``:: +``manila/tests/conf_fixture.py``:: FLAGS['lock_path'].SetDefault('/tmp') diff --git a/etc/manila/manila.conf.sample b/etc/manila/manila.conf.sample index 81edd20ffd..3190eeeb3a 100644 --- a/etc/manila/manila.conf.sample +++ b/etc/manila/manila.conf.sample @@ -13,7 +13,7 @@ # -# Options defined in manila.flags +# Options defined in manila.common.config # # Virtualization api connection type : libvirt, xenapi, or diff --git a/manila/api/__init__.py b/manila/api/__init__.py index 3374ac5e8d..36da84d5a9 100644 --- a/manila/api/__init__.py +++ b/manila/api/__init__.py @@ -16,17 +16,17 @@ # License for the specific language governing permissions and limitations # under the License. +from oslo.config import cfg + import paste.urlmap -from manila import flags - -FLAGS = flags.FLAGS +CONF = cfg.CONF def root_app_factory(loader, global_conf, **local_conf): - if not FLAGS.enable_v1_api: + if not CONF.enable_v1_api: del local_conf['/v1'] - if not FLAGS.enable_v2_api: + if not CONF.enable_v2_api: del local_conf['/v2'] return paste.urlmap.urlmap_factory(loader, global_conf, **local_conf) diff --git a/manila/api/common.py b/manila/api/common.py index 3e9d0fdbc8..e5c352fa29 100644 --- a/manila/api/common.py +++ b/manila/api/common.py @@ -23,13 +23,13 @@ import webob from manila.api.openstack import wsgi from manila.api import xmlutil -from manila import flags from manila.openstack.common import log as logging from manila import utils +from oslo.config import cfg LOG = logging.getLogger(__name__) -FLAGS = flags.FLAGS +CONF = cfg.CONF XML_NS_V1 = 'http://docs.openstack.org/volume/api/v1' @@ -73,7 +73,7 @@ def _get_marker_param(request): return request.GET['marker'] -def limited(items, request, max_limit=FLAGS.osapi_max_limit): +def limited(items, request, max_limit=CONF.osapi_max_limit): """Return a slice of items according to requested offset and limit. :param items: A sliceable entity @@ -110,7 +110,7 @@ def limited(items, request, max_limit=FLAGS.osapi_max_limit): return items[offset:range_end] -def limited_by_marker(items, request, max_limit=FLAGS.osapi_max_limit): +def limited_by_marker(items, request, max_limit=CONF.osapi_max_limit): """Return a slice of items according to the requested marker and limit.""" params = get_pagination_params(request) @@ -192,7 +192,7 @@ class ViewBuilder(object): params = request.params.copy() params["marker"] = identifier prefix = self._update_link_prefix(request.application_url, - FLAGS.osapi_share_base_URL) + CONF.osapi_share_base_URL) url = os.path.join(prefix, request.environ["manila.context"].project_id, self._collection_name) @@ -201,7 +201,7 @@ class ViewBuilder(object): def _get_href_link(self, request, identifier): """Return an href string pointing to this object.""" prefix = self._update_link_prefix(request.application_url, - FLAGS.osapi_share_base_URL) + CONF.osapi_share_base_URL) return os.path.join(prefix, request.environ["manila.context"].project_id, self._collection_name, @@ -211,7 +211,7 @@ class ViewBuilder(object): """Create a URL that refers to a specific resource.""" base_url = remove_version_from_href(request.application_url) base_url = self._update_link_prefix(base_url, - FLAGS.osapi_share_base_URL) + CONF.osapi_share_base_URL) return os.path.join(base_url, request.environ["manila.context"].project_id, self._collection_name, diff --git a/manila/api/contrib/__init__.py b/manila/api/contrib/__init__.py index 735a53fdb2..218b547f8e 100644 --- a/manila/api/contrib/__init__.py +++ b/manila/api/contrib/__init__.py @@ -22,11 +22,12 @@ It can't be called 'extensions' because that causes namespacing problems. """ from manila.api import extensions -from manila import flags + from manila.openstack.common import log as logging +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -36,4 +37,4 @@ def standard_extensions(ext_mgr): def select_extensions(ext_mgr): extensions.load_standard_extensions(ext_mgr, LOG, __path__, __package__, - FLAGS.osapi_share_ext_list) + CONF.osapi_share_ext_list) diff --git a/manila/api/extensions.py b/manila/api/extensions.py index af3a078f6f..a4ac36fdcb 100644 --- a/manila/api/extensions.py +++ b/manila/api/extensions.py @@ -25,15 +25,16 @@ import manila.api.openstack from manila.api.openstack import wsgi from manila.api import xmlutil from manila import exception -from manila import flags + from manila.openstack.common import exception as common_exception from manila.openstack.common import importutils from manila.openstack.common import log as logging import manila.policy +from oslo.config import cfg LOG = logging.getLogger(__name__) -FLAGS = flags.FLAGS +CONF = cfg.CONF class ExtensionDescriptor(object): @@ -183,7 +184,7 @@ class ExtensionManager(object): def __init__(self): LOG.audit(_('Initializing extension manager.')) - self.cls_list = FLAGS.osapi_share_extension + self.cls_list = CONF.osapi_share_extension self.extensions = {} self._load_extensions() diff --git a/manila/api/middleware/auth.py b/manila/api/middleware/auth.py index 9475e0bed1..07b3f42796 100644 --- a/manila/api/middleware/auth.py +++ b/manila/api/middleware/auth.py @@ -26,7 +26,7 @@ import webob.exc from manila.api.openstack import wsgi from manila import context -from manila import flags + from manila.openstack.common import log as logging from manila import wsgi as base_wsgi @@ -36,16 +36,16 @@ use_forwarded_for_opt = cfg.BoolOpt( help='Treat X-Forwarded-For as the canonical remote address. ' 'Only enable this if you have a sanitizing proxy.') -FLAGS = flags.FLAGS -FLAGS.register_opt(use_forwarded_for_opt) +CONF = cfg.CONF +CONF.register_opt(use_forwarded_for_opt) LOG = logging.getLogger(__name__) def pipeline_factory(loader, global_conf, **local_conf): """A paste pipeline replica that keys off of auth_strategy.""" - pipeline = local_conf[FLAGS.auth_strategy] - if not FLAGS.api_rate_limit: - limit_name = FLAGS.auth_strategy + '_nolimit' + pipeline = local_conf[CONF.auth_strategy] + if not CONF.api_rate_limit: + limit_name = CONF.auth_strategy + '_nolimit' pipeline = local_conf.get(limit_name, pipeline) pipeline = pipeline.split() filters = [loader.get_filter(n) for n in pipeline[:-1]] @@ -94,7 +94,7 @@ class ManilaKeystoneContext(base_wsgi.Middleware): # Build a context, including the auth_token... remote_address = req.remote_addr - if FLAGS.use_forwarded_for: + if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) ctx = context.RequestContext(user_id, project_id, @@ -129,7 +129,7 @@ class NoAuthMiddleware(base_wsgi.Middleware): user_id, _sep, project_id = token.partition(':') project_id = project_id or user_id remote_address = getattr(req, 'remote_address', '127.0.0.1') - if FLAGS.use_forwarded_for: + if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) ctx = context.RequestContext(user_id, project_id, diff --git a/manila/api/middleware/sizelimit.py b/manila/api/middleware/sizelimit.py index ca7a3b63a8..420cf44670 100644 --- a/manila/api/middleware/sizelimit.py +++ b/manila/api/middleware/sizelimit.py @@ -22,7 +22,7 @@ from oslo.config import cfg import webob.dec import webob.exc -from manila import flags + from manila.openstack.common import log as logging from manila import wsgi @@ -31,8 +31,8 @@ max_request_body_size_opt = cfg.IntOpt('osapi_max_request_body_size', default=114688, help='Max size for body of a request') -FLAGS = flags.FLAGS -FLAGS.register_opt(max_request_body_size_opt) +CONF = cfg.CONF +CONF.register_opt(max_request_body_size_opt) LOG = logging.getLogger(__name__) @@ -73,11 +73,11 @@ class RequestBodySizeLimiter(wsgi.Middleware): @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): - if req.content_length > FLAGS.osapi_max_request_body_size: + if req.content_length > CONF.osapi_max_request_body_size: msg = _("Request is too large.") raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg) if req.content_length is None and req.is_body_readable: limiter = LimitingReader(req.body_file, - FLAGS.osapi_max_request_body_size) + CONF.osapi_max_request_body_size) req.body_file = limiter return self.application diff --git a/manila/api/versions.py b/manila/api/versions.py index 5e186559b4..4603b475e5 100644 --- a/manila/api/versions.py +++ b/manila/api/versions.py @@ -21,9 +21,10 @@ from lxml import etree from manila.api.openstack import wsgi from manila.api.views import versions as views_versions from manila.api import xmlutil -from manila import flags -FLAGS = flags.FLAGS +from oslo.config import cfg + +CONF = cfg.CONF _KNOWN_VERSIONS = { @@ -94,9 +95,9 @@ _KNOWN_VERSIONS = { def get_supported_versions(): versions = {} - if FLAGS.enable_v1_api: + if CONF.enable_v1_api: versions['v1.0'] = _KNOWN_VERSIONS['v1.0'] - if FLAGS.enable_v2_api: + if CONF.enable_v2_api: versions['v2.0'] = _KNOWN_VERSIONS['v2.0'] return versions diff --git a/manila/flags.py b/manila/common/config.py similarity index 92% rename from manila/flags.py rename to manila/common/config.py index 422a0093b7..cee462c175 100644 --- a/manila/flags.py +++ b/manila/common/config.py @@ -28,30 +28,11 @@ stepping stone. import os import socket -import sys from oslo.config import cfg -from manila import version -FLAGS = cfg.CONF - - -def parse_args(argv, default_config_files=None): - FLAGS(argv[1:], project='manila', - 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)) +CONF = cfg.CONF def _get_my_ip(): @@ -92,7 +73,8 @@ core_opts = [ help='File name for the paste.deploy config for manila-api'), cfg.StrOpt('pybasedir', default=os.path.abspath(os.path.join(os.path.dirname(__file__), - '../')), + '..', + '..')), help='Directory where the manila python module is installed'), cfg.StrOpt('bindir', default='$pybasedir/bin', @@ -104,8 +86,8 @@ core_opts = [ debug_opts = [ ] -FLAGS.register_cli_opts(core_opts) -FLAGS.register_cli_opts(debug_opts) +CONF.register_cli_opts(core_opts) +CONF.register_cli_opts(debug_opts) global_opts = [ cfg.StrOpt('my_ip', @@ -237,4 +219,4 @@ global_opts = [ default=False, help='Whether snapshots count against GigaByte quota'), ] -FLAGS.register_opts(global_opts) +CONF.register_opts(global_opts) diff --git a/manila/db/api.py b/manila/db/api.py index f5704d36fc..f34abb2cc8 100644 --- a/manila/db/api.py +++ b/manila/db/api.py @@ -46,7 +46,7 @@ these objects be simple dictionaries. from oslo.config import cfg from manila import exception -from manila import flags + from manila import utils db_opts = [ @@ -65,8 +65,8 @@ db_opts = [ 'names'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(db_opts) +CONF = cfg.CONF +CONF.register_opts(db_opts) IMPL = utils.LazyPluggable('db_backend', sqlalchemy='manila.db.sqlalchemy.api') diff --git a/manila/db/base.py b/manila/db/base.py index dfa8d3e6d9..65fb3c399d 100644 --- a/manila/db/base.py +++ b/manila/db/base.py @@ -20,15 +20,15 @@ from oslo.config import cfg -from manila import flags + from manila.openstack.common import importutils db_driver_opt = cfg.StrOpt('db_driver', default='manila.db', help='driver to use for database access') -FLAGS = flags.FLAGS -FLAGS.register_opt(db_driver_opt) +CONF = cfg.CONF +CONF.register_opt(db_driver_opt) class Base(object): @@ -36,5 +36,5 @@ class Base(object): def __init__(self, db_driver=None): if not db_driver: - db_driver = FLAGS.db_driver + db_driver = CONF.db_driver self.db = importutils.import_module(db_driver) # pylint: disable=C0103 diff --git a/manila/db/sqlalchemy/api.py b/manila/db/sqlalchemy/api.py index 6b2c0daad6..8d457db536 100644 --- a/manila/db/sqlalchemy/api.py +++ b/manila/db/sqlalchemy/api.py @@ -23,6 +23,7 @@ import datetime import uuid import warnings +from oslo.config import cfg from sqlalchemy.exc import IntegrityError from sqlalchemy import or_ from sqlalchemy.orm import joinedload @@ -34,12 +35,11 @@ from manila import db from manila.db.sqlalchemy import models from manila.db.sqlalchemy.session import get_session from manila import exception -from manila import flags from manila.openstack.common import log as logging from manila.openstack.common import timeutils -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -278,7 +278,7 @@ def _service_get_all_topic_subquery(context, session, topic, subq, label): def service_get_all_share_sorted(context): session = get_session() with session.begin(): - topic = FLAGS.share_topic + topic = CONF.share_topic label = 'share_gigabytes' subq = model_query(context, models.Share.host, func.sum(models.Share.size).label(label), @@ -309,7 +309,7 @@ def service_get_by_args(context, host, binary): def service_create(context, values): service_ref = models.Service() service_ref.update(values) - if not FLAGS.enable_new_services: + if not CONF.enable_new_services: service_ref.disabled = True service_ref.save() return service_ref diff --git a/manila/db/sqlalchemy/migrate_repo/versions/001_manila_init.py b/manila/db/sqlalchemy/migrate_repo/versions/001_manila_init.py index 613b324644..29ef526884 100644 --- a/manila/db/sqlalchemy/migrate_repo/versions/001_manila_init.py +++ b/manila/db/sqlalchemy/migrate_repo/versions/001_manila_init.py @@ -14,13 +14,14 @@ # License for the specific language governing permissions and limitations # under the License. +from oslo.config import cfg from sqlalchemy import Boolean, Column, DateTime, ForeignKey from sqlalchemy import Integer, MetaData, String, Table -from manila import flags + from manila.openstack.common import log as logging -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) diff --git a/manila/db/sqlalchemy/migration.py b/manila/db/sqlalchemy/migration.py index 45da0760e9..a0fa5aaddc 100644 --- a/manila/db/sqlalchemy/migration.py +++ b/manila/db/sqlalchemy/migration.py @@ -19,10 +19,12 @@ import distutils.version as dist_version import os +from oslo.config import cfg + from manila.db import migration from manila.db.sqlalchemy.session import get_engine from manila import exception -from manila import flags + from manila.openstack.common import log as logging @@ -61,7 +63,7 @@ from migrate import exceptions as versioning_exceptions from migrate.versioning import api as versioning_api from migrate.versioning.repository import Repository -FLAGS = flags.FLAGS +CONF = cfg.CONF _REPOSITORY = None diff --git a/manila/db/sqlalchemy/models.py b/manila/db/sqlalchemy/models.py index d6571a85bc..9f824d86f3 100644 --- a/manila/db/sqlalchemy/models.py +++ b/manila/db/sqlalchemy/models.py @@ -30,11 +30,12 @@ from sqlalchemy.orm import relationship, backref, object_mapper from manila.db.sqlalchemy.session import get_session from manila import exception -from manila import flags + from manila.openstack.common import timeutils +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF BASE = declarative_base() @@ -216,7 +217,7 @@ class Share(BASE, ManilaBase): @property def name(self): - return FLAGS.share_name_template % self.id + return CONF.share_name_template % self.id id = Column(String(36), primary_key=True) user_id = Column(String(255)) @@ -259,11 +260,11 @@ class ShareSnapshot(BASE, ManilaBase): @property def name(self): - return FLAGS.share_snapshot_name_template % self.id + return CONF.share_snapshot_name_template % self.id @property def share_name(self): - return FLAGS.share_name_template % self.share_id + return CONF.share_name_template % self.share_id id = Column(String(36), primary_key=True) user_id = Column(String(255)) @@ -298,6 +299,6 @@ def register_models(): ShareAccessMapping, ShareSnapshot ) - engine = create_engine(FLAGS.sql_connection, echo=False) + engine = create_engine(CONF.sql_connection, echo=False) for model in models: model.metadata.create_all(engine) diff --git a/manila/db/sqlalchemy/session.py b/manila/db/sqlalchemy/session.py index 7e493d31f8..01228cacb3 100644 --- a/manila/db/sqlalchemy/session.py +++ b/manila/db/sqlalchemy/session.py @@ -20,17 +20,17 @@ import time +from oslo.config import cfg from sqlalchemy.exc import DisconnectionError, OperationalError import sqlalchemy.interfaces import sqlalchemy.orm from sqlalchemy.pool import NullPool, StaticPool import manila.exception -import manila.flags as flags from manila.openstack.common import log as logging -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) _ENGINE = None @@ -89,33 +89,33 @@ def get_engine(): """Return a SQLAlchemy engine.""" global _ENGINE if _ENGINE is None: - connection_dict = sqlalchemy.engine.url.make_url(FLAGS.sql_connection) + connection_dict = sqlalchemy.engine.url.make_url(CONF.sql_connection) engine_args = { - "pool_recycle": FLAGS.sql_idle_timeout, + "pool_recycle": CONF.sql_idle_timeout, "echo": False, 'convert_unicode': True, } # Map our SQL debug level to SQLAlchemy's options - if FLAGS.sql_connection_debug >= 100: + if CONF.sql_connection_debug >= 100: engine_args['echo'] = 'debug' - elif FLAGS.sql_connection_debug >= 50: + elif CONF.sql_connection_debug >= 50: engine_args['echo'] = True if "sqlite" in connection_dict.drivername: engine_args["poolclass"] = NullPool - if FLAGS.sql_connection == "sqlite://": + if CONF.sql_connection == "sqlite://": engine_args["poolclass"] = StaticPool engine_args["connect_args"] = {'check_same_thread': False} - _ENGINE = sqlalchemy.create_engine(FLAGS.sql_connection, **engine_args) + _ENGINE = sqlalchemy.create_engine(CONF.sql_connection, **engine_args) if 'mysql' in connection_dict.drivername: sqlalchemy.event.listen(_ENGINE, 'checkout', ping_listener) elif "sqlite" in connection_dict.drivername: - if not FLAGS.sqlite_synchronous: + if not CONF.sqlite_synchronous: sqlalchemy.event.listen(_ENGINE, 'connect', synchronous_switch_listener) @@ -125,7 +125,7 @@ def get_engine(): if not is_db_connection_error(e.args[0]): raise - remaining = FLAGS.sql_max_retries + remaining = CONF.sql_max_retries if remaining == -1: remaining = 'infinite' while True: @@ -133,7 +133,7 @@ def get_engine(): LOG.warn(msg % remaining) if remaining != 'infinite': remaining -= 1 - time.sleep(FLAGS.sql_retry_interval) + time.sleep(CONF.sql_retry_interval) try: _ENGINE.connect() break diff --git a/manila/exception.py b/manila/exception.py index 12395665c9..95ac8f2cba 100644 --- a/manila/exception.py +++ b/manila/exception.py @@ -27,7 +27,7 @@ SHOULD include dedicated exception logging. from oslo.config import cfg import webob.exc -from manila import flags + from manila.openstack.common import log as logging LOG = logging.getLogger(__name__) @@ -38,8 +38,8 @@ exc_log_opts = [ help='make exception message format errors fatal'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(exc_log_opts) +CONF = cfg.CONF +CONF.register_opts(exc_log_opts) class ConvertedException(webob.exc.WSGIHTTPException): @@ -125,7 +125,7 @@ class ManilaException(Exception): LOG.exception(_('Exception in string format operation')) for name, value in kwargs.iteritems(): LOG.error("%s: %s" % (name, value)) - if FLAGS.fatal_exception_format_errors: + if CONF.fatal_exception_format_errors: raise e else: # at least get the core message out if something happened diff --git a/manila/image/glance.py b/manila/image/glance.py index c8d20b7c66..3e6a5b1e1a 100644 --- a/manila/image/glance.py +++ b/manila/image/glance.py @@ -30,14 +30,15 @@ import glanceclient import glanceclient.exc from manila import exception -from manila import flags + from manila.openstack.common import jsonutils from manila.openstack.common import log as logging from manila.openstack.common import timeutils +from oslo.config import cfg LOG = logging.getLogger(__name__) -FLAGS = flags.FLAGS +CONF = cfg.CONF def _parse_image_ref(image_href): @@ -57,17 +58,17 @@ def _parse_image_ref(image_href): def _create_glance_client(context, host, port, use_ssl, - version=FLAGS.glance_api_version): + version=CONF.glance_api_version): """Instantiate a new glanceclient.Client object""" if version is None: - version = FLAGS.glance_api_version + version = CONF.glance_api_version if use_ssl: scheme = 'https' else: scheme = 'http' params = {} - params['insecure'] = FLAGS.glance_api_insecure - if FLAGS.auth_strategy == 'keystone': + params['insecure'] = CONF.glance_api_insecure + if CONF.auth_strategy == 'keystone': params['token'] = context.auth_token endpoint = '%s://%s:%s' % (scheme, host, port) return glanceclient.Client(str(version), endpoint, **params) @@ -75,12 +76,12 @@ def _create_glance_client(context, host, port, use_ssl, def get_api_servers(): """ - Shuffle a list of FLAGS.glance_api_servers and return an iterator + Shuffle a list of CONF.glance_api_servers and return an iterator that will cycle through the list, looping around to the beginning if necessary. """ api_servers = [] - for api_server in FLAGS.glance_api_servers: + for api_server in CONF.glance_api_servers: if '//' not in api_server: api_server = 'http://' + api_server url = urlparse.urlparse(api_server) @@ -128,7 +129,7 @@ class GlanceClientWrapper(object): def call(self, context, method, *args, **kwargs): """ Call a glance client method. If we get a connection error, - retry the request according to FLAGS.glance_num_retries. + retry the request according to CONF.glance_num_retries. """ version = self.version if version in kwargs: @@ -137,7 +138,7 @@ class GlanceClientWrapper(object): retry_excs = (glanceclient.exc.ServiceUnavailable, glanceclient.exc.InvalidEndpoint, glanceclient.exc.CommunicationError) - num_attempts = 1 + FLAGS.glance_num_retries + num_attempts = 1 + CONF.glance_num_retries for attempt in xrange(1, num_attempts + 1): client = self.client or self._create_onetime_client(context, diff --git a/manila/image/image_utils.py b/manila/image/image_utils.py index 39fe90c195..a8d0d5346c 100644 --- a/manila/image/image_utils.py +++ b/manila/image/image_utils.py @@ -32,7 +32,7 @@ import tempfile from oslo.config import cfg from manila import exception -from manila import flags + from manila.openstack.common import log as logging from manila import utils @@ -42,8 +42,8 @@ image_helper_opt = [cfg.StrOpt('image_conversion_dir', default='/tmp', help='parent dir for tempdir used for image conversion'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(image_helper_opt) +CONF = cfg.CONF +CONF.register_opts(image_helper_opt) class QemuImgInfo(object): @@ -204,15 +204,15 @@ def fetch(context, image_service, image_id, path, _user_id, _project_id): def fetch_to_raw(context, image_service, image_id, dest, user_id=None, project_id=None): - if (FLAGS.image_conversion_dir and not - os.path.exists(FLAGS.image_conversion_dir)): - os.makedirs(FLAGS.image_conversion_dir) + if (CONF.image_conversion_dir and not + os.path.exists(CONF.image_conversion_dir)): + os.makedirs(CONF.image_conversion_dir) # NOTE(avishay): I'm not crazy about creating temp files which may be # large and cause disk full errors which would confuse users. # Unfortunately it seems that you can't pipe to 'qemu-img convert' because # it seeks. Maybe we can think of something for a future version. - fd, tmp = tempfile.mkstemp(dir=FLAGS.image_conversion_dir) + fd, tmp = tempfile.mkstemp(dir=CONF.image_conversion_dir) os.close(fd) with utils.remove_path_on_error(tmp): fetch(context, image_service, image_id, tmp, user_id, project_id) diff --git a/manila/manager.py b/manila/manager.py index 1c37eab8e7..0fd82cf980 100644 --- a/manila/manager.py +++ b/manila/manager.py @@ -53,15 +53,16 @@ This module provides Manager, a base class for managers. """ +from oslo.config import cfg + from manila.db import base -from manila import flags from manila.openstack.common import log as logging from manila.openstack.common.rpc import dispatcher as rpc_dispatcher from manila.scheduler import rpcapi as scheduler_rpcapi from manila import version -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -136,7 +137,7 @@ class Manager(base.Base): def __init__(self, host=None, db_driver=None): if not host: - host = FLAGS.host + host = CONF.host self.host = host super(Manager, self).__init__(db_driver) @@ -184,8 +185,8 @@ class Manager(base.Base): def service_config(self, context): config = {} - for key in FLAGS: - config[key] = FLAGS.get(key, None) + for key in CONF: + config[key] = CONF.get(key, None) return config diff --git a/manila/policy.py b/manila/policy.py index 254afbea84..5a0f08837a 100644 --- a/manila/policy.py +++ b/manila/policy.py @@ -20,7 +20,7 @@ from oslo.config import cfg from manila import exception -from manila import flags + from manila.openstack.common import policy from manila import utils @@ -32,8 +32,8 @@ policy_opts = [ default='default', help=_('Rule checked when requested rule is not found')), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(policy_opts) +CONF = cfg.CONF +CONF.register_opts(policy_opts) _POLICY_PATH = None _POLICY_CACHE = {} @@ -51,13 +51,13 @@ def init(): global _POLICY_PATH global _POLICY_CACHE if not _POLICY_PATH: - _POLICY_PATH = utils.find_config(FLAGS.policy_file) + _POLICY_PATH = utils.find_config(CONF.policy_file) utils.read_cached_file(_POLICY_PATH, _POLICY_CACHE, reload_func=_set_brain) def _set_brain(data): - default_rule = FLAGS.policy_default_rule + default_rule = CONF.policy_default_rule policy.set_brain(policy.HttpBrain.load_json(data, default_rule)) diff --git a/manila/quota.py b/manila/quota.py index 4bfb7affe1..51ab16adf4 100644 --- a/manila/quota.py +++ b/manila/quota.py @@ -24,7 +24,6 @@ from oslo.config import cfg from manila import db from manila import exception -from manila import flags from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.openstack.common import timeutils @@ -55,8 +54,8 @@ quota_opts = [ default='manila.quota.DbQuotaDriver', help='default driver to use for quota checks'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(quota_opts) +CONF = cfg.CONF +CONF.register_opts(quota_opts) class DbQuotaDriver(object): @@ -296,7 +295,7 @@ class DbQuotaDriver(object): # Set up the reservation expiration if expire is None: - expire = FLAGS.reservation_expire + expire = CONF.reservation_expire if isinstance(expire, (int, long)): expire = datetime.timedelta(seconds=expire) if isinstance(expire, datetime.timedelta): @@ -321,7 +320,7 @@ class DbQuotaDriver(object): # session isn't available outside the DBAPI, we # have to do the work there. return db.quota_reserve(context, resources, quotas, deltas, expire, - FLAGS.until_refresh, FLAGS.max_age, + CONF.until_refresh, CONF.max_age, project_id=project_id) def commit(self, context, reservations, project_id=None): @@ -446,7 +445,7 @@ class BaseResource(object): def default(self): """Return the default value of the quota.""" - return FLAGS[self.flag] if self.flag else -1 + return CONF[self.flag] if self.flag else -1 class ReservableResource(BaseResource): @@ -538,7 +537,7 @@ class QuotaEngine(object): """Initialize a Quota object.""" if not quota_driver_class: - quota_driver_class = FLAGS.quota_driver + quota_driver_class = CONF.quota_driver if isinstance(quota_driver_class, basestring): quota_driver_class = importutils.import_object(quota_driver_class) @@ -792,7 +791,7 @@ def _sync_gigabytes(context, project_id, session): (_junk, share_gigs) = db.share_data_get_for_project(context, project_id, session=session) - if FLAGS.no_snapshot_gb_quota: + if CONF.no_snapshot_gb_quota: return {'gigabytes': share_gigs} (_junk, snap_gigs) = db.snapshot_data_get_for_project(context, diff --git a/manila/scheduler/chance.py b/manila/scheduler/chance.py index 104ed52d59..65d283ad39 100644 --- a/manila/scheduler/chance.py +++ b/manila/scheduler/chance.py @@ -24,11 +24,12 @@ Chance (Random) Scheduler implementation import random from manila import exception -from manila import flags + from manila.scheduler import driver +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class ChanceScheduler(driver.Scheduler): @@ -60,7 +61,7 @@ class ChanceScheduler(driver.Scheduler): def schedule_create_share(self, context, request_spec, filter_properties): """Picks a host that is up at random.""" - topic = FLAGS.share_topic + topic = CONF.share_topic host = self._schedule(context, topic, request_spec, filter_properties=filter_properties) share_id = request_spec['share_id'] diff --git a/manila/scheduler/driver.py b/manila/scheduler/driver.py index e6caa72f64..81a0a6c73c 100644 --- a/manila/scheduler/driver.py +++ b/manila/scheduler/driver.py @@ -24,7 +24,7 @@ Scheduler base class that all Schedulers should inherit from from oslo.config import cfg from manila import db -from manila import flags + from manila.openstack.common import importutils from manila.openstack.common import timeutils from manila.share import rpcapi as share_rpcapi @@ -39,8 +39,8 @@ scheduler_driver_opts = [ help='Maximum number of attempts to schedule a share'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(scheduler_driver_opts) +CONF = cfg.CONF +CONF.register_opts(scheduler_driver_opts) def share_update_db(context, share_id, host): @@ -58,7 +58,7 @@ class Scheduler(object): def __init__(self): self.host_manager = importutils.import_object( - FLAGS.scheduler_host_manager) + CONF.scheduler_host_manager) self.share_rpcapi = share_rpcapi.ShareAPI() def get_host_list(self): diff --git a/manila/scheduler/filter_scheduler.py b/manila/scheduler/filter_scheduler.py index d0002e8d66..2e96b7b58a 100644 --- a/manila/scheduler/filter_scheduler.py +++ b/manila/scheduler/filter_scheduler.py @@ -23,14 +23,15 @@ Weighing Functions. import operator from manila import exception -from manila import flags + from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.scheduler import driver from manila.scheduler import scheduler_options +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -72,7 +73,7 @@ class FilterScheduler(driver.Scheduler): hosts.append(host) def _max_attempts(self): - max_attempts = FLAGS.scheduler_max_attempts + max_attempts = CONF.scheduler_max_attempts if max_attempts < 1: msg = _("Invalid value for 'scheduler_max_attempts', " "must be >=1") diff --git a/manila/scheduler/host_manager.py b/manila/scheduler/host_manager.py index d2290a003c..0e6ae2708c 100644 --- a/manila/scheduler/host_manager.py +++ b/manila/scheduler/host_manager.py @@ -23,7 +23,7 @@ from oslo.config import cfg from manila import db from manila import exception -from manila import flags + from manila.openstack.common import log as logging from manila.openstack.common.scheduler import filters from manila.openstack.common.scheduler import weights @@ -46,8 +46,8 @@ host_manager_opts = [ help='Which weigher class names to use for weighing hosts.') ] -FLAGS = flags.FLAGS -FLAGS.register_opts(host_manager_opts) +CONF = cfg.CONF +CONF.register_opts(host_manager_opts) LOG = logging.getLogger(__name__) @@ -155,7 +155,7 @@ class HostManager(object): of acceptable filters. """ if filter_cls_names is None: - filter_cls_names = FLAGS.scheduler_default_filters + filter_cls_names = CONF.scheduler_default_filters if not isinstance(filter_cls_names, (list, tuple)): filter_cls_names = [filter_cls_names] good_filters = [] @@ -181,7 +181,7 @@ class HostManager(object): of acceptable weighers. """ if weight_cls_names is None: - weight_cls_names = FLAGS.scheduler_default_weighers + weight_cls_names = CONF.scheduler_default_weighers if not isinstance(weight_cls_names, (list, tuple)): weight_cls_names = [weight_cls_names] @@ -242,7 +242,7 @@ class HostManager(object): """ # Get resource usage across the available share nodes: - topic = FLAGS.share_topic + topic = CONF.share_topic share_services = db.service_get_all_by_topic(context, topic) for service in share_services: if not utils.service_is_up(service) or service['disabled']: diff --git a/manila/scheduler/manager.py b/manila/scheduler/manager.py index 524067eac0..5483faa61a 100644 --- a/manila/scheduler/manager.py +++ b/manila/scheduler/manager.py @@ -26,7 +26,7 @@ from oslo.config import cfg from manila import context from manila import db from manila import exception -from manila import flags + from manila import manager from manila.openstack.common import excutils from manila.openstack.common import importutils @@ -41,8 +41,8 @@ scheduler_driver_opt = cfg.StrOpt('scheduler_driver', 'FilterScheduler', help='Default scheduler driver to use') -FLAGS = flags.FLAGS -FLAGS.register_opt(scheduler_driver_opt) +CONF = cfg.CONF +CONF.register_opt(scheduler_driver_opt) class SchedulerManager(manager.Manager): @@ -53,7 +53,7 @@ class SchedulerManager(manager.Manager): def __init__(self, scheduler_driver=None, service_name=None, *args, **kwargs): if not scheduler_driver: - scheduler_driver = FLAGS.scheduler_driver + scheduler_driver = CONF.scheduler_driver self.driver = importutils.import_object(scheduler_driver) super(SchedulerManager, self).__init__(*args, **kwargs) diff --git a/manila/scheduler/rpcapi.py b/manila/scheduler/rpcapi.py index bb58790c99..71be6c9cb5 100644 --- a/manila/scheduler/rpcapi.py +++ b/manila/scheduler/rpcapi.py @@ -18,12 +18,13 @@ Client side of the scheduler manager RPC API. """ -from manila import flags + from manila.openstack.common import jsonutils import manila.openstack.common.rpc.proxy +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class SchedulerAPI(manila.openstack.common.rpc.proxy.RpcProxy): @@ -42,7 +43,7 @@ class SchedulerAPI(manila.openstack.common.rpc.proxy.RpcProxy): def __init__(self): super(SchedulerAPI, self).__init__( - topic=FLAGS.scheduler_topic, + topic=CONF.scheduler_topic, default_version=self.RPC_API_VERSION) def create_share(self, ctxt, topic, share_id, snapshot_id=None, diff --git a/manila/scheduler/scheduler_options.py b/manila/scheduler/scheduler_options.py index 2f4c42e747..dbedfd8829 100644 --- a/manila/scheduler/scheduler_options.py +++ b/manila/scheduler/scheduler_options.py @@ -28,7 +28,7 @@ import os from oslo.config import cfg -from manila import flags + from manila.openstack.common import log as logging from manila.openstack.common import timeutils @@ -37,8 +37,8 @@ scheduler_json_config_location_opt = cfg.StrOpt( default='', help='Absolute path to scheduler configuration JSON file.') -FLAGS = flags.FLAGS -FLAGS.register_opt(scheduler_json_config_location_opt) +CONF = cfg.CONF +CONF.register_opt(scheduler_json_config_location_opt) LOG = logging.getLogger(__name__) @@ -86,7 +86,7 @@ class SchedulerOptions(object): def get_configuration(self, filename=None): """Check the json file for changes and load it if needed.""" if not filename: - filename = FLAGS.scheduler_json_config_location + filename = CONF.scheduler_json_config_location if not filename: return self.data if self.last_checked: diff --git a/manila/scheduler/simple.py b/manila/scheduler/simple.py index a19b2a1f90..b57b0845c6 100644 --- a/manila/scheduler/simple.py +++ b/manila/scheduler/simple.py @@ -25,7 +25,7 @@ from oslo.config import cfg from manila import db from manila import exception -from manila import flags + from manila.scheduler import chance from manila.scheduler import driver from manila import utils @@ -35,8 +35,8 @@ simple_scheduler_opts = [ default=10000, help="maximum number of volume gigabytes to allow per host"), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(simple_scheduler_opts) +CONF = cfg.CONF +CONF.register_opts(simple_scheduler_opts) class SimpleScheduler(chance.ChanceScheduler): @@ -57,7 +57,7 @@ class SimpleScheduler(chance.ChanceScheduler): if availability_zone: zone, _x, host = availability_zone.partition(':') if host and context.is_admin: - service = db.service_get_by_args(elevated, host, FLAGS.share_topic) + service = db.service_get_by_args(elevated, host, CONF.share_topic) if not utils.service_is_up(service): raise exception.WillNotSchedule(host=host) updated_share = driver.share_update_db(context, share_id, host) @@ -76,7 +76,7 @@ class SimpleScheduler(chance.ChanceScheduler): if service['availability_zone'] == zone] for result in results: (service, share_gigabytes) = result - if share_gigabytes + share_size > FLAGS.max_gigabytes: + if share_gigabytes + share_size > CONF.max_gigabytes: msg = _("Not enough allocatable share gigabytes remaining") raise exception.NoValidHost(reason=msg) if utils.service_is_up(service) and not service['disabled']: diff --git a/manila/scheduler/weights/capacity.py b/manila/scheduler/weights/capacity.py index 63dc171c76..35dda0ca83 100644 --- a/manila/scheduler/weights/capacity.py +++ b/manila/scheduler/weights/capacity.py @@ -24,7 +24,7 @@ import math from oslo.config import cfg -from manila import flags + from manila.openstack.common.scheduler import weights capacity_weight_opts = [ @@ -34,14 +34,14 @@ capacity_weight_opts = [ 'Negative numbers mean to stack vs spread.'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(capacity_weight_opts) +CONF = cfg.CONF +CONF.register_opts(capacity_weight_opts) class CapacityWeigher(weights.BaseHostWeigher): def _weight_multiplier(self): """Override the weight multiplier.""" - return FLAGS.capacity_weight_multiplier + return CONF.capacity_weight_multiplier def _weigh_object(self, host_state, weight_properties): """Higher weights win. We want spreading to be the default.""" diff --git a/manila/service.py b/manila/service.py index 35843123b1..99e5c25fdf 100644 --- a/manila/service.py +++ b/manila/service.py @@ -34,7 +34,7 @@ from oslo.config import cfg from manila import context from manila import db from manila import exception -from manila import flags + from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.openstack.common import rpc @@ -63,8 +63,8 @@ service_opts = [ default=8786, help='port for os share api to listen'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(service_opts) +CONF = cfg.CONF +CONF.register_opts(service_opts) class SignalExit(SystemExit): @@ -398,7 +398,7 @@ class Service(object): self.timers.append(periodic) def _create_service_ref(self, context): - zone = FLAGS.storage_availability_zone + zone = CONF.storage_availability_zone service_ref = db.service_create(context, {'host': self.host, 'binary': self.binary, @@ -417,30 +417,30 @@ class Service(object): periodic_fuzzy_delay=None, service_name=None): """Instantiates class and passes back application object. - :param host: defaults to FLAGS.host + :param host: defaults to CONF.host :param binary: defaults to basename of executable :param topic: defaults to bin_name - 'manila-' part - :param manager: defaults to FLAGS._manager - :param report_interval: defaults to FLAGS.report_interval - :param periodic_interval: defaults to FLAGS.periodic_interval - :param periodic_fuzzy_delay: defaults to FLAGS.periodic_fuzzy_delay + :param manager: defaults to CONF._manager + :param report_interval: defaults to CONF.report_interval + :param periodic_interval: defaults to CONF.periodic_interval + :param periodic_fuzzy_delay: defaults to CONF.periodic_fuzzy_delay """ if not host: - host = FLAGS.host + host = CONF.host if not binary: binary = os.path.basename(inspect.stack()[-1][1]) if not topic: topic = binary if not manager: subtopic = topic.rpartition('manila-')[2] - manager = FLAGS.get('%s_manager' % subtopic, None) + manager = CONF.get('%s_manager' % subtopic, None) if report_interval is None: - report_interval = FLAGS.report_interval + report_interval = CONF.report_interval if periodic_interval is None: - periodic_interval = FLAGS.periodic_interval + periodic_interval = CONF.periodic_interval if periodic_fuzzy_delay is None: - periodic_fuzzy_delay = FLAGS.periodic_fuzzy_delay + periodic_fuzzy_delay = CONF.periodic_fuzzy_delay service_obj = cls(host, binary, topic, manager, report_interval=report_interval, periodic_interval=periodic_interval, @@ -486,7 +486,7 @@ class Service(object): def report_state(self): """Update the state of this service in the datastore.""" ctxt = context.get_admin_context() - zone = FLAGS.storage_availability_zone + zone = CONF.storage_availability_zone state_catalog = {} try: try: @@ -531,8 +531,8 @@ class WSGIService(object): self.manager = self._get_manager() self.loader = loader or wsgi.Loader() self.app = self.loader.load_app(name) - self.host = getattr(FLAGS, '%s_listen' % name, "0.0.0.0") - self.port = getattr(FLAGS, '%s_listen_port' % name, 0) + self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0") + self.port = getattr(CONF, '%s_listen_port' % name, 0) self.server = wsgi.Server(name, self.app, host=self.host, @@ -549,10 +549,10 @@ class WSGIService(object): """ fl = '%s_manager' % self.name - if fl not in FLAGS: + if fl not in CONF: return None - manager_class_name = FLAGS.get(fl, None) + manager_class_name = CONF.get(fl, None) if not manager_class_name: return None @@ -605,9 +605,9 @@ def serve(*servers): def wait(): - LOG.debug(_('Full set of FLAGS:')) - for flag in FLAGS: - flag_get = FLAGS.get(flag, None) + LOG.debug(_('Full set of CONF:')) + for flag in CONF: + flag_get = CONF.get(flag, None) # hide flag contents from log if contains a password # should use secret flag when switch over to openstack-common if ("_password" in flag or "_key" in flag or diff --git a/manila/share/__init__.py b/manila/share/__init__.py index 3fe5149aaa..760dac8c62 100644 --- a/manila/share/__init__.py +++ b/manila/share/__init__.py @@ -18,8 +18,9 @@ # Importing full names to not pollute the namespace and cause possible # collisions with use of 'from manila.share import ' elsewhere. -import manila.flags -import manila.openstack.common.importutils +from manila.common import config +import manila.openstack.common.importutils as import_utils -API = manila.openstack.common.importutils.import_class( - manila.flags.FLAGS.share_api_class) +CONF = config.CONF + +API = import_utils.import_class(CONF.share_api_class) diff --git a/manila/share/api.py b/manila/share/api.py index 3aedd921fa..77b41a14fd 100644 --- a/manila/share/api.py +++ b/manila/share/api.py @@ -24,7 +24,6 @@ import functools from manila.db import base from manila import exception -from manila import flags from manila.image import glance from manila.openstack.common import excutils from manila.openstack.common import log as logging @@ -38,7 +37,7 @@ from manila.share import rpcapi as share_rpcapi from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) GB = 1048576 * 1024 @@ -145,7 +144,7 @@ class API(base.Base): raise exception.ShareLimitExceeded(allowed=quotas['shares']) if availability_zone is None: - availability_zone = FLAGS.storage_availability_zone + availability_zone = CONF.storage_availability_zone options = {'size': size, 'user_id': context.user_id, @@ -179,7 +178,7 @@ class API(base.Base): self.scheduler_rpcapi.create_share( context, - FLAGS.share_topic, + CONF.share_topic, share['id'], snapshot_id, request_spec=request_spec, diff --git a/manila/share/configuration.py b/manila/share/configuration.py index bde5681121..7958698584 100644 --- a/manila/share/configuration.py +++ b/manila/share/configuration.py @@ -21,7 +21,7 @@ Configuration support for all drivers. This module allows support for setting configurations either from default -or from a particular FLAGS group, to be able to set multiple configurations +or from a particular CONF group, to be able to set multiple configurations for a given set of values. For instance, two lvm configurations can be set by naming them in groups as @@ -45,11 +45,10 @@ and registered in the group in which they are used. from oslo.config import cfg -from manila import flags from manila.openstack.common import log as logging -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -63,12 +62,12 @@ class Configuration(object): # set the local conf so that __call__'s know what to use if self.config_group: self._ensure_config_values(share_opts) - self.local_conf = FLAGS._get(self.config_group) + self.local_conf = CONF._get(self.config_group) else: - self.local_conf = FLAGS + self.local_conf = CONF def _ensure_config_values(self, share_opts): - FLAGS.register_opts(share_opts, + CONF.register_opts(share_opts, group=self.config_group) def append_config_values(self, share_opts): diff --git a/manila/share/driver.py b/manila/share/driver.py index 9f49720c75..0f07dd2311 100644 --- a/manila/share/driver.py +++ b/manila/share/driver.py @@ -25,7 +25,6 @@ import re import time from manila import exception -from manila import flags from manila.openstack.common import log as logging from manila.share.configuration import Configuration from manila import utils @@ -48,8 +47,8 @@ share_opts = [ help='The backend name for a given driver implementation'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(share_opts) +CONF = cfg.CONF +CONF.register_opts(share_opts) #TODO(rushiagr): keep the configuration option in only one class and not two diff --git a/manila/share/drivers/lvm.py b/manila/share/drivers/lvm.py index c520752701..88ebb92c88 100644 --- a/manila/share/drivers/lvm.py +++ b/manila/share/drivers/lvm.py @@ -25,7 +25,6 @@ import os import re from manila import exception -from manila import flags from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.share import driver @@ -61,8 +60,8 @@ share_opts = [ help='Specify list of share export helpers.'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(share_opts) +CONF = cfg.CONF +CONF.register_opts(share_opts) class LVMShareDriver(driver.ExecuteMixin, driver.ShareDriver): diff --git a/manila/share/drivers/netapp.py b/manila/share/drivers/netapp.py index fe130bd5e4..f75d773cb6 100644 --- a/manila/share/drivers/netapp.py +++ b/manila/share/drivers/netapp.py @@ -23,7 +23,6 @@ import suds from suds.sax import text from manila import exception -from manila import flags from manila.openstack.common import log from manila.share import driver @@ -53,8 +52,8 @@ NETAPP_NAS_OPTS = [ help='Use secure connection to server.'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(NETAPP_NAS_OPTS) +CONF = cfg.CONF +CONF.register_opts(NETAPP_NAS_OPTS) class NetAppShareDriver(driver.ShareDriver): diff --git a/manila/share/manager.py b/manila/share/manager.py index 0cce5f697b..306d8a84bd 100644 --- a/manila/share/manager.py +++ b/manila/share/manager.py @@ -24,7 +24,6 @@ from manila import context from manila import exception -from manila import flags from manila import manager from manila.openstack.common import excutils from manila.openstack.common import importutils @@ -43,8 +42,8 @@ share_manager_opts = [ help='Driver to use for share creation'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(share_manager_opts) +CONF = cfg.CONF +CONF.register_opts(share_manager_opts) QUOTAS = quota.QUOTAS diff --git a/manila/share/rpcapi.py b/manila/share/rpcapi.py index 484417b7dc..d52d04cfd1 100644 --- a/manila/share/rpcapi.py +++ b/manila/share/rpcapi.py @@ -19,12 +19,12 @@ Client side of the share RPC API. """ from manila import exception -from manila import flags from manila.openstack.common import rpc import manila.openstack.common.rpc.proxy +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class ShareAPI(manila.openstack.common.rpc.proxy.RpcProxy): @@ -41,7 +41,7 @@ class ShareAPI(manila.openstack.common.rpc.proxy.RpcProxy): def __init__(self, topic=None): super(ShareAPI, self).__init__( - topic=topic or FLAGS.share_topic, + topic=topic or CONF.share_topic, default_version=self.BASE_RPC_API_VERSION) def create_share(self, ctxt, share, host, diff --git a/manila/test.py b/manila/test.py index d430dcc774..46db4b6fdc 100644 --- a/manila/test.py +++ b/manila/test.py @@ -32,13 +32,13 @@ import nose.plugins.skip from oslo.config import cfg import stubout -from manila import flags +from manila.common import config from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.openstack.common import timeutils from manila import service from manila import tests -from manila.tests import fake_flags +from manila.tests import conf_fixture test_opts = [ cfg.StrOpt('sqlite_clean_db', @@ -48,8 +48,8 @@ test_opts = [ default=True, help='should we use everything for testing'), ] -FLAGS = flags.FLAGS -FLAGS.register_opts(test_opts) +CONF = cfg.CONF +CONF.register_opts(test_opts) LOG = logging.getLogger(__name__) @@ -104,7 +104,7 @@ def skip_if_fake(func): """Decorator that skips a test if running in fake mode.""" def _skipper(*args, **kw): """Wrapped skipper function.""" - if FLAGS.fake_tests: + if CONF.fake_tests: raise unittest.SkipTest('Test cannot be run in fake mode') else: return func(*args, **kw) @@ -122,8 +122,8 @@ class TestCase(unittest.TestCase): """Run before each test method to initialize test environment.""" super(TestCase, self).setUp() - fake_flags.set_defaults(FLAGS) - flags.parse_args([], default_config_files=[]) + conf_fixture.set_defaults(CONF) + CONF([], default_config_files=[]) # NOTE(vish): We need a better method for creating fixtures for tests # now that we have some required db setup for the system @@ -137,7 +137,7 @@ class TestCase(unittest.TestCase): self.stubs = stubout.StubOutForTesting() self.injected = [] self._services = [] - FLAGS.set_override('fatal_exception_format_errors', True) + CONF.set_override('fatal_exception_format_errors', True) def tearDown(self): """Runs after each test method to tear down test environment.""" @@ -149,7 +149,7 @@ class TestCase(unittest.TestCase): super(TestCase, self).tearDown() finally: # Reset any overridden flags - FLAGS.reset() + CONF.reset() # Stop any timers for x in self.injected: @@ -174,7 +174,7 @@ class TestCase(unittest.TestCase): def flags(self, **kw): """Override flag variables for a test.""" for k, v in kw.iteritems(): - FLAGS.set_override(k, v) + CONF.set_override(k, v) def start_service(self, name, host=None, **kwargs): host = host and host or uuid.uuid4().hex diff --git a/manila/tests/__init__.py b/manila/tests/__init__.py index 8a24821452..951351f350 100644 --- a/manila/tests/__init__.py +++ b/manila/tests/__init__.py @@ -33,6 +33,8 @@ import eventlet eventlet.monkey_patch() +from oslo.config import cfg + # See http://code.google.com/p/python-nose/issues/detail?id=373 # The code below enables nosetests to work with i18n _() blocks import __builtin__ @@ -41,45 +43,46 @@ import os import shutil from manila.db.sqlalchemy.session import get_engine -from manila import flags -FLAGS = flags.FLAGS + +CONF = cfg.CONF _DB = None def reset_db(): - if FLAGS.sql_connection == "sqlite://": + if CONF.sql_connection == "sqlite://": engine = get_engine() engine.dispose() conn = engine.connect() conn.connection.executescript(_DB) else: - shutil.copyfile(os.path.join(FLAGS.state_path, FLAGS.sqlite_clean_db), - os.path.join(FLAGS.state_path, FLAGS.sqlite_db)) + shutil.copyfile(os.path.join(CONF.state_path, CONF.sqlite_clean_db), + os.path.join(CONF.state_path, CONF.sqlite_db)) def setup(): import mox # Fail fast if you don't have mox. Workaround for bug 810424 from manila.db import migration - from manila.tests import fake_flags - fake_flags.set_defaults(FLAGS) + from manila.tests import conf_fixture - if FLAGS.sql_connection == "sqlite://": + conf_fixture.set_defaults(CONF) + + if CONF.sql_connection == "sqlite://": if migration.db_version() > 1: return else: - testdb = os.path.join(FLAGS.state_path, FLAGS.sqlite_db) + testdb = os.path.join(CONF.state_path, CONF.sqlite_db) if os.path.exists(testdb): return migration.db_sync() - if FLAGS.sql_connection == "sqlite://": + if CONF.sql_connection == "sqlite://": global _DB engine = get_engine() conn = engine.connect() _DB = "".join(line for line in conn.connection.iterdump()) else: - cleandb = os.path.join(FLAGS.state_path, FLAGS.sqlite_clean_db) + cleandb = os.path.join(CONF.state_path, CONF.sqlite_clean_db) shutil.copyfile(testdb, cleandb) diff --git a/manila/tests/api/contrib/test_share_actions.py b/manila/tests/api/contrib/test_share_actions.py index 034c6cba1b..eee6b79f2d 100644 --- a/manila/tests/api/contrib/test_share_actions.py +++ b/manila/tests/api/contrib/test_share_actions.py @@ -20,7 +20,7 @@ import webob from manila.api.contrib import share_actions from manila import exception -from manila import flags + from manila.openstack.common import jsonutils from manila.openstack.common.rpc import common as rpc_common from manila import share @@ -28,9 +28,10 @@ from manila.share import api as share_api from manila import test from manila.tests.api.contrib import stubs from manila.tests.api import fakes +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF def _fake_access_get(self, ctxt, access_id): diff --git a/manila/tests/api/middleware/test_sizelimit.py b/manila/tests/api/middleware/test_sizelimit.py index f85172d4b4..01427f4fb1 100644 --- a/manila/tests/api/middleware/test_sizelimit.py +++ b/manila/tests/api/middleware/test_sizelimit.py @@ -16,11 +16,13 @@ import StringIO import webob from manila.api.middleware import sizelimit -from manila import flags + from manila import test -FLAGS = flags.FLAGS -MAX_REQUEST_BODY_SIZE = FLAGS.osapi_max_request_body_size +from oslo.config import cfg + +CONF = cfg.CONF +MAX_REQUEST_BODY_SIZE = CONF.osapi_max_request_body_size class TestLimitingReader(test.TestCase): diff --git a/manila/tests/api/test_extensions.py b/manila/tests/api/test_extensions.py index a087d76b25..d81197572a 100644 --- a/manila/tests/api/test_extensions.py +++ b/manila/tests/api/test_extensions.py @@ -22,18 +22,19 @@ import webob from manila.api.v1 import router from manila.api import xmlutil -from manila import flags + from manila.openstack.common import jsonutils from manila import test +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF NS = "{http://docs.openstack.org/common/api/v1.0}" class ExtensionTestCase(test.TestCase): def setUp(self): super(ExtensionTestCase, self).setUp() - ext_list = FLAGS.osapi_share_extension[:] + ext_list = CONF.osapi_share_extension[:] fox = ('manila.tests.api.extensions.foxinsocks.Foxinsocks') if fox not in ext_list: ext_list.append(fox) diff --git a/manila/tests/api/test_router.py b/manila/tests/api/test_router.py index 776d2ef5ae..d381be13e4 100644 --- a/manila/tests/api/test_router.py +++ b/manila/tests/api/test_router.py @@ -17,12 +17,13 @@ from manila.api.openstack import wsgi from manila.api.v1 import router from manila.api import versions -from manila import flags + from manila.openstack.common import log as logging from manila import test from manila.tests.api import fakes +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) diff --git a/manila/tests/fake_flags.py b/manila/tests/conf_fixture.py similarity index 93% rename from manila/tests/fake_flags.py rename to manila/tests/conf_fixture.py index c5a4895098..a6cb4bd021 100644 --- a/manila/tests/fake_flags.py +++ b/manila/tests/conf_fixture.py @@ -16,11 +16,11 @@ # License for the specific language governing permissions and limitations # under the License. -from manila import flags +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF -flags.DECLARE('policy_file', 'manila.policy') +CONF.import_opt('policy_file', 'manila.policy') def_vol_type = 'fake_vol_type' diff --git a/manila/tests/declare_flags.py b/manila/tests/declare_conf.py similarity index 87% rename from manila/tests/declare_flags.py rename to manila/tests/declare_conf.py index c3fa5d0117..46c423929e 100644 --- a/manila/tests/declare_flags.py +++ b/manila/tests/declare_conf.py @@ -18,7 +18,6 @@ from oslo.config import cfg -from manila import flags -FLAGS = flags.FLAGS -FLAGS.register_opt(cfg.IntOpt('answer', default=42, help='test flag')) +CONF = cfg.CONF +CONF.register_opt(cfg.IntOpt('answer', default=42, help='test conf')) diff --git a/manila/tests/fake_utils.py b/manila/tests/fake_utils.py index c1c389e484..e1974e2ed1 100644 --- a/manila/tests/fake_utils.py +++ b/manila/tests/fake_utils.py @@ -19,7 +19,6 @@ import re from eventlet import greenthread - from manila import exception from manila.openstack.common import log as logging from manila import utils diff --git a/manila/tests/image/fake.py b/manila/tests/image/fake.py index 7ad4accfaa..e130f1478f 100644 --- a/manila/tests/image/fake.py +++ b/manila/tests/image/fake.py @@ -23,15 +23,16 @@ import datetime import uuid from manila import exception -from manila import flags + import manila.image.glance from manila.openstack.common import log as logging +from oslo.config import cfg LOG = logging.getLogger(__name__) -FLAGS = flags.FLAGS +CONF = cfg.CONF class _FakeImageService(object): diff --git a/manila/tests/image/test_glance.py b/manila/tests/image/test_glance.py index c2c08552e4..d813b2213b 100644 --- a/manila/tests/image/test_glance.py +++ b/manila/tests/image/test_glance.py @@ -25,13 +25,14 @@ from glanceclient.v2.client import Client as glanceclient_v2 from manila import context from manila import exception -from manila import flags + from manila.image import glance from manila import test from manila.tests.glance import stubs as glance_stubs +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class NullWriter(object): @@ -566,7 +567,7 @@ class TestGlanceClientVersion(test.TestCase): 9292) self.assertEquals(client_wrapper_v2.client.__module__, 'glanceclient.v2.client') - FLAGS.reset() + CONF.reset() def test_glance_version_by_arg(self): """Test glance version set by arg to GlanceClientWrapper""" diff --git a/manila/tests/integrated/integrated_helpers.py b/manila/tests/integrated/integrated_helpers.py index ec4bf0b791..d090e61bbe 100644 --- a/manila/tests/integrated/integrated_helpers.py +++ b/manila/tests/integrated/integrated_helpers.py @@ -23,13 +23,15 @@ import random import string import uuid -from manila import flags + from manila.openstack.common import log as logging from manila import service from manila import test # For the flags from manila.tests.integrated.api import client -FLAGS = flags.FLAGS +from oslo.config import cfg + +CONF = cfg.CONF LOG = logging.getLogger(__name__) diff --git a/manila/tests/integrated/test_extensions.py b/manila/tests/integrated/test_extensions.py index 9446cf1e22..264de8bb6d 100644 --- a/manila/tests/integrated/test_extensions.py +++ b/manila/tests/integrated/test_extensions.py @@ -15,19 +15,20 @@ # License for the specific language governing permissions and limitations # under the License. -from manila import flags + from manila.openstack.common import log as logging from manila.tests.integrated import integrated_helpers +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) class ExtensionsTest(integrated_helpers._IntegratedTestBase): def _get_flags(self): f = super(ExtensionsTest, self)._get_flags() - f['osapi_share_extension'] = FLAGS.osapi_share_extension[:] + f['osapi_share_extension'] = CONF.osapi_share_extension[:] f['osapi_share_extension'].append( 'manila.tests.api.extensions.foxinsocks.Foxinsocks') return f diff --git a/manila/tests/runtime_flags.py b/manila/tests/runtime_conf.py similarity index 86% rename from manila/tests/runtime_flags.py rename to manila/tests/runtime_conf.py index c13a48e25a..19efe69241 100644 --- a/manila/tests/runtime_flags.py +++ b/manila/tests/runtime_conf.py @@ -18,7 +18,6 @@ from oslo.config import cfg -from manila import flags -FLAGS = flags.FLAGS -FLAGS.register_opt(cfg.IntOpt('runtime_answer', default=54, help='test flag')) +CONF = cfg.CONF +CONF.register_opt(cfg.IntOpt('runtime_answer', default=54, help='test flag')) diff --git a/manila/tests/scheduler/test_host_manager.py b/manila/tests/scheduler/test_host_manager.py index 3b214bbbde..d1e8897f2a 100644 --- a/manila/tests/scheduler/test_host_manager.py +++ b/manila/tests/scheduler/test_host_manager.py @@ -19,15 +19,16 @@ Tests For HostManager from manila import db from manila import exception -from manila import flags + from manila.openstack.common.scheduler import filters from manila.openstack.common import timeutils from manila.scheduler import host_manager from manila import test from manila.tests.scheduler import fakes +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class FakeFilterClass1(filters.BaseHostFilter): @@ -137,7 +138,7 @@ class HostManagerTestCase(test.TestCase): def test_get_all_host_states_share(self): context = 'fake_context' - topic = FLAGS.share_topic + topic = CONF.share_topic self.mox.StubOutWithMock(db, 'service_get_all_by_topic') self.mox.StubOutWithMock(host_manager.LOG, 'warn') diff --git a/manila/tests/scheduler/test_rpcapi.py b/manila/tests/scheduler/test_rpcapi.py index 1ae7ea7371..e1caa064f9 100644 --- a/manila/tests/scheduler/test_rpcapi.py +++ b/manila/tests/scheduler/test_rpcapi.py @@ -19,13 +19,14 @@ Unit Tests for manila.scheduler.rpcapi """ from manila import context -from manila import flags + from manila.openstack.common import rpc from manila.scheduler import rpcapi as scheduler_rpcapi from manila import test +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class SchedulerRpcAPITestCase(test.TestCase): @@ -58,7 +59,7 @@ class SchedulerRpcAPITestCase(test.TestCase): retval = getattr(rpcapi, method)(ctxt, **kwargs) self.assertEqual(retval, expected_retval) - expected_args = [ctxt, FLAGS.scheduler_topic, expected_msg] + expected_args = [ctxt, CONF.scheduler_topic, expected_msg] for arg, expected_arg in zip(self.fake_args, expected_args): self.assertEqual(arg, expected_arg) diff --git a/manila/tests/scheduler/test_scheduler.py b/manila/tests/scheduler/test_scheduler.py index 74ecd7355d..f89a6cfe64 100644 --- a/manila/tests/scheduler/test_scheduler.py +++ b/manila/tests/scheduler/test_scheduler.py @@ -24,16 +24,17 @@ from mox import IsA from manila import context from manila import db from manila import exception -from manila import flags + from manila.openstack.common import timeutils from manila.scheduler import driver from manila.scheduler import manager from manila.scheduler import simple from manila import test from manila import utils +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class SchedulerManagerTestCase(test.TestCase): diff --git a/manila/tests/test_conf.py b/manila/tests/test_conf.py new file mode 100644 index 0000000000..0039ebc293 --- /dev/null +++ b/manila/tests/test_conf.py @@ -0,0 +1,83 @@ +# 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 manila 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.assertNotIn('answer', CONF) + CONF.import_opt('answer', 'manila.tests.declare_conf') + self.assertIn('answer', 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', 'manila.tests.declare_conf') + self.assertEqual(CONF.answer, 256) + + def test_runtime_and_unknown_flags(self): + self.assertNotIn('runtime_answer', CONF) + import manila.tests.runtime_conf + self.assertIn('runtime_answer', CONF) + self.assertEqual(CONF.runtime_answer, 54) + + def test_long_vs_short_flags(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_flag_leak_left(self): + self.assertEqual(CONF.conf_unittest, 'foo') + self.flags(conf_unittest='bar') + self.assertEqual(CONF.conf_unittest, 'bar') + + def test_flag_leak_right(self): + self.assertEqual(CONF.conf_unittest, 'foo') + self.flags(conf_unittest='bar') + self.assertEqual(CONF.conf_unittest, 'bar') + + def test_flag_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') diff --git a/manila/tests/test_flags.py b/manila/tests/test_flags.py deleted file mode 100644 index 65a4b396d8..0000000000 --- a/manila/tests/test_flags.py +++ /dev/null @@ -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 manila import flags -from manila 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', 'manila.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', 'manila.tests.declare_flags') - self.assertEqual(FLAGS.answer, 256) - - def test_runtime_and_unknown_flags(self): - self.assert_('runtime_answer' not in FLAGS) - import manila.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') diff --git a/manila/tests/test_policy.py b/manila/tests/test_policy.py index 8749f614b9..872cbe5fef 100644 --- a/manila/tests/test_policy.py +++ b/manila/tests/test_policy.py @@ -23,14 +23,15 @@ import urllib2 from manila import context from manila import exception -from manila import flags + import manila.openstack.common.policy from manila.openstack.common import policy as common_policy from manila import policy from manila import test from manila import utils +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class PolicyFileTestCase(test.TestCase): @@ -209,7 +210,7 @@ class ContextIsAdminPolicyTestCase(test.TestCase): rules = { 'context_is_admin': [["role:administrator"], ["role:johnny-admin"]] } - brain = common_policy.Brain(rules, FLAGS.policy_default_rule) + brain = common_policy.Brain(rules, CONF.policy_default_rule) common_policy.set_brain(brain) ctx = context.RequestContext('fake', 'fake', roles=['johnny-admin']) self.assert_(ctx.is_admin) @@ -224,7 +225,7 @@ class ContextIsAdminPolicyTestCase(test.TestCase): "admin_or_owner": [["role:admin"], ["project_id:%(project_id)s"]], "default": [["rule:admin_or_owner"]], } - brain = common_policy.Brain(rules, FLAGS.policy_default_rule) + brain = common_policy.Brain(rules, CONF.policy_default_rule) common_policy.set_brain(brain) ctx = context.RequestContext('fake', 'fake') self.assertFalse(ctx.is_admin) diff --git a/manila/tests/test_quota.py b/manila/tests/test_quota.py index cdcdb6fb4d..59e8bf4165 100644 --- a/manila/tests/test_quota.py +++ b/manila/tests/test_quota.py @@ -23,16 +23,17 @@ from manila import db from manila.db.sqlalchemy import api as sqa_api from manila.db.sqlalchemy import models as sqa_models from manila import exception -from manila import flags + from manila.openstack.common import rpc from manila.openstack.common import timeutils from manila import quota from manila import share from manila import test import manila.tests.image.fake +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class QuotaIntegrationTestCase(test.TestCase): @@ -79,7 +80,7 @@ class QuotaIntegrationTestCase(test.TestCase): @test.skip_test("SQLAlchemy sqlite insert bug") def test_too_many_shares(self): share_ids = [] - for i in range(FLAGS.quota_shares): + for i in range(CONF.quota_shares): share_ref = self._create_share() share_ids.append(share_ref['id']) self.assertRaises(exception.QuotaError, diff --git a/manila/tests/test_service.py b/manila/tests/test_service.py index 0ed5e8105a..88be3cf9a9 100644 --- a/manila/tests/test_service.py +++ b/manila/tests/test_service.py @@ -26,7 +26,7 @@ from oslo.config import cfg from manila import context from manila import db from manila import exception -from manila import flags + from manila import manager from manila import service from manila import test @@ -43,7 +43,8 @@ test_service_opts = [ default=0, help="Port number to bind test service to"), ] -flags.FLAGS.register_opts(test_service_opts) +CONF = cfg.CONF +CONF.register_opts(test_service_opts) class FakeManager(manager.Manager): diff --git a/manila/tests/test_share.py b/manila/tests/test_share.py index 5d3ecbd60b..0c1e91d765 100644 --- a/manila/tests/test_share.py +++ b/manila/tests/test_share.py @@ -29,7 +29,7 @@ import tempfile from manila import context from manila import db from manila import exception -from manila import flags + from manila.image import image_utils from manila.openstack.common import importutils from manila.openstack.common.notifier import api as notifier_api @@ -38,9 +38,10 @@ from manila.openstack.common import rpc import manila.policy from manila.share import manager from manila import test -from manila.tests import fake_flags +from manila.tests import conf_fixture +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class FakeShareDriver(object): @@ -100,7 +101,7 @@ class ShareTestCase(test.TestCase): super(ShareTestCase, self).setUp() self.flags(connection_type='fake', share_driver='manila.tests.test_share.FakeShareDriver') - self.share = importutils.import_object(FLAGS.share_manager) + self.share = importutils.import_object(CONF.share_manager) self.context = context.get_admin_context() @staticmethod @@ -112,9 +113,9 @@ class ShareTestCase(test.TestCase): share['snapshot_id'] = snapshot_id share['user_id'] = 'fake' share['project_id'] = 'fake' - share['availability_zone'] = FLAGS.storage_availability_zone + share['availability_zone'] = CONF.storage_availability_zone share['status'] = status - share['host'] = FLAGS.host + share['host'] = CONF.host return db.share_create(context.get_admin_context(), share) @staticmethod diff --git a/manila/tests/test_share_lvm.py b/manila/tests/test_share_lvm.py index 854e07430b..9d90fa0fd6 100644 --- a/manila/tests/test_share_lvm.py +++ b/manila/tests/test_share_lvm.py @@ -21,7 +21,7 @@ import os from manila import context from manila.db.sqlalchemy import models from manila import exception -from manila import flags + from manila.openstack.common import importutils from manila.openstack.common import log as logging from manila.share.configuration import Configuration @@ -29,9 +29,10 @@ from manila.share.drivers import lvm from manila import test from manila.tests.db import fakes as db_fakes from manila.tests import fake_utils +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF def fake_share(**kwargs): @@ -80,8 +81,8 @@ class LVMShareDriverTestCase(test.TestCase): self._execute = fake_utils.fake_execute self._context = context.get_admin_context() - FLAGS.set_default('share_volume_group', 'fakevg') - FLAGS.set_default('share_export_ip', '10.0.0.1') + CONF.set_default('share_volume_group', 'fakevg') + CONF.set_default('share_export_ip', '10.0.0.1') self._helper_cifs = self.mox.CreateMock(lvm.CIFSNetConfHelper) self._helper_nfs = self.mox.CreateMock(lvm.NFSHelper) @@ -152,27 +153,27 @@ class LVMShareDriverTestCase(test.TestCase): fake_utils.fake_execute_set_repliers([('vgs --noheadings -o name', exec_runner)]) - FLAGS.set_default('share_export_ip', None) + CONF.set_default('share_export_ip', None) self.mox.ReplayAll() self.assertRaises(exception.InvalidParameterValue, self._driver.check_for_setup_error) def test_local_path_normal(self): share = fake_share(name='fake_sharename') - FLAGS.set_default('share_volume_group', 'fake_vg') + CONF.set_default('share_volume_group', 'fake_vg') self.mox.ReplayAll() ret = self._driver._local_path(share) self.assertEqual(ret, '/dev/mapper/fake_vg-fake_sharename') def test_local_path_escapes(self): share = fake_share(name='fake-sharename') - FLAGS.set_default('share_volume_group', 'fake-vg') + CONF.set_default('share_volume_group', 'fake-vg') self.mox.ReplayAll() ret = self._driver._local_path(share) self.assertEqual(ret, '/dev/mapper/fake--vg-fake--sharename') def test_allocate_container_normal(self): - FLAGS.set_default('share_lvm_mirrors', 0) + CONF.set_default('share_lvm_mirrors', 0) self.mox.ReplayAll() ret = self._driver.allocate_container(self._context, self.share) expected_exec = [ @@ -182,7 +183,7 @@ class LVMShareDriverTestCase(test.TestCase): self.assertEqual(fake_utils.fake_execute_get_log(), expected_exec) def test_allocate_container_from_snapshot(self): - FLAGS.set_default('share_lvm_mirrors', 0) + CONF.set_default('share_lvm_mirrors', 0) mount_share = '/dev/mapper/fakevg-fakename' mount_snapshot = '/dev/mapper/fakevg-fakesnapshotname' self.mox.ReplayAll() @@ -202,7 +203,7 @@ class LVMShareDriverTestCase(test.TestCase): def exec_runner(*ignore_args, **ignore_kwargs): raise exception.ProcessExecutionError() - FLAGS.set_default('share_lvm_mirrors', 0) + CONF.set_default('share_lvm_mirrors', 0) mount_share = '/dev/mapper/fakevg-fakename' mount_snapshot = '/dev/mapper/fakevg-fakesnapshotname' expected_exec = [ @@ -220,7 +221,7 @@ class LVMShareDriverTestCase(test.TestCase): def test_allocate_container_mirrors(self): share = fake_share(size='2048') - FLAGS.set_default('share_lvm_mirrors', 2) + CONF.set_default('share_lvm_mirrors', 2) self.mox.ReplayAll() ret = self._driver.allocate_container(self._context, share) expected_exec = [ @@ -243,7 +244,7 @@ class LVMShareDriverTestCase(test.TestCase): 'vgs --noheadings --nosuffix --unit=G -o name,size,free fakevg', ] fake_utils.fake_execute_set_repliers([(expected_exec[0], exec_runner)]) - FLAGS.set_default('reserved_share_percentage', 1) + CONF.set_default('reserved_share_percentage', 1) self.mox.ReplayAll() ret = self._driver.get_share_stats(refresh=True) expected_ret = { @@ -267,7 +268,7 @@ class LVMShareDriverTestCase(test.TestCase): 'vgs --noheadings --nosuffix --unit=G -o name,size,free fakevg', ] fake_utils.fake_execute_set_repliers([(expected_exec[0], exec_runner)]) - FLAGS.set_default('reserved_share_percentage', 1) + CONF.set_default('reserved_share_percentage', 1) self.mox.ReplayAll() ret = self._driver.get_share_stats(refresh=True) expected_ret = { @@ -354,7 +355,7 @@ class LVMShareDriverTestCase(test.TestCase): self._driver.create_snapshot(self._context, self.snapshot) expected_exec = [ ("lvcreate -L 1G --name fakesnapshotname --snapshot %s/fakename" % - (FLAGS.share_volume_group,)), + (CONF.share_volume_group,)), ] self.assertEqual(fake_utils.fake_execute_get_log(), expected_exec) @@ -466,7 +467,7 @@ class LVMShareDriverTestCase(test.TestCase): fake_share(share_proto='FAKE')) def _get_mount_path(self, share): - return os.path.join(FLAGS.share_export_root, share['name']) + return os.path.join(CONF.share_export_root, share['name']) class NFSHelperTestCase(test.TestCase): @@ -475,7 +476,7 @@ class NFSHelperTestCase(test.TestCase): def setUp(self): super(NFSHelperTestCase, self).setUp() fake_utils.stub_out_utils_execute(self.stubs) - FLAGS.set_default('share_export_ip', '127.0.0.1') + CONF.set_default('share_export_ip', '127.0.0.1') self._execute = fake_utils.fake_execute self.fake_conf = Configuration(None) self._helper = lvm.NFSHelper(self._execute, self.fake_conf) @@ -497,7 +498,7 @@ class NFSHelperTestCase(test.TestCase): def test_create_export(self): self.mox.ReplayAll() ret = self._helper.create_export('/opt/nfs', 'volume-00001') - expected_location = '%s:/opt/nfs' % FLAGS.share_export_ip + expected_location = '%s:/opt/nfs' % CONF.share_export_ip self.assertEqual(ret, expected_location) def test_remove_export(self): @@ -545,7 +546,7 @@ class CIFSNetConfHelperTestCase(test.TestCase): def setUp(self): super(CIFSNetConfHelperTestCase, self).setUp() fake_utils.stub_out_utils_execute(self.stubs) - FLAGS.set_default('share_export_ip', '127.0.0.1') + CONF.set_default('share_export_ip', '127.0.0.1') self.share = fake_share() self._execute = fake_utils.fake_execute self.fake_conf = Configuration(None) diff --git a/manila/tests/test_share_netapp.py b/manila/tests/test_share_netapp.py index ea40a831f7..b1f175cf1d 100644 --- a/manila/tests/test_share_netapp.py +++ b/manila/tests/test_share_netapp.py @@ -680,11 +680,11 @@ class NetAppApiClientTestCase(test.TestCase): def test_successfull_setup(self): drv = self._driver for flag in drv.REQUIRED_FLAGS: - setattr(netapp.FLAGS, flag, 'val') - conf_obj = Configuration(netapp.FLAGS) + setattr(netapp.CONF, flag, 'val') + conf_obj = Configuration(netapp.CONF) drv.check_configuration(conf_obj) def test_failing_setup(self): drv = self._driver self.assertRaises(exception.Error, drv.check_configuration, - Configuration(netapp.FLAGS)) + Configuration(netapp.CONF)) diff --git a/manila/tests/test_share_rpcapi.py b/manila/tests/test_share_rpcapi.py index a37ba40a72..5a04429d76 100644 --- a/manila/tests/test_share_rpcapi.py +++ b/manila/tests/test_share_rpcapi.py @@ -21,14 +21,15 @@ Unit Tests for manila.volume.rpcapi. from manila import context from manila import db -from manila import flags + from manila.openstack.common import jsonutils from manila.openstack.common import rpc from manila.share import rpcapi as share_rpcapi from manila import test +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class ShareRpcAPITestCase(test.TestCase): @@ -37,7 +38,7 @@ class ShareRpcAPITestCase(test.TestCase): self.context = context.get_admin_context() shr = {} shr['host'] = 'fake_host' - shr['availability_zone'] = FLAGS.storage_availability_zone + shr['availability_zone'] = CONF.storage_availability_zone shr['status'] = "available" share = db.share_create(self.context, shr) acs = {} @@ -91,7 +92,7 @@ class ShareRpcAPITestCase(test.TestCase): host = kwargs['host'] else: host = kwargs['share']['host'] - expected_topic = '%s.%s' % (FLAGS.share_topic, host) + expected_topic = '%s.%s' % (CONF.share_topic, host) self.fake_args = None self.fake_kwargs = None diff --git a/manila/tests/test_utils.py b/manila/tests/test_utils.py index 0ed779083f..bf9d14fddf 100644 --- a/manila/tests/test_utils.py +++ b/manila/tests/test_utils.py @@ -28,14 +28,15 @@ import mox import manila from manila import exception -from manila import flags + from manila.openstack.common import strutils from manila.openstack.common import timeutils from manila import test from manila import utils +from oslo.config import cfg -FLAGS = flags.FLAGS +CONF = cfg.CONF class ExecuteTestCase(test.TestCase): @@ -302,7 +303,7 @@ class GenericUtilsTestCase(test.TestCase): def test_generate_glance_url(self): generated_url = utils.generate_glance_url() - actual_url = "http://%s:%d" % (FLAGS.glance_host, FLAGS.glance_port) + actual_url = "http://%s:%d" % (CONF.glance_host, CONF.glance_port) self.assertEqual(generated_url, actual_url) def test_read_cached_file(self): diff --git a/manila/tests/utils.py b/manila/tests/utils.py index 9dd5ad5c9a..b8c71b4554 100644 --- a/manila/tests/utils.py +++ b/manila/tests/utils.py @@ -19,8 +19,6 @@ import os import manila.context -FLAGS = manila.flags.FLAGS - def get_test_admin_context(): return manila.context.get_admin_context() diff --git a/manila/tests/windows/windowsutils.py b/manila/tests/windows/windowsutils.py index 7100b2cb2c..0441093191 100644 --- a/manila/tests/windows/windowsutils.py +++ b/manila/tests/windows/windowsutils.py @@ -21,13 +21,12 @@ Windows storage classes to be used in testing. import os import sys -from manila import flags # Check needed for unit testing on Unix if os.name == 'nt': import wmi -FLAGS = flags.FLAGS +CONF = cfg.CONF class WindowsUtils(object): @@ -89,7 +88,7 @@ class WindowsUtils(object): def _get_vhd_path(self, volume_name): '''Gets the path disk of the volume.''' - base_vhd_folder = FLAGS.windows_iscsi_lun_path + base_vhd_folder = CONF.windows_iscsi_lun_path return os.path.join(base_vhd_folder, volume_name + ".vhd") def delete_snapshot(self, name): diff --git a/manila/utils.py b/manila/utils.py index 9ab42365c9..62c20ddd62 100644 --- a/manila/utils.py +++ b/manila/utils.py @@ -51,9 +51,10 @@ from eventlet import event from eventlet.green import subprocess from eventlet import greenthread from eventlet import pools +from oslo.config import cfg from manila import exception -from manila import flags + from manila.openstack.common import excutils from manila.openstack.common import importutils from manila.openstack.common import lockutils @@ -61,10 +62,10 @@ from manila.openstack.common import log as logging from manila.openstack.common import timeutils +CONF = cfg.CONF LOG = logging.getLogger(__name__) ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" -FLAGS = flags.FLAGS synchronized = lockutils.synchronized_with_prefix('manila-') @@ -79,9 +80,9 @@ def find_config(config_path): """ possible_locations = [ config_path, - os.path.join(FLAGS.state_path, "etc", "manila", config_path), - os.path.join(FLAGS.state_path, "etc", config_path), - os.path.join(FLAGS.state_path, config_path), + os.path.join(CONF.state_path, "etc", "manila", config_path), + os.path.join(CONF.state_path, "etc", config_path), + os.path.join(CONF.state_path, config_path), "/etc/manila/%s" % config_path, ] @@ -149,18 +150,18 @@ def execute(*cmd, **kwargs): if run_as_root: - if FLAGS.rootwrap_config is None or FLAGS.root_helper != 'sudo': + if CONF.rootwrap_config is None or CONF.root_helper != 'sudo': LOG.deprecated(_('The root_helper option (which lets you specify ' 'a root wrapper different from manila-rootwrap, ' 'and defaults to using sudo) is now deprecated. ' 'You should use the rootwrap_config option ' 'instead.')) - if (FLAGS.rootwrap_config is not None): + if (CONF.rootwrap_config is not None): cmd = ['sudo', 'manila-rootwrap', - FLAGS.rootwrap_config] + list(cmd) + CONF.rootwrap_config] + list(cmd) else: - cmd = shlex.split(FLAGS.root_helper) + list(cmd) + cmd = shlex.split(CONF.root_helper) + list(cmd) cmd = map(str, cmd) while attempts > 0: @@ -410,7 +411,7 @@ def last_completed_audit_period(unit=None): The begin timestamp of this audit period is the same as the end of the previous.""" if not unit: - unit = FLAGS.volume_usage_audit_period + unit = CONF.volume_usage_audit_period offset = 0 if '@' in unit: @@ -564,7 +565,7 @@ class LazyPluggable(object): def __get_backend(self): if not self.__backend: - backend_name = FLAGS[self.__pivot] + backend_name = CONF[self.__pivot] if backend_name not in self.__backends: raise exception.Error(_('Invalid backend: %s') % backend_name) @@ -845,7 +846,7 @@ def monkey_patch(): this function patches a decorator for all functions in specified modules. You can set decorators for each modules - using FLAGS.monkey_patch_modules. + using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'manila.api.ec2.cloud:' \ manila.openstack.common.notifier.api.notify_decorator' @@ -856,11 +857,11 @@ def monkey_patch(): name - name of the function function - object of the function """ - # If FLAGS.monkey_patch is not True, this function do nothing. - if not FLAGS.monkey_patch: + # If CONF.monkey_patch is not True, this function do nothing. + if not CONF.monkey_patch: return # Get list of modules and decorators - for module_and_decorator in FLAGS.monkey_patch_modules: + for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) @@ -909,7 +910,7 @@ def generate_glance_url(): """Generate the URL to glance.""" # TODO(jk0): This will eventually need to take SSL into consideration # when supported in glance. - return "http://%s:%d" % (FLAGS.glance_host, FLAGS.glance_port) + return "http://%s:%d" % (CONF.glance_host, CONF.glance_port) @contextlib.contextmanager @@ -1046,7 +1047,7 @@ def service_is_up(service): last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. elapsed = total_seconds(timeutils.utcnow() - last_heartbeat) - return abs(elapsed) <= FLAGS.service_down_time + return abs(elapsed) <= CONF.service_down_time def generate_mac_address(): diff --git a/manila/wsgi.py b/manila/wsgi.py index c0a9266634..1c5c217e98 100644 --- a/manila/wsgi.py +++ b/manila/wsgi.py @@ -36,7 +36,7 @@ import webob.dec import webob.exc from manila import exception -from manila import flags + from manila.openstack.common import log as logging from manila import utils @@ -65,7 +65,7 @@ socket_opts = [ CONF = cfg.CONF CONF.register_opts(socket_opts) -FLAGS = flags.FLAGS +CONF = cfg.CONF LOG = logging.getLogger(__name__) @@ -475,7 +475,7 @@ class Loader(object): :returns: None """ - config_path = config_path or FLAGS.api_paste_config + config_path = config_path or CONF.api_paste_config self.config_path = utils.find_config(config_path) def load_app(self, name):