Switch from FLAGS to CONF in misc modules

Use the global CONF variable instead of FLAGS. This is purely a cleanup
since FLAGS is already just another reference to CONF.

We leave the nova.flags imports until a later cleanup commit since
removing them may cause unpredictable problems due to config options not
being registered.

Change-Id: Ib110ba8d1837780e90b0d3fe13f8e6b68ed15f65
This commit is contained in:
Mark McLoughlin
2012-11-04 21:32:45 +00:00
parent 45af1f23a4
commit f7bf85b5a9
10 changed files with 86 additions and 80 deletions

View File

@@ -17,9 +17,10 @@
import re import re
from nova import config
from nova import flags from nova import flags
FLAGS = flags.FLAGS CONF = config.CONF
DEFAULT_ROOT_DEV_NAME = '/dev/sda1' DEFAULT_ROOT_DEV_NAME = '/dev/sda1'
_DEFAULT_MAPPINGS = {'ami': 'sda1', _DEFAULT_MAPPINGS = {'ami': 'sda1',
@@ -94,7 +95,7 @@ def instance_block_mapping(instance, bdms):
root_device_name = instance['root_device_name'] root_device_name = instance['root_device_name']
# NOTE(clayg): remove this when xenapi is setting default_root_device # NOTE(clayg): remove this when xenapi is setting default_root_device
if root_device_name is None: if root_device_name is None:
if FLAGS.compute_driver.endswith('xenapi.XenAPIDriver'): if CONF.compute_driver.endswith('xenapi.XenAPIDriver'):
root_device_name = '/dev/xvda' root_device_name = '/dev/xvda'
else: else:
return _DEFAULT_MAPPINGS return _DEFAULT_MAPPINGS

View File

@@ -25,6 +25,7 @@ import eventlet
import eventlet.backdoor import eventlet.backdoor
import greenlet import greenlet
from nova import config
from nova import flags from nova import flags
from nova.openstack.common import cfg from nova.openstack.common import cfg
@@ -34,8 +35,8 @@ eventlet_backdoor_opts = [
help='port for eventlet backdoor to listen') help='port for eventlet backdoor to listen')
] ]
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opts(eventlet_backdoor_opts) CONF.register_opts(eventlet_backdoor_opts)
def dont_use_this(): def dont_use_this():
@@ -62,7 +63,7 @@ backdoor_locals = {
def initialize_if_enabled(): def initialize_if_enabled():
if FLAGS.backdoor_port is None: if CONF.backdoor_port is None:
return return
# NOTE(johannes): The standard sys.displayhook will print the value of # NOTE(johannes): The standard sys.displayhook will print the value of
@@ -76,5 +77,5 @@ def initialize_if_enabled():
sys.displayhook = displayhook sys.displayhook = displayhook
eventlet.spawn(eventlet.backdoor.backdoor_server, eventlet.spawn(eventlet.backdoor.backdoor_server,
eventlet.listen(('localhost', FLAGS.backdoor_port)), eventlet.listen(('localhost', CONF.backdoor_port)),
locals=backdoor_locals) locals=backdoor_locals)

View File

@@ -30,10 +30,11 @@ import os
import socket import socket
import sys import sys
from nova import config
from nova.openstack.common import cfg from nova.openstack.common import cfg
CONF = config.CONF
FLAGS = cfg.CONF FLAGS = CONF
def _get_my_ip(): def _get_my_ip():
@@ -88,8 +89,8 @@ debug_opts = [
help='Add python stack traces to SQL as comment strings'), help='Add python stack traces to SQL as comment strings'),
] ]
FLAGS.register_cli_opts(core_opts) CONF.register_cli_opts(core_opts)
FLAGS.register_cli_opts(debug_opts) CONF.register_cli_opts(debug_opts)
global_opts = [ global_opts = [
cfg.StrOpt('my_ip', cfg.StrOpt('my_ip',
@@ -376,4 +377,4 @@ global_opts = [
'vmwareapi.VMWareESXDriver'), 'vmwareapi.VMWareESXDriver'),
] ]
FLAGS.register_opts(global_opts) CONF.register_opts(global_opts)

View File

@@ -55,6 +55,7 @@ This module provides Manager, a base class for managers.
import eventlet import eventlet
from nova import config
from nova.db import base from nova.db import base
from nova import flags from nova import flags
from nova.openstack.common import log as logging from nova.openstack.common import log as logging
@@ -63,10 +64,7 @@ from nova.openstack.common.rpc import dispatcher as rpc_dispatcher
from nova.scheduler import rpcapi as scheduler_rpcapi from nova.scheduler import rpcapi as scheduler_rpcapi
from nova import version from nova import version
CONF = config.CONF
FLAGS = flags.FLAGS
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@@ -139,7 +137,7 @@ class Manager(base.Base):
def __init__(self, host=None, db_driver=None): def __init__(self, host=None, db_driver=None):
if not host: if not host:
host = FLAGS.host host = CONF.host
self.host = host self.host = host
self.load_plugins() self.load_plugins()
super(Manager, self).__init__(db_driver) super(Manager, self).__init__(db_driver)
@@ -215,8 +213,8 @@ class Manager(base.Base):
def service_config(self, context): def service_config(self, context):
config = {} config = {}
for key in FLAGS: for key in CONF:
config[key] = FLAGS.get(key, None) config[key] = CONF.get(key, None)
return config return config

View File

@@ -19,6 +19,7 @@
the system. the system.
""" """
from nova import config
import nova.context import nova.context
from nova import db from nova import db
from nova import exception from nova import exception
@@ -50,16 +51,16 @@ notify_api_faults = cfg.BoolOpt('notify_api_faults', default=False,
'in the API service.') 'in the API service.')
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opt(notify_state_opt) CONF.register_opt(notify_state_opt)
FLAGS.register_opt(notify_any_opt) CONF.register_opt(notify_any_opt)
FLAGS.register_opt(notify_api_faults) CONF.register_opt(notify_api_faults)
def send_api_fault(url, status, exception): def send_api_fault(url, status, exception):
"""Send an api.fault notification.""" """Send an api.fault notification."""
if not FLAGS.notify_api_faults: if not CONF.notify_api_faults:
return return
payload = {'url': url, 'exception': str(exception), 'status': status} payload = {'url': url, 'exception': str(exception), 'status': status}
@@ -75,7 +76,7 @@ def send_update(context, old_instance, new_instance, service=None, host=None):
in that instance in that instance
""" """
if not FLAGS.notify_on_any_change and not FLAGS.notify_on_state_change: if not CONF.notify_on_any_change and not CONF.notify_on_state_change:
# skip all this if updates are disabled # skip all this if updates are disabled
return return
@@ -91,8 +92,8 @@ def send_update(context, old_instance, new_instance, service=None, host=None):
if old_vm_state != new_vm_state: if old_vm_state != new_vm_state:
# yes, the vm state is changing: # yes, the vm state is changing:
update_with_state_change = True update_with_state_change = True
elif FLAGS.notify_on_state_change: elif CONF.notify_on_state_change:
if (FLAGS.notify_on_state_change.lower() == "vm_and_task_state" and if (CONF.notify_on_state_change.lower() == "vm_and_task_state" and
old_task_state != new_task_state): old_task_state != new_task_state):
# yes, the task state is changing: # yes, the task state is changing:
update_with_state_change = True update_with_state_change = True
@@ -120,7 +121,7 @@ def send_update_with_states(context, instance, old_vm_state, new_vm_state,
are any, in the instance are any, in the instance
""" """
if not FLAGS.notify_on_state_change: if not CONF.notify_on_state_change:
# skip all this if updates are disabled # skip all this if updates are disabled
return return
@@ -135,8 +136,8 @@ def send_update_with_states(context, instance, old_vm_state, new_vm_state,
if old_vm_state != new_vm_state: if old_vm_state != new_vm_state:
# yes, the vm state is changing: # yes, the vm state is changing:
fire_update = True fire_update = True
elif FLAGS.notify_on_state_change: elif CONF.notify_on_state_change:
if (FLAGS.notify_on_state_change.lower() == "vm_and_task_state" and if (CONF.notify_on_state_change.lower() == "vm_and_task_state" and
old_task_state != new_task_state): old_task_state != new_task_state):
# yes, the task state is changing: # yes, the task state is changing:
fire_update = True fire_update = True

View File

@@ -19,6 +19,7 @@
import os.path import os.path
from nova import config
from nova import exception from nova import exception
from nova import flags from nova import flags
from nova.openstack.common import cfg from nova.openstack.common import cfg
@@ -35,8 +36,8 @@ policy_opts = [
help=_('Rule checked when requested rule is not found')), help=_('Rule checked when requested rule is not found')),
] ]
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opts(policy_opts) CONF.register_opts(policy_opts)
_POLICY_PATH = None _POLICY_PATH = None
_POLICY_CACHE = {} _POLICY_CACHE = {}
@@ -54,17 +55,17 @@ def init():
global _POLICY_PATH global _POLICY_PATH
global _POLICY_CACHE global _POLICY_CACHE
if not _POLICY_PATH: if not _POLICY_PATH:
_POLICY_PATH = FLAGS.policy_file _POLICY_PATH = CONF.policy_file
if not os.path.exists(_POLICY_PATH): if not os.path.exists(_POLICY_PATH):
_POLICY_PATH = FLAGS.find_file(_POLICY_PATH) _POLICY_PATH = CONF.find_file(_POLICY_PATH)
if not _POLICY_PATH: if not _POLICY_PATH:
raise exception.ConfigNotFound(path=FLAGS.policy_file) raise exception.ConfigNotFound(path=CONF.policy_file)
utils.read_cached_file(_POLICY_PATH, _POLICY_CACHE, utils.read_cached_file(_POLICY_PATH, _POLICY_CACHE,
reload_func=_set_rules) reload_func=_set_rules)
def _set_rules(data): def _set_rules(data):
default_rule = FLAGS.policy_default_rule default_rule = CONF.policy_default_rule
policy.set_rules(policy.Rules.load_json(data, default_rule)) policy.set_rules(policy.Rules.load_json(data, default_rule))

