Enabled hacking check for Python3 compatible print (H233)

Also fixed all violators of this check.

Change-Id: Id87ff6f44ab76fc59b18d5da739df475400e1259
This commit is contained in:
Alex Gaynor 2013-07-27 09:04:22 -07:00
parent 4d98d7e55d
commit 25afe4574c
7 changed files with 143 additions and 132 deletions

View File

@ -20,6 +20,8 @@
Handle lease database updates from DHCP servers. Handle lease database updates from DHCP servers.
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -127,6 +129,6 @@ def main():
LOG.error(_("Environment variable 'NETWORK_ID' must be set.")) LOG.error(_("Environment variable 'NETWORK_ID' must be set."))
return(1) return(1)
print init_leases(network_id) print(init_leases(network_id))
rpc.cleanup() rpc.cleanup()

View File

@ -53,6 +53,8 @@
CLI interface for nova management. CLI interface for nova management.
""" """
from __future__ import print_function
import netaddr import netaddr
import os import os
import sys import sys
@ -204,10 +206,10 @@ class ShellCommands(object):
def _db_error(caught_exception): def _db_error(caught_exception):
print caught_exception print(caught_exception)
print _("The above error may show that the database has not " print(_("The above error may show that the database has not "
"been created.\nPlease create a database using " "been created.\nPlease create a database using "
"'nova-manage db sync' before running this command.") "'nova-manage db sync' before running this command."))
exit(1) exit(1)
@ -247,14 +249,14 @@ class ProjectCommands(object):
if value.lower() == 'unlimited': if value.lower() == 'unlimited':
value = -1 value = -1
if int(value) < -1: if int(value) < -1:
print _('Quota limit must be -1 or greater.') print(_('Quota limit must be -1 or greater.'))
return(2) return(2)
if ((int(value) < minimum) and if ((int(value) < minimum) and
(maximum != -1 or (maximum == -1 and int(value) != -1))): (maximum != -1 or (maximum == -1 and int(value) != -1))):
print _('Quota limit must greater than %s.') % minimum print(_('Quota limit must greater than %s.') % minimum)
return(2) return(2)
if maximum != -1 and int(value) > maximum: if maximum != -1 and int(value) > maximum:
print _('Quota limit must less than %s.') % maximum print(_('Quota limit must less than %s.') % maximum)
return(2) return(2)
try: try:
db.quota_create(ctxt, project_id, key, value, db.quota_create(ctxt, project_id, key, value,
@ -263,16 +265,16 @@ class ProjectCommands(object):
db.quota_update(ctxt, project_id, key, value, db.quota_update(ctxt, project_id, key, value,
user_id=user_id) user_id=user_id)
else: else:
print _('%(key)s is not a valid quota key. Valid options are: ' print(_('%(key)s is not a valid quota key. Valid options are: '
'%(options)s.') % {'key': key, '%(options)s.') % {'key': key,
'options': ', '.join(quota)} 'options': ', '.join(quota)})
return(2) return(2)
print_format = "%-36s %-10s %-10s %-10s" print_format = "%-36s %-10s %-10s %-10s"
print print_format % ( print(print_format % (
_('Quota'), _('Quota'),
_('Limit'), _('Limit'),
_('In Use'), _('In Use'),
_('Reserved')) _('Reserved')))
# Retrieve the quota after update # Retrieve the quota after update
if user_id: if user_id:
quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id) quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
@ -281,8 +283,8 @@ class ProjectCommands(object):
for key, value in quota.iteritems(): for key, value in quota.iteritems():
if value['limit'] < 0 or value['limit'] is None: if value['limit'] < 0 or value['limit'] is None:
value['limit'] = 'unlimited' value['limit'] = 'unlimited'
print print_format % (key, value['limit'], value['in_use'], print(print_format % (key, value['limit'], value['in_use'],
value['reserved']) value['reserved']))
@args('--project', dest='project_id', metavar='<Project name>', @args('--project', dest='project_id', metavar='<Project name>',
help='Project name') help='Project name')
@ -315,7 +317,7 @@ class FixedIpCommands(object):
fixed_ips = db.fixed_ip_get_by_host(ctxt, host) fixed_ips = db.fixed_ip_get_by_host(ctxt, host)
except exception.NotFound as ex: except exception.NotFound as ex:
print _("error: %s") % ex print(_("error: %s") % ex)
return(2) return(2)
instances = db.instance_get_all(context.get_admin_context()) instances = db.instance_get_all(context.get_admin_context())
@ -323,10 +325,10 @@ class FixedIpCommands(object):
for instance in instances: for instance in instances:
instances_by_uuid[instance['uuid']] = instance instances_by_uuid[instance['uuid']] = instance
print "%-18s\t%-15s\t%-15s\t%s" % (_('network'), print("%-18s\t%-15s\t%-15s\t%s" % (_('network'),
_('IP address'), _('IP address'),
_('hostname'), _('hostname'),
_('host')) _('host')))
all_networks = {} all_networks = {}
try: try:
@ -338,7 +340,7 @@ class FixedIpCommands(object):
except exception.NoNetworksFound: except exception.NoNetworksFound:
# do not have any networks, so even if there are IPs, these # do not have any networks, so even if there are IPs, these
# IPs should have been deleted ones, so return. # IPs should have been deleted ones, so return.
print _('No fixed IP found.') print(_('No fixed IP found.'))
return return
has_ip = False has_ip = False
@ -354,15 +356,15 @@ class FixedIpCommands(object):
hostname = instance['hostname'] hostname = instance['hostname']
host = instance['host'] host = instance['host']
else: else:
print _('WARNING: fixed ip %s allocated to missing' print(_('WARNING: fixed ip %s allocated to missing'
' instance') % str(fixed_ip['address']) ' instance') % str(fixed_ip['address']))
print "%-18s\t%-15s\t%-15s\t%s" % ( print("%-18s\t%-15s\t%-15s\t%s" % (
network['cidr'], network['cidr'],
fixed_ip['address'], fixed_ip['address'],
hostname, host) hostname, host))
if not has_ip: if not has_ip:
print _('No fixed IP found.') print(_('No fixed IP found.'))
@args('--address', metavar='<ip address>', help='IP address') @args('--address', metavar='<ip address>', help='IP address')
def reserve(self, address): def reserve(self, address):
@ -390,7 +392,7 @@ class FixedIpCommands(object):
db.fixed_ip_update(ctxt, fixed_ip['address'], db.fixed_ip_update(ctxt, fixed_ip['address'],
{'reserved': reserved}) {'reserved': reserved})
except exception.NotFound as ex: except exception.NotFound as ex:
print _("error: %s") % ex print(_("error: %s") % ex)
return(2) return(2)
@ -468,7 +470,7 @@ class FloatingIpCommands(object):
else: else:
floating_ips = db.floating_ip_get_all_by_host(ctxt, host) floating_ips = db.floating_ip_get_all_by_host(ctxt, host)
except exception.NoFloatingIpsDefined: except exception.NoFloatingIpsDefined:
print _("No floating IP addresses have been defined.") print(_("No floating IP addresses have been defined."))
return return
for floating_ip in floating_ips: for floating_ip in floating_ips:
instance_uuid = None instance_uuid = None
@ -476,11 +478,11 @@ class FloatingIpCommands(object):
fixed_ip = db.fixed_ip_get(ctxt, floating_ip['fixed_ip_id']) fixed_ip = db.fixed_ip_get(ctxt, floating_ip['fixed_ip_id'])
instance_uuid = fixed_ip['instance_uuid'] instance_uuid = fixed_ip['instance_uuid']
print "%s\t%s\t%s\t%s\t%s" % (floating_ip['project_id'], print("%s\t%s\t%s\t%s\t%s" % (floating_ip['project_id'],
floating_ip['address'], floating_ip['address'],
instance_uuid, instance_uuid,
floating_ip['pool'], floating_ip['pool'],
floating_ip['interface']) floating_ip['interface']))
class NetworkCommands(object): class NetworkCommands(object):
@ -530,7 +532,7 @@ class NetworkCommands(object):
def list(self): def list(self):
"""List all created networks.""" """List all created networks."""
_fmt = "%-5s\t%-18s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s" _fmt = "%-5s\t%-18s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s"
print _fmt % (_('id'), print(_fmt % (_('id'),
_('IPv4'), _('IPv4'),
_('IPv6'), _('IPv6'),
_('start address'), _('start address'),
@ -538,17 +540,17 @@ class NetworkCommands(object):
_('DNS2'), _('DNS2'),
_('VlanID'), _('VlanID'),
_('project'), _('project'),
_("uuid")) _("uuid")))
try: try:
# Since network_get_all can throw exception.NoNetworksFound # Since network_get_all can throw exception.NoNetworksFound
# for this command to show a nice result, this exception # for this command to show a nice result, this exception
# should be caught and handled as such. # should be caught and handled as such.
networks = db.network_get_all(context.get_admin_context()) networks = db.network_get_all(context.get_admin_context())
except exception.NoNetworksFound: except exception.NoNetworksFound:
print _('No networks found') print(_('No networks found'))
else: else:
for network in networks: for network in networks:
print _fmt % (network.id, print(_fmt % (network.id,
network.cidr, network.cidr,
network.cidr_v6, network.cidr_v6,
network.dhcp_start, network.dhcp_start,
@ -556,7 +558,7 @@ class NetworkCommands(object):
network.dns2, network.dns2,
network.vlan, network.vlan,
network.project_id, network.project_id,
network.uuid) network.uuid))
@args('--fixed_range', metavar='<x.x.x.x/yy>', help='Network to delete') @args('--fixed_range', metavar='<x.x.x.x/yy>', help='Network to delete')
@args('--uuid', metavar='<uuid>', help='UUID of network to delete') @args('--uuid', metavar='<uuid>', help='UUID of network to delete')
@ -634,7 +636,7 @@ class VmCommands(object):
def list(self, host=None): def list(self, host=None):
"""Show a list of all instances.""" """Show a list of all instances."""
print ("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" print(("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5s" % (_('instance'), " %-10s %-10s %-10s %-5s" % (_('instance'),
_('node'), _('node'),
_('type'), _('type'),
@ -646,7 +648,7 @@ class VmCommands(object):
_('project'), _('project'),
_('user'), _('user'),
_('zone'), _('zone'),
_('index'))) _('index'))))
if host is None: if host is None:
instances = db.instance_get_all(context.get_admin_context()) instances = db.instance_get_all(context.get_admin_context())
@ -656,7 +658,7 @@ class VmCommands(object):
for instance in instances: for instance in instances:
instance_type = flavors.extract_flavor(instance) instance_type = flavors.extract_flavor(instance)
print ("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" print(("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5d" % (instance['display_name'], " %-10s %-10s %-10s %-5d" % (instance['display_name'],
instance['host'], instance['host'],
instance_type['name'], instance_type['name'],
@ -668,7 +670,7 @@ class VmCommands(object):
instance['project_id'], instance['project_id'],
instance['user_id'], instance['user_id'],
instance['availability_zone'], instance['availability_zone'],
instance['launch_index'])) instance['launch_index'])))
class ServiceCommands(object): class ServiceCommands(object):
@ -689,22 +691,22 @@ class ServiceCommands(object):
if service: if service:
services = [s for s in services if s['binary'] == service] services = [s for s in services if s['binary'] == service]
print_format = "%-16s %-36s %-16s %-10s %-5s %-10s" print_format = "%-16s %-36s %-16s %-10s %-5s %-10s"
print print_format % ( print(print_format % (
_('Binary'), _('Binary'),
_('Host'), _('Host'),
_('Zone'), _('Zone'),
_('Status'), _('Status'),
_('State'), _('State'),
_('Updated_At')) _('Updated_At')))
for svc in services: for svc in services:
alive = servicegroup_api.service_is_up(svc) alive = servicegroup_api.service_is_up(svc)
art = (alive and ":-)") or "XXX" art = (alive and ":-)") or "XXX"
active = 'enabled' active = 'enabled'
if svc['disabled']: if svc['disabled']:
active = 'disabled' active = 'disabled'
print print_format % (svc['binary'], svc['host'], print(print_format % (svc['binary'], svc['host'],
svc['availability_zone'], active, art, svc['availability_zone'], active, art,
svc['updated_at']) svc['updated_at']))
@args('--host', metavar='<host>', help='Host') @args('--host', metavar='<host>', help='Host')
@args('--service', metavar='<service>', help='Nova service') @args('--service', metavar='<service>', help='Nova service')
@ -715,10 +717,10 @@ class ServiceCommands(object):
svc = db.service_get_by_args(ctxt, host, service) svc = db.service_get_by_args(ctxt, host, service)
db.service_update(ctxt, svc['id'], {'disabled': False}) db.service_update(ctxt, svc['id'], {'disabled': False})
except exception.NotFound as ex: except exception.NotFound as ex:
print _("error: %s") % ex print(_("error: %s") % ex)
return(2) return(2)
print (_("Service %(service)s on host %(host)s enabled.") % print((_("Service %(service)s on host %(host)s enabled.") %
{'service': service, 'host': host}) {'service': service, 'host': host}))
@args('--host', metavar='<host>', help='Host') @args('--host', metavar='<host>', help='Host')
@args('--service', metavar='<service>', help='Nova service') @args('--service', metavar='<service>', help='Nova service')
@ -729,10 +731,10 @@ class ServiceCommands(object):
svc = db.service_get_by_args(ctxt, host, service) svc = db.service_get_by_args(ctxt, host, service)
db.service_update(ctxt, svc['id'], {'disabled': True}) db.service_update(ctxt, svc['id'], {'disabled': True})
except exception.NotFound as ex: except exception.NotFound as ex:
print _("error: %s") % ex print(_("error: %s") % ex)
return(2) return(2)
print (_("Service %(service)s on host %(host)s disabled.") % print((_("Service %(service)s on host %(host)s disabled.") %
{'service': service, 'host': host}) {'service': service, 'host': host}))
def _show_host_resources(self, context, host): def _show_host_resources(self, context, host):
"""Shows the physical/usage resource given by hosts. """Shows the physical/usage resource given by hosts.
@ -799,27 +801,27 @@ class ServiceCommands(object):
host=host) host=host)
if not isinstance(result, dict): if not isinstance(result, dict):
print _('An unexpected error has occurred.') print(_('An unexpected error has occurred.'))
print _('[Result]'), result print(_('[Result]'), result)
else: else:
# Printing a total and used_now # Printing a total and used_now
# (NOTE)The host name width 16 characters # (NOTE)The host name width 16 characters
print '%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % {"a": _('HOST'), print('%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % {"a": _('HOST'),
"b": _('PROJECT'), "b": _('PROJECT'),
"c": _('cpu'), "c": _('cpu'),
"d": _('mem(mb)'), "d": _('mem(mb)'),
"e": _('hdd')} "e": _('hdd')})
print ('%(a)-16s(total)%(b)26s%(c)8s%(d)8s' % print(('%(a)-16s(total)%(b)26s%(c)8s%(d)8s' %
{"a": host, {"a": host,
"b": result['resource']['vcpus'], "b": result['resource']['vcpus'],
"c": result['resource']['memory_mb'], "c": result['resource']['memory_mb'],
"d": result['resource']['local_gb']}) "d": result['resource']['local_gb']}))
print ('%(a)-16s(used_now)%(b)23s%(c)8s%(d)8s' % print(('%(a)-16s(used_now)%(b)23s%(c)8s%(d)8s' %
{"a": host, {"a": host,
"b": result['resource']['vcpus_used'], "b": result['resource']['vcpus_used'],
"c": result['resource']['memory_mb_used'], "c": result['resource']['memory_mb_used'],
"d": result['resource']['local_gb_used']}) "d": result['resource']['local_gb_used']}))
# Printing a used_max # Printing a used_max
cpu_sum = 0 cpu_sum = 0
@ -830,18 +832,18 @@ class ServiceCommands(object):
mem_sum += val['memory_mb'] mem_sum += val['memory_mb']
hdd_sum += val['root_gb'] hdd_sum += val['root_gb']
hdd_sum += val['ephemeral_gb'] hdd_sum += val['ephemeral_gb']
print '%(a)-16s(used_max)%(b)23s%(c)8s%(d)8s' % {"a": host, print('%(a)-16s(used_max)%(b)23s%(c)8s%(d)8s' % {"a": host,
"b": cpu_sum, "b": cpu_sum,
"c": mem_sum, "c": mem_sum,
"d": hdd_sum} "d": hdd_sum})
for p_id, val in result['usage'].items(): for p_id, val in result['usage'].items():
print '%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % { print('%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % {
"a": host, "a": host,
"b": p_id, "b": p_id,
"c": val['vcpus'], "c": val['vcpus'],
"d": val['memory_mb'], "d": val['memory_mb'],
"e": val['root_gb'] + val['ephemeral_gb']} "e": val['root_gb'] + val['ephemeral_gb']})
class HostCommands(object): class HostCommands(object):
@ -851,8 +853,8 @@ class HostCommands(object):
"""Show a list of all physical hosts. Filter by zone. """Show a list of all physical hosts. Filter by zone.
args: [zone] args: [zone]
""" """
print "%-25s\t%-15s" % (_('host'), print("%-25s\t%-15s" % (_('host'),
_('zone')) _('zone')))
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
services = db.service_get_all(ctxt) services = db.service_get_all(ctxt)
services = availability_zones.set_availability_zones(ctxt, services) services = availability_zones.set_availability_zones(ctxt, services)
@ -864,7 +866,7 @@ class HostCommands(object):
hosts.append(srv) hosts.append(srv)
for h in hosts: for h in hosts:
print "%-25s\t%-15s" % (h['host'], h['availability_zone']) print("%-25s\t%-15s" % (h['host'], h['availability_zone']))
class DbCommands(object): class DbCommands(object):
@ -880,7 +882,7 @@ class DbCommands(object):
def version(self): def version(self):
"""Print the current database version.""" """Print the current database version."""
print migration.db_version() print(migration.db_version())
@args('--max_rows', metavar='<number>', @args('--max_rows', metavar='<number>',
help='Maximum number of deleted rows to archive') help='Maximum number of deleted rows to archive')
@ -891,7 +893,7 @@ class DbCommands(object):
if max_rows is not None: if max_rows is not None:
max_rows = int(max_rows) max_rows = int(max_rows)
if max_rows < 0: if max_rows < 0:
print _("Must supply a positive value for max_rows") print(_("Must supply a positive value for max_rows"))
return(1) return(1)
admin_context = context.get_admin_context() admin_context = context.get_admin_context()
db.archive_deleted_rows(admin_context, max_rows) db.archive_deleted_rows(admin_context, max_rows)
@ -905,11 +907,11 @@ class FlavorCommands(object):
def _print_flavors(self, name, val): def _print_flavors(self, name, val):
is_public = ('private', 'public')[val["is_public"] == 1] is_public = ('private', 'public')[val["is_public"] == 1]
print ("%s: Memory: %sMB, VCPUS: %s, Root: %sGB, Ephemeral: %sGb, " print(("%s: Memory: %sMB, VCPUS: %s, Root: %sGB, Ephemeral: %sGb, "
"FlavorID: %s, Swap: %sMB, RXTX Factor: %s, %s, ExtraSpecs %s") % ( "FlavorID: %s, Swap: %sMB, RXTX Factor: %s, %s, ExtraSpecs %s") % (
name, val["memory_mb"], val["vcpus"], val["root_gb"], name, val["memory_mb"], val["vcpus"], val["root_gb"],
val["ephemeral_gb"], val["flavorid"], val["swap"], val["ephemeral_gb"], val["flavorid"], val["swap"],
val["rxtx_factor"], is_public, val["extra_specs"]) val["rxtx_factor"], is_public, val["extra_specs"]))
@args('--name', metavar='<name>', @args('--name', metavar='<name>',
help='Name of flavor') help='Name of flavor')
@ -933,22 +935,22 @@ class FlavorCommands(object):
swap=swap, rxtx_factor=rxtx_factor, swap=swap, rxtx_factor=rxtx_factor,
is_public=is_public) is_public=is_public)
except exception.InvalidInput as e: except exception.InvalidInput as e:
print _("Must supply valid parameters to create flavor") print(_("Must supply valid parameters to create flavor"))
print e print(e)
return(1) return 1
except exception.InstanceTypeExists: except exception.InstanceTypeExists:
print _("Flavor exists.") print(_("Flavor exists."))
print _("Please ensure flavor name and flavorid are " print(_("Please ensure flavor name and flavorid are "
"unique.") "unique."))
print _("Currently defined flavor names and flavorids:") print(_("Currently defined flavor names and flavorids:"))
print print()
self.list() self.list()
return(2) return 2
except Exception: except Exception:
print _("Unknown error") print(_("Unknown error"))
return(3) return 3
else: else:
print _("%s created") % name print(_("%s created") % name)
@args('--name', metavar='<name>', help='Name of flavor') @args('--name', metavar='<name>', help='Name of flavor')
def delete(self, name): def delete(self, name):
@ -956,15 +958,15 @@ class FlavorCommands(object):
try: try:
flavors.destroy(name) flavors.destroy(name)
except exception.InstanceTypeNotFound: except exception.InstanceTypeNotFound:
print _("Valid flavor name is required") print(_("Valid flavor name is required"))
return(1) return 1
except db_exc.DBError as e: except db_exc.DBError as e:
print _("DB Error: %s") % e print(_("DB Error: %s") % e)
return(2) return(2)
except Exception: except Exception:
return(3) return(3)
else: else:
print _("%s deleted") % name print(_("%s deleted") % name)
@args('--name', metavar='<name>', help='Name of flavor') @args('--name', metavar='<name>', help='Name of flavor')
def list(self, name=None): def list(self, name=None):
@ -991,7 +993,7 @@ class FlavorCommands(object):
try: try:
inst_type = flavors.get_flavor_by_name(name) inst_type = flavors.get_flavor_by_name(name)
except exception.InstanceTypeNotFoundByName as e: except exception.InstanceTypeNotFoundByName as e:
print e print(e)
return(2) return(2)
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
@ -1000,9 +1002,9 @@ class FlavorCommands(object):
ctxt, ctxt,
inst_type["flavorid"], inst_type["flavorid"],
ext_spec) ext_spec)
print (_("Key %(key)s set to %(value)s on instance " print((_("Key %(key)s set to %(value)s on instance "
"type %(name)s") % "type %(name)s") %
{'key': key, 'value': value, 'name': name}) {'key': key, 'value': value, 'name': name}))
except db_exc.DBError as e: except db_exc.DBError as e:
_db_error(e) _db_error(e)
@ -1014,7 +1016,7 @@ class FlavorCommands(object):
try: try:
inst_type = flavors.get_flavor_by_name(name) inst_type = flavors.get_flavor_by_name(name)
except exception.InstanceTypeNotFoundByName as e: except exception.InstanceTypeNotFoundByName as e:
print e print(e)
return(2) return(2)
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
@ -1023,8 +1025,8 @@ class FlavorCommands(object):
inst_type["flavorid"], inst_type["flavorid"],
key) key)
print (_("Key %(key)s on flavor %(name)s unset") % print((_("Key %(key)s on flavor %(name)s unset") %
{'key': key, 'name': name}) {'key': key, 'name': name}))
except db_exc.DBError as e: except db_exc.DBError as e:
_db_error(e) _db_error(e)
@ -1084,12 +1086,12 @@ class AgentBuildCommands(object):
if hypervisor and key != hypervisor: if hypervisor and key != hypervisor:
continue continue
print _('Hypervisor: %s') % key print(_('Hypervisor: %s') % key)
print fmt % ('-' * 10, '-' * 8, '-' * 12, '-' * 32) print(fmt % ('-' * 10, '-' * 8, '-' * 12, '-' * 32))
for agent_build in buildlist: for agent_build in buildlist:
print fmt % (agent_build.os, agent_build.architecture, print(fmt % (agent_build.os, agent_build.architecture,
agent_build.version, agent_build.md5hash) agent_build.version, agent_build.md5hash))
print ' %s' % agent_build.url print(' %s' % agent_build.url)
print print
@ -1130,13 +1132,13 @@ class GetLogCommands(object):
if line.find(" ERROR ") > 0: if line.find(" ERROR ") > 0:
error_found += 1 error_found += 1
if print_name == 0: if print_name == 0:
print log_file + ":-" print(log_file + ":-")
print_name = 1 print_name = 1
linenum = len(lines) - index linenum = len(lines) - index
print (_('Line %(linenum)d : %(line)s') % print((_('Line %(linenum)d : %(line)s') %
{'linenum': linenum, 'line': line}) {'linenum': linenum, 'line': line}))
if error_found == 0: if error_found == 0:
print _('No errors in logfiles!') print(_('No errors in logfiles!'))
@args('--num_entries', metavar='<number of entries>', @args('--num_entries', metavar='<number of entries>',
help='number of entries(default: 10)') help='number of entries(default: 10)')
@ -1150,20 +1152,20 @@ class GetLogCommands(object):
elif os.path.exists('/var/log/messages'): elif os.path.exists('/var/log/messages'):
log_file = '/var/log/messages' log_file = '/var/log/messages'
else: else:
print _('Unable to find system log file!') print(_('Unable to find system log file!'))
return(1) return(1)
lines = [line.strip() for line in open(log_file, "r")] lines = [line.strip() for line in open(log_file, "r")]
lines.reverse() lines.reverse()
print _('Last %s nova syslog entries:-') % (entries) print(_('Last %s nova syslog entries:-') % (entries))
for line in lines: for line in lines:
if line.find("nova") > 0: if line.find("nova") > 0:
count += 1 count += 1
print "%s" % (line) print("%s" % (line))
if count == entries: if count == entries:
break break
if count == 0: if count == 0:
print _('No nova entries in syslog!') print(_('No nova entries in syslog!'))
class CellCommands(object): class CellCommands(object):
@ -1189,7 +1191,7 @@ class CellCommands(object):
woffset=None, wscale=None): woffset=None, wscale=None):
if cell_type not in ['parent', 'child']: if cell_type not in ['parent', 'child']:
print "Error: cell type must be 'parent' or 'child'" print("Error: cell type must be 'parent' or 'child'")
return(2) return(2)
# Set up the transport URL # Set up the transport URL
@ -1221,18 +1223,18 @@ class CellCommands(object):
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
cells = db.cell_get_all(ctxt) cells = db.cell_get_all(ctxt)
fmt = "%3s %-10s %-6s %-10s %-15s %-5s %-10s" fmt = "%3s %-10s %-6s %-10s %-15s %-5s %-10s"
print fmt % ('Id', 'Name', 'Type', 'Username', 'Hostname', print(fmt % ('Id', 'Name', 'Type', 'Username', 'Hostname',
'Port', 'VHost') 'Port', 'VHost'))
print fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15, print(fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15,
'-' * 5, '-' * 10) '-' * 5, '-' * 10))
for cell in cells: for cell in cells:
transport = rpc_driver.parse_transport_url(cell.transport_url) transport = rpc_driver.parse_transport_url(cell.transport_url)
print fmt % (cell.id, cell.name, print(fmt % (cell.id, cell.name,
'parent' if cell.is_parent else 'child', 'parent' if cell.is_parent else 'child',
transport['username'], transport['hostname'], transport['username'], transport['hostname'],
transport['port'], transport['virtual_host']) transport['port'], transport['virtual_host']))
print fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15, print(fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15,
'-' * 5, '-' * 10) '-' * 5, '-' * 10))
CATEGORIES = { CATEGORIES = {
@ -1321,27 +1323,27 @@ def main():
cfgfile = CONF.config_file[-1] if CONF.config_file else None cfgfile = CONF.config_file[-1] if CONF.config_file else None
if cfgfile and not os.access(cfgfile, os.R_OK): if cfgfile and not os.access(cfgfile, os.R_OK):
st = os.stat(cfgfile) st = os.stat(cfgfile)
print _("Could not read %s. Re-running with sudo") % cfgfile print(_("Could not read %s. Re-running with sudo") % cfgfile)
try: try:
os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv) os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv)
except Exception: except Exception:
print _('sudo failed, continuing as if nothing happened') print(_('sudo failed, continuing as if nothing happened'))
print _('Please re-run nova-manage as root.') print(_('Please re-run nova-manage as root.'))
return(2) return(2)
if CONF.category.name == "version": if CONF.category.name == "version":
print version.version_string_with_package() print(version.version_string_with_package())
return(0) return(0)
if CONF.category.name == "bash-completion": if CONF.category.name == "bash-completion":
if not CONF.category.query_category: if not CONF.category.query_category:
print " ".join(CATEGORIES.keys()) print(" ".join(CATEGORIES.keys()))
elif CONF.category.query_category in CATEGORIES: elif CONF.category.query_category in CATEGORIES:
fn = CATEGORIES[CONF.category.query_category] fn = CATEGORIES[CONF.category.query_category]
command_object = fn() command_object = fn()
actions = methods_of(command_object) actions = methods_of(command_object)
print " ".join([k for (k, v) in actions]) print(" ".join([k for (k, v) in actions]))
return(0) return(0)
fn = CONF.category.action_fn fn = CONF.category.action_fn
@ -1363,14 +1365,14 @@ def main():
# NOTE(mikal): this isn't the most helpful error message ever. It is # NOTE(mikal): this isn't the most helpful error message ever. It is
# long, and tells you a lot of things you probably don't want to know # long, and tells you a lot of things you probably don't want to know
# if you just got a single arg wrong. # if you just got a single arg wrong.
print fn.__doc__ print(fn.__doc__)
CONF.print_help() CONF.print_help()
print e print(e)
return(1) return(1)
try: try:
ret = fn(*fn_args, **fn_kwargs) ret = fn(*fn_args, **fn_kwargs)
rpc.cleanup() rpc.cleanup()
return(ret) return(ret)
except Exception: except Exception:
print _("Command failed, please check log for more info") print(_("Command failed, please check log for more info"))
raise raise

