示例#1
0
    def test_human_timestamp_format(self):
        "test output using the human timestamp format"
        shinken_logger.setLevel(INFO)
        self._collector = Collector()
        sys.stdout = StringIO()
        shinken_logger.handlers[0].stream = sys.stdout
        shinken_logger.load_obj(self._collector)
        shinken_logger.set_human_format(True)
        if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
            loglist = self.generic_tst(shinken_logger.info, 'Some log-message',
                             [1, 1],
                             [r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
                              r'^\x1b\[35m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'])
        else:
            loglist = self.generic_tst(shinken_logger.info, 'Some log-message',
                             [1, 1],
                             [r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
                              r'^\[.+?\] INFO: \[Shinken\] Some log-message$'])


        times = loglist[1][0].split(' INFO: ', 1)[0]
        _, time2 = times.rsplit('[', 1)
        time.strptime(time2.rsplit(']')[0], '%a %b %d %H:%M:%S %Y')

        logger.set_human_format(False)
    def main(self):
        try:
            self.load_config_file()
            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')
            
            self.look_for_early_exit()
            self.do_daemon_init_and_start()
            self.load_modules_manager()
            self.http_daemon.register(self.interface)
            self.http_daemon.register(self.istats)

            #self.inject = Injector(self.sched)
            #self.http_daemon.register(self.inject)

            self.http_daemon.unregister(self.interface)
            self.uri = self.http_daemon.uri
            logger.info("[scheduler] General interface is at: %s", self.uri)
            self.do_mainloop()
        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#3
0
    def main(self):
        try:
            self.load_config_file()
            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')

            self.look_for_early_exit()
            self.do_daemon_init_and_start()
            self.load_modules_manager()
            self.http_daemon.register(self.interface)
            self.http_daemon.register(self.istats)

            #self.inject = Injector(self.sched)
            #self.http_daemon.register(self.inject)

            self.http_daemon.unregister(self.interface)
            self.uri = self.http_daemon.uri
            logger.info("[scheduler] General interface is at: %s", self.uri)
            self.do_mainloop()
        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#4
0
    def test_human_timestamp_format(self):
        "test output using the human timestamp format"
        shinken_logger.setLevel(INFO)
        self._collector = Collector()
        sys.stdout = StringIO()
        shinken_logger.handlers[0].stream = sys.stdout
        shinken_logger.load_obj(self._collector)
        shinken_logger.set_human_format(True)
        if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
            loglist = self.generic_tst(shinken_logger.info, 'Some log-message', [
                1, 1
            ], [
                r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
                r'^\x1b\[35m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'
            ])
        else:
            loglist = self.generic_tst(
                shinken_logger.info, 'Some log-message', [1, 1], [
                    r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
                    r'^\[.+?\] INFO: \[Shinken\] Some log-message$'
                ])

        times = loglist[1][0].split(' INFO: ', 1)[0]
        _, time2 = times.rsplit('[', 1)
        time.strptime(time2.rsplit(']')[0], '%a %b %d %H:%M:%S %Y')

        logger.set_human_format(False)
示例#5
0
    def main(self):
        try:
            self.load_config_file()

            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')

            # Look if we are enabled or not. If ok, start the daemon mode
            self.look_for_early_exit()

            for line in self.get_header():
                logger.info(line)

            logger.info("[Receiver] Using working directory: %s",
                        os.path.abspath(self.workdir))

            self.do_daemon_init_and_start()

            self.load_modules_manager()

            self.uri2 = self.http_daemon.register(
                self.interface)  #, "ForArbiter")
            logger.debug("The Arbiter uri it at %s", self.uri2)

            self.uri3 = self.http_daemon.register(self.istats)

            # Register ibroks
            if self.ibroks is not None:
                logger.debug("Deconnecting previous Broks Interface")
                self.http_daemon.unregister(self.ibroks)
            # Create and connect it
            self.http_daemon.register(self.ibroks)

            #  We wait for initial conf
            self.wait_for_initial_conf()
            if not self.new_conf:
                return

            self.setup_new_conf()
            self.modules_manager.set_modules(self.modules)
            self.do_load_modules()
            # and start external modules too
            self.modules_manager.start_external_instances()

            # Do the modules part, we have our modules in self.modules
            # REF: doc/receiver-modules.png (1)

            # Now the main loop
            self.do_mainloop()

        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#6
