Backslash continuation removal (Nova folsom-2)

Fixes bug #938588

Backslash continuations removal for scripts in bin/, plugin/, and etc.

Change-Id: Idd17048b6e8db6e939946968e011e68da8585b8d
This commit is contained in:
Zhongyue Luo 2012-05-16 17:08:27 +08:00
parent 0f2142b14a
commit 61c5597a09
26 changed files with 220 additions and 223 deletions

View File

@ -10,6 +10,8 @@ General
-------
- Put two newlines between top-level code (funcs, classes, etc)
- Put one newline between methods in classes and anywhere else
- Long lines should be wrapped in parentheses
in preference to using a backslash for line continuation.
- Do not write "except:", use "except Exception:" at the very least
- Include your name with TODOs as in "#TODO(termie)"
- Do not shadow a built-in or reserved word. Example::

View File

@ -48,10 +48,9 @@ from nova.openstack.common import cfg
from nova import rpc
delete_exchange_opt = \
cfg.BoolOpt('delete_exchange',
default=False,
help='delete nova exchange too.')
delete_exchange_opt = cfg.BoolOpt('delete_exchange',
default=False,
help='delete nova exchange too.')
FLAGS = flags.FLAGS
FLAGS.register_cli_opt(delete_exchange_opt)

View File

@ -108,10 +108,10 @@ def main():
if action in ['add', 'del', 'old']:
mac = argv[2]
ip = argv[3]
msg = _("Called '%(action)s' for mac '%(mac)s' with ip '%(ip)s'") % \
{"action": action,
"mac": mac,
"ip": ip}
msg = (_("Called '%(action)s' for mac '%(mac)s' with ip '%(ip)s'") %
{"action": action,
"mac": mac,
"ip": ip})
LOG.debug(msg)
globals()[action + '_lease'](mac, ip)
else:

View File