View File

@ -20,6 +20,8 @@ Websocket proxy that is compatible with OpenStack Nova
noVNC consoles. Leverages websockify.py by Joel Martin noVNC consoles. Leverages websockify.py by Joel Martin
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -55,12 +57,12 @@ def main():
config.parse_args(sys.argv) config.parse_args(sys.argv)
if CONF.ssl_only and not os.path.exists(CONF.cert): if CONF.ssl_only and not os.path.exists(CONF.cert):
print "SSL only and %s not found" % CONF.cert print("SSL only and %s not found" % CONF.cert)
return(-1) return(-1)
# Check to see if novnc html/js/css files are present # Check to see if novnc html/js/css files are present
if not os.path.exists(CONF.web): if not os.path.exists(CONF.web):
print "Can not find novnc html/js/css files at %s." % CONF.web print("Can not find novnc html/js/css files at %s." % CONF.web)
return(-1) return(-1)
# Create and start the NovaWebSockets proxy # Create and start the NovaWebSockets proxy

View File

@ -20,6 +20,8 @@ Websocket proxy that is compatible with OpenStack Nova
SPICE HTML5 consoles. Leverages websockify.py by Joel Martin SPICE HTML5 consoles. Leverages websockify.py by Joel Martin
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -53,12 +55,12 @@ def main():
config.parse_args(sys.argv) config.parse_args(sys.argv)
if CONF.ssl_only and not os.path.exists(CONF.cert): if CONF.ssl_only and not os.path.exists(CONF.cert):
print "SSL only and %s not found." % CONF.cert print("SSL only and %s not found." % CONF.cert)
return(-1) return(-1)
# Check to see if spice html/js/css files are present # Check to see if spice html/js/css files are present
if not os.path.exists(CONF.web): if not os.path.exists(CONF.web):
print "Can not find spice html/js/css files at %s." % CONF.web print("Can not find spice html/js/css files at %s." % CONF.web)
return(-1) return(-1)
# Create and start the NovaWebSockets proxy # Create and start the NovaWebSockets proxy