0
    def main(self):
        try:
            self.load_config_file()

            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')

            # Look if we are enabled or not. If ok, start the daemon mode
            self.look_for_early_exit()
            self.load_parent_config()

            for line in self.get_header():
                logger.info(line)

            logger.info("[Receiver] Using working directory: %s", os.path.abspath(self.workdir))

            self.do_daemon_init_and_start()

            self.load_modules_manager()

            self.uri2 = self.http_daemon.register(self.interface)
            logger.debug("The Arbiter uri it at %s", self.uri2)

            self.uri3 = self.http_daemon.register(self.istats)

            # Register ibroks
            if self.ibroks is not None:
                logger.debug("Deconnecting previous Broks Interface")
                self.http_daemon.unregister(self.ibroks)
            # Create and connect it
            self.http_daemon.register(self.ibroks)

            #  We wait for initial conf
            self.wait_for_initial_conf()
            if not self.new_conf:
                return

            self.setup_new_conf()
            self.modules_manager.set_modules(self.modules)
            self.do_load_modules()
            # and start external modules too
            self.modules_manager.start_external_instances()

            # Do the modules part, we have our modules in self.modules
            # REF: doc/receiver-modules.png (1)

            # Now the main loop
            self.do_mainloop()

        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#7
0
 def test_basic_logging_log(self):
     sys.stdout = StringIO()
     self._collector = Collector()
     sh = StreamHandler(sys.stdout)
     sh.setFormatter(defaultFormatter)
     shinken_logger.handlers = []
     shinken_logger.addHandler(sh)
     shinken_logger.load_obj(self._collector)
     shinken_logger.setLevel(DEBUG)
     self.generic_tst(lambda x: naglog_result('info', x), 'Some log-message',
                      [1, 1], [r'^\[\d+\] Some log-message\n$', r'^\[\d+\] Some log-message$'])
示例#8
0
 def test_basic_logging_log(self):
     sys.stdout = StringIO()
     self._collector = Collector()
     sh = StreamHandler(sys.stdout)
     sh.setFormatter(defaultFormatter)
     shinken_logger.handlers = []
     shinken_logger.addHandler(sh)
     shinken_logger.load_obj(self._collector)
     shinken_logger.setLevel(DEBUG)
     self.generic_tst(
         lambda x: naglog_result('info', x), 'Some log-message', [1, 1],
         [r'^\[\d+\] Some log-message\n$', r'^\[\d+\] Some log-message$'])
示例#9
0
 def test_basic_logging_log(self):
     sys.stdout = StringIO()
     self._collector = Collector()
     sh = StreamHandler(sys.stdout)
     sh.setFormatter(defaultFormatter)
     shinken_logger.handlers = []
     shinken_logger.addHandler(sh)
     shinken_logger.load_obj(self._collector)
     logfile = NamedTemporaryFile("w", delete=False)
     logfile.close()
     self.logfile_name = logfile.name
     shinken_logger.register_local_log(logfile.name)
     shinken_logger.setLevel(DEBUG)
     self.generic_tst(lambda x: naglog_result('info', x), 'Some log-message',
                      [1, 1, 1], ['', r'^\[\d+\] Some log-message$', r'^\[\d+\] Some log-message$'])
示例#10
0
 def test_basic_logging_info_colored(self):
     shinken_logger.setLevel(INFO)
     self._collector = Collector()
     sys.stdout = StringIO()
     shinken_logger.handlers[0].stream = sys.stdout
     shinken_logger.load_obj(self._collector)
     if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
         self.generic_tst(shinken_logger.info, 'Some log-message', [1, 1], [
             r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
             r'^\x1b\[35m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'
         ])
     else:
         self.generic_tst(shinken_logger.info, 'Some log-message', [1, 1], [
             r'^\[.+?\] INFO:\s+Some log-message$',
             r'^\[.+?\] INFO:\s+Some log-message$'
         ])
示例#11
0
 def test_basic_logging_log(self):
     sys.stdout = StringIO()
     self._collector = Collector()
     sh = StreamHandler(sys.stdout)
     sh.setFormatter(defaultFormatter)
     shinken_logger.handlers = []
     shinken_logger.addHandler(sh)
     shinken_logger.load_obj(self._collector)
     logfile = NamedTemporaryFile("w", delete=False)
     logfile.close()
     self.logfile_name = logfile.name
     shinken_logger.register_local_log(logfile.name)
     shinken_logger.setLevel(DEBUG)
     self.generic_tst(
         lambda x: naglog_result('info', x), 'Some log-message', [1, 1, 1],
         ['', r'^\[\d+\] Some log-message$', r'^\[\d+\] Some log-message$'])