@ -593,8 +593,8 @@ class FixedIpCommands(object):
hostname = instance['hostname']
host = instance['host']
else:
print 'WARNING: fixed ip %s allocated to missing' \
' instance' % str(fixed_ip['address'])
print ('WARNING: fixed ip %s allocated to missing'
' instance' % str(fixed_ip['address']))
print "%-18s\t%-15s\t%-15s\t%s" % (
network['cidr'],
fixed_ip['address'],
@ -760,8 +760,8 @@ class NetworkCommands(object):
if FLAGS.network_manager in bridge_required:
raise exception.NetworkNotCreated(req='--bridge')
bridge_interface = bridge_interface or FLAGS.flat_interface or \
FLAGS.vlan_interface
bridge_interface = (bridge_interface or FLAGS.flat_interface or
FLAGS.vlan_interface)
if not bridge_interface:
interface_required = ['nova.network.manager.VlanManager']
if FLAGS.network_manager in interface_required:
@ -873,8 +873,8 @@ class NetworkCommands(object):
if uuid is None:
raise Exception("UUID is required to delete Quantum Networks")
if fixed_range:
raise Exception("Deleting by fixed_range is not supported " \
"with the QuantumManager")
raise Exception("Deleting by fixed_range is not supported "
"with the QuantumManager")
# delete the network
net_manager.delete_network(context.get_admin_context(),
fixed_range, uuid)
@ -920,20 +920,19 @@ class VmCommands(object):
def list(self, host=None):
"""Show a list of all instances"""
print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \
" %-10s %-10s %-10s %-5s" % (
_('instance'),
_('node'),
_('type'),
_('state'),
_('launched'),
_('image'),
_('kernel'),
_('ramdisk'),
_('project'),
_('user'),
_('zone'),
_('index'))
print ("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5s" % (_('instance'),
_('node'),
_('type'),
_('state'),
_('launched'),
_('image'),
_('kernel'),
_('ramdisk'),
_('project'),
_('user'),
_('zone'),
_('index')))
if host is None:
instances = db.instance_get_all(context.get_admin_context())
@ -942,20 +941,19 @@ class VmCommands(object):
context.get_admin_context(), host)
for instance in instances:
print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \
" %-10s %-10s %-10s %-5d" % (
instance['display_name'],
instance['host'],
instance['instance_type'].name,
instance['vm_state'],
instance['launched_at'],
instance['image_ref'],
instance['kernel_id'],
instance['ramdisk_id'],
instance['project_id'],
instance['user_id'],
instance['availability_zone'],
instance['launch_index'])
print ("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5d" % (instance['display_name'],
instance['host'],
instance['instance_type'].name,
instance['vm_state'],
instance['launched_at'],
instance['image_ref'],
instance['kernel_id'],
instance['ramdisk_id'],
instance['project_id'],
instance['user_id'],
instance['availability_zone'],
instance['launch_index']))
class ServiceCommands(object):
@ -1040,17 +1038,17 @@ class ServiceCommands(object):
"c": _('cpu'),
"d": _('mem(mb)'),
"e": _('hdd')}
print '%(a)-16s(total)%(b)26s%(c)8s%(d)8s' %\
{"a": host,
"b": result['resource']['vcpus'],
"c": result['resource']['memory_mb'],
"d": result['resource']['local_gb']}
print ('%(a)-16s(total)%(b)26s%(c)8s%(d)8s' %
{"a": host,
"b": result['resource']['vcpus'],
"c": result['resource']['memory_mb'],
"d": result['resource']['local_gb']})
print '%(a)-16s(used_now)%(b)23s%(c)8s%(d)8s' %\
{"a": host,
"b": result['resource']['vcpus_used'],
"c": result['resource']['memory_mb_used'],
"d": result['resource']['local_gb_used']}
print ('%(a)-16s(used_now)%(b)23s%(c)8s%(d)8s' %
{"a": host,
"b": result['resource']['vcpus_used'],
"c": result['resource']['memory_mb_used'],
"d": result['resource']['local_gb_used']})
# Printing a used_max
cpu_sum = 0
@ -1121,9 +1119,9 @@ class VersionCommands(object):
pass
def list(self):
print _("%(version)s (%(vcs)s)") % \
{'version': version.version_string(),
'vcs': version.version_string_with_vcs()}
print (_("%(version)s (%(vcs)s)") %
{'version': version.version_string(),
'vcs': version.version_string_with_vcs()})
def __call__(self):
self.list()
@ -1689,9 +1687,9 @@ def main():
script_name = argv.pop(0)
if len(argv) < 1:
print _("\nOpenStack Nova version: %(version)s (%(vcs)s)\n") % \
{'version': version.version_string(),
'vcs': version.version_string_with_vcs()}
print (_("\nOpenStack Nova version: %(version)s (%(vcs)s)\n") %
{'version': version.version_string(),
'vcs': version.version_string_with_vcs()})
print script_name + " category action [<args>]"
print _("Available categories:")
for k, _v in CATEGORIES:

View File

@ -104,8 +104,8 @@ class Extended_server_attributes(extensions.ExtensionDescriptor):
name = "ExtendedServerAttributes"
alias = "OS-EXT-SRV-ATTR"
namespace = "http://docs.openstack.org/compute/ext/" \
"extended_status/api/v1.1"
namespace = ("http://docs.openstack.org/compute/ext/"
"extended_status/api/v1.1")
updated = "2011-11-03T00:00:00+00:00"
def get_controller_extensions(self):
@ -125,9 +125,9 @@ class ExtendedServerAttributeTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('server', selector='server')
make_server(root)
return xmlutil.SlaveTemplate(root, 1, nsmap={
Extended_server_attributes.alias: \
Extended_server_attributes.namespace})
alias = Extended_server_attributes.alias
namespace = Extended_server_attributes.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})
class ExtendedServerAttributesTemplate(xmlutil.TemplateBuilder):
@ -135,6 +135,6 @@ class ExtendedServerAttributesTemplate(xmlutil.TemplateBuilder):
root = xmlutil.TemplateElement('servers')
elem = xmlutil.SubTemplateElement(root, 'server', selector='servers')
make_server(elem)
return xmlutil.SlaveTemplate(root, 1, nsmap={
Extended_server_attributes.alias: \
Extended_server_attributes.namespace})
alias = Extended_server_attributes.alias
namespace = Extended_server_attributes.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})

