Fix 'print' issue for Python 2/3 compatible code.

and remove 'H233  Python 3.x incompatible use of print operator'
pep8/flake8 ignore case in cgts-client and sysinv tox setup

enable flake8 hacking and ignore some case and fix it later for
those ignore case.

Story: 2003433
Task: 24629

Change-Id: I0dfc4c17681dd9b0042a4277b7956d270eb73495
Signed-off-by: Sun Austin <austin.sun@intel.com>
This commit is contained in:
Sun Austin 2018-11-21 14:56:00 +08:00
parent 1f53e7abf3
commit 3ee670f0c8
68 changed files with 1029 additions and 983 deletions

View File

@ -10,6 +10,7 @@
# sockets, cores per package, threads per core, # sockets, cores per package, threads per core,
# total memory, and numa nodes # total memory, and numa nodes
from __future__ import print_function
import os import os
import sys import sys
import re import re
@ -182,51 +183,51 @@ class Topology(object):
cpu_list.sort() cpu_list.sort()
total_memory_GiB = self.total_memory_MiB/1024.0 total_memory_GiB = self.total_memory_MiB/1024.0
print 'TOPOLOGY:' print('TOPOLOGY:')
print '%16s : %5d' % ('logical cpus', self.num_cpus) print('%16s : %5d' % ('logical cpus', self.num_cpus))
print '%16s : %5d' % ('sockets', self.num_sockets) print('%16s : %5d' % ('sockets', self.num_sockets))
print '%16s : %5d' % ('cores_per_pkg', self.num_cores_per_pkg) print('%16s : %5d' % ('cores_per_pkg', self.num_cores_per_pkg))
print '%16s : %5d' % ('threads_per_core', self.num_threads_per_core) print('%16s : %5d' % ('threads_per_core', self.num_threads_per_core))
print '%16s : %5d' % ('numa_nodes', self.num_nodes) print('%16s : %5d' % ('numa_nodes', self.num_nodes))
print '%16s : %5.2f %s' % ('total_memory', total_memory_GiB, 'GiB') print('%16s : %5.2f %s' % ('total_memory', total_memory_GiB, 'GiB'))
print '%16s :' % ('memory_per_node'), print('%16s :' % ('memory_per_node'), end=' ')
for node in range(self.num_nodes): for node in range(self.num_nodes):
node_memory_GiB = self.total_memory_nodes_MiB[node]/1024.0 node_memory_GiB = self.total_memory_nodes_MiB[node]/1024.0
print '%5.2f' % (node_memory_GiB), print('%5.2f' % (node_memory_GiB), end=' ')
print '%s' % ('GiB') print('%s' % ('GiB'))
print print('')
print 'LOGICAL CPU TOPOLOGY:' print('LOGICAL CPU TOPOLOGY:')
print "%9s :" % 'cpu_id', print("%9s :" % 'cpu_id', end=' ')
for cpu in cpu_list: for cpu in cpu_list:
print "%3d" % cpu, print("%3d" % cpu, end=' ')
print print('')
print "%9s :" % 'socket_id', print("%9s :" % 'socket_id', end=' ')
for cpu in cpu_list: for cpu in cpu_list:
socket_id = self.topology_idx[cpu]['s'] socket_id = self.topology_idx[cpu]['s']
print "%3d" % socket_id, print("%3d" % socket_id, end=' ')
print print('')
print "%9s :" % 'core_id', print("%9s :" % 'core_id', end=' ')
for cpu in cpu_list: for cpu in cpu_list:
core_id = self.topology_idx[cpu]['c'] core_id = self.topology_idx[cpu]['c']
print "%3d" % core_id, print("%3d" % core_id, end=' ')
print print('')
print "%9s :" % 'thread_id', print("%9s :" % 'thread_id', end=' ')
for cpu in cpu_list: for cpu in cpu_list:
thread_id = self.topology_idx[cpu]['t'] thread_id = self.topology_idx[cpu]['t']
print "%3d" % thread_id, print("%3d" % thread_id, end=' ')
print print('')
print print('')
print 'CORE TOPOLOGY:' print('CORE TOPOLOGY:')
print "%6s %9s %7s %9s %s" % ('cpu_id', 'socket_id', 'core_id', 'thread_id', 'affinity') print("%6s %9s %7s %9s %s" % ('cpu_id', 'socket_id', 'core_id', 'thread_id', 'affinity'))
for cpu in cpu_list: for cpu in cpu_list:
affinity = 1<<cpu affinity = 1<<cpu
socket_id = self.topology_idx[cpu]['s'] socket_id = self.topology_idx[cpu]['s']
core_id = self.topology_idx[cpu]['c'] core_id = self.topology_idx[cpu]['c']
thread_id = self.topology_idx[cpu]['t'] thread_id = self.topology_idx[cpu]['t']
print "%6d %9d %7d %9d 0x%x" \ print("%6d %9d %7d %9d 0x%x" \
% (cpu, socket_id, core_id, thread_id, affinity) % (cpu, socket_id, core_id, thread_id, affinity))
return None return None

View File

@ -18,7 +18,7 @@ HGAP = 10
def debug(msg): def debug(msg):
if DEBUG: if DEBUG:
print msg print(msg)
# Tracks what type of controls will implement a config question # Tracks what type of controls will implement a config question

View File

@ -5,6 +5,7 @@ SPDX-License-Identifier: Apache-2.0
""" """
from __future__ import print_function
import sys import sys
import os import os
from six.moves import configparser from six.moves import configparser
@ -24,11 +25,11 @@ def parse_config(config_file):
def show_help(): def show_help():
print ("Usage: %s\n" print("Usage: %s\n"
"Perform validation of a given configuration file\n\n" "Perform validation of a given configuration file\n\n"
"--system-config <name> Validate a system configuration file\n" "--system-config <name> Validate a system configuration file\n"
"--region-config <name> Validate a region configuration file\n" "--region-config <name> Validate a region configuration file\n"
% sys.argv[0]) % sys.argv[0])
exit(1) exit(1)
@ -44,8 +45,8 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
config_file = sys.argv[arg] config_file = sys.argv[arg]
else: else:
print "--system-config requires the filename of the config " \ print("--system-config requires the filename of the config "
"file" "file")
exit(1) exit(1)
system_config = True system_config = True
elif sys.argv[arg] == "--region-config": elif sys.argv[arg] == "--region-config":
@ -53,19 +54,19 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
config_file = sys.argv[arg] config_file = sys.argv[arg]
else: else:
print "--region-config requires the filename of the config " \ print("--region-config requires the filename of the config "
"file" "file")
exit(1) exit(1)
region_config = True region_config = True
elif sys.argv[arg] in ["--help", "-h", "-?"]: elif sys.argv[arg] in ["--help", "-h", "-?"]:
show_help() show_help()
else: else:
print "Invalid option." print("Invalid option.")
show_help() show_help()
arg += 1 arg += 1
if [system_config, region_config].count(True) != 1: if [system_config, region_config].count(True) != 1:
print "Invalid combination of options selected" print("Invalid combination of options selected")
show_help() show_help()
if system_config: if system_config:
@ -78,12 +79,12 @@ def main():
exit(1) exit(1)
# Parse the system config file # Parse the system config file
print "Parsing configuration file... ", print("Parsing configuration file... ", end=' ')
system_config = parse_config(config_file) system_config = parse_config(config_file)
print "DONE" print("DONE")
# Validate the system config file # Validate the system config file
print "Validating configuration file... ", print("Validating configuration file... ", end=' ')
try: try:
# we use the presence of tsconfig to determine if we are onboard or # we use the presence of tsconfig to determine if we are onboard or
# not since it will not be available in the offboard case # not since it will not be available in the offboard case
@ -97,4 +98,4 @@ def main():
print("Error parsing configuration file %s: %s" % (config_file, e)) print("Error parsing configuration file %s: %s" % (config_file, e))
except (ConfigFail, ValidateFail) as e: except (ConfigFail, ValidateFail) as e:
print("\nValidation failed: %s" % e) print("\nValidation failed: %s" % e)
print "DONE" print("DONE")

View File

@ -18,5 +18,20 @@ commands = {posargs}
[testenv:flake8] [testenv:flake8]
basepython = python2.7 basepython = python2.7
deps = flake8<3.6.0 deps = hacking
flake8<3.6.0
commands = flake8 {posargs} commands = flake8 {posargs}
# H series are hacking
# H102: Apache 2.0 license header not found
# H104: File contains nothing but comments
# H301: one import per line
# H306: imports not in alphabetical order
# H401: docstring should not start with a space
# H403: multi line docstrings should end on a new line
# H404: multi line docstring should start without a leading new line
# H405: multi line docstring summary not separated with an empty line
# W503 line break before binary operator
[flake8]
ignore = H102,H104,H301,H306,H401,H403,H404,H405,
W503

View File