View File

@ -19,6 +19,8 @@
"""Utility methods for working with WSGI servers.""" """Utility methods for working with WSGI servers."""
from __future__ import print_function
import os.path import os.path
import socket import socket
import sys import sys
@ -371,15 +373,15 @@ class Debug(Middleware):
@webob.dec.wsgify(RequestClass=Request) @webob.dec.wsgify(RequestClass=Request)
def __call__(self, req): def __call__(self, req):
print ('*' * 40) + ' REQUEST ENVIRON' print(('*' * 40) + ' REQUEST ENVIRON')
for key, value in req.environ.items(): for key, value in req.environ.items():
print key, '=', value print(key, '=', value)
print print()
resp = req.get_response(self.application) resp = req.get_response(self.application)
print ('*' * 40) + ' RESPONSE HEADERS' print(('*' * 40) + ' RESPONSE HEADERS')
for (key, value) in resp.headers.iteritems(): for (key, value) in resp.headers.iteritems():
print key, '=', value print(key, '=', value)
print print
resp.app_iter = self.print_generator(resp.app_iter) resp.app_iter = self.print_generator(resp.app_iter)
@ -389,12 +391,12 @@ class Debug(Middleware):
@staticmethod @staticmethod
def print_generator(app_iter): def print_generator(app_iter):
"""Iterator that prints the contents of a wrapper string.""" """Iterator that prints the contents of a wrapper string."""
print ('*' * 40) + ' BODY' print(('*' * 40) + ' BODY')
for part in app_iter: for part in app_iter:
sys.stdout.write(part) sys.stdout.write(part)
sys.stdout.flush() sys.stdout.flush()
yield part yield part
print print()
class Router(object): class Router(object):