示例#12
0
 def test_basic_logging_info_colored(self):
     shinken_logger.setLevel(INFO)
     self._collector = Collector()
     sys.stdout = StringIO()
     shinken_logger.handlers[0].stream = sys.stdout
     shinken_logger.load_obj(self._collector)
     if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
         self.generic_tst(shinken_logger.info, 'Some log-message',
                          [1, 1],
                          [r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
                           r'^\x1b\[95m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'])
     else:
         self.generic_tst(shinken_logger.info, 'Some log-message',
                          [1, 1],
                          [r'^\[.+?\] INFO:\s+Some log-message$',
                           r'^\[.+?\] INFO:\s+Some log-message$'])
示例#13
0
    def main(self):
        try:
            self.load_config_file()

            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')

            for line in self.get_header():
                logger.info(line)

            logger.info("[Broker] Using working directory: %s",
                        os.path.abspath(self.workdir))

            # Look if we are enabled or not. If ok, start the daemon mode
            self.look_for_early_exit()
            self.load_parent_config()
            self.do_daemon_init_and_start()
            self.load_modules_manager()

            self.uri2 = self.http_daemon.register(self.interface)
            logger.debug("The Arbiter uri it at %s", self.uri2)

            self.uri3 = self.http_daemon.register(self.istats)

            #  We wait for initial conf
            self.wait_for_initial_conf()
            if not self.new_conf:
                return

            self.setup_new_conf()

            # Do the modules part, we have our modules in self.modules
            # REF: doc/broker-modules.png (1)
            self.hook_point('load_retention')

            # Now the main loop
            self.do_mainloop()

        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#14
0
    def main(self):
        try:
            self.load_config_file()

            # Setting log level
            logger.setLevel(self.log_level)
            # Force the debug level if the daemon is said to start with such level
            if self.debug:
                logger.setLevel('DEBUG')

            for line in self.get_header():
                logger.info(line)

            logger.info("[Broker] Using working directory: %s", os.path.abspath(self.workdir))

            # Look if we are enabled or not. If ok, start the daemon mode
            self.look_for_early_exit()
            self.do_daemon_init_and_start()
            self.load_modules_manager()

            self.uri2 = self.http_daemon.register(self.interface)
            logger.debug("The Arbiter uri it at %s", self.uri2)

            self.uri3 = self.http_daemon.register(self.istats)

            #  We wait for initial conf
            self.wait_for_initial_conf()
            if not self.new_conf:
                return

            self.setup_new_conf()


            # Do the modules part, we have our modules in self.modules
            # REF: doc/broker-modules.png (1)
            self.hook_point('load_retention')

            # Now the main loop
            self.do_mainloop()

        except Exception, exp:
            self.print_unrecoverable(traceback.format_exc())
            raise
示例#15
0
from shinken.daemons.receiverdaemon import Receiver
from logging import ERROR

# Modules are by default on the ../modules
myself = os.path.abspath(__file__)

global modules_dir
modules_dir = os.environ.get('SHINKEN_MODULES_DIR', "modules")


class __DUMMY:
    def add(self, obj):
        pass

logger.load_obj(__DUMMY())
logger.setLevel(ERROR)

#############################################################################

def guess_sys_stdout_encoding():
    ''' Return the best guessed encoding to be used for printing on sys.stdout. '''
    return (
           getattr(sys.stdout, 'encoding', None)
        or getattr(__stdout__, 'encoding', None)
        or locale.getpreferredencoding()
        or sys.getdefaultencoding()
        or 'ascii'
    )