View File

@@ -20,6 +20,7 @@
import datetime import datetime
from nova import config
from nova import db from nova import db
from nova import exception from nova import exception
from nova import flags from nova import flags
@@ -85,8 +86,8 @@ quota_opts = [
help='default driver to use for quota checks'), help='default driver to use for quota checks'),
] ]
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opts(quota_opts) CONF.register_opts(quota_opts)
class DbQuotaDriver(object): class DbQuotaDriver(object):
@@ -314,7 +315,7 @@ class DbQuotaDriver(object):
# Set up the reservation expiration # Set up the reservation expiration
if expire is None: if expire is None:
expire = FLAGS.reservation_expire expire = CONF.reservation_expire
if isinstance(expire, (int, long)): if isinstance(expire, (int, long)):
expire = datetime.timedelta(seconds=expire) expire = datetime.timedelta(seconds=expire)
if isinstance(expire, datetime.timedelta): if isinstance(expire, datetime.timedelta):
@@ -335,7 +336,7 @@ class DbQuotaDriver(object):
# session isn't available outside the DBAPI, we # session isn't available outside the DBAPI, we
# have to do the work there. # have to do the work there.
return db.quota_reserve(context, resources, quotas, deltas, expire, return db.quota_reserve(context, resources, quotas, deltas, expire,
FLAGS.until_refresh, FLAGS.max_age) CONF.until_refresh, CONF.max_age)
def commit(self, context, reservations): def commit(self, context, reservations):
"""Commit reservations. """Commit reservations.
@@ -476,7 +477,7 @@ class BaseResource(object):
def default(self): def default(self):
"""Return the default value of the quota.""" """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): class ReservableResource(BaseResource):
@@ -568,7 +569,7 @@ class QuotaEngine(object):
"""Initialize a Quota object.""" """Initialize a Quota object."""
if not quota_driver_class: if not quota_driver_class:
quota_driver_class = FLAGS.quota_driver quota_driver_class = CONF.quota_driver
if isinstance(quota_driver_class, basestring): if isinstance(quota_driver_class, basestring):
quota_driver_class = importutils.import_object(quota_driver_class) quota_driver_class = importutils.import_object(quota_driver_class)

View File

@@ -31,6 +31,7 @@ import eventlet
import greenlet import greenlet
from nova.common import eventlet_backdoor from nova.common import eventlet_backdoor
from nova import config
from nova import context from nova import context
from nova import db from nova import db
from nova import exception from nova import exception
@@ -90,8 +91,8 @@ service_opts = [
help='Number of workers for metadata service'), help='Number of workers for metadata service'),
] ]
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opts(service_opts) CONF.register_opts(service_opts)
class SignalExit(SystemExit): class SignalExit(SystemExit):
@@ -167,9 +168,9 @@ class ServiceLauncher(Launcher):
signal.signal(signal.SIGTERM, self._handle_signal) signal.signal(signal.SIGTERM, self._handle_signal)
signal.signal(signal.SIGINT, self._handle_signal) signal.signal(signal.SIGINT, self._handle_signal)
LOG.debug(_('Full set of FLAGS:')) LOG.debug(_('Full set of CONF:'))
for flag in FLAGS: for flag in CONF:
flag_get = FLAGS.get(flag, None) flag_get = CONF.get(flag, None)
# hide flag contents from log if contains a password # hide flag contents from log if contains a password
# should use secret flag when switch over to openstack-common # should use secret flag when switch over to openstack-common
if ("_password" in flag or "_key" in flag or if ("_password" in flag or "_key" in flag or
@@ -436,7 +437,7 @@ class Service(object):
self.timers.append(periodic) self.timers.append(periodic)
def _create_service_ref(self, context): def _create_service_ref(self, context):
zone = FLAGS.node_availability_zone zone = CONF.node_availability_zone
service_ref = db.service_create(context, service_ref = db.service_create(context,
{'host': self.host, {'host': self.host,
'binary': self.binary, 'binary': self.binary,
@@ -455,30 +456,30 @@ class Service(object):
periodic_fuzzy_delay=None): periodic_fuzzy_delay=None):
"""Instantiates class and passes back application object. """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 binary: defaults to basename of executable
:param topic: defaults to bin_name - 'nova-' part :param topic: defaults to bin_name - 'nova-' part
:param manager: defaults to FLAGS.<topic>_manager :param manager: defaults to CONF.<topic>_manager
:param report_interval: defaults to FLAGS.report_interval :param report_interval: defaults to CONF.report_interval
:param periodic_interval: defaults to FLAGS.periodic_interval :param periodic_interval: defaults to CONF.periodic_interval
:param periodic_fuzzy_delay: defaults to FLAGS.periodic_fuzzy_delay :param periodic_fuzzy_delay: defaults to CONF.periodic_fuzzy_delay
""" """
if not host: if not host:
host = FLAGS.host host = CONF.host
if not binary: if not binary:
binary = os.path.basename(inspect.stack()[-1][1]) binary = os.path.basename(inspect.stack()[-1][1])
if not topic: if not topic:
topic = binary.rpartition('nova-')[2] topic = binary.rpartition('nova-')[2]
if not manager: if not manager:
manager = FLAGS.get('%s_manager' % manager = CONF.get('%s_manager' %
binary.rpartition('nova-')[2], None) binary.rpartition('nova-')[2], None)
if report_interval is None: if report_interval is None:
report_interval = FLAGS.report_interval report_interval = CONF.report_interval
if periodic_interval is None: if periodic_interval is None:
periodic_interval = FLAGS.periodic_interval periodic_interval = CONF.periodic_interval
if periodic_fuzzy_delay is None: 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, service_obj = cls(host, binary, topic, manager,
report_interval=report_interval, report_interval=report_interval,
periodic_interval=periodic_interval, periodic_interval=periodic_interval,
@@ -523,7 +524,7 @@ class Service(object):
def report_state(self): def report_state(self):
"""Update the state of this service in the datastore.""" """Update the state of this service in the datastore."""
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
zone = FLAGS.node_availability_zone zone = CONF.node_availability_zone
state_catalog = {} state_catalog = {}
try: try:
try: try:
@@ -568,9 +569,9 @@ class WSGIService(object):
self.manager = self._get_manager() self.manager = self._get_manager()
self.loader = loader or wsgi.Loader() self.loader = loader or wsgi.Loader()
self.app = self.loader.load_app(name) self.app = self.loader.load_app(name)
self.host = getattr(FLAGS, '%s_listen' % name, "0.0.0.0") self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0")
self.port = getattr(FLAGS, '%s_listen_port' % name, 0) self.port = getattr(CONF, '%s_listen_port' % name, 0)
self.workers = getattr(FLAGS, '%s_workers' % name, None) self.workers = getattr(CONF, '%s_workers' % name, None)
self.server = wsgi.Server(name, self.server = wsgi.Server(name,
self.app, self.app,
host=self.host, host=self.host,
@@ -589,10 +590,10 @@ class WSGIService(object):
""" """
fl = '%s_manager' % self.name fl = '%s_manager' % self.name
if not fl in FLAGS: if not fl in CONF:
return None return None
manager_class_name = FLAGS.get(fl, None) manager_class_name = CONF.get(fl, None)
if not manager_class_name: if not manager_class_name:
return None return None

View File

@@ -47,6 +47,7 @@ from eventlet import greenthread
from eventlet import semaphore from eventlet import semaphore
import netaddr import netaddr
from nova import config
from nova import exception from nova import exception
from nova import flags from nova import flags
from nova.openstack.common import cfg from nova.openstack.common import cfg
@@ -57,9 +58,8 @@ from nova.openstack.common import timeutils
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
FLAGS = flags.FLAGS CONF = config.CONF
CONF.register_opt(
FLAGS.register_opt(
cfg.BoolOpt('disable_process_locking', default=False, cfg.BoolOpt('disable_process_locking', default=False,
help='Whether to disable inter-process locks')) help='Whether to disable inter-process locks'))
@@ -171,7 +171,7 @@ def execute(*cmd, **kwargs):
'to utils.execute: %r') % kwargs) 'to utils.execute: %r') % kwargs)
if run_as_root and os.geteuid() != 0: if run_as_root and os.geteuid() != 0:
cmd = ['sudo', 'nova-rootwrap', FLAGS.rootwrap_config] + list(cmd) cmd = ['sudo', 'nova-rootwrap', CONF.rootwrap_config] + list(cmd)
cmd = map(str, cmd) cmd = map(str, cmd)
@@ -330,7 +330,7 @@ def last_completed_audit_period(unit=None, before=None):
The begin timestamp of this audit period is the same as the The begin timestamp of this audit period is the same as the
end of the previous.""" end of the previous."""
if not unit: if not unit:
unit = FLAGS.instance_usage_audit_period unit = CONF.instance_usage_audit_period
offset = 0 offset = 0
if '@' in unit: if '@' in unit:
@@ -483,7 +483,7 @@ class LazyPluggable(object):
def __get_backend(self): def __get_backend(self):
if not self.__backend: if not self.__backend:
backend_name = FLAGS[self.__pivot] backend_name = CONF[self.__pivot]
if backend_name not in self.__backends: if backend_name not in self.__backends:
msg = _('Invalid backend: %s') % backend_name msg = _('Invalid backend: %s') % backend_name
raise exception.NovaException(msg) raise exception.NovaException(msg)
@@ -851,7 +851,7 @@ def monkey_patch():
this function patches a decorator this function patches a decorator
for all functions in specified modules. for all functions in specified modules.
You can set decorators for each 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". The format is "Module path:Decorator function".
Example: 'nova.api.ec2.cloud:nova.notifier.api.notify_decorator' Example: 'nova.api.ec2.cloud:nova.notifier.api.notify_decorator'
@@ -861,11 +861,11 @@ def monkey_patch():
name - name of the function name - name of the function
function - object of the function function - object of the function
""" """
# If FLAGS.monkey_patch is not True, this function do nothing. # If CONF.monkey_patch is not True, this function do nothing.
if not FLAGS.monkey_patch: if not CONF.monkey_patch:
return return
# Get list of modules and decorators # 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(':') module, decorator_name = module_and_decorator.split(':')
# import decorator function # import decorator function
decorator = importutils.import_class(decorator_name) decorator = importutils.import_class(decorator_name)
@@ -913,7 +913,7 @@ def generate_glance_url():
"""Generate the URL to glance.""" """Generate the URL to glance."""
# TODO(jk0): This will eventually need to take SSL into consideration # TODO(jk0): This will eventually need to take SSL into consideration
# when supported in glance. # when supported in glance.
return "http://%s:%d" % (FLAGS.glance_host, FLAGS.glance_port) return "http://%s:%d" % (CONF.glance_host, CONF.glance_port)
def generate_image_url(image_ref): def generate_image_url(image_ref):
@@ -1044,7 +1044,7 @@ def service_is_up(service):
last_heartbeat = service['updated_at'] or service['created_at'] last_heartbeat = service['updated_at'] or service['created_at']
# Timestamps in DB are UTC. # Timestamps in DB are UTC.
elapsed = total_seconds(timeutils.utcnow() - last_heartbeat) 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(): def generate_mac_address():

View File

@@ -30,6 +30,7 @@ import routes.middleware
import webob.dec import webob.dec
import webob.exc import webob.exc
from nova import config
from nova import exception from nova import exception
from nova import flags from nova import flags
from nova.openstack.common import cfg from nova.openstack.common import cfg
@@ -44,8 +45,8 @@ wsgi_opts = [
'into it: client_ip, date_time, request_line, status_code, ' 'into it: client_ip, date_time, request_line, status_code, '
'body_length, wall_seconds.') 'body_length, wall_seconds.')
] ]
FLAGS = flags.FLAGS CONF = config.CONF
FLAGS.register_opts(wsgi_opts) CONF.register_opts(wsgi_opts)
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@@ -95,7 +96,7 @@ class Server(object):
protocol=self._protocol, protocol=self._protocol,
custom_pool=self._pool, custom_pool=self._pool,
log=self._wsgi_logger, log=self._wsgi_logger,
log_format=FLAGS.wsgi_log_format) log_format=CONF.wsgi_log_format)
def stop(self): def stop(self):
"""Stop this server. """Stop this server.
@@ -362,11 +363,11 @@ class Loader(object):
:returns: None :returns: None
""" """
config_path = config_path or FLAGS.api_paste_config config_path = config_path or CONF.api_paste_config
if os.path.exists(config_path): if os.path.exists(config_path):
self.config_path = config_path self.config_path = config_path
else: else:
self.config_path = FLAGS.find_file(config_path) self.config_path = CONF.find_file(config_path)
if not self.config_path: if not self.config_path:
raise exception.ConfigNotFound(path=config_path) raise exception.ConfigNotFound(path=config_path)