View File

@ -55,8 +55,7 @@ class FlavorextradataController(wsgi.Controller):
resp_obj.attach(xml=FlavorextradatumTemplate())
try:
flavor_ref = instance_types.\
get_instance_type_by_flavor_id(id)
flavor_ref = instance_types.get_instance_type_by_flavor_id(id)
except exception.FlavorNotFound:
explanation = _("Flavor not found.")
raise exception.HTTPNotFound(explanation=explanation)
@ -118,8 +117,9 @@ class FlavorextradatumTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('flavor', selector='flavor')
make_flavor(root)
return xmlutil.SlaveTemplate(root, 1, nsmap={
Flavorextradata.alias: Flavorextradata.namespace})
alias = Flavorextradata.alias
namespace = Flavorextradata.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})
class FlavorextradataTemplate(xmlutil.TemplateBuilder):
@ -127,5 +127,6 @@ class FlavorextradataTemplate(xmlutil.TemplateBuilder):
root = xmlutil.TemplateElement('flavors')
elem = xmlutil.SubTemplateElement(root, 'flavor', selector='flavors')
make_flavor(elem)
return xmlutil.SlaveTemplate(root, 1, nsmap={
Flavorextradata.alias: Flavorextradata.namespace})
alias = Flavorextradata.alias
namespace = Flavorextradata.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})

View File

@ -344,15 +344,16 @@ class NetworkInfo(list):
gateway = get_ip(subnet_v4['gateway'])
dhcp_server = subnet_v4.get_meta('dhcp_server', gateway)
network_dict = \
{'bridge': network['bridge'],
'id': network['id'],
'cidr': subnet_v4['cidr'],
'cidr_v6': subnet_v6['cidr'] if subnet_v6 else None,
'vlan': network.get_meta('vlan'),
'injected': network.get_meta('injected', False),
'multi_host': network.get_meta('multi_host', False),
'bridge_interface': network.get_meta('bridge_interface')}
network_dict = {
'bridge': network['bridge'],
'id': network['id'],
'cidr': subnet_v4['cidr'],
'cidr_v6': subnet_v6['cidr'] if subnet_v6 else None,
'vlan': network.get_meta('vlan'),
'injected': network.get_meta('injected', False),
'multi_host': network.get_meta('multi_host', False),
'bridge_interface': network.get_meta('bridge_interface')
}
# NOTE(tr3buchet): 'ips' bit here is tricky, we support a single
# subnet but we want all the IPs to be there
# so use the v4_subnets[0] and its IPs are first

View File

@ -283,8 +283,8 @@ class QuantumManager(manager.FloatingIP, manager.FlatManager):
# Now we can delete the network
self.q_conn.delete_network(q_tenant_id, net_uuid)
LOG.debug("Deleting network %s for tenant: %s" % \
(net_uuid, q_tenant_id))
LOG.debug("Deleting network %s for tenant: %s" %
(net_uuid, q_tenant_id))
self.ipam.delete_subnets_by_net_id(context, net_uuid, project_id)
# Get rid of dnsmasq
if FLAGS.quantum_use_dhcp:

View File