示例#16
0
def test_rod():
    import objects
    from property import Property

    class docsis2xCm(objects.GetObject):
        timeout = 3
        retries = 0

        properties = {
            'uptime':
            Property(oid=('SNMPv2-MIB', 'sysUpTime', 0)),
            '_ethinoctets':
            Property(oid=('IF-MIB', 'ifInOctets', 1)),
            '_ethoutoctets':
            Property(oid=('IF-MIB', 'ifOutOctets', 1)),
            'configfile':
            Property(oid=('DOCS-CABLE-DEVICE-MIB', 'docsDevServerConfigFile',
                          0)),
            # 'sn': Property(oid=('DOCS-CABLE-DEVICE-MIB', 'docsDevSerialNumber', 0)),
            '_dnfreq':
            Property(oid=('DOCS-IF-MIB', 'docsIfDownChannelFrequency', 3)),
            '_dnrx':
            Property(oid=('DOCS-IF-MIB', 'docsIfDownChannelPower', 3)),
            '_dnsnr':
            Property(oid=('DOCS-IF-MIB', 'docsIfSigQSignalNoise', 3)),
            '_dnunerroreds':
            Property(oid=('DOCS-IF-MIB', 'docsIfSigQUnerroreds', 3)),
            '_dncorrecteds':
            Property(oid=('DOCS-IF-MIB', 'docsIfSigQCorrecteds', 3)),
            '_dnuncorrectables':
            Property(oid=('DOCS-IF-MIB', 'docsIfSigQUncorrectables', 3)),
            '_upfreq':
            Property(oid=('DOCS-IF-MIB', 'docsIfUpChannelFrequency', 4)),
            '_upmodulationprofile':
            Property(oid=('DOCS-IF-MIB', 'docsIfUpChannelModulationProfile',
                          4)),
            '_uptx':
            Property(oid=('DOCS-IF-MIB', 'docsIfCmStatusTxPower', 2)),

            # 'cpeipmax': (('DOCS-CABLE-DEVICE-MIB', 'docsDevCpeIpMax', 0),
        }

    p = SnmpPoller(threads=6, timeout=10)
    os = [
        # docsis2xCm(community='public', ip='10.6.93.139'),
        # docsis2xCm(community='public', ip='10.6.69.37'),
        docsis2xCm(community='public', ip='10.4.85.101'),
        docsis2xCm(community='public', ip='10.4.85.246'),
        docsis2xCm(community='public', ip='10.4.85.109'),
        docsis2xCm(community='public', ip='10.4.85.130'),
        docsis2xCm(community='public', ip='10.4.84.39'),
        docsis2xCm(community='public', ip='10.4.77.28'),
        docsis2xCm(community='public', ip='10.4.81.195'),
        docsis2xCm(community='public', ip='10.4.80.147'),
        docsis2xCm(community='public', ip='10.4.89.76'),
        docsis2xCm(community='public', ip='10.4.85.113'),
        docsis2xCm(community='public', ip='10.4.90.109'),
        docsis2xCm(community='public', ip='10.4.87.148'),
        docsis2xCm(community='public', ip='10.4.79.142'),
        docsis2xCm(community='public', ip='10.4.81.213'),
        docsis2xCm(community='public', ip='10.4.85.29'),
        docsis2xCm(community='public', ip='10.4.81.99'),
        docsis2xCm(community='public', ip='10.4.87.189'),
        docsis2xCm(community='public', ip='10.4.80.254'),
        docsis2xCm(community='public', ip='10.4.85.222'),
        docsis2xCm(community='public', ip='10.4.83.35'),
        docsis2xCm(community='public', ip='10.4.90.211'),
        docsis2xCm(community='public', ip='10.4.78.101'),
        docsis2xCm(community='public', ip='10.4.93.188'),
        docsis2xCm(community='public', ip='10.4.88.153'),
        docsis2xCm(community='public', ip='10.4.81.48'),
        docsis2xCm(community='public', ip='10.4.80.130'),
    ]

    p.set_mib_mibsources(
        mibs=['DOCS-CABLE-DEVICE-MIB'],
        mibSources=[
            '/var/lib/shinken/modules/krill-docsis/module/snmpcmts/pymibs'
        ])
    p.set_objects_to_poll(os)

    import logging
    logger.setLevel(logging.DEBUG)

    while True:
        snmp_polling_attempts = 0
        snmp_polling_succeded = False
        while not snmp_polling_succeded and snmp_polling_attempts < 3:
            try:
                p.sync()
                snmp_polling_succeded = True
            except SnmpPollerException, exc:
                print 'SnmpPollerException ', exc
                snmp_polling_attempts += 1

        for o in os:
            print 'cm:', o.configfile, o._dnrx

        logger.warning('[TEST] sleep...')
        time.sleep(1)
