Beispiel #1
0
 def __init__(self, conf, hosts_conf, log):
     self._conf = conf
     self._hosts_conf = hosts_conf
     self._log = log
     if log is None:
         self._log = create_logger()
Beispiel #2
0
 def __init__(self, conf, hosts_conf, log):
     self._conf = conf
     self._hosts_conf = hosts_conf
     self._log = log
     if log is None:
         self._log = create_logger()
Beispiel #3
0
# -*- coding: utf-8 -*-
import os
import pytest
import tempfile
from cStringIO import StringIO
import utils
utils.append_home_to_path(__file__)

from btfly.utils import create_logger
from btfly.main import Main

TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
HOME_DIR = os.path.dirname(os.path.dirname(TESTS_DIR))
CONF_DIR = os.path.join(HOME_DIR, 'conf')

log = create_logger(True)

def test_01_run():
    out = StringIO()
    main = Main(__file__, CONF_DIR, "env".split())
    main.run(out)
    assert "BTFLY_HOSTS=(web01 db01 db02 db03)" == out.getvalue().rstrip(), "run"

def test_02_run_validation_errors():
    with pytest.raises(RuntimeError):
        out = StringIO()
        conf_path = os.path.join(TESTS_DIR, 'invalid_duplicated_statuses.yaml')
        main = Main(__file__, CONF_DIR, ("--conf=%s env" % (conf_path)).split())
        main.run(out)

def test_03_run_status_not_defined():
Beispiel #4
0
    def __init__(self, file, conf_dir, commandline_args=sys.argv[1:]):
        log = None
        env_debug = os.getenv('BTFLY_DEBUG') or '0'
        if env_debug == '1' or env_debug.lower() == 'true':
            log = create_logger(True)
        else:
            log = create_logger(False)
        self._log = log

        log.debug("PYTHON_PATH = " + str(sys.path))

        parser = argparse.ArgumentParser(
            prog = os.path.basename(file),
            description = "A micro host management program.",
            conflict_handler = 'resolve'
        )
        default_conf_path = os.path.join(conf_dir, 'conf.yaml')
        parser.add_argument(
            '-c', '--conf', default=default_conf_path,
            help='Configuration file path. (default: %s)' % (default_conf_path)
        )
        parser.add_argument(
            '--conf-url', help='Configuration file url.'
        )
        default_hosts_conf_path = self.default_hosts_conf_path(conf_dir)
        parser.add_argument(
            '-h', '--hosts-conf', default=default_hosts_conf_path,
            help='Hosts configuration file path. (default: %s)' % (default_hosts_conf_path)
        )
        parser.add_argument(
           '--hosts-conf-url', help='Hosts configuration file url.'
        )
        parser.add_argument(
            '-s', '--statuses', help='Specify statues.'
        )
        parser.add_argument(
            '-t', '--tags', help='Specify tags.'
        )
        parser.add_argument(
            '-f', '--field', help='Specify a field.'
        )
        parser.add_argument(
            '-o', '--output-file', type=argparse.FileType('w'),
            help='Specify a file path to output. Default behavior is outputing to stdout.'
        )
        parser.add_argument(
            '-D', '--debug', action='store_true', default=False,
            help='Enable debug output.',
        )
        parser.add_argument(
            '--version', action='version', 
            version='%(prog)s ' + __version__
            + ' with Python ' + '.'.join(map(str, sys.version_info[0:3])),
        )

        self._conf_dir = conf_dir
        self._file = file

        plugin_manager = PluginManager(log, parser)
        # Load plugins
        plugin_manager.load_plugins(self.plugin_dirs(conf_dir))
        log.debug("All plugins are registered.")

        self._arg_parser = parser
        self._args = parser.parse_args(commandline_args)
        self._options = self._args.__dict__
        self._plugin_manager = plugin_manager

        # Load configuration
        conf = load_url_conf(self._options['conf_url'])
        if conf == None:
            conf = load_conf(self._options['conf'])
        hosts_conf = load_url_conf(self._options['hosts_conf_url'])
        if hosts_conf == None:
            hosts_conf = load_conf(self._options['hosts_conf'])
        self._hosts_manager = HostsManager(conf, hosts_conf, self._log)
        
        validation_errors = self._hosts_manager.validate(
            self._options['conf'], self._options['hosts_conf']
        )
        if validation_errors:
            for e in validation_errors:
                print >> sys.stderr, e.message
            raise RuntimeError("There are some errors in configuration files.")

        error = False
        if self._options.get('statuses'):
            # Check given --statuses are defined.
            conf_statuses = conf.get('statuses')
            option_statuses_list = [ s.strip() for s in self._options.get('statuses').split(',') ]
            statuses_list = []
            for s in option_statuses_list:
                if s in conf_statuses:
                    statuses_list.append(s)
                else:
                    print >>sys.stderr, "status '%s' is not defined in configuration." % (s)
                    error = True
            self._options['statuses_list'] = statuses_list
        if error:
            raise ValueError("Option --statuses error")

        if self._options.get('tags'):
            # Check given --tags are defined.
            conf_tags = conf.get('tags')
            tags_list = [ s.strip() for s in self._options.get('tags').split(',') ]
            tags = []
            for t in tags_list:
                if t in [ conf_tag.keys()[0] for conf_tag in conf_tags ]:
                    tags.append(t)
                else:
                    print >>sys.stderr, "tag '%s' is not defined in configuration." % (s)
                    error = True
            self._options['tags'] = tags
        if error:
            raise ValueError("Option --tags error")