@ -68,8 +68,8 @@ def send_update_with_states(context, instance, old_vm_state, new_vm_state,
if old_vm_state != new_vm_state:
# yes, the vm state is changing:
fire_update = True
elif FLAGS.notify_on_state_change.lower() == "vm_and_task_state" and \
old_task_state != new_task_state:
elif (FLAGS.notify_on_state_change.lower() == "vm_and_task_state" and
old_task_state != new_task_state):
# yes, the task state is changing:
fire_update = True

View File

@ -4094,13 +4094,14 @@ class KeypairAPITestCase(BaseTestCase):
self.keypair_api = compute_api.KeypairAPI()
self.ctxt = context.RequestContext('fake', 'fake')
self._keypair_db_call_stubs()
self.pub_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLnVkqJu9WVf' \
'/5StU3JCrBR2r1s1j8K1tux+5XeSvdqaM8lMFNorzbY5iyoBbRS56gy' \
'1jmm43QsMPJsrpfUZKcJpRENSe3OxIIwWXRoiapZe78u/a9xKwj0avF' \
'YMcws9Rk9iAB7W4K1nEJbyCPl5lRBoyqeHBqrnnuXWEgGxJCK0Ah6wc' \
'OzwlEiVjdf4kxzXrwPHyi7Ea1qvnNXTziF8yYmUlH4C8UXfpTQckwSw' \
'pDyxZUc63P8q+vPbs3Q2kw+/7vvkCKHJAXVI+oCiyMMfffoTq16M1xf' \
'V58JstgtTqAXG+ZFpicGajREUE/E3hO5MGgcHmyzIrWHKpe1n3oEGuz'
self.pub_key = ('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLnVkqJu9WVf'
'/5StU3JCrBR2r1s1j8K1tux+5XeSvdqaM8lMFNorzbY5iyoBbR'
'S56gy1jmm43QsMPJsrpfUZKcJpRENSe3OxIIwWXRoiapZe78u/'
'a9xKwj0avFYMcws9Rk9iAB7W4K1nEJbyCPl5lRBoyqeHBqrnnu'
'XWEgGxJCK0Ah6wcOzwlEiVjdf4kxzXrwPHyi7Ea1qvnNXTziF8'
'yYmUlH4C8UXfpTQckwSwpDyxZUc63P8q+vPbs3Q2kw+/7vvkCK'
'HJAXVI+oCiyMMfffoTq16M1xfV58JstgtTqAXG+ZFpicGajREU'
'E/E3hO5MGgcHmyzIrWHKpe1n3oEGuz')
self.fingerprint = '4e:48:c6:a0:4a:f9:dd:b5:4c:85:54:5a:af:43:47:5a'
def _keypair_db_call_stubs(self):

View File

@ -128,8 +128,8 @@ class VolumeTestCase(test.TestCase):
self.volume.create_volume(self.context, volume_id)
self.mox.StubOutWithMock(self.volume.driver, 'delete_volume')
self.volume.driver.delete_volume(mox.IgnoreArg()) \
.AndRaise(exception.VolumeIsBusy)
self.volume.driver.delete_volume(mox.IgnoreArg()).AndRaise(
exception.VolumeIsBusy)
self.mox.ReplayAll()
res = self.volume.delete_volume(self.context, volume_id)
self.assertEqual(True, res)
@ -374,8 +374,8 @@ class VolumeTestCase(test.TestCase):
self.volume.create_snapshot(self.context, volume_id, snapshot_id)
self.mox.StubOutWithMock(self.volume.driver, 'delete_snapshot')
self.volume.driver.delete_snapshot(mox.IgnoreArg()) \
.AndRaise(exception.SnapshotIsBusy)
self.volume.driver.delete_snapshot(mox.IgnoreArg()).AndRaise(
exception.SnapshotIsBusy)
self.mox.ReplayAll()
self.volume.delete_snapshot(self.context, snapshot_id)
snapshot_ref = db.snapshot_get(self.context, snapshot_id)

View File

@ -129,9 +129,8 @@ def bind(src, target, instance_name):
s = os.stat(src)
cgroup_info = "b %s:%s rwm\n" % (os.major(s.st_rdev),
os.minor(s.st_rdev))
cgroups_path = \
"/sys/fs/cgroup/devices/libvirt/lxc/%s/devices.allow" \
% instance_name
cgroups_path = ("/sys/fs/cgroup/devices/libvirt/lxc/"
"%s/devices.allow" % instance_name)
utils.execute('tee', cgroups_path,
process_input=cgroup_info, run_as_root=True)

View File

@ -95,9 +95,9 @@ class LibvirtConfigGuestDisk(LibvirtConfigGuestDevice):
dev.set("type", self.source_type)
dev.set("device", self.source_device)
if self.driver_name is not None or \
self.driver_format is not None or \
self.driver_cache is not None:
if (self.driver_name is not None or
self.driver_format is not None or
self.driver_cache is not None):
drv = etree.Element("driver")
if self.driver_name is not None:
drv.set("name", self.driver_name)

View File

@ -1760,8 +1760,8 @@ class LibvirtConnection(driver.ComputeDriver):
return []
return filter(bool,
[target.get("dev") \
for target in doc.findall('devices/disk/target')])
[target.get("dev")
for target in doc.findall('devices/disk/target')])
def get_interfaces(self, instance_name):
"""

View File

@ -50,66 +50,65 @@ class Host(object):
def host_maintenance_mode(self, host, mode):
"""Start/Stop host maintenance window. On start, it triggers
guest VMs evacuation."""
if mode:
host_list = [host_ref for host_ref in
self._session.call_xenapi('host.get_all') \
if host_ref != self._session.get_xenapi_host()]
migrations_counter = vm_counter = 0
ctxt = context.get_admin_context()
for vm_ref, vm_rec in vm_utils.VMHelper.list_vms(self._session):
for host_ref in host_list:
try:
# Ensure only guest instances are migrated
uuid = vm_rec['other_config'].get('nova_uuid')
if not uuid:
name = vm_rec['name_label']
uuid = _uuid_find(ctxt, host, name)
if not uuid:
msg = _('Instance %(name)s running on %(host)s'
' could not be found in the database:'
' assuming it is a worker VM and skip'
'ping migration to a new host')
LOG.info(msg % locals())
continue
instance = db.instance_get_by_uuid(ctxt, uuid)
vm_counter = vm_counter + 1
dest = _host_find(ctxt, self._session, host, host_ref)
(old_ref, new_ref) = \
db.instance_update_and_get_original(ctxt,
instance.id,
{'host': dest,
'vm_state': vm_states.MIGRATING})
notifications.send_update(ctxt, old_ref, new_ref)
self._session.call_xenapi('VM.pool_migrate',
vm_ref, host_ref, {})
migrations_counter = migrations_counter + 1
(old_ref, new_ref) = \
db.instance_update_and_get_original(ctxt,
instance.id,
{'vm_state': vm_states.ACTIVE})
notifications.send_update(ctxt, old_ref, new_ref)
break
except self.XenAPI.Failure:
LOG.exception('Unable to migrate VM %(vm_ref)s'
'from %(host)s' % locals())
(old_ref, new_ref) = \
db.instance_update_and_get_original(ctxt,
instance.id,
{'hosts': host,
'vm_state': vm_states.ACTIVE})
notifications.send_update(ctxt, old_ref, new_ref)
if vm_counter == migrations_counter:
return 'on_maintenance'
else:
raise exception.NoValidHost(reason='Unable to find suitable '
'host for VMs evacuation')
else:
if not mode:
return 'off_maintenance'
host_list = [host_ref for host_ref in
self._session.call_xenapi('host.get_all')
if host_ref != self._session.get_xenapi_host()]
migrations_counter = vm_counter = 0
ctxt = context.get_admin_context()
for vm_ref, vm_rec in vm_utils.VMHelper.list_vms(self._session):
for host_ref in host_list:
try:
# Ensure only guest instances are migrated
uuid = vm_rec['other_config'].get('nova_uuid')
if not uuid:
name = vm_rec['name_label']
uuid = _uuid_find(ctxt, host, name)
if not uuid:
msg = _('Instance %(name)s running on %(host)s'
' could not be found in the database:'
' assuming it is a worker VM and skip'
' ping migration to a new host')
LOG.info(msg % locals())
continue
instance = db.instance_get_by_uuid(ctxt, uuid)
vm_counter = vm_counter + 1
dest = _host_find(ctxt, self._session, host, host_ref)
(old_ref, new_ref) = db.instance_update_and_get_original(
ctxt,
instance.id,
{'host': dest,
'vm_state': vm_states.MIGRATING})
notifications.send_update(ctxt, old_ref, new_ref)
self._session.call_xenapi('VM.pool_migrate',
vm_ref, host_ref, {})
migrations_counter = migrations_counter + 1
(old_ref, new_ref) = db.instance_update_and_get_original(
ctxt,
instance.id,
{'vm_state': vm_states.ACTIVE})
notifications.send_update(ctxt, old_ref, new_ref)
break
except self.XenAPI.Failure:
LOG.exception('Unable to migrate VM %(vm_ref)s'
'from %(host)s' % locals())
(old_ref, new_ref) = db.instance_update_and_get_original(
ctxt,
instance.id,
{'hosts': host,
'vm_state': vm_states.ACTIVE})
notifications.send_update(ctxt, old_ref, new_ref)
if vm_counter == migrations_counter:
return 'on_maintenance'
else:
raise exception.NoValidHost(reason='Unable to find suitable '
'host for VMs evacuation')
def set_host_enabled(self, _host, enabled):
"""Sets the specified host's ability to accept new instances."""