import os
import sys
import time
import random
import unittest

from shinken.modulesctx import modulesctx
from shinken.objects.module import Module
from shinken_test import ShinkenTest
from pprint import pprint
from shinken.log import logger
import logging

if os.getenv("TEST_DEBUG") == "1" or True:
    logger.setLevel(logging.DEBUG)

sys.setcheckinterval(10000)

path = ".."
modulesctx.set_modulesdir(path)

livestatus_broker = modulesctx.get_module('module')
LiveStatus_broker = livestatus_broker.LiveStatus_broker
LiveStatus = livestatus_broker.LiveStatus


class LivestatusTestBase(ShinkenTest):

    cfg_file = 'etc/shinken_5r_10h_200s.cfg'
示例#18
0
def main(custom_args=None):
    parser = optparse.OptionParser('',
                                   version="%prog " + VERSION,
                                   add_help_option=False)
    parser.add_option(
        '--proxy',
        dest="proxy",
        help="""Proxy URI. Like http://user:password@proxy-server:3128""")
    parser.add_option('-A',
                      '--api-key',
                      dest="api_key",
                      help=("Your API key for uploading the package to the "
                            "Shinken.io website. If you don't have one, "
                            "please go to your account page"))
    parser.add_option('-l',
                      '--list',
                      action='store_true',
                      dest="do_list",
                      help=("List available commands"))
    parser.add_option('--init',
                      action='store_true',
                      dest="do_init",
                      help=("Initialize/refill your shinken.ini file "
                            "(default to %s)" % DEFAULT_CFG))
    parser.add_option('-D',
                      action='store_true',
                      dest="do_debug",
                      help=("Enable the debug mode"))
    parser.add_option('-c',
                      '--config',
                      dest="iniconfig",
                      default=DEFAULT_CFG,
                      help=("Path to your shinken.ini file. Default: %s" %
                            DEFAULT_CFG))
    parser.add_option('-v',
                      action='store_true',
                      dest="do_verbose",
                      help=("Be more verbose"))
    parser.add_option('-h',
                      '--help',
                      action='store_true',
                      dest="do_help",
                      help=("Print help"))

    # First parsing, for purely internal parameters, but disable
    # errors, because we only want to see the -D -v things
    old_error = parser.error
    parser.error = lambda x: 1
    opts, args = parser.parse_args(custom_args)
    # reenable the errors for later use
    parser.error = old_error

    do_help = opts.do_help
    if do_help and len(args) == 0:
        parser.print_help()
        sys.exit(0)

    if opts.do_verbose:
        logger.setLevel('INFO')

    if opts.do_debug:
        logger.setLevel('DEBUG')

    cfg = None
    if not os.path.exists(opts.iniconfig):
        logger.debug('Missing configuration file!')
    else:
        cfg = ConfigParser.ConfigParser()
        cfg.read(opts.iniconfig)
        for section in cfg.sections():
            if section not in CONFIG:
                CONFIG[section] = {}
            for (key, value) in cfg.items(section):
                CONFIG[section][key] = value

    # Now replace if given in command line
    if opts.api_key:
        CONFIG['shinken.io']['api_key'] = opts.api_key
        logger.debug("Using given api-key in command line")

    if opts.proxy:
        CONFIG['shinken.io']['proxy'] = opts.proxy
        logger.debug("Using given proxy in command line")

    CLI = CLICommander(CONFIG, cfg, opts)

    # We should look on the sys.argv if we find a valid keywords to
    # call in one loop or not.
    def hack_sys_argv():
        command_values = []
        internal_values = []
        # print "RARGS", parser.rargs
        founded = False
        for arg in sys.argv:
            if arg in CLI.keywords:
                founded = True
            # Did we found it?
            if founded:
                command_values.append(arg)
            else:  # ok still not, it's for the shinekn command so
                internal_values.append(arg)

        sys.argv = internal_values
        return command_values

    # We will remove specific commands from the sys.argv list and keep
    # them for parsing them after
    command_args = hack_sys_argv()

    # Global command parsing, with the error enabled this time
    opts, args = parser.parse_args(custom_args)

    if opts.do_help:
        if len(command_args) == 0:
            logger.error("Cannot find any help for you")
            sys.exit(1)
        a = command_args.pop(0)
        if a not in CLI.keywords:
            logger.error("Cannot find any help for %s" % a)
            sys.exit(1)
        cprint('%s' % a, 'green')
        for arg in CLI.keywords[a]['args']:
            n = arg.get('name', '')
            desc = arg.get('description', '')
            cprint('\t%s' % n, 'green', end='')
            cprint(': %s' % desc)

        sys.exit(0)

    # If the user explicitely set the proxy, take it!
    if opts.proxy:
        CONFIG['shinken.io']['proxy'] = opts.proxy

    # Maybe he/she just want to list our commands?
    if opts.do_list:
        if not CLI.init_done:
            sys.exit(0)
        print "Available commands:"
        all_from = {}
        for (k, m) in CLI.keywords.iteritems():
            came_from = m['came_from']
            if came_from not in all_from:
                all_from[came_from] = [(k, m)]
            else:
                all_from[came_from].append((k, m))
        _mods = all_from.keys()
        _mods.sort()
        for mod_name in _mods:
            d = all_from[mod_name]
            print '%s:' % mod_name
            d.sort(key=lambda e: e[0])
            for (k, m) in d:
                cprint('\t%s ' % k, 'green', end='')
                cprint(': %s' % m['description'])
        sys.exit(0)

    if opts.do_init:
        write_ini_file(cfg, CLI, opts)
        sys.exit(0)

    # if just call shinken, we must open a prompt, but will be for another version
    if len(command_args) == 0:
        CLI.loop()
        sys.exit(0)

    # If it's just a one call shot, do it!
    CLI.one_loop(command_args)
