Review options for configuration files

- Add --config or -c to specify the configuration file location.
- Change --conf_file to --inventory or -i to manage managers.
- Configuration file and version are macros replaced by installation
  process
- Fix almost all PEP8 issues
This commit is contained in:
Uggla 2016-02-27 21:01:43 +01:00
parent 68f114dc71
commit 3404767cdc

View File

@ -19,7 +19,8 @@ redfish-client ::
Options: Options:
-h --help Show this screen. -h --help Show this screen.
--version Show version. --version Show version.
--conf_file FILE Configuration file [default: ~/.redfish.conf] -c --config FILE Configuration file
-i --inventory FILE Configuration file [default: $HOME/.redfish.conf]
--insecure Ignore SSL certificates --insecure Ignore SSL certificates
--debug LEVEL Run in debug mode, LEVEL from 1 to 3 increase verbosity --debug LEVEL Run in debug mode, LEVEL from 1 to 3 increase verbosity
Security warning LEVEL > 1 could reveal password into the logs Security warning LEVEL > 1 could reveal password into the logs
@ -42,24 +43,25 @@ import jinja2
import requests.packages.urllib3 import requests.packages.urllib3
import redfish import redfish
class ConfigFile(object):
'''redfisht-client configuration file management''' class InventoryFile(object):
def __init__(self, config_file): '''redfisht-client inventory file management'''
'''Initialize the configuration file def __init__(self, inventory_file):
'''Initialize the inventory file
Open and load configuration file data. Open and load configuration file data.
If the file does not exist create an empty one ready to receive data If the file does not exist create an empty one ready to receive data
:param config_file: File name of the configuration file :param inventory_file: File name of the configuration file
default: ~/.redfish.conf default: ~/.redfish.conf
:type config-file: str :type config-file: str
:returns: Nothing :returns: Nothing
''' '''
self._config_file = config_file self._inventory_file = inventory_file
# read json file # read json file
try: try:
with open(self._config_file) as json_data: with open(self._inventory_file) as json_data:
self.data = json.load(json_data) self.data = json.load(json_data)
json_data.close() json_data.close()
except (ValueError, IOError): except (ValueError, IOError):
@ -68,7 +70,7 @@ class ConfigFile(object):
def save(self): def save(self):
'''Save the configuration file data''' '''Save the configuration file data'''
try: try:
with open(self._config_file, 'w') as json_data: with open(self._inventory_file, 'w') as json_data:
json.dump(self.data, json_data) json.dump(self.data, json_data)
json_data.close() json_data.close()
except IOError as e: except IOError as e:
@ -141,7 +143,8 @@ class ConfigFile(object):
self.manager_incorect(e) self.manager_incorect(e)
elif parameter == 'password': elif parameter == 'password':
try: try:
self.data['Managers'][manager_name]['password'] = parameter_value self.data['Managers'][manager_name]['password'] \
= parameter_value
except KeyError as e: except KeyError as e:
self.manager_incorect(e) self.manager_incorect(e)
elif parameter == 'manager_name': elif parameter == 'manager_name':
@ -209,7 +212,6 @@ class RedfishClientException(Exception):
if __name__ == '__main__': if __name__ == '__main__':
'''Main application redfish-client''' '''Main application redfish-client'''
# Functions # Functions
def show_manager(all=False): def show_manager(all=False):
'''Display manager info '''Display manager info
@ -219,16 +221,19 @@ if __name__ == '__main__':
''' '''
print('Managers configured :') print('Managers configured :')
for manager in conf_file.get_managers(): if(not inventory.get_managers()):
print("None")
else:
for manager in inventory.get_managers():
print(manager) print(manager)
if all is True: if all is True:
info = conf_file.get_manager_info(manager) info = inventory.get_manager_info(manager)
print('\tUrl : {}'.format(info['url'])) print('\tUrl : {}'.format(info['url']))
print('\tLogin : {}'.format(info['login'])) print('\tLogin : {}'.format(info['login']))
print('\tPassword : {}'.format(info['password'])) print('\tPassword : {}'.format(info['password']))
def get_manager_info(manager_name, check_SSL): def get_manager_info(manager_name, check_SSL):
connection_parameters = conf_file.get_manager_info(manager_name) connection_parameters = inventory.get_manager_info(manager_name)
if not connection_parameters['login']: if not connection_parameters['login']:
simulator = True simulator = True
enforceSSL = False enforceSSL = False
@ -256,14 +261,17 @@ if __name__ == '__main__':
try: try:
template = jinja2_env.get_template("manager_info.template") template = jinja2_env.get_template("manager_info.template")
except jinja2.exceptions.TemplateNotFound as e: except jinja2.exceptions.TemplateNotFound as e:
print('Template "{}" not found in {}.'.format(e.message, jinja2_env.loader.searchpath[0])) print('Template "{}" not found in {}.'
logger.debug('Template "%s" not found in %s.' % (e.message, jinja2_env.loader.searchpath[0])) .format(e.message, jinja2_env.loader.searchpath[0]))
logger.debug('Template "%s" not found in %s.'
% (e.message, jinja2_env.loader.searchpath[0]))
sys.exit(1) sys.exit(1)
print template.render(r=remote_mgmt) print template.render(r=remote_mgmt)
#################################################################
# Main program # Main program
#################################################################
redfishclient_version = "redfish-client PBVER" redfishclient_version = "redfish-client PBVER"
# Parse and manage arguments # Parse and manage arguments
@ -320,46 +328,42 @@ if __name__ == '__main__':
logger.info("Arguments parsed") logger.info("Arguments parsed")
logger.debug(arguments) logger.debug(arguments)
# Get $HOME and $VIRTUAL_ENV environment variables. # Get $HOME environment variables.
HOME = os.getenv('HOME') HOME = os.getenv('HOME')
VIRTUAL_ENV = os.getenv('VIRTUAL_ENV')
if not HOME: if(not HOME):
print('$HOME environment variable not set, please check your system') print('$HOME environment variable not set, please check your system')
logger.error('$HOME environment variable not set') logger.error('$HOME environment variable not set')
sys.exit(1) sys.exit(1)
logger.debug("Home directory : %s" % HOME) logger.debug("Home directory : %s" % HOME)
if VIRTUAL_ENV: # Load config
logger.debug("Virtual env : %s" % VIRTUAL_ENV)
# Load master conf file
config = ConfigParser.ConfigParser(allow_no_value=True) config = ConfigParser.ConfigParser(allow_no_value=True)
logger.debug("Read master configuration file") logger.debug("Read configuration file")
master_conf_file_path = "/etc/redfish-client.conf" configfile = 'PBCONFFILE'
if VIRTUAL_ENV: if(arguments['--config']):
logger.debug("Read master configuration file from virtual environment") configfile = [arguments['--config']]
master_conf_file_path = VIRTUAL_ENV + master_conf_file_path logger.debug("Overwrite configuration specified by user at %s"
% configfile)
if not os.path.isfile(master_conf_file_path): if(os.path.isfile(configfile)):
print('Master configuration file not found at {}.'.format(master_conf_file_path)) logger.debug('Configuration found at %s.' % configfile)
logger.error('Master configuration file not found at %s.' % master_conf_file_path) config.read(configfile)
else:
print('Configuration file not found at {}.'.format(configfile))
logger.error('Configuration file not found at %s.' % configfile)
sys.exit(1) sys.exit(1)
config.read(master_conf_file_path) arguments['--inventory'] = arguments['--inventory'].replace('~', HOME)
arguments['--inventory'] = arguments['--inventory'].replace('$HOME', HOME)
arguments['--conf_file'] = arguments['--conf_file'].replace('~', HOME) inventory = InventoryFile(arguments['--inventory'])
conf_file = ConfigFile(arguments['--conf_file'])
# Initialize Template system (jinja2) # Initialize Template system (jinja2)
# TODO : set the template file location into cmd line default to /usr/share/python-redfish/templates ?
templates_path = config.get("redfish-client", "templates_path") templates_path = config.get("redfish-client", "templates_path")
logger.debug("Initialize template system") logger.debug("Initialize template system")
if VIRTUAL_ENV: jinja2_env = jinja2.Environment(
logger.debug("Read templates file from virtual environment") loader=jinja2.FileSystemLoader(templates_path))
templates_path = VIRTUAL_ENV + templates_path
jinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_path))
# Check cmd line parameters # Check cmd line parameters
if arguments['config'] is True: if arguments['config'] is True:
@ -372,37 +376,37 @@ if __name__ == '__main__':
show_manager(True) show_manager(True)
elif arguments['add'] is True: elif arguments['add'] is True:
logger.debug('add command') logger.debug('add command')
conf_file.add_manager(arguments['<manager_name>'], inventory.add_manager(arguments['<manager_name>'],
arguments['<manager_url>'], arguments['<manager_url>'],
arguments['<login>'], arguments['<login>'],
arguments['<password>']) arguments['<password>'])
logger.debug(conf_file.data) logger.debug(inventory.data)
conf_file.save() inventory.save()
elif arguments['del'] is True: elif arguments['del'] is True:
logger.debug('del command') logger.debug('del command')
conf_file.delete_manager(arguments['<manager_name>']) inventory.delete_manager(arguments['<manager_name>'])
logger.debug(conf_file.data) logger.debug(inventory.data)
conf_file.save() inventory.save()
elif arguments['modify'] is True: elif arguments['modify'] is True:
logger.debug('modify command') logger.debug('modify command')
if arguments['url'] is not False: if arguments['url'] is not False:
conf_file.modify_manager(arguments['<manager_name>'], inventory.modify_manager(arguments['<manager_name>'],
'url', 'url',
arguments['<changed_value>']) arguments['<changed_value>'])
elif arguments['login'] is not False: elif arguments['login'] is not False:
conf_file.modify_manager(arguments['<manager_name>'], inventory.modify_manager(arguments['<manager_name>'],
'login', 'login',
arguments['<changed_value>']) arguments['<changed_value>'])
elif arguments['password'] is not False: elif arguments['password'] is not False:
conf_file.modify_manager(arguments['<manager_name>'], inventory.modify_manager(arguments['<manager_name>'],
'password', 'password',
arguments['<changed_value>']) arguments['<changed_value>'])
elif arguments['manager_name'] is not False: elif arguments['manager_name'] is not False:
conf_file.modify_manager(arguments['<manager_name>'], inventory.modify_manager(arguments['<manager_name>'],
'manager_name', 'manager_name',
arguments['<changed_value>']) arguments['<changed_value>'])
logger.debug(conf_file.data) logger.debug(inventory.data)
conf_file.save() inventory.save()
if arguments['manager'] is True: if arguments['manager'] is True:
logger.debug("Manager commands") logger.debug("Manager commands")
if arguments['getinfo'] is True: if arguments['getinfo'] is True:
@ -413,7 +417,7 @@ if __name__ == '__main__':
else: else:
manager_name = arguments['<manager_name>'] manager_name = arguments['<manager_name>']
# Check if the default section is available in our conf file # Check if the default section is available in our conf file
conf_file.check_manager(manager_name) inventory.check_manager(manager_name)
if arguments['--insecure'] is True: if arguments['--insecure'] is True:
get_manager_info(manager_name, False) get_manager_info(manager_name, False)
else: else: