Merge "Don't use locals() and globals(), use a dict instead"

This commit is contained in:
Jenkins 2016-07-25 20:51:15 +00:00 committed by Gerrit Code Review
commit 015baf0d6c
4 changed files with 64 additions and 19 deletions

View File

@ -81,12 +81,17 @@ def add_action_parsers(subparsers):
# is passed if known. We don't care about
# hostname, but argparse will complain if we
# do not accept it.
for action in ['add', 'del', 'old']:
actions = {
'add': add_lease,
'del': del_lease,
'old': old_lease,
}
for action, func in actions.items():
parser = subparsers.add_parser(action)
parser.add_argument('mac')
parser.add_argument('ip')
parser.add_argument('hostname', nargs='?', default='')
parser.set_defaults(func=globals()[action + '_lease'])
parser.set_defaults(func=func)
CONF.register_cli_opt(

View File

@ -1101,11 +1101,6 @@ class NetworkManager(manager.Manager):
bridge_interface=None, dns1=None, dns2=None,
fixed_cidr=None, allowed_start=None,
allowed_end=None, **kwargs):
arg_names = ("label", "cidr", "multi_host", "num_networks",
"network_size", "cidr_v6",
"gateway", "gateway_v6", "bridge",
"bridge_interface", "dns1", "dns2",
"fixed_cidr", "allowed_start", "allowed_end")
if 'mtu' not in kwargs:
kwargs['mtu'] = CONF.network_device_mtu
if 'dhcp_server' not in kwargs:
@ -1114,8 +1109,23 @@ class NetworkManager(manager.Manager):
kwargs['enable_dhcp'] = True
if 'share_address' not in kwargs:
kwargs['share_address'] = CONF.share_dhcp_address
for name in arg_names:
kwargs[name] = locals()[name]
kwargs.update({
'label': label,
'cidr': cidr,
'multi_host': multi_host,
'num_networks': num_networks,
'network_size': network_size,
'cidr_v6': cidr_v6,
'gateway': gateway,
'gateway_v6': gateway_v6,
'bridge': bridge,
'bridge_interface': bridge_interface,
'dns1': dns1,
'dns2': dns2,
'fixed_cidr': fixed_cidr,
'allowed_start': allowed_start,
'allowed_end': allowed_end,
})
self._convert_int_args(kwargs)
kwargs["bridge"] = kwargs["bridge"] or CONF.flat_network_bridge

View File