示例#19
0
def main(custom_args=None):
    parser = optparse.OptionParser(
        '',
        version="%prog " + VERSION,
        add_help_option=False)
    parser.add_option('--proxy', dest="proxy",
                      help="""Proxy URI. Like http://user:password@proxy-server:3128""")
    parser.add_option('-A', '--api-key',
                      dest="api_key", help=("Your API key for uploading the package to the "
                                            "Shinken.io website. If you don't have one, "
                                            "please go to your account page"))
    parser.add_option('-l', '--list', action='store_true',
                      dest="do_list", help=("List available commands"))
    parser.add_option('--init', action='store_true',
                      dest="do_init", help=("Initialize/refill your shinken.ini file "
                                            "(default to %s)" % DEFAULT_CFG))
    parser.add_option('-D', action='store_true',
                      dest="do_debug", help=("Enable the debug mode"))
    parser.add_option('-c', '--config', dest="iniconfig", default=DEFAULT_CFG,
                      help=("Path to your shinken.ini file. Default: %s" % DEFAULT_CFG))
    parser.add_option('-v', action='store_true',
                      dest="do_verbose", help=("Be more verbose"))
    parser.add_option('-h', '--help', action='store_true',
                      dest="do_help", help=("Print help"))

    # First parsing, for purely internal parameters, but disable
    # errors, because we only want to see the -D -v things
    old_error = parser.error
    parser.error = lambda x: 1
    opts, args = parser.parse_args(custom_args)
    # reenable the errors for later use
    parser.error = old_error

    do_help = opts.do_help
    if do_help and len(args) == 0:
        parser.print_help()
        sys.exit(0)

    if opts.do_verbose:
        logger.setLevel('INFO')

    if opts.do_debug:
        logger.setLevel('DEBUG')

    cfg = None
    if not os.path.exists(opts.iniconfig):
        logger.debug('Missing configuration file!')
    else:
        cfg = ConfigParser.ConfigParser()
        cfg.read(opts.iniconfig)
        for section in cfg.sections():
            if section not in CONFIG:
                CONFIG[section] = {}
            for (key, value) in cfg.items(section):
                CONFIG[section][key] = value

    # Now replace if given in command line
    if opts.api_key:
        CONFIG['shinken.io']['api_key'] = opts.api_key
        logger.debug("Using given api-key in command line")

    if opts.proxy:
        CONFIG['shinken.io']['proxy'] = opts.proxy
        logger.debug("Using given proxy in command line")

    CLI = CLICommander(CONFIG, cfg, opts)

    # We should look on the sys.argv if we find a valid keywords to
    # call in one loop or not.
    def hack_sys_argv():
        command_values = []
        internal_values = []
        # print "RARGS", parser.rargs
        founded = False
        for arg in sys.argv:
            if arg in CLI.keywords:
                founded = True
            # Did we found it?
            if founded:
                command_values.append(arg)
            else:  # ok still not, it's for the shinekn command so
                internal_values.append(arg)

        sys.argv = internal_values
        return command_values

    # We will remove specific commands from the sys.argv list and keep
    # them for parsing them after
    command_args = hack_sys_argv()

    # Global command parsing, with the error enabled this time
    opts, args = parser.parse_args(custom_args)

    if opts.do_help:
        if len(command_args) == 0:
            logger.error("Cannot find any help for you")
            sys.exit(1)
        a = command_args.pop(0)
        if a not in CLI.keywords:
            logger.error("Cannot find any help for %s" % a)
            sys.exit(1)
        cprint('%s' % a, 'green')
        for arg in CLI.keywords[a]['args']:
            n = arg.get('name', '')
            desc = arg.get('description', '')
            cprint('\t%s' % n, 'green', end='')
            cprint(': %s' % desc)

        sys.exit(0)

    # If the user explicitely set the proxy, take it!
    if opts.proxy:
        CONFIG['shinken.io']['proxy'] = opts.proxy

    # Maybe he/she just want to list our commands?
    if opts.do_list:
        if not CLI.init_done:
            sys.exit(0)
        print "Available commands:"
        all_from = {}
        for (k, m) in CLI.keywords.iteritems():
            came_from = m['came_from']
            if came_from not in all_from:
                all_from[came_from] = [(k, m)]
            else:
                all_from[came_from].append((k, m))
        _mods = all_from.keys()
        _mods.sort()
        for mod_name in _mods:
            d = all_from[mod_name]
            print '%s:' % mod_name
            d.sort(key=lambda e: e[0])
            for (k, m) in d:
                cprint('\t%s ' % k, 'green', end='')
                cprint(': %s' % m['description'])
        sys.exit(0)

    if opts.do_init:
        write_ini_file(cfg, CLI, opts)
        sys.exit(0)

    # if just call shinken, we must open a prompt, but will be for another version
    if len(command_args) == 0:
        CLI.loop()
        sys.exit(0)

    # If it's just a one call shot, do it!
    CLI.one_loop(command_args)