View File

@ -76,8 +76,8 @@ class XenAPIBridgeDriver(XenVIFDriver):
vlan_num = network.get_meta('vlan')
bridge = network['bridge']
bridge_interface = FLAGS.vlan_interface or \
network.get_meta('bridge_interface')
bridge_interface = (FLAGS.vlan_interface or
network.get_meta('bridge_interface'))
# Check whether bridge already exists
# Retrieve network whose name_label is "bridge"
network_ref = network_utils.NetworkHelper.find_network_with_name_label(

View File

@ -1433,8 +1433,8 @@ class VMOps(object):
for vif in network_info:
xs_data = self._vif_xenstore_data(vif)
location = \
'vm-data/networking/%s' % vif['address'].replace(':', '')
location = ('vm-data/networking/%s' %
vif['address'].replace(':', ''))
self._add_to_param_xenstore(vm_ref, location, json.dumps(xs_data))
try:
self._write_to_xenstore(instance, location, xs_data,

View File

@ -30,9 +30,8 @@ import novalib
def main(command, phys_dev_name):
ovs_ofctl = lambda *rule: novalib.execute('/usr/bin/ovs-ofctl', *rule)
bridge_name = \
novalib.execute_get_output('/usr/bin/ovs-vsctl',
'iface-to-br', phys_dev_name)
bridge_name = novalib.execute_get_output('/usr/bin/ovs-vsctl',
'iface-to-br', phys_dev_name)
# always clear all flows first
ovs_ofctl('del-flows', bridge_name)
@ -50,9 +49,9 @@ def main(command, phys_dev_name):
# Allow traffic from dom0 if there is a management interface
# present (its IP address is on the bridge itself)
bridge_addr = \
novalib.execute_get_output('/sbin/ip', '-o', '-f', 'inet', 'addr',
'show', bridge_name)
bridge_addr = novalib.execute_get_output('/sbin/ip', '-o', '-f',
'inet', 'addr', 'show',
bridge_name)
if bridge_addr != '':
ovs_ofctl('add-flow', bridge_name,
"priority=2,in_port=LOCAL,actions=normal")

View File

@ -95,8 +95,8 @@ def main(command, vif_raw, net_type):
apply_ovs_ipv4_flows(ovs, bridge, params)
if net_type in ('ipv6', 'all') and 'ip6s' in data:
for ip6 in data['ip6s']:
link_local = str(netaddr.EUI(data['mac']).eui64()\
.ipv6_link_local())
mac_eui64 = netaddr.EUI(data['mac']).eui64()
link_local = str(mac_eui64.ipv6_link_local())
ovs.params.update({'IPV6_LINK_LOCAL_ADDR': link_local})
ovs.params.update({'IPV6_GLOBAL_ADDR': ip6['ip']})
apply_ovs_ipv6_flows(ovs, bridge, params)
@ -228,8 +228,8 @@ def apply_ovs_ipv6_flows(ovs, bridge, params):
if __name__ == "__main__":
if len(sys.argv) != 4:
print "usage: %s [online|offline] vif-domid-idx [ipv4|ipv6|all] " % \
os.path.basename(sys.argv[0])
print ("usage: %s [online|offline] vif-domid-idx [ipv4|ipv6|all] " %
os.path.basename(sys.argv[0]))
sys.exit(1)
else:
command, vif_raw, net_type = sys.argv[1:4]

View File

@ -125,8 +125,8 @@ def apply_ebtables_rules(command, params):
if __name__ == "__main__":
if len(sys.argv) < 3:
print "usage: %s dom_id online|offline [vif]" % \
os.path.basename(sys.argv[0])
print ("usage: %s dom_id online|offline [vif]" %
os.path.basename(sys.argv[0]))
sys.exit(1)
else:
dom_id, command = sys.argv[1:3]

View File

@ -146,8 +146,8 @@ def _download_tarball(sr_path, image_id, glance_host, glance_port, auth_token):
if auth_token:
headers['x-auth-token'] = auth_token
url = "http://%(glance_host)s:%(glance_port)d/v1/images/"\
"%(image_id)s" % locals()
url = ("http://%(glance_host)s:%(glance_port)d/v1/images/"
"%(image_id)s" % locals())
logging.info("Downloading %s" % url)
request = urllib2.Request(url, headers=headers)

View File

@ -133,9 +133,9 @@ class _Win32Colorizer(object):
See _AnsiColorizer docstring.
"""
def __init__(self, stream):
from win32console import GetStdHandle, STD_OUT_HANDLE, \
FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
FOREGROUND_INTENSITY
from win32console import (GetStdHandle, STD_OUT_HANDLE,
FOREGROUND_RED, FOREGROUND_GREEN,
FOREGROUND_BLUE, FOREGROUND_INTENSITY)
red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
FOREGROUND_BLUE, FOREGROUND_INTENSITY)
self.stream = stream
@ -291,8 +291,8 @@ class NovaTestRunner(core.TextTestRunner):
if __name__ == '__main__':
if not os.getenv('EC2_ACCESS_KEY'):
print _('Missing EC2 environment variables. Please ' \
'source the appropriate novarc file before ' \
print _('Missing EC2 environment variables. Please '
'source the appropriate novarc file before '
'running this test.')
sys.exit(1)

View File

@ -233,8 +233,8 @@ def main():
ORIG_DUMP = ORIG_DB + ".dump"
NEW_DUMP = NEW_DB + ".dump"
db_type, orig_branch, orig_version, new_branch, new_version =\
parse_options()
options = parse_options()
db_type, orig_branch, orig_version, new_branch, new_version = options
# Since we're going to be switching branches, ensure user doesn't have any
# uncommited changes

View File

@ -119,21 +119,20 @@ def _get_windows_network_adapters():
wbem_service = wbem_locator.ConnectServer('.', 'root\cimv2')
wbem_network_adapters = wbem_service.InstancesOf('Win32_NetworkAdapter')
network_adapters = []
for wbem_network_adapter in wbem_network_adapters:
if wbem_network_adapter.NetConnectionStatus == 2 or \
wbem_network_adapter.NetConnectionStatus == 7:
adapter_name = wbem_network_adapter.NetConnectionID
mac_address = wbem_network_adapter.MacAddress.lower()
wbem_network_adapter_config = \
wbem_network_adapter.associators_(
for adapter in wbem_network_adapters:
if (adapter.NetConnectionStatus == 2 or
adapter.NetConnectionStatus == 7):
adapter_name = adapter.NetConnectionID
mac_address = adapter.MacAddress.lower()
config = adapter.associators_(
'Win32_NetworkAdapterSetting',
'Win32_NetworkAdapterConfiguration')[0]
ip_address = ''
subnet_mask = ''
if wbem_network_adapter_config.IPEnabled:
ip_address = wbem_network_adapter_config.IPAddress[0]
subnet_mask = wbem_network_adapter_config.IPSubnet[0]
#wbem_network_adapter_config.DefaultIPGateway[0]
if config.IPEnabled:
ip_address = config.IPAddress[0]
subnet_mask = config.IPSubnet[0]
#config.DefaultIPGateway[0]
network_adapters.append({'name': adapter_name,
'mac-address': mac_address,
'ip-address': ip_address,
@ -160,9 +159,8 @@ def _get_linux_network_adapters():
sock.fileno(),
0x8912,
struct.pack('iL', max_bytes, names.buffer_info()[0])))[0]
adapter_names = \
[names.tostring()[n_counter:n_counter + offset1].split('\0', 1)[0]
for n_counter in xrange(0, outbytes, offset2)]
adapter_names = [names.tostring()[n_cnt:n_cnt + offset1].split('\0', 1)[0]
for n_cnt in xrange(0, outbytes, offset2)]
network_adapters = []
for adapter_name in adapter_names:
ip_address = socket.inet_ntoa(fcntl.ioctl(
@ -257,10 +255,10 @@ def _windows_set_networking():
cmd = ['"' + vmware_tools_bin + '"', '--cmd', 'machine.id.get']
for network_detail in _parse_network_details(_execute(cmd,
check_exit_code=False)):
mac_address, ip_address, subnet_mask, gateway, broadcast,\
dns_servers = network_detail
adapter_name, current_ip_address = \
_get_win_adapter_name_and_ip_address(mac_address)
(mac_address, ip_address, subnet_mask, gateway, broadcast,
dns_servers) = network_detail
name_and_ip = _get_win_adapter_name_and_ip_address(mac_address)
adapter_name, current_ip_address = name_and_ip
if adapter_name and not ip_address == current_ip_address:
cmd = ['netsh', 'interface', 'ip', 'set', 'address',
'name="%s"' % adapter_name, 'source=static', ip_address,
@ -289,14 +287,14 @@ def _set_rhel_networking(network_details=None):
network_details = network_details or []
all_dns_servers = []
for network_detail in network_details:
mac_address, ip_address, subnet_mask, gateway, broadcast,\
dns_servers = network_detail
(mac_address, ip_address, subnet_mask, gateway, broadcast,
dns_servers) = network_detail
all_dns_servers.extend(dns_servers)
adapter_name, current_ip_address = \
_get_linux_adapter_name_and_ip_address(mac_address)
name_and_ip = _get_linux_adapter_name_and_ip_address(mac_address)
adapter_name, current_ip_address = name_and_ip
if adapter_name and not ip_address == current_ip_address:
interface_file_name = \
'/etc/sysconfig/network-scripts/ifcfg-%s' % adapter_name
interface_file_name = ('/etc/sysconfig/network-scripts/ifcfg-%s' %
adapter_name)
# Remove file
os.remove(interface_file_name)
# Touch file
@ -337,11 +335,11 @@ def _set_ubuntu_networking(network_details=None):
_execute(['touch', interface_file_name])
interface_file = open(interface_file_name, 'w')
for device, network_detail in enumerate(network_details):
mac_address, ip_address, subnet_mask, gateway, broadcast,\
dns_servers = network_detail
(mac_address, ip_address, subnet_mask, gateway, broadcast,
dns_servers) = network_detail
all_dns_servers.extend(dns_servers)
adapter_name, current_ip_address = \
_get_linux_adapter_name_and_ip_address(mac_address)
name_and_ip = _get_linux_adapter_name_and_ip_address(mac_address)
adapter_name, current_ip_address = name_and_ip
if adapter_name:
interface_file.write('\nauto %s' % adapter_name)

View File

@ -48,8 +48,8 @@ VERBOSE_MISSING_IMPORT = False
def is_import_exception(mod):
return mod in IMPORT_EXCEPTIONS or \
any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS)
return (mod in IMPORT_EXCEPTIONS or
any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS))
def import_normalize(line):
@ -114,9 +114,9 @@ def nova_one_import_per_line(logical_line):
"""
pos = logical_line.find(',')
parts = logical_line.split()
if pos > -1 and (parts[0] == "import" or
parts[0] == "from" and parts[2] == "import") and \
not is_import_exception(parts[1]):
if (pos > -1 and (parts[0] == "import" or
parts[0] == "from" and parts[2] == "import") and
not is_import_exception(parts[1])):
return pos, "NOVA N301: one import per line"
_missingImport = set([])

View File

@ -143,8 +143,8 @@ class Fedora(Distro):
def get_distro():
if os.path.exists('/etc/fedora-release') or \
os.path.exists('/etc/redhat-release'):
if (os.path.exists('/etc/fedora-release') or
os.path.exists('/etc/redhat-release')):
return Fedora()
else:
return Distro()