@ -392,11 +392,11 @@ def inject_data(image, key=None, net=None, metadata=None, admin_password=None,
Returns True if all requested operations completed without issue.
Raises an exception if a mandatory item can't be injected.
"""
items = {'image': image, 'key': key, 'net': net, 'metadata': metadata,
'files': files, 'partition': partition}
LOG.debug("Inject data image=%(image)s key=%(key)s net=%(net)s "
"metadata=%(metadata)s admin_password=<SANITIZED> "
"files=%(files)s partition=%(partition)s",
{'image': image, 'key': key, 'net': net, 'metadata': metadata,
'files': files, 'partition': partition})
"files=%(files)s partition=%(partition)s", items)
try:
fs = vfs.VFS.instance_for_image(image, partition)
fs.setup()
@ -404,7 +404,7 @@ def inject_data(image, key=None, net=None, metadata=None, admin_password=None,
# If a mandatory item is passed to this function,
# then reraise the exception to indicate the error.
for inject in mandatory:
inject_val = locals()[inject]
inject_val = items[inject]
if inject_val:
raise
LOG.warning(_LW('Ignoring error injecting data into image %(image)s '
@ -493,12 +493,20 @@ def inject_data_into_fs(fs, key, net, metadata, admin_password, files,
Returns True if all requested operations completed without issue.
Raises an exception if a mandatory item can't be injected.
"""
items = {'key': key, 'net': net, 'metadata': metadata,
'admin_password': admin_password, 'files': files}
functions = {
'key': _inject_key_into_fs,
'net': _inject_net_into_fs,
'metadata': _inject_metadata_into_fs,
'admin_password': _inject_admin_password_into_fs,
'files': _inject_files_into_fs,
}
status = True
for inject in ('key', 'net', 'metadata', 'admin_password', 'files'):
inject_val = locals()[inject]
inject_func = globals()['_inject_%s_into_fs' % inject]
for inject, inject_val in items.items():
if inject_val:
try:
inject_func = functions[inject]
inject_func(inject_val, fs)
except Exception as e:
if inject in mandatory:

View File

@ -68,12 +68,23 @@ from nova.virt.xenapi.client import session as xenapi_session
_CLASSES = ['host', 'network', 'session', 'pool', 'SR', 'VBD',
'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task']
_after_create_functions = {}
_destroy_functions = {}
_db_content = {}
LOG = logging.getLogger(__name__)
def add_to_dict(functions):
"""A decorator that adds a function to dictionary."""
def decorator(func):
functions[func.__name__] = func
return func
return decorator
def reset():
for c in _CLASSES:
_db_content[c] = {}
@ -137,6 +148,7 @@ def create_vm(name_label, status, **kwargs):
return vm_ref
@add_to_dict(_destroy_functions)
def destroy_vm(vm_ref):
vm_rec = _db_content['VM'][vm_ref]
@ -149,6 +161,7 @@ def destroy_vm(vm_ref):
del _db_content['VM'][vm_ref]
@add_to_dict(_destroy_functions)
def destroy_vbd(vbd_ref):
vbd_rec = _db_content['VBD'][vbd_ref]
@ -163,6 +176,7 @@ def destroy_vbd(vbd_ref):
del _db_content['VBD'][vbd_ref]
@add_to_dict(_destroy_functions)
def destroy_vdi(vdi_ref):
vdi_rec = _db_content['VDI'][vdi_ref]
@ -196,6 +210,7 @@ def create_vdi(name_label, sr_ref, **kwargs):
return vdi_ref
@add_to_dict(_after_create_functions)
def after_VDI_create(vdi_ref, vdi_rec):
vdi_rec.setdefault('VBDs', [])
@ -214,6 +229,7 @@ def create_vbd(vm_ref, vdi_ref, userdevice=0, other_config=None):
return vbd_ref
@add_to_dict(_after_create_functions)
def after_VBD_create(vbd_ref, vbd_rec):
"""Create read-only fields and backref from VM and VDI to VBD when VBD
is created.
@ -235,6 +251,7 @@ def after_VBD_create(vbd_ref, vbd_rec):
vdi_rec['VBDs'].append(vbd_ref)
@add_to_dict(_after_create_functions)
def after_VIF_create(vif_ref, vif_rec):
"""Create backref from VM to VIF when VIF is created.
"""
@ -243,6 +260,7 @@ def after_VIF_create(vif_ref, vif_rec):
vm_rec['VIFs'].append(vif_ref)
@add_to_dict(_after_create_functions)
def after_VM_create(vm_ref, vm_rec):
"""Create read-only fields in the VM record."""
vm_rec.setdefault('domid', "-1")
@ -998,8 +1016,12 @@ class SessionBase(object):
# Call hook to provide any fixups needed (ex. creating backrefs)
after_hook = 'after_%s_create' % cls
if after_hook in globals():
globals()[after_hook](ref, params[1])
try:
func = _after_create_functions[after_hook]
except KeyError:
pass
else:
func(ref, params[1])
obj = get_record(cls, ref)
@ -1017,7 +1039,7 @@ class SessionBase(object):
raise Failure(['HANDLE_INVALID', table, ref])
# Call destroy function (if exists)
destroy_func = globals().get('destroy_%s' % table.lower())
destroy_func = _destroy_functions.get('destroy_%s' % table.lower())
if destroy_func:
destroy_func(ref)
else: