Add config.py module

This patch is adding a config.py module to the project. The
configuration file should be placed at ~/.vbmc/virtualbmc.conf and the
current options available are:

[log]
debug=True/False
logfile=<Path to a file>
This commit is contained in:
Lucas Alvares Gomes 2016-02-17 12:20:52 +00:00
parent 7f81c4bd26
commit 89128bef0f
4 changed files with 93 additions and 13 deletions

60
virtualbmc/config.py Normal file
View File

@ -0,0 +1,60 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from six.moves import configparser
import utils
__all__ = ['get_config']
CONFIG_FILE = os.path.join(utils.CONFIG_PATH, 'virtualbmc.conf')
CONFIG = None
class VirtualBMCConfig(object):
DEFAULTS = {'log': {'logfile': None,
'debug': 'false'}}
def __init__(self):
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
self._conf_dict = self._as_dict(config)
self._validate()
def _as_dict(self, config):
conf_dict = self.DEFAULTS
for section in config.sections():
if section not in conf_dict:
conf_dict[section] = {}
for key, val in config.items(section):
conf_dict[section][key] = val
return conf_dict
def _validate(self):
self._conf_dict['log']['debug'] = utils.str2bool(
self._conf_dict['log']['debug'])
def __getitem__(self, key):
return self._conf_dict[key]
def get_config():
global CONFIG
if CONFIG is None:
CONFIG = VirtualBMCConfig()
return CONFIG

View File

@ -14,6 +14,8 @@ import logging
import errno
import sys
import config
__all__ = ['get_logger']
DEFAULT_LOG_FORMAT = ('%(asctime)s.%(msecs)03d %(process)d %(levelname)s '
@ -21,8 +23,9 @@ DEFAULT_LOG_FORMAT = ('%(asctime)s.%(msecs)03d %(process)d %(levelname)s '
LOGGER = None
class Logger(logging.Logger):
def __init__(self, level, logfile=None):
class VirtualBMCLogger(logging.Logger):
def __init__(self, debug=False, logfile=None):
logging.Logger.__init__(self, 'VirtualBMC')
try:
if logfile is not None:
@ -33,14 +36,22 @@ class Logger(logging.Logger):
formatter = logging.Formatter(DEFAULT_LOG_FORMAT)
self.handler.setFormatter(formatter)
self.addHandler(self.handler)
if debug:
self.setLevel(logging.DEBUG)
else:
self.setLevel(logging.INFO)
except IOError, e:
if e.errno == errno.EACCES:
pass
def get_logger(level=logging.DEBUG, logfile=None):
def get_logger():
global LOGGER
if LOGGER is None:
LOGGER = Logger(level=level, logfile=logfile)
log_conf = config.get_config()['log']
LOGGER = VirtualBMCLogger(debug=log_conf['debug'],
logfile=log_conf['logfile'])
return LOGGER

View File

@ -31,13 +31,12 @@ RUNNING = 'running'
DOWN = 'down'
DEFAULT_SECTION = 'VirtualBMC'
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.vbmc')
class VirtualBMCManager(object):
def _parse_config(self, domain_name):
config_path = os.path.join(CONFIG_PATH, domain_name, 'config')
config_path = os.path.join(utils.CONFIG_PATH, domain_name, 'config')
if not os.path.exists(config_path):
raise exception.DomainNotFound(domain=domain_name)
@ -57,7 +56,7 @@ class VirtualBMCManager(object):
def _show(self, domain_name):
running = False
try:
pidfile_path = os.path.join(CONFIG_PATH, domain_name, 'pid')
pidfile_path = os.path.join(utils.CONFIG_PATH, domain_name, 'pid')
with open(pidfile_path, 'r') as f:
pid = int(f.read())
@ -73,7 +72,7 @@ class VirtualBMCManager(object):
domain_name, libvirt_uri):
utils.check_libvirt_connection_and_domain(libvirt_uri, domain_name)
domain_path = os.path.join(CONFIG_PATH, domain_name)
domain_path = os.path.join(utils.CONFIG_PATH, domain_name)
try:
os.makedirs(domain_path)
except OSError as e:
@ -93,7 +92,7 @@ class VirtualBMCManager(object):
config.write(f)
def delete(self, domain_name):
domain_path = os.path.join(CONFIG_PATH, domain_name)
domain_path = os.path.join(utils.CONFIG_PATH, domain_name)
if not os.path.exists(domain_path):
raise exception.DomainNotFound(domain=domain_name)
@ -105,7 +104,7 @@ class VirtualBMCManager(object):
shutil.rmtree(domain_path)
def start(self, domain_name):
domain_path = os.path.join(CONFIG_PATH, domain_name)
domain_path = os.path.join(utils.CONFIG_PATH, domain_name)
if not os.path.exists(domain_path):
raise exception.DomainNotFound(domain=domain_name)
@ -145,7 +144,7 @@ class VirtualBMCManager(object):
def stop(sel, domain_name):
LOG.debug('Stopping Virtual BMC for domain %s', domain_name)
domain_path = os.path.join(CONFIG_PATH, domain_name)
domain_path = os.path.join(utils.CONFIG_PATH, domain_name)
if not os.path.exists(domain_path):
raise exception.DomainNotFound(domain=domain_name)
@ -169,8 +168,9 @@ class VirtualBMCManager(object):
def list(self):
bmcs = []
try:
for domain in os.listdir(CONFIG_PATH):
bmcs.append(self._show(domain))
for domain in os.listdir(utils.CONFIG_PATH):
if os.path.isdir(os.path.join(utils.CONFIG_PATH, domain)):
bmcs.append(self._show(domain))
except OSError as e:
if e.errno == errno.EEXIST:
return bmcs

View File

@ -10,10 +10,13 @@
# License for the specific language governing permissions and limitations
# under the License.
import os
import libvirt
import exception
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.vbmc')
class libvirt_open(object):
@ -57,3 +60,9 @@ def is_pid_running(pid):
return False
def str2bool(string):
lower = string.lower()
if lower not in ('true', 'false'):
raise ValueError('Value "%s" can not be interpreted as '
'boolean' % string)
return lower == 'true'