@ -8,6 +8,7 @@
Backup & Restore Backup & Restore
""" """
from __future__ import print_function
import copy import copy
import filecmp import filecmp
import fileinput import fileinput
@ -336,7 +337,7 @@ def restore_configuration(archive, staging_dir):
# The INSTALL_UUID must be updated to match the new INSTALL_UUID # The INSTALL_UUID must be updated to match the new INSTALL_UUID
# which was generated when this controller was installed prior to # which was generated when this controller was installed prior to
# doing the restore. # doing the restore.
print "INSTALL_UUID=%s" % install_uuid print("INSTALL_UUID=%s" % install_uuid)
elif line.startswith("management_interface=") or \ elif line.startswith("management_interface=") or \
line.startswith("oam_interface=") or \ line.startswith("oam_interface=") or \
line.startswith("infrastructure_interface=") or \ line.startswith("infrastructure_interface=") or \
@ -346,7 +347,7 @@ def restore_configuration(archive, staging_dir):
# platform_conf manifest will add these back in. # platform_conf manifest will add these back in.
pass pass
else: else:
print line, print(line, end=' ')
fileinput.close() fileinput.close()
# Move updated platform.conf file into place. # Move updated platform.conf file into place.
os.rename(temp_platform_conf_file, tsconfig.PLATFORM_CONF_FILE) os.rename(temp_platform_conf_file, tsconfig.PLATFORM_CONF_FILE)
@ -965,10 +966,10 @@ def check_size(archive_dir, cinder_config):
utils.filesystem_get_free_space(archive_dir) utils.filesystem_get_free_space(archive_dir)
if backup_size > archive_dir_free_space: if backup_size > archive_dir_free_space:
print ("Archive directory (%s) does not have enough free " print("Archive directory (%s) does not have enough free "
"space (%s), estimated backup size is %s." % "space (%s), estimated backup size is %s." %
(archive_dir, utils.print_bytes(archive_dir_free_space), (archive_dir, utils.print_bytes(archive_dir_free_space),
utils.print_bytes(backup_size))) utils.print_bytes(backup_size)))
raise BackupFail("Not enough free space for backup.") raise BackupFail("Not enough free space for backup.")
@ -1155,12 +1156,12 @@ def backup(backup_name, archive_dir, clone=False):
system_msg += ": " + system_tar_path system_msg += ": " + system_tar_path
images_msg += ": " + images_tar_path images_msg += ": " + images_tar_path
print system_msg print(system_msg)
if tsconfig.region_config != "yes": if tsconfig.region_config != "yes":
print images_msg print(images_msg)
if warnings != '': if warnings != '':
print "WARNING: The following problems occurred:" print("WARNING: The following problems occurred:")
print textwrap.fill(warnings, 80) print(textwrap.fill(warnings, 80))
def create_restore_runtime_config(filename): def create_restore_runtime_config(filename):
@ -1206,11 +1207,11 @@ def restore_complete():
""" """
if utils.get_system_type() == sysinv_constants.TIS_AIO_BUILD: if utils.get_system_type() == sysinv_constants.TIS_AIO_BUILD:
if not os.path.isfile(restore_system_ready): if not os.path.isfile(restore_system_ready):
print textwrap.fill( print(textwrap.fill(
"--restore-complete can only be run " "--restore-complete can only be run "
"after restore-system has completed " "after restore-system has completed "
"successfully", 80 "successfully", 80
) ))
return False return False
# The iscsi target config file must be overwritten with the # The iscsi target config file must be overwritten with the
@ -1222,9 +1223,9 @@ def restore_complete():
# we use use that. # we use use that.
overwrite_iscsi_target_config() overwrite_iscsi_target_config()
print ("\nApplying compute manifests for %s. " % print("\nApplying compute manifests for %s. " %
(utils.get_controller_hostname())) (utils.get_controller_hostname()))
print ("Node will reboot on completion.") print("Node will reboot on completion.")
sysinv.do_compute_config_complete(utils.get_controller_hostname()) sysinv.do_compute_config_complete(utils.get_controller_hostname())
@ -1241,11 +1242,11 @@ def restore_complete():
else: else:
if not os.path.isfile(restore_system_ready): if not os.path.isfile(restore_system_ready):
print textwrap.fill( print(textwrap.fill(
"--restore-complete can only be run " "--restore-complete can only be run "
"after restore-system has completed " "after restore-system has completed "
"successfully", 80 "successfully", 80
) ))
return False return False
overwrite_iscsi_target_config() overwrite_iscsi_target_config()
os.remove(restore_system_ready) os.remove(restore_system_ready)
@ -1258,11 +1259,11 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
if (os.path.exists(constants.CGCS_CONFIG_FILE) or if (os.path.exists(constants.CGCS_CONFIG_FILE) or
os.path.exists(tsconfig.CONFIG_PATH) or os.path.exists(tsconfig.CONFIG_PATH) or
os.path.exists(constants.INITIAL_CONFIG_COMPLETE_FILE)): os.path.exists(constants.INITIAL_CONFIG_COMPLETE_FILE)):
print textwrap.fill( print(textwrap.fill(
"Configuration has already been done. " "Configuration has already been done. "
"A system restore operation can only be done " "A system restore operation can only be done "
"immediately after the load has been installed.", 80) "immediately after the load has been installed.", 80))
print print('')
raise RestoreFail("System configuration already completed") raise RestoreFail("System configuration already completed")
if not os.path.isabs(backup_file): if not os.path.isabs(backup_file):
@ -1288,7 +1289,7 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
LOG.error("The cgts-vg volume group was not found") LOG.error("The cgts-vg volume group was not found")
raise RestoreFail("Volume groups not configured") raise RestoreFail("Volume groups not configured")
print "\nRestoring system (this will take several minutes):" print("\nRestoring system (this will take several minutes):")
# Use /scratch for the staging dir for now, # Use /scratch for the staging dir for now,
# until /opt/backups is available # until /opt/backups is available
staging_dir = tempfile.mkdtemp(dir='/scratch') staging_dir = tempfile.mkdtemp(dir='/scratch')
@ -1343,10 +1344,10 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
# If the controller was impacted by patches, we need to reboot. # If the controller was impacted by patches, we need to reboot.
if os.path.isfile(node_is_patched): if os.path.isfile(node_is_patched):
if not clone: if not clone:
print ("\nThis controller has been patched. " + print("\nThis controller has been patched. " +
"A reboot is required.") "A reboot is required.")
print ("After the reboot is complete, " + print("After the reboot is complete, " +
"re-execute the restore command.") "re-execute the restore command.")
while True: while True:
user_input = input( user_input = input(
"Enter 'reboot' to reboot controller: ") "Enter 'reboot' to reboot controller: ")
@ -1581,7 +1582,7 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
if tsconfig.system_mode != sysinv_constants.SYSTEM_MODE_SIMPLEX: if tsconfig.system_mode != sysinv_constants.SYSTEM_MODE_SIMPLEX:
print "\nRestoring node states (this will take several minutes):" print("\nRestoring node states (this will take several minutes):")
backend_services = sysinv.get_storage_backend_services() backend_services = sysinv.get_storage_backend_services()
@ -1621,7 +1622,7 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
LOG.info("At least one node is not in a disabling state. " LOG.info("At least one node is not in a disabling state. "
"Continuing.") "Continuing.")
print "\nLocking nodes:" print("\nLocking nodes:")
try: try:
failed_hosts = client.lock_hosts(skip_hosts, failed_hosts = client.lock_hosts(skip_hosts,
utils.progress, utils.progress,
@ -1635,7 +1636,7 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
failed_lock_host = True failed_lock_host = True
if not failed_lock_host: if not failed_lock_host:
print "\nPowering-off nodes:" print("\nPowering-off nodes:")
try: try:
client.power_off_hosts(skip_hosts, client.power_off_hosts(skip_hosts,
utils.progress, utils.progress,
@ -1646,25 +1647,25 @@ def restore_system(backup_file, include_storage_reinstall=False, clone=False):
if failed_lock_host or len(skip_hosts) > skip_hosts_count: if failed_lock_host or len(skip_hosts) > skip_hosts_count:
if include_storage_reinstall: if include_storage_reinstall:
print textwrap.fill( print(textwrap.fill(
"Failed to lock at least one node. " + "Failed to lock at least one node. " +
"Please lock the unlocked nodes manually.", 80 "Please lock the unlocked nodes manually.", 80
) ))
else: else:
print textwrap.fill( print(textwrap.fill(
"Failed to lock at least one node. " + "Failed to lock at least one node. " +
"Please lock the unlocked controller-1 or " + "Please lock the unlocked controller-1 or " +
"compute nodes manually.", 80 "compute nodes manually.", 80
) ))
if not clone: if not clone:
print textwrap.fill( print(textwrap.fill(
"Before continuing to the next step in the restore, " + "Before continuing to the next step in the restore, " +
"please ensure all nodes other than controller-0 " + "please ensure all nodes other than controller-0 " +
"and storage nodes, if they are not being " + "and storage nodes, if they are not being " +
"reinstalled, are powered off. Please refer to the " + "reinstalled, are powered off. Please refer to the " +
"system administration guide for more details.", 80 "system administration guide for more details.", 80
) ))
finally: finally:
os.remove(restore_in_progress) os.remove(restore_in_progress)
@ -1705,11 +1706,11 @@ def restore_images(backup_file, clone=False):
"""Restoring images.""" """Restoring images."""
if not os.path.exists(constants.INITIAL_CONFIG_COMPLETE_FILE): if not os.path.exists(constants.INITIAL_CONFIG_COMPLETE_FILE):
print textwrap.fill( print(textwrap.fill(
"System restore has not been done. " "System restore has not been done. "
"An image restore operation can only be done after " "An image restore operation can only be done after "
"the system restore has been completed.", 80) "the system restore has been completed.", 80))
print print('')
raise RestoreFail("System restore required") raise RestoreFail("System restore required")
if not os.path.isabs(backup_file): if not os.path.isabs(backup_file):
@ -1725,7 +1726,7 @@ def restore_images(backup_file, clone=False):
newline = clone newline = clone
try: try:
print "\nRestoring images (this will take several minutes):" print("\nRestoring images (this will take several minutes):")
os.chdir('/') os.chdir('/')
step = 1 step = 1

View File

@ -9,6 +9,7 @@ Clone a Configured System and Install the image on another
identical hardware or the same hardware. identical hardware or the same hardware.
""" """
from __future__ import print_function
import os import os
import re import re
import glob import glob
@ -116,11 +117,11 @@ def check_size(archive_dir):
utils.filesystem_get_free_space(archive_dir) utils.filesystem_get_free_space(archive_dir)
if clone_size > archive_dir_free_space: if clone_size > archive_dir_free_space:
print ("\nArchive directory (%s) does not have enough free " print("\nArchive directory (%s) does not have enough free "
"space (%s), estimated size to create image is %s." % "space (%s), estimated size to create image is %s." %
(archive_dir, (archive_dir,
utils.print_bytes(archive_dir_free_space), utils.print_bytes(archive_dir_free_space),
utils.print_bytes(clone_size))) utils.print_bytes(clone_size)))
raise CloneFail("Not enough free space.\n") raise CloneFail("Not enough free space.\n")
@ -475,7 +476,7 @@ def find_and_replace_in_file(target, find, replace):
fpat = r'\b' + find + r'\b' fpat = r'\b' + find + r'\b'
line = re.sub(fpat, replace, line) line = re.sub(fpat, replace, line)
found = True found = True
print line, print(line, end=' ')
except Exception as e: except Exception as e:
LOG.error("Failed to replace [{}] with [{}] in [{}]: {}" LOG.error("Failed to replace [{}] with [{}] in [{}]: {}"

View File

@ -5,6 +5,7 @@ SPDX-License-Identifier: Apache-2.0
""" """
from __future__ import print_function
import json import json
import netaddr import netaddr
import os import os
@ -20,19 +21,19 @@ from six.moves import input
def is_valid_management_address(ip_address, management_subnet): def is_valid_management_address(ip_address, management_subnet):
"""Determine whether a management address is valid.""" """Determine whether a management address is valid."""
if ip_address == management_subnet.network: if ip_address == management_subnet.network:
print "Cannot use network address" print("Cannot use network address")
return False return False
elif ip_address == management_subnet.broadcast: elif ip_address == management_subnet.broadcast:
print "Cannot use broadcast address" print("Cannot use broadcast address")
return False return False
elif ip_address.is_multicast(): elif ip_address.is_multicast():
print "Invalid address - multicast address not allowed" print("Invalid address - multicast address not allowed")
return False return False
elif ip_address.is_loopback(): elif ip_address.is_loopback():
print "Invalid address - loopback address not allowed" print("Invalid address - loopback address not allowed")
return False return False
elif ip_address not in management_subnet: elif ip_address not in management_subnet:
print "Address must be in the management subnet" print("Address must be in the management subnet")
return False return False
else: else:
return True return True
@ -42,7 +43,7 @@ def configure_management():
interface_list = list() interface_list = list()
lldp_interface_list = list() lldp_interface_list = list()
print "Enabling interfaces... ", print("Enabling interfaces... ", end=' ')
ip_link_output = subprocess.check_output(['ip', '-o', 'link']) ip_link_output = subprocess.check_output(['ip', '-o', 'link'])
for line in ip_link_output.splitlines(): for line in ip_link_output.splitlines():
@ -50,43 +51,44 @@ def configure_management():
if interface != 'lo': if interface != 'lo':
interface_list.append(interface) interface_list.append(interface)
subprocess.call(['ip', 'link', 'set', interface, 'up']) subprocess.call(['ip', 'link', 'set', interface, 'up'])
print 'DONE' print('DONE')
wait_seconds = 120 wait_seconds = 120
delay_seconds = 5 delay_seconds = 5
print "Waiting %d seconds for LLDP neighbor discovery" % wait_seconds, print("Waiting %d seconds for LLDP neighbor discovery" % wait_seconds,
end=' ')
while wait_seconds > 0: while wait_seconds > 0:
sys.stdout.write('.') sys.stdout.write('.')
sys.stdout.flush() sys.stdout.flush()
time.sleep(delay_seconds) time.sleep(delay_seconds)
wait_seconds -= delay_seconds wait_seconds -= delay_seconds
print ' DONE' print(' DONE')
print "Retrieving neighbor details... ", print("Retrieving neighbor details... ", end=' ')
lldpcli_show_output = subprocess.check_output( lldpcli_show_output = subprocess.check_output(
['sudo', 'lldpcli', 'show', 'neighbors', 'summary', '-f', 'json']) ['sudo', 'lldpcli', 'show', 'neighbors', 'summary', '-f', 'json'])
lldp_interfaces = json.loads(lldpcli_show_output)['lldp'][0]['interface'] lldp_interfaces = json.loads(lldpcli_show_output)['lldp'][0]['interface']
print "DONE" print("DONE")
print "\nAvailable interfaces:" print("\nAvailable interfaces:")
print "%-20s %s" % ("local interface", "remote port") print("%-20s %s" % ("local interface", "remote port"))
print "%-20s %s" % ("---------------", "-----------") print("%-20s %s" % ("---------------", "-----------"))
for interface in lldp_interfaces: for interface in lldp_interfaces:
print "%-20s %s" % (interface['name'], print("%-20s %s" % (interface['name'],
interface['port'][0]['id'][0]['value']) interface['port'][0]['id'][0]['value']))
lldp_interface_list.append(interface['name']) lldp_interface_list.append(interface['name'])
for interface in interface_list: for interface in interface_list:
if interface not in lldp_interface_list: if interface not in lldp_interface_list:
print "%-20s %s" % (interface, 'unknown') print("%-20s %s" % (interface, 'unknown'))
print print('')
while True: while True:
user_input = input("Enter management interface name: ") user_input = input("Enter management interface name: ")
if user_input in interface_list: if user_input in interface_list:
management_interface = user_input management_interface = user_input
break break
else: else:
print "Invalid interface name" print("Invalid interface name")
continue continue
while True: while True:
@ -133,31 +135,31 @@ def configure_management():
user_input, min_addresses) user_input, min_addresses)
break break
except cexeptions.ValidateFail as e: except cexeptions.ValidateFail as e:
print "{}".format(e) print("{}".format(e))
print "Disabling non-management interfaces... ", print("Disabling non-management interfaces... ", end=' ')
for interface in interface_list: for interface in interface_list:
if interface != management_interface: if interface != management_interface:
subprocess.call(['ip', 'link', 'set', interface, 'down']) subprocess.call(['ip', 'link', 'set', interface, 'down'])
print 'DONE' print('DONE')
print "Configuring management interface... ", print("Configuring management interface... ", end=' ')
subprocess.call(['ip', 'addr', 'add', str(management_cidr), 'dev', subprocess.call(['ip', 'addr', 'add', str(management_cidr), 'dev',
management_interface]) management_interface])
print "DONE" print("DONE")
print "Adding route to System Controller... ", print("Adding route to System Controller... ", end=' ')
subprocess.call(['ip', 'route', 'add', str(system_controller_subnet), subprocess.call(['ip', 'route', 'add', str(system_controller_subnet),
'dev', management_interface, 'via', 'dev', management_interface, 'via',
str(management_gateway_address)]) str(management_gateway_address)])
print "DONE" print("DONE")
def main(): def main():
if not os.geteuid() == 0: if not os.geteuid() == 0:
print "%s must be run with root privileges" % sys.argv[0] print("%s must be run with root privileges" % sys.argv[0])
exit(1) exit(1)
try: try:
configure_management() configure_management()
except KeyboardInterrupt: except KeyboardInterrupt:
print "\nAborted" print("\nAborted")

View File

@ -5,6 +5,7 @@ SPDX-License-Identifier: Apache-2.0
""" """
from __future__ import print_function
from six.moves import configparser from six.moves import configparser
import os import os
import subprocess import subprocess
@ -545,16 +546,16 @@ def configure_region(config_file, config_type=REGION_CONFIG):
"""Configure the region""" """Configure the region"""
# Parse the region/subcloud config file # Parse the region/subcloud config file
print "Parsing configuration file... ", print("Parsing configuration file... ", end=' ')
region_config = parse_system_config(config_file) region_config = parse_system_config(config_file)
print "DONE" print("DONE")
if config_type == SUBCLOUD_CONFIG: if config_type == SUBCLOUD_CONFIG:
# Set defaults in region_config for subclouds # Set defaults in region_config for subclouds
set_subcloud_config_defaults(region_config) set_subcloud_config_defaults(region_config)
# Validate the region/subcloud config file # Validate the region/subcloud config file
print "Validating configuration file... ", print("Validating configuration file... ", end=' ')
try: try:
create_cgcs_config_file(None, region_config, None, None, None, create_cgcs_config_file(None, region_config, None, None, None,
config_type=config_type, config_type=config_type,
@ -562,15 +563,15 @@ def configure_region(config_file, config_type=REGION_CONFIG):
except configparser.Error as e: except configparser.Error as e:
raise ConfigFail("Error parsing configuration file %s: %s" % raise ConfigFail("Error parsing configuration file %s: %s" %
(config_file, e)) (config_file, e))
print "DONE" print("DONE")
# Bring up management interface to allow us to reach Region 1 # Bring up management interface to allow us to reach Region 1
print "Configuring management interface... ", print("Configuring management interface... ", end=' ')
configure_management_interface(region_config, config_type=config_type) configure_management_interface(region_config, config_type=config_type)
print "DONE" print("DONE")
# Get token from keystone # Get token from keystone
print "Retrieving keystone token...", print("Retrieving keystone token...", end=' ')
sys.stdout.flush() sys.stdout.flush()
auth_url = region_config.get('SHARED_SERVICES', 'KEYSTONE_ADMINURL') auth_url = region_config.get('SHARED_SERVICES', 'KEYSTONE_ADMINURL')
if region_config.has_option('SHARED_SERVICES', 'ADMIN_TENANT_NAME'): if region_config.has_option('SHARED_SERVICES', 'ADMIN_TENANT_NAME'):
@ -604,18 +605,19 @@ def configure_region(config_file, config_type=REGION_CONFIG):
if not token: if not token:
attempts += 1 attempts += 1
if attempts < 10: if attempts < 10:
print "\rRetrieving keystone token...{}".format( print("\rRetrieving keystone token...{}".format(
'.' * attempts), '.' * attempts), end=' ')
sys.stdout.flush() sys.stdout.flush()
time.sleep(10) time.sleep(10)
else: else:
raise ConfigFail( raise ConfigFail(
"Unable to obtain keystone token. Please ensure " "Unable to obtain keystone token. Please ensure "
"networking and keystone configuration is correct.") "networking and keystone configuration is correct.")
print "DONE" print("DONE")
# Get services, endpoints, users and domains from keystone # Get services, endpoints, users and domains from keystone
print "Retrieving services, endpoints and users from keystone... ", print("Retrieving services, endpoints and users from keystone... ",
end=' ')
region_name = region_config.get('SHARED_SERVICES', 'REGION_NAME') region_name = region_config.get('SHARED_SERVICES', 'REGION_NAME')
service_name = region_config.get('SHARED_SERVICES', service_name = region_config.get('SHARED_SERVICES',
'KEYSTONE_SERVICE_NAME') 'KEYSTONE_SERVICE_NAME')
@ -634,12 +636,12 @@ def configure_region(config_file, config_type=REGION_CONFIG):
raise ConfigFail( raise ConfigFail(
"Unable to retrieve services, endpoints or users from keystone. " "Unable to retrieve services, endpoints or users from keystone. "
"Please ensure networking and keystone configuration is correct.") "Please ensure networking and keystone configuration is correct.")
print "DONE" print("DONE")
user_config = None user_config = None
if config_type == SUBCLOUD_CONFIG: if config_type == SUBCLOUD_CONFIG:
# Retrieve subcloud configuration from dcmanager # Retrieve subcloud configuration from dcmanager
print "Retrieving configuration from dcmanager... ", print("Retrieving configuration from dcmanager... ", end=' ')
dcmanager_url = token.get_service_url( dcmanager_url = token.get_service_url(
'SystemController', 'dcmanager', 'dcmanager', "admin") 'SystemController', 'dcmanager', 'dcmanager', "admin")
subcloud_name = region_config.get('REGION_2_SERVICES', subcloud_name = region_config.get('REGION_2_SERVICES',
@ -651,7 +653,7 @@ def configure_region(config_file, config_type=REGION_CONFIG):
subcloud_name, subcloud_name,
hash_string) hash_string)
user_config = subcloud_config['users'] user_config = subcloud_config['users']
print "DONE" print("DONE")
try: try:
# Configure missing region one keystone entries # Configure missing region one keystone entries
@ -659,28 +661,28 @@ def configure_region(config_file, config_type=REGION_CONFIG):
# Prepare region configuration for puppet to create keystone identities # Prepare region configuration for puppet to create keystone identities
if (region_config.has_option('REGION_2_SERVICES', 'CREATE') and if (region_config.has_option('REGION_2_SERVICES', 'CREATE') and
region_config.get('REGION_2_SERVICES', 'CREATE') == 'Y'): region_config.get('REGION_2_SERVICES', 'CREATE') == 'Y'):
print "Preparing keystone configuration... ", print("Preparing keystone configuration... ", end=' ')
# If keystone configuration for this region already in place, # If keystone configuration for this region already in place,
# validate it only # validate it only
else: else:
# Validate region one keystone config # Validate region one keystone config
create = False create = False
print "Validating keystone configuration... ", print("Validating keystone configuration... ", end=' ')
validate_region_one_keystone_config(region_config, token, api_url, validate_region_one_keystone_config(region_config, token, api_url,
users, services, endpoints, create, users, services, endpoints, create,
config_type=config_type, config_type=config_type,
user_config=user_config) user_config=user_config)
print "DONE" print("DONE")
# validate ldap if it is shared # validate ldap if it is shared
if region_config.has_option('SHARED_SERVICES', 'LDAP_SERVICE_URL'): if region_config.has_option('SHARED_SERVICES', 'LDAP_SERVICE_URL'):
print "Validating ldap configuration... ", print("Validating ldap configuration... ", end=' ')
validate_region_one_ldap_config(region_config) validate_region_one_ldap_config(region_config)
print "DONE" print("DONE")
# Create cgcs_config file # Create cgcs_config file
print "Creating config apply file... ", print("Creating config apply file... ", end=' ')
try: try:
create_cgcs_config_file(TEMP_CGCS_CONFIG_FILE, region_config, create_cgcs_config_file(TEMP_CGCS_CONFIG_FILE, region_config,
services, endpoints, domains, services, endpoints, domains,
@ -688,33 +690,33 @@ def configure_region(config_file, config_type=REGION_CONFIG):
except configparser.Error as e: except configparser.Error as e:
raise ConfigFail("Error parsing configuration file %s: %s" % raise ConfigFail("Error parsing configuration file %s: %s" %
(config_file, e)) (config_file, e))
print "DONE" print("DONE")
# Configure controller # Configure controller
assistant = ConfigAssistant() assistant = ConfigAssistant()
assistant.configure(TEMP_CGCS_CONFIG_FILE, display_config=False) assistant.configure(TEMP_CGCS_CONFIG_FILE, display_config=False)
except ConfigFail as e: except ConfigFail as e:
print "A configuration failure has occurred.", print("A configuration failure has occurred.", end=' ')
raise e raise e
def show_help_region(): def show_help_region():
print ("Usage: %s [OPTIONS] <CONFIG_FILE>" % sys.argv[0]) print("Usage: %s [OPTIONS] <CONFIG_FILE>" % sys.argv[0])
print textwrap.fill( print(textwrap.fill(
"Perform region configuration using the region " "Perform region configuration using the region "
"configuration from CONFIG_FILE.", 80) "configuration from CONFIG_FILE.", 80))
print ("--allow-ssh Allow configuration to be executed in " print("--allow-ssh Allow configuration to be executed in "
"ssh\n") "ssh\n")
def show_help_subcloud(): def show_help_subcloud():
print ("Usage: %s [OPTIONS] <CONFIG_FILE>" % sys.argv[0]) print("Usage: %s [OPTIONS] <CONFIG_FILE>" % sys.argv[0])
print textwrap.fill( print(textwrap.fill(
"Perform subcloud configuration using the subcloud " "Perform subcloud configuration using the subcloud "
"configuration from CONFIG_FILE.", 80) "configuration from CONFIG_FILE.", 80))
print ("--allow-ssh Allow configuration to be executed in " print("--allow-ssh Allow configuration to be executed in "
"ssh\n") "ssh\n")
def config_main(config_type=REGION_CONFIG): def config_main(config_type=REGION_CONFIG):
@ -739,7 +741,7 @@ def config_main(config_type=REGION_CONFIG):
elif arg == len(sys.argv) - 1: elif arg == len(sys.argv) - 1:
config_file = sys.argv[arg] config_file = sys.argv[arg]
else: else:
print "Invalid option. Use --help for more information." print("Invalid option. Use --help for more information.")
exit(1) exit(1)
arg += 1 arg += 1
@ -748,26 +750,26 @@ def config_main(config_type=REGION_CONFIG):
# Check if that the command is being run from the console # Check if that the command is being run from the console
if utils.is_ssh_parent(): if utils.is_ssh_parent():
if allow_ssh: if allow_ssh:
print textwrap.fill(constants.SSH_WARNING_MESSAGE, 80) print(textwrap.fill(constants.SSH_WARNING_MESSAGE, 80))
print print('')
else: else:
print textwrap.fill(constants.SSH_ERROR_MESSAGE, 80) print(textwrap.fill(constants.SSH_ERROR_MESSAGE, 80))
exit(1) exit(1)
if not os.path.isfile(config_file): if not os.path.isfile(config_file):
print "Config file %s does not exist." % config_file print("Config file %s does not exist." % config_file)
exit(1) exit(1)
try: try:
configure_region(config_file, config_type=config_type) configure_region(config_file, config_type=config_type)
except KeyboardInterrupt: except KeyboardInterrupt:
print "\nAborting configuration" print("\nAborting configuration")
except ConfigFail as e: except ConfigFail as e:
LOG.exception(e) LOG.exception(e)
print "\nConfiguration failed: {}".format(e) print("\nConfiguration failed: {}".format(e))
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
print "\nConfiguration failed: {}".format(e) print("\nConfiguration failed: {}".format(e))
else: else:
print("\nConfiguration finished successfully.") print("\nConfiguration finished successfully.")
finally: finally:

View File

@ -5,6 +5,7 @@ SPDX-License-Identifier: Apache-2.0
""" """
from __future__ import print_function
from six.moves import configparser from six.moves import configparser
import os import os
import readline import readline
@ -249,73 +250,73 @@ def configure_system(config_file):
"""Configure the system""" """Configure the system"""
# Parse the system config file # Parse the system config file
print "Parsing system configuration file... ", print("Parsing system configuration file... ", end=' ')
system_config = parse_system_config(config_file) system_config = parse_system_config(config_file)
print "DONE" print("DONE")
# Validate the system config file # Validate the system config file
print "Validating system configuration file... ", print("Validating system configuration file... ", end=' ')
try: try:
create_cgcs_config_file(None, system_config, None, None, None, create_cgcs_config_file(None, system_config, None, None, None,
DEFAULT_CONFIG, validate_only=True) DEFAULT_CONFIG, validate_only=True)
except configparser.Error as e: except configparser.Error as e:
raise ConfigFail("Error parsing configuration file %s: %s" % raise ConfigFail("Error parsing configuration file %s: %s" %
(config_file, e)) (config_file, e))
print "DONE" print("DONE")
# Create cgcs_config file # Create cgcs_config file
print "Creating config apply file... ", print("Creating config apply file... ", end=' ')
try: try:
create_cgcs_config_file(TEMP_CGCS_CONFIG_FILE, system_config, create_cgcs_config_file(TEMP_CGCS_CONFIG_FILE, system_config,
None, None, None, DEFAULT_CONFIG) None, None, None, DEFAULT_CONFIG)
except configparser.Error as e: except configparser.Error as e:
raise ConfigFail("Error parsing configuration file %s: %s" % raise ConfigFail("Error parsing configuration file %s: %s" %
(config_file, e)) (config_file, e))
print "DONE" print("DONE")
def show_help(): def show_help():
print ("Usage: %s\n" print("Usage: %s\n"
"Perform system configuration\n" "Perform system configuration\n"
"\nThe default action is to perform the initial configuration for " "\nThe default action is to perform the initial configuration for "
"the system.\nThe following options are also available:\n" "the system.\nThe following options are also available:\n"
"--config-file <name> Perform configuration using INI file\n" "--config-file <name> Perform configuration using INI file\n"
"--backup <name> Backup configuration using the given " "--backup <name> Backup configuration using the given "
"name\n" "name\n"
"--clone-iso <name> Clone and create an image with " "--clone-iso <name> Clone and create an image with "
"the given file name\n" "the given file name\n"
"--clone-status Status of the last installation of " "--clone-status Status of the last installation of "
"cloned image\n" "cloned image\n"
"--restore-system " "--restore-system "
"<include-storage-reinstall | exclude-storage-reinstall> " "<include-storage-reinstall | exclude-storage-reinstall> "
"<name>\n" "<name>\n"
" Restore system configuration from backup " " Restore system configuration from backup "
"file with\n" "file with\n"
" the given name, full path required\n" " the given name, full path required\n"
"--restore-images <name> Restore images from backup file with the " "--restore-images <name> Restore images from backup file with the "
"given name,\n" "given name,\n"
" full path required\n" " full path required\n"
"--restore-complete Complete restore of controller-0\n" "--restore-complete Complete restore of controller-0\n"
"--allow-ssh Allow configuration to be executed in " "--allow-ssh Allow configuration to be executed in "
"ssh\n" "ssh\n"
% sys.argv[0]) % sys.argv[0])
def show_help_lab_only(): def show_help_lab_only():
print ("Usage: %s\n" print("Usage: %s\n"
"Perform initial configuration\n" "Perform initial configuration\n"
"\nThe following options are for lab use only:\n" "\nThe following options are for lab use only:\n"
"--answerfile <file> Apply the configuration from the specified " "--answerfile <file> Apply the configuration from the specified "
"file without\n" "file without\n"
" any validation or user interaction\n" " any validation or user interaction\n"
"--default Apply default configuration with no NTP or " "--default Apply default configuration with no NTP or "
"DNS server\n" "DNS server\n"
" configuration (suitable for testing in a " " configuration (suitable for testing in a "
"virtual\n" "virtual\n"
" environment)\n" " environment)\n"
"--archive-dir <dir> Directory to store the archive in\n" "--archive-dir <dir> Directory to store the archive in\n"
"--provision Provision initial system data only\n" "--provision Provision initial system data only\n"
% sys.argv[0]) % sys.argv[0])
def no_complete(text, state): def no_complete(text, state):
@ -356,14 +357,14 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
answerfile = sys.argv[arg] answerfile = sys.argv[arg]
else: else:
print "--answerfile option requires a file to be specified" print("--answerfile option requires a file to be specified")
exit(1) exit(1)
elif sys.argv[arg] == "--backup": elif sys.argv[arg] == "--backup":
arg += 1 arg += 1
if arg < len(sys.argv): if arg < len(sys.argv):
backup_name = sys.argv[arg] backup_name = sys.argv[arg]
else: else:
print "--backup requires the name of the backup" print("--backup requires the name of the backup")
exit(1) exit(1)
do_backup = True do_backup = True
elif sys.argv[arg] == "--restore-system": elif sys.argv[arg] == "--restore-system":
@ -377,16 +378,16 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
backup_name = sys.argv[arg] backup_name = sys.argv[arg]
else: else:
print textwrap.fill( print(textwrap.fill(
"--restore-system requires the filename " "--restore-system requires the filename "
" of the backup", 80) " of the backup", 80))
exit(1) exit(1)
else: else:
backup_name = sys.argv[arg] backup_name = sys.argv[arg]
else: else:
print textwrap.fill( print(textwrap.fill(
"--restore-system requires the filename " "--restore-system requires the filename "
"of the backup", 80) "of the backup", 80))
exit(1) exit(1)
do_system_restore = True do_system_restore = True
elif sys.argv[arg] == "--restore-images": elif sys.argv[arg] == "--restore-images":
@ -394,7 +395,7 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
backup_name = sys.argv[arg] backup_name = sys.argv[arg]
else: else:
print "--restore-images requires the filename of the backup" print("--restore-images requires the filename of the backup")
exit(1) exit(1)
do_images_restore = True do_images_restore = True
elif sys.argv[arg] == "--restore-complete": elif sys.argv[arg] == "--restore-complete":
@ -404,14 +405,14 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
archive_dir = sys.argv[arg] archive_dir = sys.argv[arg]
else: else:
print "--archive-dir requires a directory" print("--archive-dir requires a directory")
exit(1) exit(1)
elif sys.argv[arg] == "--clone-iso": elif sys.argv[arg] == "--clone-iso":
arg += 1 arg += 1
if arg < len(sys.argv): if arg < len(sys.argv):
backup_name = sys.argv[arg] backup_name = sys.argv[arg]
else: else:
print "--clone-iso requires the name of the image" print("--clone-iso requires the name of the image")
exit(1) exit(1)
do_clone = True do_clone = True
elif sys.argv[arg] == "--clone-status": elif sys.argv[arg] == "--clone-status":
@ -424,7 +425,7 @@ def main():
if arg < len(sys.argv): if arg < len(sys.argv):
system_config_file = sys.argv[arg] system_config_file = sys.argv[arg]
else: else:
print "--config-file requires the filename of the config file" print("--config-file requires the filename of the config file")
exit(1) exit(1)
do_non_interactive = True do_non_interactive = True
elif sys.argv[arg] in ["--help", "-h", "-?"]: elif sys.argv[arg] in ["--help", "-h", "-?"]:
@ -442,7 +443,7 @@ def main():
# are stable, we will remove it and make kubernetes the default. # are stable, we will remove it and make kubernetes the default.
options['kubernetes'] = True options['kubernetes'] = True
else: else:
print "Invalid option. Use --help for more information." print("Invalid option. Use --help for more information.")
exit(1) exit(1)
arg += 1 arg += 1
@ -453,7 +454,7 @@ def main():
do_clone, do_clone,
do_default_config, do_default_config,
do_non_interactive].count(True) > 1: do_non_interactive].count(True) > 1:
print "Invalid combination of options selected" print("Invalid combination of options selected")
exit(1) exit(1)
if answerfile and [do_backup, if answerfile and [do_backup,
@ -463,7 +464,8 @@ def main():
do_clone, do_clone,
do_default_config, do_default_config,
do_non_interactive].count(True) > 0: do_non_interactive].count(True) > 0:
print "The --answerfile option cannot be used with the selected option" print("The --answerfile option cannot be used with the selected "
"option")
exit(1) exit(1)
log.configure() log.configure()
@ -472,10 +474,10 @@ def main():
# Check if that the command is being run from the console # Check if that the command is being run from the console
if utils.is_ssh_parent(): if utils.is_ssh_parent():
if allow_ssh: if allow_ssh:
print textwrap.fill(constants.SSH_WARNING_MESSAGE, 80) print(textwrap.fill(constants.SSH_WARNING_MESSAGE, 80))
print print('')
else: else:
print textwrap.fill(constants.SSH_ERROR_MESSAGE, 80) print(textwrap.fill(constants.SSH_ERROR_MESSAGE, 80))
exit(1) exit(1)
# Reduce the printk console log level to avoid noise during configuration # Reduce the printk console log level to avoid noise during configuration
@ -490,19 +492,19 @@ def main():
try: try:
if do_backup: if do_backup:
backup_restore.backup(backup_name, archive_dir) backup_restore.backup(backup_name, archive_dir)
print "\nBackup complete" print("\nBackup complete")
elif do_system_restore: elif do_system_restore:
backup_restore.restore_system(backup_name, backup_restore.restore_system(backup_name,
include_storage_reinstall) include_storage_reinstall)
print "\nSystem restore complete" print("\nSystem restore complete")
elif do_images_restore: elif do_images_restore:
backup_restore.restore_images(backup_name) backup_restore.restore_images(backup_name)
print "\nImages restore complete" print("\nImages restore complete")
elif do_complete_restore: elif do_complete_restore:
backup_restore.restore_complete() backup_restore.restore_complete()
elif do_clone: elif do_clone:
clone.clone(backup_name, archive_dir) clone.clone(backup_name, archive_dir)
print "\nCloning complete" print("\nCloning complete")
elif do_provision: elif do_provision:
assistant = ConfigAssistant(**options) assistant = ConfigAssistant(**options)
assistant.provision(answerfile) assistant.provision(answerfile)
@ -521,24 +523,24 @@ def main():
answerfile = TEMP_CGCS_CONFIG_FILE answerfile = TEMP_CGCS_CONFIG_FILE
assistant = ConfigAssistant(**options) assistant = ConfigAssistant(**options)
assistant.configure(answerfile, do_default_config) assistant.configure(answerfile, do_default_config)
print "\nConfiguration was applied\n" print("\nConfiguration was applied\n")
print textwrap.fill( print(textwrap.fill(
"Please complete any out of service commissioning steps " "Please complete any out of service commissioning steps "
"with system commands and unlock controller to proceed.", 80) "with system commands and unlock controller to proceed.", 80))
assistant.check_required_interfaces_status() assistant.check_required_interfaces_status()
except KeyboardInterrupt: except KeyboardInterrupt:
print "\nAborting configuration" print("\nAborting configuration")
except BackupFail as e: except BackupFail as e:
print "\nBackup failed: {}".format(e) print("\nBackup failed: {}".format(e))
except RestoreFail as e: except RestoreFail as e:
print "\nRestore failed: {}".format(e) print("\nRestore failed: {}".format(e))
except ConfigFail as e: except ConfigFail as e:
print "\nConfiguration failed: {}".format(e) print("\nConfiguration failed: {}".format(e))
except CloneFail as e: except CloneFail as e:
print "\nCloning failed: {}".format(e) print("\nCloning failed: {}".format(e))
except UserQuit: except UserQuit:
print "\nAborted configuration" print("\nAborted configuration")
finally: finally:
if os.path.isfile(TEMP_CGCS_CONFIG_FILE): if os.path.isfile(TEMP_CGCS_CONFIG_FILE):
os.remove(TEMP_CGCS_CONFIG_FILE) os.remove(TEMP_CGCS_CONFIG_FILE)

View File

@ -35,7 +35,7 @@ def _test_answerfile(tmpdir, filename,
assistant.input_config_from_file(answerfile) assistant.input_config_from_file(answerfile)
# Test the display method # Test the display method
print "Output from display_config:" print("Output from display_config:")
assistant.display_config() assistant.display_config()
# Ensure we can write the configuration # Ensure we can write the configuration
@ -50,7 +50,7 @@ def _test_answerfile(tmpdir, filename,
f.write("\n[cAUTHENTICATION]\nADMIN_PASSWORD=Li69nux*\n") f.write("\n[cAUTHENTICATION]\nADMIN_PASSWORD=Li69nux*\n")
# Do a diff between the answerfile and the generated config file # Do a diff between the answerfile and the generated config file
print "\n\nDiff of answerfile vs. generated config file:\n" print("\n\nDiff of answerfile vs. generated config file:\n")
with open(answerfile) as a, open(constants.CGCS_CONFIG_FILE) as b: with open(answerfile) as a, open(constants.CGCS_CONFIG_FILE) as b:
a_lines = a.readlines() a_lines = a.readlines()
b_lines = b.readlines() b_lines = b.readlines()

View File

@ -5,6 +5,7 @@ SPDX-License-Identifier: Apache-2.0
""" """
from __future__ import print_function
from six.moves import configparser from six.moves import configparser
import difflib import difflib
import filecmp import filecmp
@ -436,16 +437,16 @@ FAKE_DOMAIN_DATA = {u'domains': [
def _dump_config(config): def _dump_config(config):
""" Prints contents of config object """ """ Prints contents of config object """
for section in config.sections(): for section in config.sections():
print "[%s]" % section print("[%s]" % section)
for (name, value) in config.items(section): for (name, value) in config.items(section):
print "%s=%s" % (name, value) print("%s=%s" % (name, value))
def _replace_in_file(filename, old, new): def _replace_in_file(filename, old, new):
""" Replaces old with new in file filename. """ """ Replaces old with new in file filename. """
for line in fileinput.FileInput(filename, inplace=1): for line in fileinput.FileInput(filename, inplace=1):
line = line.replace(old, new) line = line.replace(old, new)
print line, print(line, end=' ')
fileinput.close() fileinput.close()
@ -463,7 +464,7 @@ def _test_region_config(tmpdir, inputfile, resultfile,
region_config = cr.parse_system_config(inputfile) region_config = cr.parse_system_config(inputfile)
# Dump results for debugging # Dump results for debugging
print "Parsed region_config:\n" print("Parsed region_config:\n")
_dump_config(region_config) _dump_config(region_config)
# Validate the region config file # Validate the region config file
@ -477,7 +478,7 @@ def _test_region_config(tmpdir, inputfile, resultfile,
shutil.copyfile(resultfile, local_resultfile) shutil.copyfile(resultfile, local_resultfile)
# Do a diff between the output and the expected results # Do a diff between the output and the expected results
print "\n\nDiff of output file vs. expected results file:\n" print("\n\nDiff of output file vs. expected results file:\n")
with open(outputfile) as a, open(local_resultfile) as b: with open(outputfile) as a, open(local_resultfile) as b:
a_lines = a.readlines() a_lines = a.readlines()
b_lines = b.readlines() b_lines = b.readlines()
@ -515,7 +516,7 @@ def test_region_config_simple(tmpdir):
def test_region_config_simple_can_ips(tmpdir): def test_region_config_simple_can_ips(tmpdir):
""" Test import of simple region_config file with unit ips for CAN """ """ Test import of simple region_config file with unit ips for CAN """
print "IN TEST ################################################" print("IN TEST ################################################")
regionfile = os.path.join( regionfile = os.path.join(
os.getcwd(), "controllerconfig/tests/files/", os.getcwd(), "controllerconfig/tests/files/",
"region_config.simple.can_ips") "region_config.simple.can_ips")

View File

@ -22,9 +22,9 @@ import controllerconfig.systemconfig as cr # noqa: E402
def _dump_config(config): def _dump_config(config):
""" Prints contents of config object """ """ Prints contents of config object """
for section in config.sections(): for section in config.sections():
print "[%s]" % section print("[%s]" % section)
for (name, value) in config.items(section): for (name, value) in config.items(section):
print "%s=%s" % (name, value) print("%s=%s" % (name, value))
def _test_system_config(filename): def _test_system_config(filename):
@ -34,7 +34,7 @@ def _test_system_config(filename):
system_config = cr.parse_system_config(filename) system_config = cr.parse_system_config(filename)
# Dump results for debugging # Dump results for debugging
print "Parsed system_config:\n" print("Parsed system_config:\n")
_dump_config(system_config) _dump_config(system_config)
# Validate the system config file # Validate the system config file

View File

@ -124,10 +124,10 @@ class OpenStack(object):
def show_help(): def show_help():
print ("Usage: %s <user_action_log_file>" % sys.argv[0]) print("Usage: %s <user_action_log_file>" % sys.argv[0])
print textwrap.fill( print(textwrap.fill(
"Tidy storage post system restore. Check user actions " "Tidy storage post system restore. Check user actions "
"in the generated user_action_log_file.", 80) "in the generated user_action_log_file.", 80))
def tidy_storage(result_file): def tidy_storage(result_file):
@ -219,7 +219,7 @@ def tidy_storage(result_file):
'rbd://{}/images/{}/snap'.format(ceph_cluster[0], 'rbd://{}/images/{}/snap'.format(ceph_cluster[0],
image) image)
print ("Creating a Glance image %s ...\n " % fields['name']) print("Creating a Glance image %s ...\n " % fields['name'])
g_client_v1.images.create(**fields) g_client_v1.images.create(**fields)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
LOG.error("Failed to access rbd image %s" % image) LOG.error("Failed to access rbd image %s" % image)
@ -242,7 +242,7 @@ def tidy_storage(result_file):
snaps_no_backend_vol = [] snaps_no_backend_vol = []
for snap in snap_l: for snap in snap_l:
print ("Check if volume snapshot %s has backend " % snap.name) print("Check if volume snapshot %s has backend " % snap.name)
try: try:
output = subprocess.check_output( output = subprocess.check_output(
["rbd", "ls", "--pool", "cinder-volumes"], ["rbd", "ls", "--pool", "cinder-volumes"],
@ -278,8 +278,8 @@ def tidy_storage(result_file):
if not keep_snap: if not keep_snap:
try: try:
print ("Volume snapshot %s has no backend data. " print("Volume snapshot %s has no backend data. "
"Deleting it from Cinder...\n" % snap.name) "Deleting it from Cinder...\n" % snap.name)
c_client.volume_snapshots.delete(c_utils.find_resource( c_client.volume_snapshots.delete(c_utils.find_resource(
c_client.volume_snapshots, snap.id), force=True) c_client.volume_snapshots, snap.id), force=True)
@ -387,9 +387,9 @@ def tidy_storage(result_file):
# supported in rbd. So we just remove the snapshot. # supported in rbd. So we just remove the snapshot.
# Remove the snapshot # Remove the snapshot
print (textwrap.fill( print(textwrap.fill(
"Removing snapshot %s from volume %s " "Removing snapshot %s from volume %s "
"in rbd...\n" % (snap, vol_id), 76)) "in rbd...\n" % (snap, vol_id), 76))
del_snap = '{}@{}'.format(volume, snap) del_snap = '{}@{}'.format(volume, snap)
output = subprocess.check_output( output = subprocess.check_output(
["rbd", "snap", "unprotect", del_snap], ["rbd", "snap", "unprotect", del_snap],
@ -440,8 +440,8 @@ def tidy_storage(result_file):
for snap in snap_l: for snap in snap_l:
if snap not in cinder_snap_l: if snap not in cinder_snap_l:
print ("Creating volume snapshot found-%s " print("Creating volume snapshot found-%s "
"in Cinder...\n" % snap) "in Cinder...\n" % snap)
c_client.volume_snapshots.manage( c_client.volume_snapshots.manage(
volume_id=vol_id, volume_id=vol_id,

View File

@ -450,7 +450,7 @@ def import_databases(from_release, to_release, from_path=None, simplex=False):
# Execute import commands # Execute import commands
for cmd in import_commands: for cmd in import_commands:
try: try:
print "Importing %s" % cmd[0] print("Importing %s" % cmd[0])
LOG.info("Executing import command: %s" % cmd[1]) LOG.info("Executing import command: %s" % cmd[1])
subprocess.check_call([cmd[1]], subprocess.check_call([cmd[1]],
shell=True, stdout=devnull) shell=True, stdout=devnull)
@ -483,7 +483,7 @@ def create_databases(from_release, to_release, db_credentials):
with conn: with conn:
with conn.cursor() as cur: with conn.cursor() as cur:
for database in databases_to_create: for database in databases_to_create:
print "Creating %s database" % database print("Creating %s database" % database)
username = psycopg2.extensions.AsIs( username = psycopg2.extensions.AsIs(
'\"%s\"' % db_credentials[database]['username']) '\"%s\"' % db_credentials[database]['username'])
db_name = psycopg2.extensions.AsIs('\"%s\"' % database) db_name = psycopg2.extensions.AsIs('\"%s\"' % database)
@ -513,7 +513,7 @@ def migrate_sysinv_database():
sysinv_cmd = 'sysinv-dbsync' sysinv_cmd = 'sysinv-dbsync'
try: try:
print "Migrating sysinv" print("Migrating sysinv")
LOG.info("Executing migrate command: %s" % sysinv_cmd) LOG.info("Executing migrate command: %s" % sysinv_cmd)
subprocess.check_call([sysinv_cmd], subprocess.check_call([sysinv_cmd],
shell=True, stdout=devnull, stderr=devnull) shell=True, stdout=devnull, stderr=devnull)
@ -686,7 +686,7 @@ def migrate_databases(from_release, shared_services, db_credentials,
# Execute migrate commands # Execute migrate commands
for cmd in migrate_commands: for cmd in migrate_commands:
try: try:
print "Migrating %s" % cmd[0] print("Migrating %s" % cmd[0])
LOG.info("Executing migrate command: %s" % cmd[1]) LOG.info("Executing migrate command: %s" % cmd[1])
subprocess.check_call([cmd[1]], subprocess.check_call([cmd[1]],
shell=True, stdout=devnull, stderr=devnull) shell=True, stdout=devnull, stderr=devnull)
@ -826,19 +826,19 @@ def upgrade_controller(from_release, to_release):
nfs_mount_filesystem(utils.POSTGRES_PATH, POSTGRES_MOUNT_PATH) nfs_mount_filesystem(utils.POSTGRES_PATH, POSTGRES_MOUNT_PATH)
# Migrate keyring data # Migrate keyring data
print "Migrating keyring data..." print("Migrating keyring data...")
migrate_keyring_data(from_release, to_release) migrate_keyring_data(from_release, to_release)
# Migrate pxeboot config # Migrate pxeboot config
print "Migrating pxeboot configuration..." print("Migrating pxeboot configuration...")
migrate_pxeboot_config(from_release, to_release) migrate_pxeboot_config(from_release, to_release)
# Migrate sysinv data. # Migrate sysinv data.
print "Migrating sysinv configuration..." print("Migrating sysinv configuration...")
migrate_sysinv_data(from_release, to_release) migrate_sysinv_data(from_release, to_release)
# Prepare for database migration # Prepare for database migration
print "Preparing for database migration..." print("Preparing for database migration...")
prepare_postgres_filesystems() prepare_postgres_filesystems()
# Create the postgres database # Create the postgres database
@ -863,7 +863,7 @@ def upgrade_controller(from_release, to_release):
time.sleep(5) time.sleep(5)
# Import databases # Import databases
print "Importing databases..." print("Importing databases...")
import_databases(from_release, to_release) import_databases(from_release, to_release)
shared_services = get_shared_services() shared_services = get_shared_services()
@ -881,17 +881,17 @@ def upgrade_controller(from_release, to_release):
db_credentials = get_db_credentials(shared_services, from_release) db_credentials = get_db_credentials(shared_services, from_release)
# Create any new databases # Create any new databases
print "Creating new databases..." print("Creating new databases...")
create_databases(from_release, to_release, db_credentials) create_databases(from_release, to_release, db_credentials)
print "Migrating databases..." print("Migrating databases...")
# Migrate sysinv database # Migrate sysinv database
migrate_sysinv_database() migrate_sysinv_database()
# Migrate databases # Migrate databases
migrate_databases(from_release, shared_services, db_credentials) migrate_databases(from_release, shared_services, db_credentials)
print "Applying configuration..." print("Applying configuration...")
# Execute migration scripts # Execute migration scripts
utils.execute_migration_scripts( utils.execute_migration_scripts(
@ -934,7 +934,7 @@ def upgrade_controller(from_release, to_release):
LOG.info("Failed to update hiera configuration") LOG.info("Failed to update hiera configuration")
raise raise
print "Shutting down upgrade processes..." print("Shutting down upgrade processes...")
# Stop postgres service # Stop postgres service
LOG.info("Stopping postgresql service") LOG.info("Stopping postgresql service")
@ -957,7 +957,7 @@ def upgrade_controller(from_release, to_release):
raise raise
# Copy upgraded database back to controller-0 # Copy upgraded database back to controller-0
print "Writing upgraded databases..." print("Writing upgraded databases...")
LOG.info("Copying upgraded database to controller-0") LOG.info("Copying upgraded database to controller-0")
try: try:
subprocess.check_call( subprocess.check_call(
@ -1003,13 +1003,13 @@ def upgrade_controller(from_release, to_release):
unmount_filesystem("/tmp/etc_platform") unmount_filesystem("/tmp/etc_platform")
os.rmdir("/tmp/etc_platform") os.rmdir("/tmp/etc_platform")
print "Controller-1 upgrade complete" print("Controller-1 upgrade complete")
LOG.info("Controller-1 upgrade complete!!!") LOG.info("Controller-1 upgrade complete!!!")
def show_help(): def show_help():
print ("Usage: %s <FROM_RELEASE> <TO_RELEASE>" % sys.argv[0]) print("Usage: %s <FROM_RELEASE> <TO_RELEASE>" % sys.argv[0])
print "Upgrade controller-1. For internal use only." print("Upgrade controller-1. For internal use only.")
def main(): def main():
@ -1026,22 +1026,22 @@ def main():
elif arg == 2: elif arg == 2:
to_release = sys.argv[arg] to_release = sys.argv[arg]
else: else:
print ("Invalid option %s. Use --help for more information." % print("Invalid option %s. Use --help for more information." %
sys.argv[arg]) sys.argv[arg])
exit(1) exit(1)
arg += 1 arg += 1
log.configure() log.configure()
if not from_release or not to_release: if not from_release or not to_release:
print "Both the FROM_RELEASE and TO_RELEASE must be specified" print("Both the FROM_RELEASE and TO_RELEASE must be specified")
exit(1) exit(1)
try: try:
upgrade_controller(from_release, to_release) upgrade_controller(from_release, to_release)
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
print "Upgrade failed: {}".format(e) print("Upgrade failed: {}".format(e))
# Set upgrade fail flag on mate controller # Set upgrade fail flag on mate controller
LOG.info("Set upgrade fail flag on mate controller") LOG.info("Set upgrade fail flag on mate controller")
@ -1520,13 +1520,13 @@ def upgrade_controller_simplex(backup_file):
def print_log_info(string): def print_log_info(string):
print string print(string)
LOG.info(string) LOG.info(string)
def show_help_simplex(): def show_help_simplex():
print ("Usage: %s <BACKUP_FILE>" % sys.argv[0]) print("Usage: %s <BACKUP_FILE>" % sys.argv[0])
print "Upgrade controller-0 simplex. For internal use only." print("Upgrade controller-0 simplex. For internal use only.")
def simplex_main(): def simplex_main():
@ -1539,8 +1539,8 @@ def simplex_main():
elif arg == 1: elif arg == 1:
backup_file = sys.argv[arg] backup_file = sys.argv[arg]
else: else:
print ("Invalid option %s. Use --help for more information." % print("Invalid option %s. Use --help for more information." %
sys.argv[arg]) sys.argv[arg])
exit(1) exit(1)
arg += 1 arg += 1
@ -1554,14 +1554,14 @@ def simplex_main():
exit(1) exit(1)
if not backup_file: if not backup_file:
print "The BACKUP_FILE must be specified" print("The BACKUP_FILE must be specified")
exit(1) exit(1)
try: try:
upgrade_controller_simplex(backup_file) upgrade_controller_simplex(backup_file)
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
print "Upgrade failed: {}".format(e) print("Upgrade failed: {}".format(e))
# TODO SET Upgrade fail flag # TODO SET Upgrade fail flag
# Set upgrade fail flag on mate controller # Set upgrade fail flag on mate controller
exit(1) exit(1)

View File

@ -247,5 +247,5 @@ def apply_upgrade_manifest(controller_address):
subprocess.check_call(cmd, stdout=flog, stderr=flog) subprocess.check_call(cmd, stdout=flog, stderr=flog)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
msg = "Failed to execute upgrade manifest" msg = "Failed to execute upgrade manifest"
print msg print(msg)
raise Exception(msg) raise Exception(msg)

View File

@ -626,7 +626,7 @@ def apply_manifest(controller_address_0, personality, manifest, hieradata,
subprocess.check_call(cmd, stdout=flog, stderr=flog) subprocess.check_call(cmd, stdout=flog, stderr=flog)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
msg = "Failed to execute %s manifest" % manifest msg = "Failed to execute %s manifest" % manifest
print msg print(msg)
raise Exception(msg) raise Exception(msg)
@ -657,7 +657,7 @@ def create_static_config():
subprocess.check_call(cmd) subprocess.check_call(cmd)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
msg = "Failed to create puppet hiera static config" msg = "Failed to create puppet hiera static config"
print msg print(msg)
raise Exception(msg) raise Exception(msg)
@ -669,7 +669,7 @@ def create_system_config():
subprocess.check_call(cmd) subprocess.check_call(cmd)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
msg = "Failed to update puppet hiera system config" msg = "Failed to update puppet hiera system config"
print msg print(msg)
raise Exception(msg) raise Exception(msg)
@ -684,7 +684,7 @@ def create_host_config(hostname=None):
subprocess.check_call(cmd) subprocess.check_call(cmd)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
msg = "Failed to update puppet hiera host config" msg = "Failed to update puppet hiera host config"
print msg print(msg)
raise Exception(msg) raise Exception(msg)
@ -821,7 +821,7 @@ def apply_banner_customization():
stdout=blog, stderr=blog) stdout=blog, stderr=blog)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
error_text = "Failed to apply banner customization" error_text = "Failed to apply banner customization"
print "%s; see %s for detail" % (error_text, logfile) print("%s; see %s for detail" % (error_text, logfile))
def mtce_restart(): def mtce_restart():

View File

@ -52,7 +52,7 @@ def main():
elif arg == 3: elif arg == 3:
action = sys.argv[arg] action = sys.argv[arg]
else: else:
print ("Invalid option %s." % sys.argv[arg]) print("Invalid option %s." % sys.argv[arg])
return 1 return 1
arg += 1 arg += 1
@ -65,7 +65,7 @@ def main():
do_migration_work() do_migration_work()
except Exception as ex: except Exception as ex:
LOG.exception(ex) LOG.exception(ex)
print ex print(ex)
return 1 return 1

View File

@ -30,11 +30,26 @@ commands = pylint {posargs} controllerconfig --rcfile=./pylint.rc --extension-pk
[testenv:flake8] [testenv:flake8]
basepython = python2.7 basepython = python2.7
deps = flake8<3.6.0 deps = hacking
flake8<3.6.0
commands = flake8 {posargs} commands = flake8 {posargs}
[flake8] [flake8]
ignore = W503 # H series are hacking
# H101: Use TODO(NAME)
# H102: Apache 2.0 license header not found
# H104: File contains nothing but comments
# H231: Python 3.x incompatible 'except x,y:' construct
# H232: Python 3.x incompatible octal 400 should be written as 0o400
# H238: old style class declaration, use new style (inherit from `object`)
# H301: one import per line
# H306: imports not in alphabetical order
# H401: docstring should not start with a space
# H403: multi line docstrings should end on a new line
# H404: multi line docstring should start without a leading new line
# H405: multi line docstring summary not separated with an empty line
ignore = H101,H102,H104,H231,H232,H238,H301,H306,H401,H403,H404,H405,
W503
[testenv:py27] [testenv:py27]
basepython = python2.7 basepython = python2.7

View File

@ -32,7 +32,7 @@ def main():
elif arg == 3: elif arg == 3:
action = sys.argv[arg] action = sys.argv[arg]
else: else:
print ("Invalid option %s." % sys.argv[arg]) print("Invalid option %s." % sys.argv[arg])
return 1 return 1
arg += 1 arg += 1
@ -47,7 +47,7 @@ def main():
move_distributed_port_bindings_off_controller_1() move_distributed_port_bindings_off_controller_1()
except Exception as ex: except Exception as ex:
LOG.exception(ex) LOG.exception(ex)
print ex print(ex)
return 1 return 1

View File

@ -37,7 +37,7 @@ def main():
elif arg == 3: elif arg == 3:
action = sys.argv[arg] action = sys.argv[arg]
else: else:
print ("Invalid option %s." % sys.argv[arg]) print("Invalid option %s." % sys.argv[arg])
return 1 return 1
arg += 1 arg += 1

View File

@ -14,6 +14,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from __future__ import print_function
try: try:
import tsconfig.tsconfig as tsc import tsconfig.tsconfig as tsc
is_remote = False is_remote = False
@ -225,7 +226,7 @@ def _sort_for_list(objs, fields, formatters={}, sortby=0, reversesort=False):
def default_printer(s): def default_printer(s):
print s print(s)
def pt_builder(field_labels, fields, formatters, paging, printer=default_printer): def pt_builder(field_labels, fields, formatters, paging, printer=default_printer):
@ -410,7 +411,7 @@ def print_tuple_list(tuples, tuple_labels=[], formatters={}):
v = formatters[f](v) v = formatters[f](v)
pt.add_row([l, v]) pt.add_row([l, v])
print pt.get_string() print(pt.get_string())
def str_height(text): def str_height(text):
@ -465,7 +466,7 @@ def print_dict(d, dict_property="Property", wrap=0):
col1 = '' col1 = ''
else: else:
pt.add_row([k, v]) pt.add_row([k, v])
print pt.get_string() print(pt.get_string())
def find_resource(manager, name_or_id): def find_resource(manager, name_or_id):
@ -561,7 +562,7 @@ def dict_to_patch(values, op='replace'):
def exit(msg=''): def exit(msg=''):
if msg: if msg:
print >> sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(1) sys.exit(1)

View File

@ -800,7 +800,7 @@ def _simpleTestHarness(no_wrap):
utils.print_list(logs, fields, field_labels, formatters=formatters, sortby=6, utils.print_list(logs, fields, field_labels, formatters=formatters, sortby=6,
reversesort=True, no_wrap_fields=['entity_instance_id']) reversesort=True, no_wrap_fields=['entity_instance_id'])
print "nowrap = {}".format(is_nowrap_set()) print("nowrap = {}".format(is_nowrap_set()))
if __name__ == "__main__": if __name__ == "__main__":
_simpleTestHarness(True) _simpleTestHarness(True)

View File

@ -98,7 +98,7 @@ def generate(srcfiles):
for group, opts in opts_by_group.items(): for group, opts in opts_by_group.items():
print_group_opts(group, opts) print_group_opts(group, opts)
print "# Total option count: %d" % OPTION_COUNT print("# Total option count: %d" % OPTION_COUNT)
def _import_module(mod_str): def _import_module(mod_str):
@ -162,18 +162,18 @@ def _list_opts(obj):
def print_group_opts(group, opts_by_module): def print_group_opts(group, opts_by_module):
print "[%s]" % group print("[%s]" % group)
print print('')
global OPTION_COUNT global OPTION_COUNT
for mod, opts in opts_by_module: for mod, opts in opts_by_module:
OPTION_COUNT += len(opts) OPTION_COUNT += len(opts)
print '#' print('#')
print '# Options defined in %s' % mod print('# Options defined in %s' % mod)
print '#' print('#')
print print('')
for opt in opts: for opt in opts:
_print_opt(opt) _print_opt(opt)
print print('')
def _get_my_ip(): def _get_my_ip():
@ -213,33 +213,33 @@ def _print_opt(opt):
sys.stderr.write("%s\n" % str(err)) sys.stderr.write("%s\n" % str(err))
sys.exit(1) sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')' opt_help += ' (' + OPT_TYPES[opt_type] + ')'
print '#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)) print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
try: try:
if opt_default is None: if opt_default is None:
print '#%s=<None>' % opt_name print('#%s=<None>' % opt_name)
elif opt_type == STROPT: elif opt_type == STROPT:
assert(isinstance(opt_default, six.string_types)) assert(isinstance(opt_default, six.string_types))
print '#%s=%s' % (opt_name, _sanitize_default(opt_default)) print('#%s=%s' % (opt_name, _sanitize_default(opt_default)))
elif opt_type == BOOLOPT: elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool)) assert(isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, str(opt_default).lower()) print('#%s=%s' % (opt_name, str(opt_default).lower()))
elif opt_type == INTOPT: elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool)) not isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, opt_default) print('#%s=%s' % (opt_name, opt_default))
elif opt_type == FLOATOPT: elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float)) assert(isinstance(opt_default, float))
print '#%s=%s' % (opt_name, opt_default) print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT: elif opt_type == LISTOPT:
assert(isinstance(opt_default, list)) assert(isinstance(opt_default, list))
print '#%s=%s' % (opt_name, ','.join(opt_default)) print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == MULTISTROPT: elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list)) assert(isinstance(opt_default, list))
if not opt_default: if not opt_default:
opt_default = [''] opt_default = ['']
for default in opt_default: for default in opt_default:
print '#%s=%s' % (opt_name, default) print('#%s=%s' % (opt_name, default))
print print('')
except Exception: except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name) sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1) sys.exit(1)
@ -247,7 +247,7 @@ def _print_opt(opt):
def main(): def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
print "usage: %s [srcfile]...\n" % sys.argv[0] print("usage: %s [srcfile]...\n" % sys.argv[0])
sys.exit(0) sys.exit(0)
generate(sys.argv[1:]) generate(sys.argv[1:])

View File

@ -18,6 +18,7 @@
Command-line interface for System Inventory and Maintenance Command-line interface for System Inventory and Maintenance
""" """
from __future__ import print_function
import argparse import argparse
import httplib2 import httplib2
import logging import logging
@ -338,14 +339,14 @@ def main():
CgtsShell().main(sys.argv[1:]) CgtsShell().main(sys.argv[1:])
except KeyboardInterrupt as e: except KeyboardInterrupt as e:
print >> sys.stderr, ('caught: %r, aborting' % (e)) print(('caught: %r, aborting' % (e)), file=sys.stderr)
sys.exit(0) sys.exit(0)
except IOError as e: except IOError as e:
sys.exit(0) sys.exit(0)
except Exception as e: except Exception as e:
print >> sys.stderr, e print(e, file=sys.stderr)
sys.exit(1) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -59,7 +59,7 @@ def do_addrpool_list(cc, args):
def do_addrpool_delete(cc, args): def do_addrpool_delete(cc, args):
"""Delete an IP address pool.""" """Delete an IP address pool."""
cc.address_pool.delete(args.address_pool_uuid) cc.address_pool.delete(args.address_pool_uuid)
print 'Deleted address pool: %s' % (args.address_pool_uuid) print('Deleted address pool: %s' % (args.address_pool_uuid))
def _get_range_tuples(data): def _get_range_tuples(data):

View File

@ -51,7 +51,7 @@ def do_host_addr_list(cc, args):
def do_host_addr_delete(cc, args): def do_host_addr_delete(cc, args):
"""Delete an IP address.""" """Delete an IP address."""
cc.address.delete(args.address_uuid) cc.address.delete(args.address_uuid)
print 'Deleted Address: %s' % (args.address_uuid) print('Deleted Address: %s' % (args.address_uuid))
@utils.arg('hostnameorid', @utils.arg('hostnameorid',

View File

@ -62,13 +62,13 @@ def do_ceph_mon_modify(cc, args):
for ceph_mon in cc.ceph_mon.list(): for ceph_mon in cc.ceph_mon.list():
cc.ceph_mon.update(ceph_mon.uuid, patch) cc.ceph_mon.update(ceph_mon.uuid, patch)
_print_ceph_mon_list(cc) _print_ceph_mon_list(cc)
print "\nNOTE: ceph_mon_gib for both controllers are changed." print("\nNOTE: ceph_mon_gib for both controllers are changed.")
else: else:
ceph_mon = cc.ceph_mon.update(ceph_mon.uuid, patch) ceph_mon = cc.ceph_mon.update(ceph_mon.uuid, patch)
_print_ceph_mon_show(ceph_mon) _print_ceph_mon_show(ceph_mon)
print "\nSystem configuration has changed.\nplease follow the " \ print("\nSystem configuration has changed.\nplease follow the "
"administrator guide to complete configuring system.\n" "administrator guide to complete configuring system.\n")
def do_ceph_mon_list(cc, args): def do_ceph_mon_list(cc, args):

View File

@ -40,14 +40,14 @@ def do_certificate_show(cc, args):
args.certificate_uuid = cert.uuid args.certificate_uuid = cert.uuid
break break
else: else:
print "No TPM certificate installed" print("No TPM certificate installed")
return return
certificate = cc.certificate.get(args.certificate_uuid) certificate = cc.certificate.get(args.certificate_uuid)
if certificate: if certificate:
_print_certificate_show(certificate) _print_certificate_show(certificate)
else: else:
print "No Certificates installed" print("No Certificates installed")
def do_certificate_list(cc, args): def do_certificate_list(cc, args):
@ -85,9 +85,9 @@ def do_certificate_install(cc, args):
'mode': args.mode, 'mode': args.mode,
'certificate_file': os.path.abspath(args.certificate_file)} 'certificate_file': os.path.abspath(args.certificate_file)}
print "WARNING: For security reasons, the original certificate, " print("WARNING: For security reasons, the original certificate, ")
print "containing the private key, will be removed, " print("containing the private key, will be removed, ")
print "once the private key is processed." print("once the private key is processed.")
try: try:
response = cc.certificate.certificate_install(sec_file, data=data) response = cc.certificate.certificate_install(sec_file, data=data)

View File

@ -141,4 +141,4 @@ if os.path.exists('/var/run/.sysinv_running_in_lab'):
def do_cluster_delete(cc, args): def do_cluster_delete(cc, args):
"""Delete a Cluster.""" """Delete a Cluster."""
cc.cluster.delete(args.cluster_uuid) cc.cluster.delete(args.cluster_uuid)
print 'Deleted cluster: %s' % args.cluster_uuid print('Deleted cluster: %s' % args.cluster_uuid)

View File

@ -9,6 +9,7 @@
# All Rights Reserved. # All Rights Reserved.
# #
from __future__ import print_function
import argparse import argparse
import sys import sys
import time import time
@ -44,7 +45,7 @@ def do_drbdsync_show(cc, args):
drbdconfigs = cc.drbdconfig.list() drbdconfigs = cc.drbdconfig.list()
_print_drbdsync_show(drbdconfigs[0]) _print_drbdsync_show(drbdconfigs[0])
print print('')
ihosts = cc.ihost.list_personality(personality=CONTROLLER) ihosts = cc.ihost.list_personality(personality=CONTROLLER)
_print_controller_config_show(ihosts) _print_controller_config_show(ihosts)
@ -72,7 +73,7 @@ def do_drbdsync_modify(cc, args):
if len(attributes) > 0: if len(attributes) > 0:
attributes.append('action=apply') attributes.append('action=apply')
else: else:
print "No options provided." print("No options provided.")
return return
patch = utils.args_array_to_patch("replace", attributes) patch = utils.args_array_to_patch("replace", attributes)
@ -90,9 +91,9 @@ def do_drbdsync_modify(cc, args):
for ihost in ihosts: for ihost in ihosts:
if ihost.config_target and ihost.config_applied != ihost.config_target: if ihost.config_target and ihost.config_applied != ihost.config_target:
is_config = True is_config = True
print ("host %s is configuring ..." % (ihost.hostname)) print("host %s is configuring ..." % (ihost.hostname))
if is_config: if is_config:
print "Cannot apply update while controller configuration in progress." print("Cannot apply update while controller configuration in progress.")
return return
try: try:
@ -117,16 +118,16 @@ def do_drbdsync_modify(cc, args):
hosts.append(ihost.hostname) hosts.append(ihost.hostname)
if do_wait: if do_wait:
if x == 0: if x == 0:
print ("waiting for hosts: %s to finish configuring" % print(("waiting for hosts: %s to finish configuring" %
', '.join(hosts)), ', '.join(hosts)), end=' ')
sys.stdout.flush() sys.stdout.flush()
else: else:
print ".", print(".", end=' ')
sys.stdout.flush() sys.stdout.flush()
time.sleep(wait_interval) time.sleep(wait_interval)
else: else:
print print('')
print "DRBD configuration finished." print("DRBD configuration finished.")
break break
if do_wait: if do_wait:
print "DRBD configuration timed out." print("DRBD configuration timed out.")

View File

@ -12,9 +12,9 @@
def do_health_query(cc, args): def do_health_query(cc, args):
"""Run the Health Check.""" """Run the Health Check."""
print cc.health.get() print(cc.health.get())
def do_health_query_upgrade(cc, args): def do_health_query_upgrade(cc, args):
"""Run the Health Check for an Upgrade.""" """Run the Health Check for an Upgrade."""
print cc.health.get_upgrade() print(cc.health.get_upgrade())

View File

@ -53,8 +53,8 @@ def do_helm_override_delete(cc, args):
"""Delete overrides for a chart.""" """Delete overrides for a chart."""
try: try:
cc.helm.delete_overrides(args.chart, args.namespace) cc.helm.delete_overrides(args.chart, args.namespace)
print 'Deleted chart overrides for %s:%s' % ( print('Deleted chart overrides for %s:%s' % (
args.chart, args.namespace) args.chart, args.namespace))
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('chart overrides not found: %s:%s' % ( raise exc.CommandError('chart overrides not found: %s:%s' % (
args.chart, args.namespace)) args.chart, args.namespace))

View File

@ -191,9 +191,9 @@ def do_host_bulk_add(cc, args):
success = response.get('success') success = response.get('success')
error = response.get('error') error = response.get('error')
if success: if success:
print "Success: " + success + "\n" print("Success: " + success + "\n")
if error: if error:
print "Error:\n" + error print("Error:\n" + error)
@utils.arg('-m', '--mgmt_mac', @utils.arg('-m', '--mgmt_mac',
@ -235,7 +235,7 @@ def do_host_delete(cc, args):
for n in args.hostnameorid: for n in args.hostnameorid:
try: try:
cc.ihost.delete(n) cc.ihost.delete(n)
print 'Deleted host %s' % n print('Deleted host %s' % n)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('host not found: %s' % n) raise exc.CommandError('host not found: %s' % n)
@ -642,17 +642,17 @@ def do_host_patch_reboot(cc, args):
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Host not found: %s' % args.hostnameorid) raise exc.CommandError('Host not found: %s' % args.hostnameorid)
print "The host-patch-reboot command has been deprecated." print("The host-patch-reboot command has been deprecated.")
print "Please use the following procedure:" print("Please use the following procedure:")
print "1. Lock the node:" print("1. Lock the node:")
print " system host-lock %s" % ihost.hostname print(" system host-lock %s" % ihost.hostname)
print "2. Issue patch install request:" print("2. Issue patch install request:")
print " sudo sw-patch host-install %s" % ihost.hostname print(" sudo sw-patch host-install %s" % ihost.hostname)
print " Or to issue non-blocking requests for parallel install:" print(" Or to issue non-blocking requests for parallel install:")
print " sudo sw-patch host-install-async %s" % ihost.hostname print(" sudo sw-patch host-install-async %s" % ihost.hostname)
print " sudo sw-patch query-hosts" print(" sudo sw-patch query-hosts")
print "3. Unlock node once install completes:" print("3. Unlock node once install completes:")
print " system host-unlock %s" % ihost.hostname print(" system host-unlock %s" % ihost.hostname)
@utils.arg('--filename', @utils.arg('--filename',
@ -668,9 +668,9 @@ def do_host_bulk_export(cc, args):
try: try:
with open(config_filename, 'wb') as fw: with open(config_filename, 'wb') as fw:
fw.write(xml_content) fw.write(xml_content)
print _('Export successfully to %s') % config_filename print(_('Export successfully to %s') % config_filename)
except IOError: except IOError:
print _('Cannot write to file: %s') % config_filename print(_('Cannot write to file: %s') % config_filename)
return return
@ -697,7 +697,7 @@ def do_host_downgrade(cc, args):
'Are you absolutely sure you want to continue? [yes/N]: ') 'Are you absolutely sure you want to continue? [yes/N]: ')
confirm = input(warning_message) confirm = input(warning_message)
if confirm != 'yes': if confirm != 'yes':
print "Operation cancelled." print("Operation cancelled.")
return return
ihost = cc.ihost.downgrade(args.hostid, args.force) ihost = cc.ihost.downgrade(args.hostid, args.force)
@ -726,7 +726,7 @@ def do_host_upgrade(cc, args):
'Are you absolutely sure you want to continue? [yes/N]: ') 'Are you absolutely sure you want to continue? [yes/N]: ')
confirm = input(warning_message) confirm = input(warning_message)
if confirm != 'yes': if confirm != 'yes':
print "Operation cancelled." print("Operation cancelled.")
return return
ihost = cc.ihost.upgrade(args.hostid, args.force) ihost = cc.ihost.upgrade(args.hostid, args.force)

View File

@ -77,4 +77,4 @@ def do_snmp_comm_delete(cc, args):
cc.icommunity.delete(c) cc.icommunity.delete(c)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Community not found: %s' % c) raise exc.CommandError('Community not found: %s' % c)
print 'Deleted community %s' % c print('Deleted community %s' % c)

View File

@ -106,7 +106,7 @@ def do_host_disk_wipe(cc, args):
"Continue [yes/N]: ") "Continue [yes/N]: ")
confirm = input(warning_message) confirm = input(warning_message)
if confirm != 'yes': if confirm != 'yes':
print "Operation cancelled." print("Operation cancelled.")
return return
ihost = ihost_utils._find_ihost(cc, args.hostnameorid) ihost = ihost_utils._find_ihost(cc, args.hostnameorid)

View File

@ -26,7 +26,7 @@ def do_infra_show(cc, args):
iinfras = cc.iinfra.list() iinfras = cc.iinfra.list()
if not iinfras: if not iinfras:
print "Infrastructure network not configured" print("Infrastructure network not configured")
return return
iinfra = iinfras[0] iinfra = iinfras[0]
@ -73,7 +73,7 @@ def do_infra_modify(cc, args):
iinfras = cc.iinfra.list() iinfras = cc.iinfra.list()
if not iinfras: if not iinfras:
print "Infrastructure network not configured" print("Infrastructure network not configured")
return return
iinfra = iinfras[0] iinfra = iinfras[0]
@ -97,7 +97,7 @@ def do_infra_modify(cc, args):
def do_infra_apply(cc, args): def do_infra_apply(cc, args):
infras = cc.iinfra.list() infras = cc.iinfra.list()
if not infras: if not infras:
print "Infrastructure network not configured" print("Infrastructure network not configured")
return return
infra = infras[0] infra = infras[0]

View File

@ -111,7 +111,7 @@ def do_host_if_delete(cc, args):
ihost = ihost_utils._find_ihost(cc, args.hostnameorid) ihost = ihost_utils._find_ihost(cc, args.hostnameorid)
i = _find_interface(cc, ihost, args.ifnameoruuid) i = _find_interface(cc, ihost, args.ifnameoruuid)
cc.iinterface.delete(i.uuid) cc.iinterface.delete(i.uuid)
print 'Deleted interface: host %s if %s' % (args.hostnameorid, args.ifnameoruuid) print('Deleted interface: host %s if %s' % (args.hostnameorid, args.ifnameoruuid))
@utils.arg('hostnameorid', @utils.arg('hostnameorid',

View File

@ -85,7 +85,7 @@ def do_host_node_delete(cc, args):
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Delete node failed: host %s if %s' % raise exc.CommandError('Delete node failed: host %s if %s' %
(args.hostnameorid, args.inodeuuid)) (args.hostnameorid, args.inodeuuid))
print 'Deleted node: host %s if %s' % (args.hostnameorid, args.inodeuuid) print('Deleted node: host %s if %s' % (args.hostnameorid, args.inodeuuid))
@utils.arg('hostnameorid', @utils.arg('hostnameorid',

View File

@ -92,4 +92,4 @@ def do_interface_network_assign(cc, args):
def do_interface_network_remove(cc, args): def do_interface_network_remove(cc, args):
"""Remove an assigned network from an interface.""" """Remove an assigned network from an interface."""
cc.interface_network.remove(args.interface_network_uuid) cc.interface_network.remove(args.interface_network_uuid)
print 'Deleted Interface Network: %s' % args.interface_network_uuid print('Deleted Interface Network: %s' % args.interface_network_uuid)

View File

@ -163,7 +163,7 @@ def do_ifprofile_delete(cc, args):
cc.iprofile.delete(iprofile.uuid) cc.iprofile.delete(iprofile.uuid)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('if profile delete failed: %s' % n) raise exc.CommandError('if profile delete failed: %s' % n)
print 'Deleted if profile %s' % n print('Deleted if profile %s' % n)
# #
# CPU PROFILES # CPU PROFILES
@ -281,7 +281,7 @@ def do_cpuprofile_delete(cc, args):
cc.iprofile.delete(iprofile.uuid) cc.iprofile.delete(iprofile.uuid)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Cpu profile delete failed: %s' % n) raise exc.CommandError('Cpu profile delete failed: %s' % n)
print 'Deleted cpu profile %s' % n print('Deleted cpu profile %s' % n)
# #
@ -420,9 +420,9 @@ def do_storprofile_list(cc, args):
storprofiles.append(profile) storprofiles.append(profile)
if profile_disk_invalid: if profile_disk_invalid:
print "WARNING: Storage profiles from a previous release are " \ print("WARNING: Storage profiles from a previous release are "
"missing the persistent disk name in the disk config field. " \ "missing the persistent disk name in the disk config field. "
"These profiles need to be deleted and recreated." "These profiles need to be deleted and recreated.")
if storprofiles: if storprofiles:
field_labels = ['uuid', 'name', 'disk config', 'partition config', field_labels = ['uuid', 'name', 'disk config', 'partition config',
@ -469,9 +469,9 @@ def do_storprofile_show(cc, args):
profile_disk_invalid = get_storprofile_data(cc, iprofile, detailed=True) profile_disk_invalid = get_storprofile_data(cc, iprofile, detailed=True)
if profile_disk_invalid: if profile_disk_invalid:
print "WARNING: This storage profile, from a previous release, is " \ print("WARNING: This storage profile, from a previous release, is "
"missing the persistent disk name in the disk config field. " \ "missing the persistent disk name in the disk config field. "
"This profile needs to be deleted and recreated." "This profile needs to be deleted and recreated.")
_print_storprofile_show(iprofile) _print_storprofile_show(iprofile)
@ -518,7 +518,7 @@ def do_storprofile_delete(cc, args):
cc.iprofile.delete(iprofile.uuid) cc.iprofile.delete(iprofile.uuid)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Storage profile delete failed: %s' % n) raise exc.CommandError('Storage profile delete failed: %s' % n)
print 'Deleted storage profile %s' % n print('Deleted storage profile %s' % n)
# #
# MEMORY PROFILES # MEMORY PROFILES
@ -642,7 +642,7 @@ def do_memprofile_delete(cc, args):
cc.iprofile.delete(iprofile.uuid) cc.iprofile.delete(iprofile.uuid)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Memory profile delete failed: %s' % n) raise exc.CommandError('Memory profile delete failed: %s' % n)
print 'Deleted memory profile %s' % n print('Deleted memory profile %s' % n)
@utils.arg('profilefilename', @utils.arg('profilefilename',
@ -662,9 +662,9 @@ def do_profile_import(cc, args):
if results: if results:
for result in results: for result in results:
if(result['result'] == 'Invalid'): if(result['result'] == 'Invalid'):
print 'error: %s is not a valid profile file.' % (filename) print('error: %s is not a valid profile file.' % (filename))
else: else:
print result['msg'] print(result['msg'])
if result['detail']: if result['detail']:
print ' %s' % (result['detail']) print(' %s' % (result['detail']))

View File

@ -206,5 +206,5 @@ def donot_host_sensor_delete(cc, args):
ihost = ihost_utils._find_ihost(cc, args.hostnameorid) ihost = ihost_utils._find_ihost(cc, args.hostnameorid)
i = _find_sensor(cc, ihost, args.sensor_uuid) i = _find_sensor(cc, ihost, args.sensor_uuid)
cc.isensor.delete(i.uuid) cc.isensor.delete(i.uuid)
print 'Deleted sensor: host %s sensor %s' % (args.hostnameorid, print('Deleted sensor: host %s sensor %s' % (args.hostnameorid,
args.sensor_uuid) args.sensor_uuid))

View File

@ -185,13 +185,13 @@ def do_host_sensorgroup_relearn(cc, args):
isensorgroups = cc.isensorgroup.relearn(ihost.uuid) isensorgroups = cc.isensorgroup.relearn(ihost.uuid)
print ("%s sensor model and any related alarm assertions are being " print("%s sensor model and any related alarm assertions are being "
"deleted." % (args.hostnameorid)) "deleted." % (args.hostnameorid))
print ("Any sensor suppression settings at the group or sensor levels " print("Any sensor suppression settings at the group or sensor levels "
"will be lost.") "will be lost.")
print ("Will attempt to preserve customized group actions and monitor " print("Will attempt to preserve customized group actions and monitor "
"interval when the model is relearned on next audit interval.") "interval when the model is relearned on next audit interval.")
print ("The learning process may take several minutes. Please stand-by.") print("The learning process may take several minutes. Please stand-by.")
@utils.arg('hostnameorid', @utils.arg('hostnameorid',
@ -238,5 +238,5 @@ def donot_host_sensorgroup_delete(cc, args):
ihost = ihost_utils._find_ihost(cc, args.hostnameorid) ihost = ihost_utils._find_ihost(cc, args.hostnameorid)
i = _find_sensorgroup(cc, ihost, args.sensorgroup_uuid) i = _find_sensorgroup(cc, ihost, args.sensorgroup_uuid)
cc.isensorgroup.delete(i.uuid) cc.isensorgroup.delete(i.uuid)
print ('Deleted sensorgroup: host %s sensorgroup %s' % print('Deleted sensorgroup: host %s sensorgroup %s' %
(args.hostnameorid, args.sensorgroup_uuid)) (args.hostnameorid, args.sensorgroup_uuid))

View File

@ -91,7 +91,7 @@ def do_service_delete(cc, args):
cc.iservice.delete(c) cc.iservice.delete(c)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Service not found: %s' % c) raise exc.CommandError('Service not found: %s' % c)
print 'Deleted service %s' % c print('Deleted service %s' % c)
@utils.arg('iservice', @utils.arg('iservice',

View File

@ -80,7 +80,7 @@ def do_servicegroup_delete(cc, args):
cc.iservicegroup.delete(c) cc.iservicegroup.delete(c)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Service not found: %s' % c) raise exc.CommandError('Service not found: %s' % c)
print 'Deleted servicegroup %s' % c print('Deleted servicegroup %s' % c)
@utils.arg('iservicegroup', @utils.arg('iservicegroup',

View File

@ -129,9 +129,9 @@ def do_modify(cc, args):
confirm = input(warning_message) confirm = input(warning_message)
if confirm != 'yes': if confirm != 'yes':
print "Operation cancelled." print("Operation cancelled.")
return return
print 'Please follow the admin guide to complete the reconfiguration.' print('Please follow the admin guide to complete the reconfiguration.')
field_list = ['name', 'system_mode', 'description', 'location', 'contact', field_list = ['name', 'system_mode', 'description', 'location', 'contact',
'timezone', 'sdn_enabled', 'https_enabled', 'vswitch_type', 'security_feature'] 'timezone', 'sdn_enabled', 'https_enabled', 'vswitch_type', 'security_feature']
@ -158,5 +158,5 @@ def do_modify(cc, args):
_print_isystem_show(isystem) _print_isystem_show(isystem)
if print_https_warning: if print_https_warning:
print "HTTPS enabled with a self-signed certificate.\nThis should be " \ print("HTTPS enabled with a self-signed certificate.\nThis should be "
"changed to a CA-signed certificate with 'system certificate-install'. " "changed to a CA-signed certificate with 'system certificate-install'. ")

View File

@ -81,4 +81,4 @@ def do_snmp_trapdest_delete(cc, args):
cc.itrapdest.delete(c) cc.itrapdest.delete(c)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('IP not found: %s' % c) raise exc.CommandError('IP not found: %s' % c)
print 'Deleted ip %s' % c print('Deleted ip %s' % c)

View File

@ -75,7 +75,7 @@ def do_host_label_remove(cc, args):
lbl = _find_host_label(cc, ihost, i) lbl = _find_host_label(cc, ihost, i)
if lbl: if lbl:
cc.label.remove(lbl.uuid) cc.label.remove(lbl.uuid)
print 'Deleted host label %s for host %s' % (i, ihost.hostname) print('Deleted host label %s for host %s' % (i, ihost.hostname))
def _find_host_label(cc, host, label): def _find_host_label(cc, host, label):

View File

@ -47,6 +47,6 @@ def do_license_install(cc, args):
success = response.get('success') success = response.get('success')
error = response.get('error') error = response.get('error')
if success: if success:
print success + "\n" print(success + "\n")
if error: if error:
print error + "\n" print(error + "\n")

View File

@ -53,7 +53,7 @@ def do_load_delete(cc, args):
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Delete load failed: load %s' % args.loadid) raise exc.CommandError('Delete load failed: load %s' % args.loadid)
print 'Deleted load: load %s' % args.loadid print('Deleted load: load %s' % args.loadid)
@utils.arg('isopath', @utils.arg('isopath',

View File

@ -76,4 +76,4 @@ def do_network_add(cc, args):
def do_network_delete(cc, args): def do_network_delete(cc, args):
"""Delete a network""" """Delete a network"""
cc.network.delete(args.network_uuid) cc.network.delete(args.network_uuid)
print 'Deleted Network: %s' % args.network_uuid print('Deleted Network: %s' % args.network_uuid)

View File

@ -67,7 +67,7 @@ def do_ptp_modify(cc, args):
if args.mechanism is not None: if args.mechanism is not None:
attributes.append('mechanism=%s' % args.mechanism) attributes.append('mechanism=%s' % args.mechanism)
if len(attributes) == 0: if len(attributes) == 0:
print "No options provided." print("No options provided.")
return return
patch = utils.args_array_to_patch("replace", attributes) patch = utils.args_array_to_patch("replace", attributes)

View File

@ -82,7 +82,7 @@ def do_remotelogging_modify(cc, args):
if len(attributes) > 0: if len(attributes) > 0:
attributes.append('action=apply') attributes.append('action=apply')
else: else:
print "No options provided." print("No options provided.")
return return
patch = utils.args_array_to_patch("replace", attributes) patch = utils.args_array_to_patch("replace", attributes)

View File

@ -51,7 +51,7 @@ def do_host_route_list(cc, args):
def do_host_route_delete(cc, args): def do_host_route_delete(cc, args):
"""Delete an IP route.""" """Delete an IP route."""
cc.route.delete(args.route_uuid) cc.route.delete(args.route_uuid)
print 'Deleted Route: %s' % (args.route_uuid) print('Deleted Route: %s' % (args.route_uuid))
@utils.arg('hostnameorid', @utils.arg('hostnameorid',

View File

@ -100,7 +100,7 @@ def do_sdn_controller_delete(cc, args):
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError("Failed to delete SDN controller entry: " raise exc.CommandError("Failed to delete SDN controller entry: "
"invalid uuid: %s" % args.uuid) "invalid uuid: %s" % args.uuid)
print 'Deleted SDN controller: uuid %s' % args.uuid print('Deleted SDN controller: uuid %s' % args.uuid)
@utils.arg('uuid', @utils.arg('uuid',

View File

@ -61,7 +61,7 @@ def do_service_parameter_delete(cc, args):
"""Delete a Service Parameter.""" """Delete a Service Parameter."""
cc.service_parameter.delete(args.uuid) cc.service_parameter.delete(args.uuid)
print 'Deleted service parameter: %s' % args.uuid print('Deleted service parameter: %s' % args.uuid)
def _find_service_parameter(cc, service, section, name): def _find_service_parameter(cc, service, section, name):
@ -132,7 +132,7 @@ def do_service_parameter_apply(cc, args):
cc.service_parameter.apply(args.service) cc.service_parameter.apply(args.service)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Failed to apply service parameters') raise exc.CommandError('Failed to apply service parameters')
print 'Applying %s service parameters' % args.service print('Applying %s service parameters' % args.service)
@utils.arg('service', @utils.arg('service',

View File

@ -93,7 +93,7 @@ def donot_servicegroup_delete(cc, args):
cc.smapiClient.iservicegroup.delete(c) cc.smapiClient.iservicegroup.delete(c)
except exc.HTTPNotFound: except exc.HTTPNotFound:
raise exc.CommandError('Service not found: %s' % c) raise exc.CommandError('Service not found: %s' % c)
print 'Deleted servicegroup %s' % c print('Deleted servicegroup %s' % c)
@utils.arg('iservicegroup', @utils.arg('iservicegroup',

View File

@ -130,8 +130,8 @@ def backend_show(cc, backend_name_or_uuid, asdict=False):
def _display_next_steps(): def _display_next_steps():
print "\nSystem configuration has changed.\nPlease follow the " \ print("\nSystem configuration has changed.\nPlease follow the "
"administrator guide to complete configuring the system.\n" "administrator guide to complete configuring the system.\n")
def backend_add(cc, backend, args): def backend_add(cc, backend, args):

View File

@ -145,4 +145,4 @@ def do_storage_backend_delete(cc, args):
storage_backend_utils.backend_delete( storage_backend_utils.backend_delete(
cc, args.backend_name_or_uuid) cc, args.backend_name_or_uuid)
else: else:
print "Deleting a storage backend is not supported." print("Deleting a storage backend is not supported.")

View File

@ -28,7 +28,7 @@ def do_upgrade_show(cc, args):
if upgrades: if upgrades:
_print_upgrade_show(upgrades[0]) _print_upgrade_show(upgrades[0])
else: else:
print 'No upgrade in progress' print('No upgrade in progress')
@utils.arg('-f', '--force', @utils.arg('-f', '--force',
@ -131,12 +131,12 @@ def do_upgrade_abort(cc, args):
confirm = input(warning_message) confirm = input(warning_message)
if confirm != 'yes': if confirm != 'yes':
print "Operation cancelled." print("Operation cancelled.")
return return
elif abort_required: elif abort_required:
confirm = input("Type 'abort' to confirm: ") confirm = input("Type 'abort' to confirm: ")
if confirm != 'abort': if confirm != 'abort':
print "Operation cancelled." print("Operation cancelled.")
return return
data = dict() data = dict()

View File

@ -54,11 +54,10 @@ commands =
show-source = true show-source = true
exclude=.*,dist,*lib/python*,*egg,build exclude=.*,dist,*lib/python*,*egg,build
max-complexity=25 max-complexity=25
ignore = H102,H104,H105,H233,H238,H404,H405,E501,F841 ignore = H102,H104,H105,H238,H404,H405,E501,F841
#H102 Apache 2.0 license header not found #H102 Apache 2.0 license header not found
#H104 File contains nothing but comments #H104 File contains nothing but comments
#H105 Don't use author tags #H105 Don't use author tags
#H233 Python 3.x incompatible use of print operator
#H238 old style class declaration, use new style (inherit from `object`) #H238 old style class declaration, use new style (inherit from `object`)
#H404 multi line docstring should start without a leading new line #H404 multi line docstring should start without a leading new line
#H405 multi line docstring summary not separated with an empty line #H405 multi line docstring summary not separated with an empty line

View File

@ -33,6 +33,7 @@ Commands (from conductors) are received via RPC calls.
""" """
from __future__ import print_function
import errno import errno
import fcntl import fcntl
import fileinput import fileinput
@ -1310,9 +1311,9 @@ class AgentManager(service.PeriodicService):
shutil.copyfile(tsc.PLATFORM_CONF_FILE, temp_platform_conf_file) shutil.copyfile(tsc.PLATFORM_CONF_FILE, temp_platform_conf_file)
for line in fileinput.FileInput(temp_platform_conf_file, inplace=1): for line in fileinput.FileInput(temp_platform_conf_file, inplace=1):
if line.startswith("INSTALL_UUID="): if line.startswith("INSTALL_UUID="):
print "INSTALL_UUID=%s" % install_uuid print("INSTALL_UUID=%s" % install_uuid)
else: else:
print line, print(line, end=' ')
fileinput.close() fileinput.close()
os.rename(temp_platform_conf_file, tsc.PLATFORM_CONF_FILE) os.rename(temp_platform_conf_file, tsc.PLATFORM_CONF_FILE)

View File

@ -89,7 +89,7 @@ pci_inics = my_pci_inics.pci_inics_get()
# post these to database by host, pciaddr # post these to database by host, pciaddr
for i in pci_inics: for i in pci_inics:
print ("JKUNG pciaddr=%s, iclass=%s, vendor=%s, device=%s, rev=%s, svendor=%s, sdevice=%s" % (i.pciaddr, i.iclass, i.vendor, i.device, i.revision, i.svendor, i.sdevice)) print("JKUNG pciaddr=%s, iclass=%s, vendor=%s, device=%s, rev=%s, svendor=%s, sdevice=%s" % (i.pciaddr, i.iclass, i.vendor, i.device, i.revision, i.svendor, i.sdevice))
# try: # try:
# rpc.db_post_by_host_and_mac() # rpc.db_post_by_host_and_mac()

View File

@ -166,19 +166,19 @@ def get_cluster_controller_services(host_names, print_to_screen=False,
for service in services.list: for service in services.list:
if print_to_screen: if print_to_screen:
print " " print(" ")
print "servicename: %s" % service.name print("servicename: %s" % service.name)
print "status : %s" % service.state print("status : %s" % service.state)
instances_data = [] instances_data = []
for instance in service.instances: for instance in service.instances:
if print_to_screen: if print_to_screen:
print "\thostname: %s" % instance.host_name print("\thostname: %s" % instance.host_name)
print "\tactivity: %s" % instance.activity print("\tactivity: %s" % instance.activity)
print "\tstate : %s" % instance.state print("\tstate : %s" % instance.state)
print "\treason : %s" % instance.reason print("\treason : %s" % instance.reason)
print " " print(" ")
instances_data += ([{'hostname': instance.host_name, instances_data += ([{'hostname': instance.host_name,
'activity': instance.activity, 'activity': instance.activity,
@ -190,7 +190,7 @@ def get_cluster_controller_services(host_names, print_to_screen=False,
'instances': instances_data}]) 'instances': instances_data}])
if print_json_str: if print_json_str:
print (json.dumps(services_data)) print(json.dumps(services_data))
return json.dumps(services_data) return json.dumps(services_data)
@ -232,14 +232,14 @@ def get_cluster_controller_node_state(host_name, print_to_screen=False,
state = "unknown" state = "unknown"
if print_to_screen: if print_to_screen:
print " " print(" ")
print "%s state is %s" % (host_name, state) print("%s state is %s" % (host_name, state))
# Build Json Data # Build Json Data
node_data = ({'hostname': host_name, 'state': state}) node_data = ({'hostname': host_name, 'state': state})
if print_json_str: if print_json_str:
print (json.dumps(node_data)) print(json.dumps(node_data))
return json.dumps(node_data) return json.dumps(node_data)

View File

@ -89,4 +89,4 @@ def main():
CONF.action.repository, CONF.action.repository,
CONF.action.namespace) CONF.action.namespace)
except Exception as e: except Exception as e:
print e print(e)

View File

@ -151,7 +151,7 @@ def _gpt_table_present(device_node):
output, _, _ = _command(["parted", "-s", device_node, "print"], output, _, _ = _command(["parted", "-s", device_node, "print"],
device_node=device_node) device_node=device_node)
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, returning" % device_node print("Format of disk node %s is not GPT, returning" % device_node)
return False return False
return True return True
@ -395,7 +395,7 @@ def _send_inventory_update(partition_update):
sw_mismatch = os.environ.get('CONTROLLER_SW_VERSIONS_MISMATCH', None) sw_mismatch = os.environ.get('CONTROLLER_SW_VERSIONS_MISMATCH', None)
hostname = socket.gethostname() hostname = socket.gethostname()
if sw_mismatch and hostname == constants.CONTROLLER_1_HOSTNAME: if sw_mismatch and hostname == constants.CONTROLLER_1_HOSTNAME:
print "Don't send information to N-1 sysinv conductor, return." print("Don't send information to N-1 sysinv conductor, return.")
return return
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
@ -411,14 +411,14 @@ def _send_inventory_update(partition_update):
rpcapi.update_partition_information(ctxt, partition_update) rpcapi.update_partition_information(ctxt, partition_update)
break break
except Exception as ex: except Exception as ex:
print "Exception trying to contact sysinv conductor: %s: %s " % \ print("Exception trying to contact sysinv conductor: %s: %s " %
(type(ex).__name__, str(ex)) (type(ex).__name__, str(ex)))
if num_of_try < max_tries and "Timeout" in type(ex).__name__: if num_of_try < max_tries and "Timeout" in type(ex).__name__:
print "Could not contact sysinv conductor, try one more time.." print("Could not contact sysinv conductor, try one more time..")
continue continue
else: else:
print "Quit trying to send extra info to the conductor, " \ print("Quit trying to send extra info to the conductor, "
"sysinv agent will provide this info later..." "sysinv agent will provide this info later...")
def _wipe_partition(disk_node, start_in_sectors, size_in_sectors, sector_size): def _wipe_partition(disk_node, start_in_sectors, size_in_sectors, sector_size):
@ -472,7 +472,7 @@ def create_partitions(data, mode, pfile):
_send_inventory_update(p) _send_inventory_update(p)
return return
print data print(data)
json_body = json.loads(data) json_body = json.loads(data)
for p in json_body: for p in json_body:
@ -484,8 +484,8 @@ def create_partitions(data, mode, pfile):
# Obtain parted device and parted disk for the given disk device # Obtain parted device and parted disk for the given disk device
# path. # path.
if _partition_exists(part_device_path): if _partition_exists(part_device_path):
print "Partition %s already exists, returning." % \ print("Partition %s already exists, returning." %
part_device_path part_device_path)
continue continue
# If we only allow to add and remove partition to/from the end, # If we only allow to add and remove partition to/from the end,
@ -493,7 +493,7 @@ def create_partitions(data, mode, pfile):
# the beginning and the rest of the available disk, if any). # the beginning and the rest of the available disk, if any).
free_spaces = _get_free_space(device_node=disk_device_path) free_spaces = _get_free_space(device_node=disk_device_path)
if len(free_spaces) > 2: if len(free_spaces) > 2:
print ("Disk %s is fragmented. Partition creation aborted." % print("Disk %s is fragmented. Partition creation aborted." %
disk_device_path) disk_device_path)
free_space = free_spaces[-1] free_space = free_spaces[-1]
@ -501,7 +501,7 @@ def create_partitions(data, mode, pfile):
number_of_partitions = _get_no_of_partitions(disk_device_path) number_of_partitions = _get_no_of_partitions(disk_device_path)
# If this is the 1st partition, allocate an extra 1MiB. # If this is the 1st partition, allocate an extra 1MiB.
if number_of_partitions == 0: if number_of_partitions == 0:
print "First partition, use an extra MiB" print("First partition, use an extra MiB")
start_mib = 1 start_mib = 1
else: else:
# Free space in sectors. # Free space in sectors.
@ -787,8 +787,8 @@ def delete_partitions(data, mode, pfile):
try: try:
# Delete the partition. # Delete the partition.
print "Delete partition %s from %s" % (disk_device_path, print("Delete partition %s from %s" % (disk_device_path,
part_number) part_number))
_delete_partition(disk_device_path, part_number) _delete_partition(disk_device_path, part_number)
disk_available_mib = _get_available_space(disk_device_path) disk_available_mib = _get_available_space(disk_device_path)
response.update({'available_mib': disk_available_mib, response.update({'available_mib': disk_available_mib,
@ -836,8 +836,8 @@ def check_partitions(data, mode, pfile):
lambda p, q: p.get('start_mib') - q.get('start_mib')): lambda p, q: p.get('start_mib') - q.get('start_mib')):
disk = _get_disk_device_path(p.get('device_path')) disk = _get_disk_device_path(p.get('device_path'))
if _partition_exists(p.get('device_path')): if _partition_exists(p.get('device_path')):
print 'Partition {} already exists on disk {}'.format( print('Partition {} already exists on disk {}'.format(
p.get('device_path'), disk) p.get('device_path'), disk))
continue continue
partition_number = _get_partition_number(p.get('device_path')) partition_number = _get_partition_number(p.get('device_path'))
_create_partition(disk, partition_number, p.get('start_mib'), _create_partition(disk, partition_number, p.get('start_mib'),
@ -881,7 +881,7 @@ def main(argv):
"pfile": CONF.action.pfile, "pfile": CONF.action.pfile,
"data": CONF.action.data}) "data": CONF.action.data})
LOG.info(msg) LOG.info(msg)
print msg print(msg)
run(CONF.action.func, CONF.action.data, run(CONF.action.func, CONF.action.data,
CONF.action.mode, CONF.action.pfile) CONF.action.mode, CONF.action.pfile)
else: else:

View File

@ -98,7 +98,7 @@ def generate(srcfiles):
for group, opts in opts_by_group.items(): for group, opts in opts_by_group.items():
print_group_opts(group, opts) print_group_opts(group, opts)
print "# Total option count: %d" % OPTION_COUNT print("# Total option count: %d" % OPTION_COUNT)
def _import_module(mod_str): def _import_module(mod_str):
@ -162,18 +162,18 @@ def _list_opts(obj):
def print_group_opts(group, opts_by_module): def print_group_opts(group, opts_by_module):
print "[%s]" % group print("[%s]" % group)
print print('')
global OPTION_COUNT global OPTION_COUNT
for mod, opts in opts_by_module: for mod, opts in opts_by_module:
OPTION_COUNT += len(opts) OPTION_COUNT += len(opts)
print '#' print('#')
print '# Options defined in %s' % mod print('# Options defined in %s' % mod)
print '#' print('#')
print print('')
for opt in opts: for opt in opts:
_print_opt(opt) _print_opt(opt)
print print('')
def _get_my_ip(): def _get_my_ip():
@ -213,33 +213,33 @@ def _print_opt(opt):
sys.stderr.write("%s\n" % str(err)) sys.stderr.write("%s\n" % str(err))
sys.exit(1) sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')' opt_help += ' (' + OPT_TYPES[opt_type] + ')'
print '#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)) print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
try: try:
if opt_default is None: if opt_default is None:
print '#%s=<None>' % opt_name print('#%s=<None>' % opt_name)
elif opt_type == STROPT: elif opt_type == STROPT:
assert(isinstance(opt_default, six.string_types)) assert(isinstance(opt_default, six.string_types))
print '#%s=%s' % (opt_name, _sanitize_default(opt_default)) print('#%s=%s' % (opt_name, _sanitize_default(opt_default)))
elif opt_type == BOOLOPT: elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool)) assert(isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, str(opt_default).lower()) print('#%s=%s' % (opt_name, str(opt_default).lower()))
elif opt_type == INTOPT: elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool)) not isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, opt_default) print('#%s=%s' % (opt_name, opt_default))
elif opt_type == FLOATOPT: elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float)) assert(isinstance(opt_default, float))
print '#%s=%s' % (opt_name, opt_default) print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT: elif opt_type == LISTOPT:
assert(isinstance(opt_default, list)) assert(isinstance(opt_default, list))
print '#%s=%s' % (opt_name, ','.join(opt_default)) print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == MULTISTROPT: elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list)) assert(isinstance(opt_default, list))
if not opt_default: if not opt_default:
opt_default = [''] opt_default = ['']
for default in opt_default: for default in opt_default:
print '#%s=%s' % (opt_name, default) print('#%s=%s' % (opt_name, default))
print print('')
except Exception: except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name) sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1) sys.exit(1)
@ -247,7 +247,7 @@ def _print_opt(opt):
def main(): def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
print "usage: %s [srcfile]...\n" % sys.argv[0] print("usage: %s [srcfile]...\n" % sys.argv[0])
sys.exit(0) sys.exit(0)
generate(sys.argv[1:]) generate(sys.argv[1:])

View File

@ -66,7 +66,7 @@ commands =
# H501: Do not use self.__dict__ for string formatting # H501: Do not use self.__dict__ for string formatting
[flake8] [flake8]
ignore = E126,E127,E128,E402,E501, ignore = E126,E127,E128,E402,E501,
H101,H102,H104,H105,H231,H232,H233,H234,H235,H236,H237,H238, H101,H102,H104,H105,H231,H232,H234,H235,H236,H237,H238,
H301,H306,H401,H403,H404,H405,H501 H301,H306,H401,H403,H404,H405,H501
builtins = _ builtins = _