示例#20
0
    # or parent directory to support running without installation.
    # Submodules will then be loaded from there, too.
    import imp
    imp.load_module('shinken',
                    *imp.find_module('shinken',
                                     [os.path.realpath("."),
                                      os.path.realpath(".."),
                                      os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),
                                                   "..")]))
    from shinken.bin import VERSION

from shinken.log import logger, cprint, nagFormatter
from shinken.objects.config import Config


logger.setLevel('WARNING')
logger.handlers[0].setFormatter(nagFormatter)

# Handle some signals
def sig_handler(signalnum, handle):
    """ Handle some signals """
    sys.exit(0)

signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)


CONFIG = {}


class Dummy():
示例#21
0
from logging import ERROR

# Modules are by default on the ../modules
myself = os.path.abspath(__file__)

global modules_dir
modules_dir = os.environ.get('SHINKEN_MODULES_DIR', "modules")


class __DUMMY:
    def add(self, obj):
        pass


logger.load_obj(__DUMMY())
logger.setLevel(ERROR)

#############################################################################


def guess_sys_stdout_encoding():
    ''' Return the best guessed encoding to be used for printing on sys.stdout. '''
    return (getattr(sys.stdout, 'encoding', None)
            or getattr(__stdout__, 'encoding', None)
            or locale.getpreferredencoding() or sys.getdefaultencoding()
            or 'ascii')


def safe_print(*args, **kw):
    """" "print" args to sys.stdout,
    If some of the args aren't unicode then convert them first to unicode,
示例#22
0
    # or parent directory to support running without installation.
    # Submodules will then be loaded from there, too.
    import imp
    imp.load_module(
        'shinken',
        *imp.find_module('shinken', [
            os.path.realpath("."),
            os.path.realpath(".."),
            os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), "..")
        ]))
    from shinken.bin import VERSION

from shinken.log import logger, cprint, nagFormatter
from shinken.objects.config import Config

logger.setLevel('WARNING')
logger.handlers[0].setFormatter(nagFormatter)


# Handle some signals
def sig_handler(signalnum, handle):
    """ Handle some signals """
    sys.exit(0)


signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)

CONFIG = {}