View File

@ -55,6 +55,8 @@ To run a single test module:
""" """
from __future__ import print_function
import os import os
import sys import sys
import unittest import unittest
@ -295,9 +297,9 @@ class NovaTestRunner(core.TextTestRunner):
if __name__ == '__main__': if __name__ == '__main__':
if not os.getenv('EC2_ACCESS_KEY'): if not os.getenv('EC2_ACCESS_KEY'):
print _('Missing EC2 environment variables. Please ' print(_('Missing EC2 environment variables. Please '
'source the appropriate novarc file before ' 'source the appropriate novarc file before '
'running this test.') 'running this test.'))
sys.exit(1) sys.exit(1)
argv = FLAGS(sys.argv) argv = FLAGS(sys.argv)

View File

@ -43,10 +43,9 @@ commands = {posargs}
[flake8] [flake8]
# TODO Hacking 0.6 checks to fix # TODO Hacking 0.6 checks to fix
# H102 Apache 2.0 license header not found # H102 Apache 2.0 license header not found
# H233 Python 3.x incompatible use of print operator
# H501 Do not use locals() for string formatting # H501 Do not use locals() for string formatting
ignore = E121,E122,E123,E124,E126,E127,E128,E711,E712,H102,H233,H302,H303,H404,F403,H501,F811,F841,N309 ignore = E121,E122,E123,E124,E126,E127,E128,E711,E712,H102,H302,H303,H404,F403,H501,F811,F841,N309
exclude = .venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,build,*plugins/xenserver*,tools exclude = .venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,build,*plugins/xenserver*,tools
[hacking] [hacking]