Merge "Python 3 compatibility: use print as a function."

This commit is contained in:
Zuul 2018-11-02 18:38:13 +00:00 committed by Gerrit Code Review
commit 4d6ad383ec
8 changed files with 76 additions and 76 deletions

View File

@ -78,7 +78,7 @@ def is_partitioning_correct(disk_path, partition_sizes):
output, _, _ = command(["udevadm", "settle", "-E", disk_node]) output, _, _ = command(["udevadm", "settle", "-E", disk_node])
output, _, _ = command(["parted", "-s", disk_node, "print"]) output, _, _ = command(["parted", "-s", disk_node, "print"])
if not re.search('Partition Table: gpt', output): if not re.search('Partition Table: gpt', output):
print "Format of disk node %s is not GPT, zapping disk" % disk_node print("Format of disk node %s is not GPT, zapping disk" % disk_node)
return False return False
# Check each partition size # Check each partition size
@ -189,10 +189,10 @@ def mount_data_partition(data_path, osdid):
_, _, ret = command(cmd) _, _, ret = command(cmd)
params = {"node": data_node, "path": mount_path} params = {"node": data_node, "path": mount_path}
if ret: if ret:
print "Failed to mount %(node)s to %(path), aborting" % params print("Failed to mount %(node)s to %(path), aborting" % params)
exit(1) exit(1)
else: else:
print "Mounted %(node)s to %(path)s" % params print("Mounted %(node)s to %(path)s" % params)
return mount_path return mount_path
@ -224,9 +224,9 @@ def fix_location(mount_point, journal_path, osdid):
if os.path.lexists(path): if os.path.lexists(path):
os.unlink(path) # delete the old symlink os.unlink(path) # delete the old symlink
os.symlink(new_target, path) os.symlink(new_target, path)
print "Symlink created: %(path)s -> %(target)s" % params print("Symlink created: %(path)s -> %(target)s" % params)
except: except:
print "Failed to create symlink: %(path)s -> %(target)s" % params print("Failed to create symlink: %(path)s -> %(target)s" % params)
exit(1) exit(1)
# Fix journal_uuid # Fix journal_uuid
path = mount_point + "/journal_uuid" path = mount_point + "/journal_uuid"
@ -237,7 +237,7 @@ def fix_location(mount_point, journal_path, osdid):
# The operation is noncritical, it only makes 'ceph-disk list' # The operation is noncritical, it only makes 'ceph-disk list'
# display complete output. We log and continue. # display complete output. We log and continue.
params = {"path": path, "uuid": journal_uuid} params = {"path": path, "uuid": journal_uuid}
print "WARNING: Failed to set uuid of %(path)s to %(uuid)s" % params print("WARNING: Failed to set uuid of %(path)s to %(uuid)s" % params)
# Clean the journal partition # Clean the journal partition
# even if erasing the partition table, if another journal was present here # even if erasing the partition table, if another journal was present here
@ -258,7 +258,7 @@ def fix_location(mount_point, journal_path, osdid):
"reason": err} "reason": err}
if not ret: if not ret:
print("Prepared new journal partition: %(journal_node)s " print("Prepared new journal partition: %(journal_node)s "
"for osd id: %(osdid)s") % params "for osd id: %(osdid)s" % params)
else: else:
print("Error initializing journal node: " print("Error initializing journal node: "
"%(journal_node)s for osd id: %(osdid)s " "%(journal_node)s for osd id: %(osdid)s "
@ -293,7 +293,7 @@ def main(argv):
else: else:
err = True err = True
if err: if err:
print "Command intended for internal use only" print("Command intended for internal use only")
exit(-1) exit(-1)
if partitions: if partitions:

View File

@ -1161,23 +1161,23 @@ index 808e53a..9265cd9 100644
self._firstconflicts = True self._firstconflicts = True
@@ -711,6 +734,22 @@ class TextOutput(NullOutput): @@ -711,6 +734,22 @@ class TextOutput(NullOutput):
name = str(prvpkg) name = str(prvpkg)
print " ", "%s (%s)" % (name, prv) print(" ", "%s (%s)" % (name, prv))
+ def showRecommends(self, pkg, rec): + def showRecommends(self, pkg, rec):
+ if self._firstrecommends: + if self._firstrecommends:
+ self._firstrecommends = False + self._firstrecommends = False
+ print " ", _("Recommends:") + print(" ", _("Recommends:"))
+ print " ", rec + print(" ", rec)
+ +
+ def showRecommendsProvidedBy(self, pkg, req, prv, prvpkg): + def showRecommendsProvidedBy(self, pkg, req, prv, prvpkg):
+ if self._firstrecommendsprovidedby: + if self._firstrecommendsprovidedby:
+ self._firstrecommendsprovidedby = False + self._firstrecommendsprovidedby = False
+ print " ", _("Provided By:") + print(" ", _("Provided By:"))
+ if self.opts.hide_version: + if self.opts.hide_version:
+ name = prvpkg.name + name = prvpkg.name
+ else: + else:
+ name = str(prvpkg) + name = str(prvpkg)
+ print " ", "%s (%s)" % (name, prv) + print(" ", "%s (%s)" % (name, prv))
+ +
def showUpgrades(self, pkg, upg): def showUpgrades(self, pkg, upg):
if self._firstupgrades: if self._firstupgrades:
@ -1189,14 +1189,14 @@ index 808e53a..9265cd9 100644
+ def showRecommends(self, pkg, req): + def showRecommends(self, pkg, req):
+ if (pkg, req) not in self._shown: + if (pkg, req) not in self._shown:
+ self._shown[pkg, req] = True + self._shown[pkg, req] = True
+ print ' "%s" -> "Recommends: %s";' % (pkg, req) + print(' "%s" -> "Recommends: %s";' % (pkg, req))
+ +
+ def showRecommendsProvidedBy(self, pkg, req, prv, prvpkg): + def showRecommendsProvidedBy(self, pkg, req, prv, prvpkg):
+ self.showPackage(prvpkg) + self.showPackage(prvpkg)
+ self.showProvides(prvpkg, prv) + self.showProvides(prvpkg, prv)
+ if (req, prv) not in self._shown: + if (req, prv) not in self._shown:
+ self._shown[req, prv] = True + self._shown[req, prv] = True
+ print ' "Recommends: %s" -> "Provides: %s";' % (req, prv) + print(' "Recommends: %s" -> "Provides: %s";' % (req, prv))
+ +
def showUpgrades(self, pkg, upg): def showUpgrades(self, pkg, upg):
if (pkg, upg) not in self._shown: if (pkg, upg) not in self._shown:

View File

@ -112,9 +112,9 @@ def main():
logger = Logger(logging.DEBUG).get_logger() logger = Logger(logging.DEBUG).get_logger()
logger.info("Starting....") logger.info("Starting....")
logger.info("Parsed options: %s" % options) logger.info("Parsed options: %s" % options)
print logger print(logger)
buddy = BuddyInfo(logger) buddy = BuddyInfo(logger)
print buddy print(buddy)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1218,7 +1218,7 @@ def checkDuration(duration):
return None return None
else: else:
time.sleep(duration) time.sleep(duration)
print "Duration interval has ended. Killing processes now" print("Duration interval has ended. Killing processes now")
logging.warning("Duration interval has ended. Killing processes now") logging.warning("Duration interval has ended. Killing processes now")
raise KeyboardInterrupt raise KeyboardInterrupt
@ -1262,7 +1262,7 @@ def createDB(influx_info, grafana_port, grafana_api_key):
if p is not None: if p is not None:
p.kill() p.kill()
except Exception as e: except Exception as e:
print e.message print(e.message)
sys.exit(0) sys.exit(0)
@ -1277,7 +1277,7 @@ def deleteDB(influx_info, grafana_port, grafana_api_key):
if answer is None or answer == "" or answer == "y" or answer == "yes": if answer is None or answer == "" or answer == "y" or answer == "yes":
try: try:
logging.info("Removing database from InfluxDB and Grafana") logging.info("Removing database from InfluxDB and Grafana")
print "Removing database from InfluxDB and Grafana. Please wait..." print("Removing database from InfluxDB and Grafana. Please wait...")
# delete database from InfluxDB # delete database from InfluxDB
p = Popen("curl -s -XPOST 'http://'{}':'{}'/query' --data-urlencode 'q=DROP DATABASE {}'".format(influx_info[0], influx_info[1], influx_info[2]), shell=True, stdout=PIPE) p = Popen("curl -s -XPOST 'http://'{}':'{}'/query' --data-urlencode 'q=DROP DATABASE {}'".format(influx_info[0], influx_info[1], influx_info[2]), shell=True, stdout=PIPE)
response = p.stdout.read().strip("\n") response = p.stdout.read().strip("\n")
@ -1306,7 +1306,7 @@ def deleteDB(influx_info, grafana_port, grafana_api_key):
if p is not None: if p is not None:
p.kill() p.kill()
except Exception as e: except Exception as e:
print e.message print(e.message)
sys.exit(0) sys.exit(0)
@ -1322,7 +1322,7 @@ def appendToFile(file, content):
if __name__ == "__main__": if __name__ == "__main__":
# make sure user is root # make sure user is root
if os.geteuid() != 0: if os.geteuid() != 0:
print "Must be run as root!\n" print("Must be run as root!\n")
sys.exit(0) sys.exit(0)
# initialize variables # initialize variables
@ -1432,7 +1432,7 @@ if __name__ == "__main__":
else: else:
SERVICES[service_tuple[0]] = {'name': service_tuple[1], 'api-port': None} SERVICES[service_tuple[0]] = {'name': service_tuple[1], 'api-port': None}
except Exception: except Exception:
print "An error has occurred when parsing the engtools.conf configuration file: {}".format(sys.exc_info()) print("An error has occurred when parsing the engtools.conf configuration file: {}".format(sys.exc_info()))
sys.exit(0) sys.exit(0)
syseng_services = live_svc + static_svcs syseng_services = live_svc + static_svcs
@ -1579,7 +1579,7 @@ if __name__ == "__main__":
tasks.append(p) tasks.append(p)
p.start() p.start()
print "Sending data to InfluxDB. Please tail /tmp/livestream.log" print("Sending data to InfluxDB. Please tail /tmp/livestream.log")
checkDuration(duration) checkDuration(duration)
# give a small delay to ensure services have started # give a small delay to ensure services have started

View File

@ -436,23 +436,23 @@ if __name__ == "__main__":
pool_size = len(controller_list) + len(compute_list) + len(storage_list) pool_size = len(controller_list) + len(compute_list) + len(storage_list)
if options.file_list is not None and options.parse_all is True: if options.file_list is not None and options.parse_all is True:
print "You cannot use the -a option with the -f option" print("You cannot use the -a option with the -f option")
sys.exit(0) sys.exit(0)
if options.postgres_list is not None and options.file_list is not None: if options.postgres_list is not None and options.file_list is not None:
print "You cannot use the -p option with the -f option" print("You cannot use the -p option with the -f option")
sys.exit(0) sys.exit(0)
if options.parse_all is True and options.node_list is not None: if options.parse_all is True and options.node_list is not None:
print "You cannot use the -a option with the -n option. Ex: -n controller-0" print("You cannot use the -a option with the -n option. Ex: -n controller-0")
sys.exit(0) sys.exit(0)
if options.file_list is not None and options.node_list is None: if options.file_list is not None and options.node_list is None:
print "You must specify a node and a file. Ex: -n controller-0 -f postgres-conns.csv" print("You must specify a node and a file. Ex: -n controller-0 -f postgres-conns.csv")
sys.exit(0) sys.exit(0)
working_dir = os.getcwd() working_dir = os.getcwd()
pool = Pool(processes=pool_size) pool = Pool(processes=pool_size)
proc_list = [] proc_list = []
print "Sending data to InfluxDB. Please tail /tmp/csv-to-influx.log" print("Sending data to InfluxDB. Please tail /tmp/csv-to-influx.log")
# create a process per node # create a process per node
if len(controller_list) > 0: if len(controller_list) > 0:

View File

@ -200,7 +200,7 @@ def print_disk_view(rows=None, extended=False):
if len(rows) > 0: if len(rows) > 0:
print print
print "DISKs: (Physical disk view)" print("DISKs: (Physical disk view)")
pt = PrettyTable(disk_lables_extended) if extended else \ pt = PrettyTable(disk_lables_extended) if extended else \
PrettyTable(disk_lables_brief) PrettyTable(disk_lables_brief)
@ -210,9 +210,9 @@ def print_disk_view(rows=None, extended=False):
if len(r) == len(pt.field_names): if len(r) == len(pt.field_names):
pt.add_row(r) pt.add_row(r)
else: else:
print "Disk row has incorrect number of values: %s" % r print("Disk row has incorrect number of values: %s" % r)
print pt print(pt)
def print_vg_view(rows=None, extended=False): def print_vg_view(rows=None, extended=False):
@ -228,7 +228,7 @@ def print_vg_view(rows=None, extended=False):
if len(rows) > 0: if len(rows) > 0:
print print
print "VOLUME GROUPS: (VG view)" print("VOLUME GROUPS: (VG view)")
pt = PrettyTable(vg_labels_extended) if extended else \ pt = PrettyTable(vg_labels_extended) if extended else \
PrettyTable(vg_labels_brief) PrettyTable(vg_labels_brief)
@ -240,9 +240,9 @@ def print_vg_view(rows=None, extended=False):
if len(r) == len(pt.field_names): if len(r) == len(pt.field_names):
pt.add_row(r) pt.add_row(r)
else: else:
print "VG row has incorrect number of values: %s" % r print("VG row has incorrect number of values: %s" % r)
print pt print(pt)
def get_info_and_display(cc, show=None): def get_info_and_display(cc, show=None):
@ -409,8 +409,8 @@ def main():
prog = os.path.basename(sys.argv[0]) prog = os.path.basename(sys.argv[0])
ts = datetime.datetime.now() ts = datetime.datetime.now()
if show['debug']: if show['debug']:
print "%s: %s options: view:%s System api version: %s" \ print("%s: %s options: view:%s System api version: %s"
% (prog, ts.isoformat(), show, api_version) % (prog, ts.isoformat(), show, api_version))
cgts_client_creds = get_system_creds() cgts_client_creds = get_system_creds()
if not cgts_client_creds['os_username']: if not cgts_client_creds['os_username']:

View File

@ -855,7 +855,7 @@ def print_all_tables(tenants=None,
# Print list of aggregates # Print list of aggregates
if show['aggregates']: if show['aggregates']:
print print
print "AGGREGATES:" print("AGGREGATES:")
pt = PrettyTable( pt = PrettyTable(
['Name', ['Name',
'Avail Zone', 'Avail Zone',
@ -870,13 +870,13 @@ def print_all_tables(tenants=None,
", ".join([str(x) for x in A.hosts]), ", ".join([str(x) for x in A.hosts]),
str(A.metadata) str(A.metadata)
]) ])
print pt print(pt)
# Print list of compute host hypervisors, showing per numa details # Print list of compute host hypervisors, showing per numa details
if show['computes']: if show['computes']:
print print
print 'COMPUTE HOSTS: ' \ print('COMPUTE HOSTS: '
'Legend: U = Used, A = Avail' 'Legend: U = Used, A = Avail')
pt = PrettyTable( pt = PrettyTable(
['Host', ['Host',
'status', 'status',
@ -1018,7 +1018,7 @@ def print_all_tables(tenants=None,
# Print list of compute hosts topology # Print list of compute hosts topology
if show['topology']: if show['topology']:
print print
print 'LOGICAL CPU TOPOLOGY (compute hosts):' print('LOGICAL CPU TOPOLOGY (compute hosts):')
for host_name, topology in sorted(topologies.iteritems(), for host_name, topology in sorted(topologies.iteritems(),
key=lambda (k, v): (natural_keys(k))): key=lambda (k, v): (natural_keys(k))):
H = hypervisors[host_name] H = hypervisors[host_name]
@ -1042,13 +1042,13 @@ def print_all_tables(tenants=None,
n_cores = len(topology[socket_id].keys()) n_cores = len(topology[socket_id].keys())
n_threads = len(topology[socket_id][core_id].keys()) n_threads = len(topology[socket_id][core_id].keys())
print '%s: Model:%s, Arch:%s, Vendor:%s, ' \ print('%s: Model:%s, Arch:%s, Vendor:%s, '
'Sockets=%d, Cores/Socket=%d, Threads/Core=%d, Logical=%d' \ 'Sockets=%d, Cores/Socket=%d, Threads/Core=%d, Logical=%d'
% (host_name, % (host_name,
H.cpu_info['model'], H.cpu_info['model'],
H.cpu_info['arch'], H.cpu_info['arch'],
H.cpu_info['vendor'], H.cpu_info['vendor'],
n_sockets, n_cores, n_threads, len(cpu_ids)) n_sockets, n_cores, n_threads, len(cpu_ids)))
# cpu_id row # cpu_id row
L = ['cpu_id'] L = ['cpu_id']
@ -1076,13 +1076,13 @@ def print_all_tables(tenants=None,
{L.append(','.join( {L.append(','.join(
str(s) for s in siblings[i]) or '-') for i in cpu_ids} str(s) for s in siblings[i]) or '-') for i in cpu_ids}
pt.add_row(L) pt.add_row(L)
print pt print(pt)
print print
# Print list of compute hosts topology # Print list of compute hosts topology
if show['topology-long']: if show['topology-long']:
print print
print 'LOGICAL CPU TOPOLOGY (compute hosts):' print('LOGICAL CPU TOPOLOGY (compute hosts):')
for host_name, topology in sorted(topologies.iteritems(), for host_name, topology in sorted(topologies.iteritems(),
key=lambda (k, v): (natural_keys(k))): key=lambda (k, v): (natural_keys(k))):
H = hypervisors[host_name] H = hypervisors[host_name]
@ -1106,13 +1106,13 @@ def print_all_tables(tenants=None,
n_cores = len(topology[socket_id].keys()) n_cores = len(topology[socket_id].keys())
n_threads = len(topology[socket_id][core_id].keys()) n_threads = len(topology[socket_id][core_id].keys())
print '%s: Model:%s, Arch:%s, Vendor:%s, ' \ print('%s: Model:%s, Arch:%s, Vendor:%s, '
'Sockets=%d, Cores/Socket=%d, Threads/Core=%d, Logical=%d' \ 'Sockets=%d, Cores/Socket=%d, Threads/Core=%d, Logical=%d'
% (host_name, % (host_name,
H.cpu_info['model'], H.cpu_info['model'],
H.cpu_info['arch'], H.cpu_info['arch'],
H.cpu_info['vendor'], H.cpu_info['vendor'],
n_sockets, n_cores, n_threads, len(cpu_ids)) n_sockets, n_cores, n_threads, len(cpu_ids)))
pt = PrettyTable( pt = PrettyTable(
['cpu_id', ['cpu_id',
'socket_id', 'socket_id',
@ -1132,14 +1132,14 @@ def print_all_tables(tenants=None,
list_to_range(siblings[i]) or '-', list_to_range(siblings[i]) or '-',
'0x%x' % (1 << i) '0x%x' % (1 << i)
]) ])
print pt print(pt)
print print
# Print list of servers # Print list of servers
if show['servers']: if show['servers']:
re_server_group = re.compile(r'^(\S+)\s+\((\S+)\)$') re_server_group = re.compile(r'^(\S+)\s+\((\S+)\)$')
print print
print 'SERVERS (nova view):' print('SERVERS (nova view):')
pt = PrettyTable( pt = PrettyTable(
['tenant', ['tenant',
'ID', 'ID',
@ -1237,8 +1237,8 @@ def print_all_tables(tenants=None,
# Print each libvirt domain info # Print each libvirt domain info
if show['libvirt']: if show['libvirt']:
print print
print 'SERVERS (libvirt view): ' \ print('SERVERS (libvirt view): '
'Legend: cpulist = [pcpu[i], ...]' 'Legend: cpulist = [pcpu[i], ...]')
pt = PrettyTable( pt = PrettyTable(
['uuid', ['uuid',
'instance_name', 'instance_name',
@ -1278,7 +1278,7 @@ def print_all_tables(tenants=None,
# Print list of in-progress migrations # Print list of in-progress migrations
if show['migrations']: if show['migrations']:
print print
print "MIGRATIONS (in progress): Legend: S=Source, D=Destination" print("MIGRATIONS (in progress): Legend: S=Source, D=Destination")
pt = PrettyTable( pt = PrettyTable(
['ID', ['ID',
'status', 'status',
@ -1310,7 +1310,7 @@ def print_all_tables(tenants=None,
pp = pprint.PrettyPrinter(indent=1, width=40) pp = pprint.PrettyPrinter(indent=1, width=40)
if show['flavors']: if show['flavors']:
print print
print "FLAVORS (in use):" print("FLAVORS (in use):")
pt = PrettyTable( pt = PrettyTable(
['id', ['id',
'name', 'name',
@ -1342,13 +1342,13 @@ def print_all_tables(tenants=None,
F.is_public, F.is_public,
pp.pformat(extra_specs[F.id]), pp.pformat(extra_specs[F.id]),
]) ])
print pt print(pt)
# Print images for instances currently in use # Print images for instances currently in use
pp = pprint.PrettyPrinter(indent=1, width=40) pp = pprint.PrettyPrinter(indent=1, width=40)
if show['images']: if show['images']:
print print
print "IMAGES (in use):" print("IMAGES (in use):")
pt = PrettyTable( pt = PrettyTable(
['id', ['id',
'name', 'name',
@ -1373,12 +1373,12 @@ def print_all_tables(tenants=None,
I.status, I.status,
I.properties, I.properties,
]) ])
print pt print(pt)
# Print server groups for instances currently in use (exclude members data) # Print server groups for instances currently in use (exclude members data)
if show['server_groups']: if show['server_groups']:
print print
print "SERVER GROUPS (in use):" print("SERVER GROUPS (in use):")
pt = PrettyTable( pt = PrettyTable(
['Tenant', ['Tenant',
'Id', 'Id',
@ -1398,7 +1398,7 @@ def print_all_tables(tenants=None,
str(S.policies), str(S.policies),
str(S.metadata), str(S.metadata),
]) ])
print pt print(pt)
def _get_host_id(tenant_id=None, host_name=None): def _get_host_id(tenant_id=None, host_name=None):
@ -2108,12 +2108,12 @@ def get_info_and_display(show=None):
# Print out warnings if we detect mismatches between nova and libvirt # Print out warnings if we detect mismatches between nova and libvirt
if warnings: if warnings:
print print
print "WARNINGS (mismatch):" print("WARNINGS (mismatch):")
pt = PrettyTable(['Message']) pt = PrettyTable(['Message'])
pt.align = 'l' pt.align = 'l'
for W in warnings: for W in warnings:
pt.add_row([W]) pt.add_row([W])
print pt print(pt)
if True in debug.values(): if True in debug.values():
logger.debug('done.') logger.debug('done.')
@ -2136,7 +2136,7 @@ def main():
# Print selected options, and timestamp # Print selected options, and timestamp
prog = os.path.basename(sys.argv[0]) prog = os.path.basename(sys.argv[0])
ts = datetime.datetime.now() ts = datetime.datetime.now()
print "%s: %s options: show:%s" % (prog, ts.isoformat(), show['show']) print("%s: %s options: show:%s" % (prog, ts.isoformat(), show['show']))
if show['volumes']: if show['volumes']:
logger.info('volumes selected: displaying will take some time') logger.info('volumes selected: displaying will take some time')

View File

@ -185,7 +185,7 @@ def main():
if len(sys.argv) == 2 : if len(sys.argv) == 2 :
licensefile = sys.argv[1] licensefile = sys.argv[1]
else: else:
print "Usage: verify-license <license file>" print("Usage: verify-license <license file>")
exit(-1) exit(-1)
try: try: