def load_configuration(config_file=DEFAULT_CONFIG_FILE):
"""
Loads logging configuration from the given configuration file.
:param config_file:
the configuration file (default=/etc/package/logging.conf)
:type config_file: str
"""
if not os.path.exists(config_file) or not os.path.isfile(config_file):
msg = '%s configuration file does not exist!', config_file
logging.getLogger(__name__).error(msg)
raise ValueError(msg)
try:
config.fileConfig(config_file, disable_existing_loggers=False)
logging.getLogger(__name__).info(
'%s configuration file was loaded.', config_file)
except Exception as e:
logging.getLogger(__name__).error(
'Failed to load configuration from %s!', config_file)
logging.getLogger(__name__).debug(str(e), exc_info=True)
raise e
python类conf()的实例源码
def configure_logging(log_file_path):
"""Loads logging.conf file
Loads logging.conf file to create the logger configuration.
The logger configuration has two handlers, one of stream
(show logs in the console) and other of file (save a log file)
where you can choose one of it in [logger_root : handlers].
In it you can choose the logger level as well.
Level: Numeric value
---------------------
CRITICAL: 50
ERROR: 40
WARNING: 30
INFO: 20
DEBUG: 10
NOTSET: 00
---------------------
How to use: import logging and logging.exception('message')
Args:
log_file_path: logging.conf path.
Exception:
Exception: if logging.conf file not found.
"""
if os.path.isfile(log_file_path) is False:
raise Exception("Config file {} not found".format(log_file_path))
else:
logging.config.fileConfig(log_file_path)
def load_conf(conf_file):
"""Loads and parses conf file
Loads and parses the module conf file
Args:
conf_file: string with the conf file name
Returns:
ConfigParser object with conf_file configs
Exception:
OneViewRedfishResourceNotFoundError:
- if conf file not found
"""
if not os.path.isfile(conf_file):
raise errors.OneViewRedfishResourceNotFoundError(conf_file, 'File')
config = configparser.ConfigParser()
config.optionxform = str
try:
config.read(conf_file)
except Exception:
raise
return config
def init_stderr_logging(formatter=None, rootlogger=''):
"""Initializes logging to stderr.
Log levels are read from logging.conf, the root logger's format is set to
NAV's default format, and its handler is set to a StreamHandler writing
to sys.stderr.
"""
set_log_config()
handler = logging.StreamHandler(sys.stderr)
formatter = formatter or DEFAULT_LOG_FORMATTER
handler.setFormatter(formatter)
root = logging.getLogger(rootlogger)
root.addHandler(handler)
def load_config(conf_file):
"""Loads redfish.conf file
Loads and parsers the system conf file into config global var
Loads json schemas into schemas_dict global var
Established a connection with OneView and sets in as ov_conn
global var
Args:
conf_file: string with the conf file name
Returns:
None
Exception:
OneViewRedfishResourceNotFoundError:
- if conf file not found
- if any of the schemas files are not found
- if the schema directory is not found
OneViewRedFishResourceNotAccessibleError:
- if can't access schema's directory
HPOneViewException:
- if fails to connect to oneview
"""
config = load_conf(conf_file)
globals()['config'] = config
# Config file read set global vars
# Setting ov_config
ov_config = dict(config.items('oneview_config'))
ov_config['credentials'] = dict(config.items('credentials'))
ov_config['api_version'] = int(ov_config['api_version'])
globals()['ov_config'] = ov_config
# Setting schemas_dict
schemas = dict(config.items('schemas'))
globals()['schemas'] = schemas
registries = dict(config.items('registry'))
# Load schemas | Store schemas | Connect to OneView
try:
ov_client = OneViewClient(ov_config)
globals()['ov_client'] = ov_client
registry_dict = load_registry(
config['redfish']['registry_dir'],
registries)
globals()['registry_dict'] = registry_dict
store_schemas(config['redfish']['schema_dir'])
except errors.OneViewRedfishResourceNotFoundError as e:
raise errors.OneViewRedfishError(
'Failed to load schemas or registries: {}'.format(e)
)
except Exception as e:
raise errors.OneViewRedfishError(
'Failed to connect to OneView: {}'.format(e)
)
def get_oneview_client(session_id=None, is_service_root=False):
"""Establishes a OneView connection to be used in the module
Establishes a OV connection if one does not exists.
If one exists, do a single OV access to check if its sill
valid. If not tries to establish a new connection.
Sets the connection on the ov_conn global var
Args:
session_id: The ID of a valid authenticated session, if the
authentication_mode is session. Defaults to None.
is_service_root: Informs if who is calling this function is the
ServiceRoot blueprint. If true, even if authentication_mode is
set to session it will use the information on the conf file to
return a connection. This is a workaround to allow ServiceRoot
to retrieve the appliance UUID before user logs in.
Returns:
OneViewClient object
Exceptions:
HPOneViewException if can't connect or reconnect to OV
"""
config = globals()['config']
auth_mode = config["redfish"]["authentication_mode"]
if auth_mode == "conf" or is_service_root:
# Doing conf based authentication
ov_client = globals()['ov_client']
ov_config = globals()['ov_config']
# Check if connection is ok yet
try:
ov_client.connection.get('/rest/logindomains')
return ov_client
# If expired try to make a new connection
except Exception:
try:
logging.exception('Re-authenticated')
ov_client.connection.login(ov_config['credentials'])
return ov_client
# if faild abort
except Exception:
raise
else:
# Auth mode is session
oneview_config = dict(config.items('oneview_config'))
oneview_config['credentials'] = {"sessionID": session_id}
oneview_config['api_version'] = int(oneview_config['api_version'])
try:
oneview_client = OneViewClient(oneview_config)
oneview_client.connection.get('/rest/logindomains')
return oneview_client
except Exception:
logging.exception("Failed to recover session based connection")
raise