Beispiel #1
0
class NSCAServerTest(BasicTest):
    instance = None
    key = ''
    reg = None
    conf = None
    core = None
    _responses = {}

    def has_response(self, id):
        with sync:
            return id in self._responses

    def get_response(self, id):
        with sync:
            if id in self._responses:
                return self._responses[id]
            msg = NSCAMessage(id)
            self._responses[id] = msg
            return msg

    def set_response(self, msg):
        with sync:
            if msg.uuid in self._responses:
                self._responses[msg.uuid].copy_changed_attributes(msg)
            else:
                self._responses[msg.uuid] = msg

    def del_response(self, id):
        with sync:
            del self._responses[id]

    def desc(self):
        return 'Testcase for NSCA protocol'

    def title(self):
        return 'NSCA Server test'

    def setup(self, plugin_id, prefix):
        self.key = '_%stest_command' % prefix
        self.reg = Registry.get(plugin_id)
        self.reg.simple_subscription('nsca_test_inbox',
                                     NSCAServerTest.simple_inbox_handler)
        self.reg.subscription('nsca_test_inbox', NSCAServerTest.inbox_handler)

    def simple_inbox_handler(channel, source, command, code, message, perf):
        instance = NSCAServerTest.getInstance()
        return instance.simple_inbox_handler_wrapped(channel, source, command,
                                                     code, message, perf)

    simple_inbox_handler = Callable(simple_inbox_handler)

    def inbox_handler(channel, request):
        instance = NSCAServerTest.getInstance()
        return instance.inbox_handler_wrapped(channel, request)

    inbox_handler = Callable(inbox_handler)

    def simple_inbox_handler_wrapped(self, channel, source, command, status,
                                     message, perf):
        log('Got message %s on %s' % (command, channel))
        msg = NSCAMessage(command)
        msg.source = source
        msg.status = status
        msg.message = message
        msg.perfdata = perf
        msg.got_simple_response = True
        self.set_response(msg)
        return True

    def inbox_handler_wrapped(self, channel, request):
        message = plugin_pb2.SubmitRequestMessage()
        message.ParseFromString(request)
        if len(message.payload) != 1:
            log_error("Got invalid message on channel: %s" % channel)
            return None
        command = message.payload[0].command
        log('Got message %s on %s' % (command, channel))

        msg = NSCAMessage(command)
        msg.got_response = True
        self.set_response(msg)
        return None

    def teardown(self):
        None

    def wait_and_validate(self, uuid, result, msg, perf, tag):
        found = False
        for i in range(0, 10):
            if not self.has_response(uuid):
                log('Waiting for %s (%d/10)' % (uuid, i + 1))
                sleep(200)
            else:
                log('Got response %s' % uuid)
                found = True
                break
        if not found:
            result.add_message(
                False, 'Failed to recieve message %s using %s' % (uuid, tag))
            return False

        for i in range(0, 10):
            rmsg = self.get_response(uuid)
            if not rmsg.got_simple_response or not rmsg.got_response:
                log('Waiting for delayed response %s s/m: %s/%s - (%d/10)' %
                    (uuid, rmsg.got_simple_response, rmsg.got_response, i + 1))
                sleep(500)
            else:
                log('Got delayed response %s' % uuid)
                break

        result.add_message(rmsg.got_response,
                           'Testing to recieve message using %s' % tag)
        result.add_message(rmsg.got_simple_response,
                           'Testing to recieve simple message using %s' % tag)
        result.assert_equals(
            rmsg.command, uuid,
            'Verify that command is sent through using %s' % tag)
        result.assert_contains(
            rmsg.message, msg,
            'Verify that message is sent through using %s' % tag)

        #result.assert_equals(rmsg.last_source, source, 'Verify that source is sent through')
        #result.assert_equals(rmsg.perfdata, perf, 'Verify that performance data is sent through using %s'%tag)
        self.del_response(uuid)
        return True

    def submit_payload(self, encryption, target, length, source, status, msg,
                       perf, tag):
        message = plugin_pb2.SubmitRequestMessage()

        message.header.version = plugin_pb2.Common.VERSION_1
        message.header.recipient_id = target
        message.channel = 'nsca_test_outbox'
        host = message.header.hosts.add()
        host.id = target
        if (target == 'valid'):
            pass
        else:
            host.address = "127.0.0.1:15667"
            enc = host.metadata.add()
            enc.key = "encryption"
            enc.value = encryption
            enc = host.metadata.add()
            enc.key = "password"
            enc.value = 'pwd-%s' % encryption
            enc = host.metadata.add()
            enc.key = "payload length"
            enc.value = '%d' % length

        uid = str(uuid.uuid4())
        payload = message.payload.add()
        payload.result = status
        payload.command = uid
        payload.message = '%s - %s' % (uid, msg)
        payload.source = source
        (result_code, err) = self.core.submit('nsca_test_outbox',
                                              message.SerializeToString())

        result = TestResult('Testing payload submission (via API): %s' % tag)
        result.add_message(
            len(err) == 0, 'Testing to send message using %s/sbp' % tag, err)
        self.wait_and_validate(uid, result, msg, perf, '%s/spb' % tag)
        return result

    def submit_via_exec(self, encryption, target, length, source, status, msg,
                        perf, tag):
        uid = str(uuid.uuid4())

        args = [
            #'--exec', 'submit',
            '--alias',
            uid,
            '--result',
            '%d' % status,
            '--message',
            '%s - %s' % (uid, msg),
            '--target',
            target,
        ]
        if (target == 'valid'):
            pass
        else:
            args.extend([
                '--address',
                '127.0.0.1:15667',
                '--encryption',
                encryption,
                '--password',
                'pwd-%s' % encryption,
                '--payload-length',
                '%d' % length,
            ])
        (result_code,
         result_message) = self.core.simple_exec('any', 'nsca_submit', args)
        result = TestResult(
            'Testing payload submission (via command line exec): %s' % tag)

        result.add_message(result_code == 0,
                           'Testing to send message using %s/exec:1' % tag)
        result.add_message(
            len(result_message) == 1,
            'Testing to send message using %s/exec:2' % tag)
        if len(result_message) == 1:
            result.assert_equals(
                result_message[0], "Submission successful",
                'Testing to send message using %s/exec:3' % tag)
        return result

    def test_one_crypto_full(self, encryption, state, key, target, length):
        result = TestResult('Testing %s/%s' % (encryption, key))
        result.add(
            self.submit_payload(
                encryption, target, length, '%ssrc%s' % (key, key), state,
                '%smsg%s' % (key, key), '',
                '%s/%s/%d/%s' % (state, encryption, length, target)))
        result.add(
            self.submit_via_exec(
                encryption, target, length, '%ssrc%s' % (key, key), state,
                '%smsg%s' % (key, key), '',
                '%s/%s/%d/%s' % (state, encryption, length, target)))
        return result

    def test_one_crypto(self, crypto, length=512):
        conf = self.conf
        conf.set_string('/settings/NSCA/test_nsca_server', 'encryption',
                        '%s' % crypto)
        conf.set_string('/settings/NSCA/test_nsca_server', 'password',
                        'pwd-%s' % crypto)
        conf.set_int('/settings/NSCA/test_nsca_server', 'payload length',
                     length)
        self.core.reload('test_nsca_server')

        conf.set_string('/settings/NSCA/test_nsca_client/targets/default',
                        'address', 'nsca://127.0.0.1:35667')
        conf.set_string('/settings/NSCA/test_nsca_client/targets/default',
                        'encryption', '%s' % crypto)
        conf.set_string('/settings/NSCA/test_nsca_client/targets/default',
                        'password', 'default-%s' % crypto)
        conf.set_int('/settings/NSCA/test_nsca_client/targets/default',
                     'payload length', length * 3)

        conf.set_string('/settings/NSCA/test_nsca_client/targets/invalid',
                        'address', 'nsca://127.0.0.1:25667')
        conf.set_string('/settings/NSCA/test_nsca_client/targets/invalid',
                        'encryption', 'none')
        conf.set_string('/settings/NSCA/test_nsca_client/targets/invalid',
                        'password', 'invalid-%s' % crypto)
        conf.set_int('/settings/NSCA/test_nsca_client/targets/invalid',
                     'payload length', length * 2)

        conf.set_string('/settings/NSCA/test_nsca_client/targets/valid',
                        'address', 'nsca://127.0.0.1:15667')
        conf.set_string('/settings/NSCA/test_nsca_client/targets/valid',
                        'encryption', '%s' % crypto)
        conf.set_string('/settings/NSCA/test_nsca_client/targets/valid',
                        'password', 'pwd-%s' % crypto)
        conf.set_int('/settings/NSCA/test_nsca_client/targets/valid',
                     'payload length', length)
        self.core.reload('test_nsca_client')

        result = TestResult('Testing: %s/%d' % (crypto, length))
        result.add_message(isOpen('localhost', 15667),
                           'Checking that port is open')
        for target in ['valid', 'test_rp', 'invalid']:
            result.add(
                self.test_one_crypto_full(crypto, status.UNKNOWN, 'unknown',
                                          target, length))
            result.add(
                self.test_one_crypto_full(crypto, status.OK, 'ok', target,
                                          length))
            result.add(
                self.test_one_crypto_full(crypto, status.WARNING, 'warn',
                                          target, length))
            result.add(
                self.test_one_crypto_full(crypto, status.CRITICAL, 'crit',
                                          target, length))
        return result

    def run_test(self):
        result = TestResult()
        cryptos = [
            "none", "xor", "des", "3des", "cast128", "xtea", "blowfish",
            "twofish", "rc2", "aes", "aes256", "aes192", "aes128", "serpent",
            "gost", "3way"
        ]
        for c in cryptos:
            for l in [128, 512, 1024, 4096]:
                result.add(self.test_one_crypto(c, l))
            #result.add(self.test_one_crypto(c))

        return result

    def install(self, arguments):
        conf = self.conf
        conf.set_string('/modules', 'test_nsca_server', 'NSCAServer')
        conf.set_string('/modules', 'test_nsca_client', 'NSCAClient')
        conf.set_string('/modules', 'pytest', 'PythonScript')

        conf.set_string('/settings/pytest/scripts', 'test_nsca',
                        'test_nsca.py')

        conf.set_string('/settings/NSCA/test_nsca_server', 'port', '15667')
        conf.set_string('/settings/NSCA/test_nsca_server', 'inbox',
                        'nsca_test_inbox')
        conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '1')

        conf.set_string('/settings/NSCA/test_nsca_client/targets',
                        'nsca_test_local', 'nsca://127.0.0.1:15667')
        conf.set_string('/settings/NSCA/test_nsca_client', 'channel',
                        'nsca_test_outbox')

        conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def init(self, plugin_id, prefix):
        self.key = '_%stest_command' % prefix
        self.reg = Registry.get(plugin_id)
        self.core = Core.get(plugin_id)
        self.conf = Settings.get(plugin_id)

    def shutdown(self):
        None

    def require_boot(self):
        return True
Beispiel #2
0
class PythonTest(BasicTest):

    noop_count = 0
    stress_count = 0

    key = ''
    reg = None
    conf = None
    core = None

    def noop_handler(arguments):
        instance = PythonTest.getInstance()
        instance.noop_count = instance.noop_count + 1
        return (status.OK, 'Got call %d' % instance.noop_count, '')

    noop_handler = Callable(noop_handler)

    def stress_handler(channel, source, command, code, message, perf):
        instance = PythonTest.getInstance()
        instance.stress_count = instance.stress_count + 1
        #log('Got message %d/%d on %s'%(instance.stress_count, instance.noop_count, channel))

    stress_handler = Callable(stress_handler)

    def desc(self):
        return 'Testcase for python script module'

    def title(self):
        return 'PythonScript tests'

    def setup(self, plugin_id, prefix):
        log('Loading Python unit tests')
        self.key = '_%stest_command' % prefix
        self.reg.simple_function('py_stress_noop', PythonTest.noop_handler,
                                 'This is a simple noop command')
        self.reg.simple_subscription('py_stress_test',
                                     PythonTest.stress_handler)
        self.conf.set_string('/settings/test_scheduler', 'threads', '50')
        self.core.reload('test_scheduler')

    def teardown(self):
        self.conf.set_string('/settings/test_scheduler', 'threads', '0')
        self.core.reload('test_scheduler')
        None

    def run_test(self):
        result = TestResult()
        start = time()
        total_count = install_checks * time_to_run / 5
        while self.stress_count < total_count:
            log('Waiting for %d: %d/%d' %
                (total_count, self.stress_count, self.noop_count))
            old_stress_count = self.stress_count
            old_noop_count = self.noop_count
            sleep(5000)
            result.add_message(
                True, 'Commands/second: %d/%d' %
                ((self.stress_count - old_stress_count) / 5,
                 (self.noop_count - old_noop_count) / 5))
        elapsed = (time() - start)
        if elapsed == 0:
            elapsed = 1
        result.add_message(
            True, 'Summary Collected %d instance in %d seconds: %d/s' %
            (self.stress_count, elapsed, self.stress_count / elapsed))
        return result

    def install(self, arguments):
        self.conf.set_string('/modules', 'test_scheduler', 'Scheduler')
        self.conf.set_string('/modules', 'pytest', 'PythonScript')

        self.conf.set_string('/settings/pytest/scripts', 'test_python',
                             'test_python.py')

        base_path = '/settings/test_scheduler'
        self.conf.set_string(base_path, 'threads', '0')

        default_path = '%s/schedules/default' % base_path
        self.conf.set_string(default_path, 'channel', 'py_stress_test')
        self.conf.set_string(default_path, 'alias', 'stress')
        self.conf.set_string(default_path, 'command', 'py_stress_noop')
        self.conf.set_string(default_path, 'interval', '5s')
        for i in range(1, install_checks):
            alias = 'stress_python_%i' % i
            self.conf.set_string('%s/schedules' % (base_path), alias,
                                 'py_stress_noop')

        self.conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def init(self, plugin_id, prefix):
        self.key = '_%stest_command' % prefix
        self.reg = Registry.get(plugin_id)
        self.core = Core.get(plugin_id)
        self.conf = Settings.get(plugin_id)

        None

    def shutdown(self):
        None
Beispiel #3
0
class EventLogTest(BasicTest):
    instance = None
    key = ''
    reg = None
    conf = None
    core = None
    last_tag = []
    got_simple_response = None
    message_count = 0
    messages = []

    class SingletonHelper:
        def __call__(self, *args, **kw):
            if EventLogTest.instance is None:
                object = EventLogTest()
                EventLogTest.instance = object
            return EventLogTest.instance

    getInstance = SingletonHelper()

    def desc(self):
        return 'Testcase for eventlog'

    def title(self):
        return 'EventLog test'

    def setup(self, plugin_id, prefix):
        self.key = '_%stest_command' % prefix
        self.reg = Registry.get(plugin_id)
        self.reg.simple_subscription('pytest_evlog_01',
                                     EventLogTest.simple_inbox_handler_01)
        self.reg.simple_subscription('pytest_evlog_02',
                                     EventLogTest.simple_inbox_handler_02)

    def simple_inbox_handler_01(channel, source, command, code, message, perf):
        instance = EventLogTest.getInstance()
        return instance.simple_inbox_handler_wrapped(channel, source, command,
                                                     code, message, perf,
                                                     '001')

    simple_inbox_handler_01 = Callable(simple_inbox_handler_01)

    def simple_inbox_handler_02(channel, source, command, code, message, perf):
        instance = EventLogTest.getInstance()
        return instance.simple_inbox_handler_wrapped(channel, source, command,
                                                     code, message, perf,
                                                     '002')

    simple_inbox_handler_02 = Callable(simple_inbox_handler_02)

    def simple_inbox_handler_wrapped(self, channel, source, command, status,
                                     message, perf, tag):
        msg = Message(channel, source, command, status, message, perf, tag)
        msg.delivered = True
        self.messages.append(msg)
        log('Recieved: %s' % msg)
        return True

    def teardown(self):
        None

    def test_create(self, source, id, level, severity, category, facility,
                    arguments):
        result = TestResult(
            'Creating log message: i:%d, l:%s, s:%s, c:%d, f:%d' %
            (id, level, severity, category, facility))
        args = [
            '--source',
            source,
            '--id',
            id,  # Any number (corresponds with message identifier)								-- Identifies message
            '--level',
            level,  # error(1), warning(2), success(0), info(4), auditSuccess(8), auditFailure(10)	-- Loglevel severity (ie log level)
            '--severity',
            severity,  # success(0), informational(1), warning(2), error(3) 							-- Developer severity (ie classification)
            '--category',
            category,  #
            '--facility',
            facility  #
        ]
        for f in arguments:
            args.append('--argument')
            args.append(f)
        (ret, msg) = self.core.simple_exec('eventlog', 'insert', args)
        result.assert_equals(ret, 0, 'return code')
        result.assert_equals(len(msg), 1, 'Message length')
        if len(msg) == 1:
            result.assert_equals(msg[0], 'Message reported successfully',
                                 'Status message')
        return result

    def test_w_expected(self, filter, syntax, expected):
        result = TestResult('Validating filter: %s (%d)' % (filter, expected))
        (res, msg, perf) = self.core.simple_query('CheckEventLog', [
            'file=Application', 'debug=false',
            'warn=gt:%d' % expected,
            'crit=gt:%d' % expected,
            'filter=%s' % filter,
            'syntax=%s' % syntax, 'scan-range=-10m',
            'top-syntax=${status} ${count}==%d: ${list}' % expected
        ])
        result.assert_equals(res, status.OK,
                             "Validate status OK for %s" % filter)
        (res, msg, perf) = self.core.simple_query('CheckEventLog', [
            'file=Application', 'debug=false',
            'warn=eq:%d' % expected,
            'crit=gt:%d' % expected,
            'filter=%s' % filter,
            'syntax=%s' % syntax, 'scan-range=-10m',
            'top-syntax=${status} ${count}==%d: ${list}' % expected
        ])
        result.assert_equals(res, status.WARNING,
                             "Validate status OK for %s" % filter)
        (res, msg, perf) = self.core.simple_query('CheckEventLog', [
            'file=Application', 'debug=false',
            'warn=eq:%d' % expected,
            'crit=eq:%d' % expected,
            'filter=%s' % filter,
            'syntax=%s' % syntax, 'scan-range=-10m',
            'top-syntax=${status} ${count}==%d: ${list}' % expected
        ])
        result.assert_equals(res, status.CRITICAL,
                             "Validate status CRIT for %s" % filter)
        return result

    def test_syntax(self, filter, syntax, expected):
        result = TestResult('Validating syntax: %s' % syntax)
        (res, msg, perf) = self.core.simple_query('CheckEventLog', [
            'file=Application', 'warn=ne:1',
            'filter=%s' % filter,
            'syntax=%s' % syntax, 'descriptions', 'scan-range=-10m'
        ])
        result.assert_equals(msg, expected,
                             "Validate message rendering syntax: %s" % msg)
        return result

    def run_test(self):
        result = TestResult('Checking CheckEventLog')
        cache = TestResult('Checking CheckEventLog CACHE')

        sleep(2000)

        #(res, msg, perf) = self.core.simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:2'])
        #cache.assert_equals(res, status.OK, "Validate cache is empty")
        #cache.assert_equals(msg, 'Eventlog check ok', "Validate cache is ok: %s"%msg)

        a_list = [
            'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'
        ]
        result.add(
            self.test_create('Application Error', 1000, 'error', 'success', 0,
                             0, a_list))
        result.add(
            self.test_create('Application Error', 1000, 'warning',
                             'informational', 1, 5, a_list))
        result.add(
            self.test_create('Application Error', 1000, 'success', 'warning',
                             2, 5, a_list))
        result.add(
            self.test_create('Application Error', 1000, 'info', 'error', 3, 5,
                             a_list))
        for x in range(1, 10):
            log('Waiting...%d/4.' % len(self.messages))
            sleep(100)
            if len(self.messages) == 4:
                break
        log('Recieved %d messages.' % len(self.messages))
        result.assert_equals(len(self.messages), 4,
                             'Verify that all 4 messages are sent through')

        for msg in self.messages:
            if msg.message.startswith('X1'):
                r = TestResult('Validating message X1')
                r.assert_equals(msg.message, 'X1 warning Application Error: ',
                                'Verify message')
                r.assert_equals(msg.channel, 'pytest_evlog_01',
                                'Verify channel')
                r.assert_equals(msg.tag, '001', 'Verify tag')
                r.assert_equals(msg.status, status.WARNING, 'Verify status')
                result.add(r)
            elif msg.message.startswith('X2'):
                r = TestResult('Validating message X2')
                r.assert_equals(msg.message, 'X2 success Application Error: ',
                                'Verify message')
                r.assert_equals(msg.channel, 'pytest_evlog_02',
                                'Verify channel')
                r.assert_equals(msg.tag, '002', 'Verify tag')
                r.assert_equals(msg.status, status.CRITICAL, 'Verify status')
                result.add(r)
            elif msg.message.startswith('X3'):
                r = TestResult('Validating message X3')
                r.assert_equals(msg.message, 'X3 info Application Error: ',
                                'Verify message')
                r.assert_equals(msg.channel, 'pytest_evlog_01',
                                'Verify channel')
                r.assert_equals(msg.tag, '001', 'Verify tag')
                r.assert_equals(msg.status, status.UNKNOWN, 'Verify status')
                result.add(r)
            elif msg.message.startswith('X4'):
                r = TestResult('Validating message X4')
                r.assert_equals(msg.message, 'X4 error Application Error: ',
                                'Verify message')
                r.assert_equals(msg.channel, 'pytest_evlog_01',
                                'Verify channel')
                r.assert_equals(msg.tag, '001', 'Verify tag')
                r.assert_equals(msg.status, status.OK, 'Verify status')
                result.add(r)

        #(res, msg, perf) = self.core.simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:4'])
        #cache.assert_equals(res, status.CRITICAL, "Validate cache has items: %s"%msg)
        #cache.assert_equals(msg, 'X4 error Application Error: , X1 warning Application Error: , X2 success Application Error: , X3 info Application Error: , eventlog: 4 = critical', "Validate cache message")
        #cache.assert_equals(perf, "'eventlog'=4;1;4", "Validate cache performance")
        #(res, msg, perf) = self.core.simple_query('CheckEventLogCACHE', ['warn=eq:1', 'crit=eq:2'])
        #cache.assert_equals(res, status.OK, "Validate cache is empty (again)")
        #cache.assert_equals(msg, 'Eventlog check ok', "Validate cache is ok: %s"%msg)

        #result.add(cache)

        r = TestResult('Checking filters')
        r.add(
            self.test_w_expected('id = 1000 and generated gt 1m',
                                 '%generated%', 0))
        r.add(
            self.test_w_expected('id = 1000 and generated gt -1m',
                                 '%generated%', 4))
        r.add(
            self.test_w_expected(
                'id = 1000 and generated gt -1m and id = 1000',
                '%generated%: %id%, %category%', 4))
        r.add(
            self.test_w_expected(
                'id = 1000 and generated gt -1m and category = 1',
                '%category%', 1))
        r.add(
            self.test_w_expected(
                'id = 1000 and generated gt -1m and category = 0',
                '%category%', 1))
        r.add(
            self.test_w_expected(
                "id = 1000 and generated gt -1m and level = 'error'",
                '%level%', 1))
        r.add(
            self.test_w_expected(
                "id = 1000 and generated gt -1m and level = 'warning'",
                '%level%', 1))
        result.add(r)

        r = TestResult('Checking syntax')
        r.add(
            self.test_syntax('id = 1000 and generated gt -2m and category = 0',
                             '%source% - %type% - %category%',
                             'Application Error - error - 0'))
        r.add(
            self.test_syntax('id = 1000 and generated gt -2m and category = 1',
                             '%source% - %type% - %category%',
                             'Application Error - warning - 1'))
        r.add(
            self.test_syntax('id = 1000 and generated gt -2m and category = 2',
                             '%source% - %type% - %category%',
                             'Application Error - information - 2'))
        r.add(
            self.test_syntax('id = 1000 and generated gt -2m and category = 3',
                             '%source% - %type% - %category%',
                             'Application Error - information - 3'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%facility% - %qualifier% - %customer%', '0 - 0 - 0'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%facility% - %qualifier% - %customer%', '5 - 5 - 0'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%rawid% - %severity% - %log%', '1000 - success - Application'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%rawid% - %severity% - %log%', '1074070504 - informational - Application'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 2', '%rawid% - %severity% - %log%', '2147812328 - warning - Application'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 3', '%rawid% - %severity% - %log%', '3221554152 - error - Application'))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 0', '%id% - %strings%', '1000 - a, a, a, a, a, a, a, a, a, a, a, a, a, '))
        #r.add(self.test_syntax('id = 1000 and generated gt -2m and category = 1', '%id% - %strings%', '1000 - a, a, a, a, a, a, a, a, a, a, a, a, a, '))
        result.add(r)

        return result

    def install_filter(self,
                       conf,
                       path,
                       target,
                       filter=None,
                       syntax='%type% %source%: %message%',
                       severity='OK',
                       lang='english',
                       age='5s'):
        if filter:
            conf.set_string(path, 'filter', filter)
        if target:
            conf.set_string(path, 'target', target)
        if lang:
            conf.set_string(path, 'language', lang)
        if age:
            conf.set_string(path, 'maximum age', age)
        if syntax:
            conf.set_string(path, 'detail syntax', syntax)
        if severity:
            conf.set_string(path, 'severity', severity)
        conf.set_string(path, 'log', 'application')
        conf.set_string(path, 'debug', 'true')

    def install(self, arguments):
        conf = self.conf
        conf.set_string('/modules', 'pytest_eventlog', 'CheckEventLog')
        conf.set_string('/modules', 'pytest', 'PythonScript')

        conf.set_string('/settings/pytest/scripts', 'test_eventlog',
                        'test_eventlog.py')

        conf.set_string('/settings/pytest_eventlog/real-time', 'enabled',
                        'true')

        self.install_filter(
            conf, '/settings/pytest_eventlog/real-time/filters/default',
            'pytest_evlog_01', 'id = 1000 and category = 0',
            '%type% %source%: %message%', 'OK')
        base_syntax = '${id},${category} ${source}: ${message}'

        self.install_filter(
            conf, '/settings/pytest_eventlog/real-time/filters/py_test_001',
            'pytest_evlog_01', 'id = 1000 and category = 1',
            'X1 %s' % base_syntax, 'WARNING')
        self.install_filter(
            conf, '/settings/pytest_eventlog/real-time/filters/py_test_002',
            'pytest_evlog_02', 'id = 1000 and category = 2',
            'X2 %s' % base_syntax, 'CRITICAL')
        self.install_filter(
            conf, '/settings/pytest_eventlog/real-time/filters/py_test_003',
            None, 'id = 1000 and category = 3', 'X3 %s' % base_syntax,
            'UNKNOWN')
        self.install_filter(
            conf, '/settings/pytest_eventlog/real-time/filters/py_test_004',
            None, None, 'X4 %s' % base_syntax, None)

        conf.set_string('/settings/pytest_eventlog/real-time', 'maximum age',
                        '5s')
        conf.set_string('/settings/pytest_eventlog/real-time', 'debug', 'true')
        conf.set_string('/settings/pytest_eventlog/real-time', 'enable active',
                        'true')

        conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def init(self, plugin_id, prefix):
        self.reg = Registry.get(plugin_id)
        self.core = Core.get(plugin_id)
        self.conf = Settings.get(plugin_id)

    def shutdown(self):
        None
Beispiel #4
0
class SchedulerTest(BasicTest):

    check_count = 0
    results_count = 0
    command_count = {}
    
    sched_alias = 'test_sched_%s'%prefix
    python_channel = 'test_sched_%s_py'%prefix
    command = 'test_sched_%s'%prefix
    sched_base_path = '/settings/%s'%sched_alias
    
    def simple_check_handler(arguments):
        instance = SchedulerTest.getInstance()
        return instance.wrapped_simple_check_handler(arguments)
    simple_check_handler = Callable(simple_check_handler)

    def wrapped_simple_check_handler(self, arguments):
        self.check_count = self.check_count + 1
        if arguments:
            if not arguments[0] in self.command_count:
                self.command_count[arguments[0]] = 1
            else:
                self.command_count[arguments[0]] = self.command_count[arguments[0]] + 1
            return (status.OK, arguments[0], '')
        return (status.OK, 'pong', '')

    def on_stress_handler(channel, source, command, code, message, perf):
        instance = SchedulerTest.getInstance()
        instance.wrapped_on_stress_handler(channel, source, command, code, message, perf)
    on_stress_handler = Callable(on_stress_handler)

    def wrapped_on_stress_handler(self, channel, source, command, code, message, perf):
        self.results_count = self.results_count + 1
        return None

    def desc(self):
        return 'Testcase for Scheduler'

    def title(self):
        return 'Test Scheduler'

    def setup(self, plugin_id, prefix):
        self.reg.simple_function(self.command, SchedulerTest.simple_check_handler, 'This is a simple noop command')
        self.reg.simple_subscription(self.python_channel, SchedulerTest.on_stress_handler)

        #self.core.reload('%s,delayed'%self.sched_alias)
        

    def teardown(self):
        self.conf.set_string(self.sched_base_path, 'threads', '0')
        self.core.reload(self.sched_alias)

    def check_one(self, result, key, min, max):
        result.assert_gt(self.command_count[key], min, 'check %s (%d) fired more then %d'%(key, self.command_count[key], min))
        result.assert_lt(self.command_count[key], max, 'check %s (%d) fired less then %d'%(key, self.command_count[key], max))
    
    def run_test(self):
        self.core.load_module('Scheduler', self.sched_alias)
        result = TestResult()
        start = time()

        last_major = 0
        elapsed = time()-start
        while elapsed < 60:
            if elapsed > 0:
                log("testing scheduler %d%% (collected %d instance in %d seconds)"%(elapsed/60*100, self.results_count, elapsed))
            sleep(2000)
            elapsed = time()-start
        result.add_message(True, 'Summary Collected %d instance in %d seconds: %d/s'%(self.results_count, elapsed, self.results_count/elapsed))
        self.check_one(result, "rand", 5, 10)
        self.check_one(result, "1s", 55, 65)
        self.check_one(result, "short", 10, 14)
        self.check_one(result, "30s", 1, 3)
        self.check_one(result, "explicit", 10, 14)
        self.check_one(result, "10s", 5, 7)

        return result

    def install(self, arguments):
        # Configure required modules
        self.conf.set_string('/modules', 'pytest', 'PythonScript')
        #self.conf.set_string('/modules', self.sched_alias, 'Scheduler')
        self.conf.set_string('/modules', 'CheckSystem', 'enabled')

        # Configure python
        self.conf.set_string('/settings/pytest/scripts', 'test_stress', 'test_scheduler.py')
        
        default_path = '%s/schedules/default'%self.sched_base_path
        self.conf.set_string(default_path, 'channel', self.python_channel)
        self.conf.set_string(default_path, 'command', "%s default"%self.command)
        self.conf.set_string(default_path, 'interval', '5s')
        self.conf.set_string(default_path, 'randomness', '0%')

        self.conf.set_string('%s/schedules'%(self.sched_base_path), 'python_checker_d', "%s short"%self.command)

        self.conf.set_string('%s/schedules/python_checker_e'%(self.sched_base_path), 'command', "%s explicit"%self.command)

        #self.conf.set_string('%s/schedules/python_checker_i'%(self.sched_base_path), 'interval', '1s')

        self.conf.set_string('%s/schedules/python_checker_1s'%(self.sched_base_path), 'command', "%s 1s"%self.command)
        self.conf.set_string('%s/schedules/python_checker_1s'%(self.sched_base_path), 'interval', '1s')

        self.conf.set_string('%s/schedules/python_checker_10s'%(self.sched_base_path), 'command', "%s 10s"%self.command)
        self.conf.set_string('%s/schedules/python_checker_10s'%(self.sched_base_path), 'interval', '10s')

        self.conf.set_string('%s/schedules/python_checker_30s'%(self.sched_base_path), 'command', "%s 30s"%self.command)
        self.conf.set_string('%s/schedules/python_checker_30s'%(self.sched_base_path), 'interval', '30s')

        self.conf.set_string('%s/schedules/python_checker_r10s'%(self.sched_base_path), 'command', "%s rand"%self.command)
        self.conf.set_string('%s/schedules/python_checker_r10s'%(self.sched_base_path), 'interval', '10s')
        self.conf.set_string('%s/schedules/python_checker_r10s'%(self.sched_base_path), 'randomness', '50%')

        self.conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def init(self, plugin_id, prefix):
        self.reg = Registry.get(plugin_id)
        self.conf = Settings.get(plugin_id)
        self.core = Core.get(plugin_id)
        None

    def shutdown(self):
        None

    def require_boot(self):
        return True
Beispiel #5
0
class StressTest(BasicTest):

    check_count = 0
    results_count = 0

    sched_alias = 'test_sched_%s' % prefix
    nsca_server_alias = 'test_nsca_s_%s' % prefix
    nsca_client_alias = 'test_nsca_c_%s' % prefix
    python_channel = 'test_stress_%s_py' % prefix
    nsca_channel = 'test_stress_%s_nsca' % prefix
    command = 'test_stress_%s' % prefix
    port = 15568
    sched_base_path = '/settings/%s' % sched_alias

    background = False

    checks = [['CheckCPU', ['MaxWarn=20', 'MaxCrit=20']],
              ['CheckMEM', ['MaxWarn=20', 'MaxCrit=20']]]

    def get_random_check(self):
        return random.choice(self.checks)

    def random_check_handler(arguments):
        instance = StressTest.getInstance()
        return instance.wrapped_random_check_handler(arguments)

    random_check_handler = Callable(random_check_handler)

    def wrapped_random_check_handler(self, arguments):
        global is_windows
        if is_windows:
            check = self.get_random_check()
            self.check_count = self.check_count + 1
            return core.simple_query(check[0], check[1])
        else:
            return (status.OK, 'Got call %d' % (self.check_count), '')

    def on_stress_handler(channel, source, command, code, message, perf):
        instance = StressTest.getInstance()
        instance.wrapped_on_stress_handler(channel, source, command, code,
                                           message, perf)

    on_stress_handler = Callable(on_stress_handler)

    def wrapped_on_stress_handler(self, channel, source, command, code,
                                  message, perf):
        check = self.get_random_check()
        self.results_count = self.results_count + 1
        log_debug('Got result %s <%d/%d> on %s' %
                  (message, self.results_count, self.check_count, channel))
        return None

    def desc(self):
        return 'Testcase for stresstest script module'

    def title(self):
        return 'StressTest tests'

    def setup(self, plugin_id, prefix):
        self.reg = Registry.get(plugin_id)
        self.reg.simple_function(self.command, StressTest.random_check_handler,
                                 'This is a simple noop command')
        self.reg.simple_subscription(self.python_channel,
                                     StressTest.on_stress_handler)
        conf = Settings.get()
        conf.set_string(self.sched_base_path, 'threads', '%d' % use_threads)
        core.reload(self.sched_alias)

    def teardown(self):
        if not self.background:
            conf = Settings.get()
            conf.set_string(self.sched_base_path, 'threads', '0')
            core.reload(self.sched_alias)

    def run_test(self):
        global time_to_run, check_per_second
        result = TestResult()
        start = time()
        if isinstance(time_to_run, str) and time_to_run == 'infinate':
            time_to_run = -1
        elif isinstance(time_to_run, str):
            time_to_run = 5

        if time_to_run == -1:
            total_count = -1
        else:
            total_count = check_per_second * time_to_run

        if time_to_run != -1:
            self.background = False
            last_major = 0
            while self.results_count < total_count:
                old_stress_count = self.results_count
                old_noop_count = self.check_count
                sleep(5000)
                result.add_message(
                    True, 'Commands/second: %d/%d' %
                    ((self.results_count - old_stress_count) / 5,
                     (self.check_count - old_noop_count) / 5))
                if (self.results_count * 100 / total_count) > last_major + 10:
                    last_major = last_major + 10
                    log('%d%% Complete: %d checks per second <%d/%d>' %
                        (self.results_count * 100 / total_count,
                         (self.results_count - old_stress_count) / 5,
                         self.results_count, total_count))
            elapsed = (time() - start)
            if elapsed == 0:
                elapsed = 1
            result.add_message(
                True, 'Summary Collected %d instance in %d seconds: %d/s' %
                (self.results_count, elapsed, self.results_count / elapsed))
        else:
            self.background = True
            result.add_message(
                True,
                'Test running in background, run py_unittest_collect to collect results at any time.'
            )
        return result

    def install(self, arguments):
        global is_windows, route_via_python, route_via_nsca, use_threads
        conf = Settings.get()

        # Configure required modules
        if route_via_python:
            conf.set_string('/modules', 'pytest', 'PythonScript')
        conf.set_string('/modules', self.sched_alias, 'Scheduler')
        if is_windows:
            conf.set_string('/modules', 'CheckSystem', 'enabled')
        conf.set_string('/modules', 'CheckHelpers', 'enabled')

        if route_via_nsca:
            conf.set_string('/modules', self.nsca_server_alias, 'NSCAServer')
            conf.set_string('/modules', self.nsca_client_alias, 'NSCAClient')

            # Configure NSCA Server
            conf.set_string('/settings/NSCA/%s' % self.nsca_server_alias,
                            'port', '%d' % self.port)
            conf.set_string('/settings/NSCA/%s' % self.nsca_server_alias,
                            'inbox', self.python_channel)
            conf.set_string('/settings/NSCA/%s' % self.nsca_server_alias,
                            'encryption', 'aes')

            # Configure NSCA Client
            conf.set_string(
                '/settings/NSCA/%s/targets/default' % self.nsca_client_alias,
                'address', 'nsca://127.0.0.1:%d' % self.port)
            conf.set_string(
                '/settings/NSCA/%s/targets/default' % self.nsca_client_alias,
                'encryption', 'aes')
            conf.set_string('/settings/NSCA/%s' % self.nsca_client_alias,
                            'channel', self.nsca_channel)

        # Configure python
        if route_via_python:
            conf.set_string('/settings/pytest/scripts', 'test_stress',
                            'test_stress.py')

        # Configure Scheduler
        if route_via_python:
            conf.set_string(self.sched_base_path, 'threads', '0')
        else:
            conf.set_string(self.sched_base_path, 'threads', '50')

        default_path = '%s/default' % self.sched_base_path
        if route_via_nsca:
            conf.set_string(default_path, 'channel', self.nsca_channel)
        else:
            conf.set_string(default_path, 'channel', self.python_channel)

        conf.set_string(default_path, 'alias', 'stress')
        #conf.set_string(default_path, 'target', 'stress_001')

        use_command = self.command
        if not route_via_python:
            use_command = 'CheckOK'

        conf.set_string(default_path, 'command', use_command)
        conf.set_string(default_path, 'interval', '5s')
        for i in range(1, (check_per_second * 5) + 1):
            alias = 'stress_python_%i' % i
            conf.set_string('%s/schedules' % (self.sched_base_path), alias,
                            use_command)

        conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def init(self, plugin_id):
        None

    def shutdown(self):
        None
Beispiel #6
0
class CommandTest:
	instance = None
	key = ''
	reg = None
	
	class SingletonHelper:
		def __call__( self, *args, **kw ) :
			if CommandTest.instance is None :
				object = CommandTest()
				CommandTest.instance = object
			return CommandTest.instance

	getInstance = SingletonHelper()

	def desc(self):
		return 'Testing that channels work'

	def test_command_handler_001(arguments):
		if len(arguments) == 0:
			return (status.OK, 'no-arguments', '')
		retcode = status.UNKNOWN
		message = ''
		perf = ''
		if len(arguments) > 0:
			if arguments[0] == 'OK':
				retcode = status.OK
			elif arguments[0] == 'WARNING':
				retcode = status.WARNING
			elif arguments[0] == 'CRITICAL':
				retcode = status.CRITICAL
			elif arguments[0] == 'UNKNOWN':
				retcode = status.UNKNOWN
			message = 'arg-count: %d'%len(arguments)
		return (retcode, message, perf)
	test_command_handler_001 = Callable(test_command_handler_001)

	def setup(self, plugin_id, prefix):
		self.key = '_%stest_command'%prefix
		self.reg = Registry.get(plugin_id)
		self.reg.simple_function('%s_001'%self.key, CommandTest.test_command_handler_001, 'This is a sample command')
		
	def teardown(self):
		None
		#self.reg.unregister_simple_function('%s_001'%self.key)

	def test_simple(self, key, args, code, message, perf, tag):
		(retcode, retmessage, retperf) = core.simple_query(key, args)
		isok = True
		if code and retcode != code:
			log('FAILED - Test did not return correct values (code): %s = %s (%s)'%(retcode, code, retmessage))
			isok = False
		if message and retmessage != message:
			log('FAILED - Test did not return correct values (message): %s = %s'%(retmessage, message))
			isok = False
		if perf and retperf != perf:
			log('FAILED - Test did not return correct values (perf): %s = %s'%(retperf, perf))
			isok = False
		if isok:
			log('OK - Test successfull: %s'%tag)
			return 0
		return 1
		

	def run_test(self):
		count = 0
		key001 = '%s_001'%self.key
		count += self.test_simple(key001, [], status.OK, 'no-arguments', '', 'simple check')
		count += self.test_simple(key001, ['OK'], status.OK, 'arg-count: 1', None, 'simple check: Ok')
		count += self.test_simple(key001, ['WARNING'], status.WARNING, 'arg-count: 1', None, 'simple check: Warn')
		count += self.test_simple(key001, ['UNKNOWN'], status.UNKNOWN, 'arg-count: 1', None, 'simple check: Unknown')
		count += self.test_simple(key001, ['CRITICAL'], status.CRITICAL, 'arg-count: 1', None, 'simple check: Crit')
		if count > 0:
			log("ERROR: %d tests failed"%count)
		else:
			log("OK: all tests successfull")
		return (count, 9)
Beispiel #7
0
class ChannelTest:
	instance = None
	channel = ''
	reg = None
	
	last_channel = ''
	last_command = ''
	last_status = status.UNKNOWN
	last_message = ''
	last_perf = ''

	class SingletonHelper:
		def __call__( self, *args, **kw ) :
			if ChannelTest.instance is None :
				object = ChannelTest()
				ChannelTest.instance = object
			return ChannelTest.instance

	getInstance = SingletonHelper()

	def desc(self):
		return 'Testing that channels work'

	def test_submission_handler_001(channel, command, code, message, perf):
		instance = ChannelTest.getInstance()
		instance.last_channel = channel
		instance.last_command = command
		instance.last_status = code
		instance.last_message = message
		instance.last_perf = perf
	test_submission_handler_001 = Callable(test_submission_handler_001)
		
	def test_command_handler_001(arguments):
		instance = ChannelTest.getInstance()
		return (instance.last_status, instance.last_message, instance.last_perf)
	test_command_handler_001 = Callable(test_command_handler_001)

	def setup(self, plugin_id, prefix):
		self.channel = '_%stest_channel'%prefix
		self.reg = Registry.get(plugin_id)
		self.reg.simple_subscription('%s_001'%self.channel, ChannelTest.test_submission_handler_001)
		self.reg.simple_function('%s_001'%self.channel, ChannelTest.test_command_handler_001, 'This is a sample command')
		
	def teardown(self):
		None
		#self.reg.unregister_simple_subscription('%s_001'%self.channel)
		#self.reg.unregister_simple_function('%s_001'%self.channel)

	def test_simple(self, channel, command, code, message, perf, tag):
		core.simple_submit('%s'%channel, '%s'%command, code, '%s'%message, '%s'%perf)
		(retcode, retmessage, retperf) = core.simple_query(channel, [])
		isok = True
		if retcode != code:
			log('FAILED - Test did not get the correct retuirn code: %s = %s (%s)'%(retcode, code, retmessage))
			isok = False
		if retmessage != message:
			log('FAILED - Test did not get the correct retuirn code: %s = %s'%(retmessage, message))
			isok = False
		if retperf != perf:
			log('FAILED - Test did not get the correct retuirn code: %s = %s'%(retperf, perf))
			isok = False
		if isok:
			log('OK - Test successfull: %s'%tag)
			return 0
		return 1
		

	def run_test(self):
		count = 0
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', '', 'simple ok')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.WARNING, 'foobar', '', 'simple warning')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.CRITICAL, 'test', '', 'simple critical')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.UNKNOWN, '1234567890', '', 'simple unknown')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', "'foo'=5%", 'simple performance data 001')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', "'foo'=5%;10", 'simple performance data 002')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', "'foo'=5%;10;23", 'simple performance data 003')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', "'foo'=5%;10;23;10;78", 'simple performance data 004')
		count += self.test_simple('%s_001'%self.channel, 'foobar', status.OK, 'qwerty', "'foo'=5%;10;23;10;78 'bar'=1k;2;3", 'simple performance data 005')
		if count > 0:
			log("ERROR: %d tests failed"%count)
		else:
			log("OK: all tests successfull")
		return (count, 9)
Beispiel #8
0
class NRPEServerTest(BasicTest):
    instance = None
    key = ''
    reg = None
    conf = None
    core = None
    _responses = {}
    _requests = {}

    def has_response(self, id):
        with sync:
            return id in self._responses

    def get_response(self, id):
        with sync:
            if id in self._responses:
                return self._responses[id]
            msg = NRPEMessage(id)
            self._responses[id] = msg
            return msg

    def set_response(self, msg):
        with sync:
            self._responses[msg.uuid] = msg

    def del_response(self, id):
        with sync:
            del self._responses[id]

    def get_request(self, id):
        with sync:
            if id in self._requests:
                return self._requests[id]
            msg = NRPEMessage(id)
            self._requests[id] = msg
            return msg

    def set_request(self, msg):
        with sync:
            self._requests[msg.uuid] = msg

    def del_request(self, id):
        with sync:
            del self._requests[id]

    def desc(self):
        return 'Testcase for NRPE protocol'

    def title(self):
        return 'NRPE Client/Server test'

    def init(self, plugin_id, prefix):
        self.key = '_%stest_command' % prefix
        self.reg = Registry.get(plugin_id)
        self.core = Core.get(plugin_id)
        self.conf = Settings.get(plugin_id)

    def setup(self, plugin_id, prefix):
        self.reg.simple_function('check_py_nrpe_test_s',
                                 NRPEServerTest.simple_handler, 'TODO')
        self.reg.function('check_py_nrpe_test', NRPEServerTest.handler, 'TODO')

    def simple_handler(arguments):
        instance = NRPEServerTest.getInstance()
        return instance.simple_handler_wrapped(arguments)

    simple_handler = Callable(simple_handler)

    def handler(channel, request):
        instance = NRPEServerTest.getInstance()
        return instance.handler_wrapped(channel, request)

    handler = Callable(handler)

    def simple_handler_wrapped(self, arguments):
        log('Got simple message %s' % arguments)
        msg = self.get_response(arguments[0])
        msg.got_simple_response = True
        self.set_response(msg)
        rmsg = self.get_request(arguments[0])
        return (rmsg.status, rmsg.message, rmsg.perfdata)

    def handler_wrapped(self, channel, request):
        log_error('DISCARDING message on %s' % (channel))

        message = plugin_pb2.SubmitRequestMessage()
        message.ParseFromString(request)
        command = message.payload[0].command
        log('Got message %s on %s' % (command, channel))

        msg = self.get_response(command)
        msg.got_response = True
        self.set_response(msg)
        return None

    def teardown(self):
        None

    def submit_payload(self, alias, ssl, length, source, status, msg, perf,
                       target):
        message = plugin_pb2.QueryRequestMessage()

        message.header.version = plugin_pb2.Common.VERSION_1
        message.header.recipient_id = target
        host = message.header.hosts.add()
        host.address = "127.0.0.1:15666"
        host.id = target
        if (target == 'valid'):
            pass
        else:
            enc = host.metadata.add()
            enc.key = "use ssl"
            enc.value = '%s' % ssl
            enc = host.metadata.add()
            enc.key = "payload length"
            enc.value = '%d' % length
        enc = host.metadata.add()
        enc.key = "timeout"
        enc.value = '5'

        uid = str(uuid.uuid4())
        payload = message.payload.add()
        payload.command = 'check_py_nrpe_test_s'
        payload.arguments.append(uid)
        rmsg = self.get_request(uid)
        rmsg.status = status
        rmsg.message = msg
        rmsg.perfdata = perf
        self.set_request(rmsg)
        (result_code, response) = self.core.query('nrpe_forward',
                                                  message.SerializeToString())
        response_message = plugin_pb2.QueryResponseMessage()
        response_message.ParseFromString(response)
        result = TestResult('Testing NRPE: %s for %s' % (alias, target))

        found = False
        for i in range(0, 10):
            if self.has_response(uid):
                rmsg = self.get_response(uid)
                #result.add_message(rmsg.got_response, 'Testing to recieve message using %s'%alias)
                result.add_message(
                    rmsg.got_simple_response,
                    'Testing to recieve simple message using %s' % alias)
                result.add_message(
                    len(response_message.payload) == 1,
                    'Verify that we only get one payload response for %s' %
                    alias, '%s != 1' % len(response_message.payload))
                if len(response_message.payload) == 1:
                    result.assert_equals(
                        response_message.payload[0].result, status,
                        'Verify that status is sent through %s' % alias)
                    result.assert_equals(
                        response_message.payload[0].message, msg,
                        'Verify that message is sent through %s' % alias)
                    #result.assert_equals(rmsg.perfdata, perf, 'Verify that performance data is sent through')
                self.del_response(uid)
                found = True
                break
            else:
                log('Waiting for %s (%s/%s)' % (uid, alias, target))
                sleep(500)
        if not found:
            result.add_message(False,
                               'Testing to recieve message using %s' % alias)
        return result

    def test_one(self,
                 ssl=True,
                 length=1024,
                 state=status.UNKNOWN,
                 tag='TODO'):
        result = TestResult('Testing NRPE: %s/%s/%s with various targets' %
                            (ssl, length, tag))
        for t in ['valid', 'test_rp', 'invalid']:
            result.add(
                self.submit_payload('%s/%s/%s' % (ssl, length, tag), ssl,
                                    length, '%ssrc%s' % (tag, tag), state,
                                    '%smsg%s' % (tag, tag), '', t))
        return result

    def do_one_test(self, ssl=True, length=1024):
        conf = self.conf
        conf.set_int('/settings/NRPE/test_nrpe_server', 'payload length',
                     length)
        conf.set_bool('/settings/NRPE/test_nrpe_server', 'use ssl', ssl)
        conf.set_bool('/settings/NRPE/test_nrpe_server', 'allow arguments',
                      True)
        # TODO: conf.set_string('/settings/NRPE/test_nrpe_server', 'certificate', ssl)
        self.core.reload('test_nrpe_server')

        conf.set_string('/settings/NRPE/test_nrpe_client/targets/default',
                        'address', 'nrpe://127.0.0.1:35666')
        conf.set_bool('/settings/NRPE/test_nrpe_client/targets/default',
                      'use ssl', not ssl)
        conf.set_int('/settings/NRPE/test_nrpe_client/targets/default',
                     'payload length', length * 3)

        conf.set_string('/settings/NRPE/test_nrpe_client/targets/invalid',
                        'address', 'nrpe://127.0.0.1:25666')
        conf.set_bool('/settings/NRPE/test_nrpe_client/targets/invalid',
                      'use ssl', not ssl)
        conf.set_int('/settings/NRPE/test_nrpe_client/targets/invalid',
                     'payload length', length * 2)

        conf.set_string('/settings/NRPE/test_nrpe_client/targets/valid',
                        'address', 'nrpe://127.0.0.1:15666')
        conf.set_bool('/settings/NRPE/test_nrpe_client/targets/valid',
                      'use ssl', ssl)
        conf.set_int('/settings/NRPE/test_nrpe_client/targets/valid',
                     'payload length', length)
        self.core.reload('test_nrpe_client')

        result = TestResult()
        result.add_message(isOpen('127.0.0.1', 15666),
                           'Checking that port is open (server is up)')
        result.add(
            self.test_one(ssl, length, state=status.UNKNOWN, tag='unknown'))
        result.add(self.test_one(ssl, length, state=status.OK, tag='ok'))
        result.add(self.test_one(ssl, length, state=status.WARNING,
                                 tag='warn'))
        result.add(
            self.test_one(ssl, length, state=status.CRITICAL, tag='crit'))
        return result

    def run_test(self):
        result = TestResult()
        result.add(self.do_one_test(ssl=True))
        result.add(self.do_one_test(ssl=False))
        result.add(self.do_one_test(ssl=True, length=4096))
        result.add(self.do_one_test(ssl=True, length=65536))
        result.add(self.do_one_test(ssl=True, length=1048576))
        return result

    def install(self, arguments):
        conf = self.conf
        conf.set_string('/modules', 'test_nrpe_server', 'NRPEServer')
        conf.set_string('/modules', 'test_nrpe_client', 'NRPEClient')
        conf.set_string('/modules', 'pytest', 'PythonScript')

        conf.set_string('/settings/pytest/scripts', 'test_nrpe',
                        'test_nrpe.py')

        conf.set_string('/settings/NRPE/test_nrpe_server', 'port', '15666')
        conf.set_string('/settings/NRPE/test_nrpe_server', 'inbox',
                        'nrpe_test_inbox')
        conf.set_string('/settings/NRPE/test_nrpe_server', 'encryption', '1')

        conf.set_string('/settings/NRPE/test_nrpe_client/targets',
                        'nrpe_test_local', 'nrpe://127.0.0.1:15666')
        conf.set_string('/settings/NRPE/test_nrpe_client', 'channel',
                        'nrpe_test_outbox')

        conf.save()

    def uninstall(self):
        None

    def help(self):
        None

    def shutdown(self):
        None

    def require_boot(self):
        return True
Beispiel #9
0
class ChannelTest:
	instance = None
	channel = ''
	reg = None
	
	last_channel = ''
	last_command = ''
	last_status = status.UNKNOWN
	last_message = ''
	last_perf = ''

	instance = None
	class SingletonHelper:
		def __call__( self, *args, **kw ) :
			if ChannelTest.instance is None :
				object = ChannelTest()
				ChannelTest.instance = object
			return ChannelTest.instance

	getInstance = SingletonHelper()

	def title(self):
		return 'Channel Test'

	def desc(self):
		return 'Testing that channels work'

	def test_submission_handler_001(channel, source, command, code, message, perf):
		log('Got messgae on %s'%channel)
		instance = ChannelTest.getInstance()
		instance.set_last(channel, command, code, message, perf)
	test_submission_handler_001 = Callable(test_submission_handler_001)
		
	def test_command_handler_001(arguments):
		instance = ChannelTest.getInstance()
		return (instance.last_status, '%s'%instance.last_message, '%s'%instance.last_perf)
	test_command_handler_001 = Callable(test_command_handler_001)

	def setup(self, plugin_id, prefix):
		self.channel = '_%stest_channel'%prefix
		self.reg = Registry.get(plugin_id)
		self.reg.simple_subscription(self.channel, ChannelTest.test_submission_handler_001)
		self.reg.simple_function(self.channel, ChannelTest.test_command_handler_001, 'This is a sample command')
		
	def teardown(self):
		None
		#self.reg.unregister_simple_subscription('%s_001'%self.channel)
		#self.reg.unregister_simple_function('%s_001'%self.channel)

	def reset_last(self):
		self.last_channel = None
		self.last_command = None
		self.last_status = None
		self.last_message = None
		self.last_perf = None

	def set_last(self, channel, command, status, message, perf):
		self.last_channel = channel
		self.last_command = command
		self.last_status = status
		self.last_message = message
		self.last_perf = perf
		
	def test_simple(self, command, code, message, perf, tag):
		result = TestResult()
		core = Core.get()
		self.reset_last()
		(ret, msg) = core.simple_submit(self.channel, '%s'%command, code, '%s'%message, '%s'%perf)
		result.add_message(ret, 'Testing channels: %s'%tag, msg)
		r1 = TestResult()
		r1.assert_equals(self.last_status, code, 'Return code')
		r1.assert_equals(self.last_message, message, 'Message')
		r1.assert_equals(self.last_perf, perf, 'Performance data')
		result.add(r1)
		
		self.set_last('', '', code, message, perf)
		(retcode, retmessage, retperf) = core.simple_query(self.channel, [])
		result.add_message(True, 'Testing queries: %s'%tag)
		r2 = TestResult()
		r2.assert_equals(self.last_status, code, 'Return code')
		r2.assert_equals(self.last_message, message, 'Message')
		r2.assert_equals(self.last_perf, perf, 'Performance data')
		result.add(r2)
		return result
		

	def run_test(self):
		result = TestResult()
		result.add(self.test_simple('foobar', status.OK, 'qwerty', '', 'simple ok'))
		result.add(self.test_simple('foobar', status.WARNING, 'foobar', '', 'simple warning'))
		result.add(self.test_simple('foobar', status.CRITICAL, 'test', '', 'simple critical'))
		result.add(self.test_simple('foobar', status.UNKNOWN, '1234567890', '', 'simple unknown'))
		result.add(self.test_simple('foobar', status.OK, 'qwerty', "'foo'=5%", 'simple performance data 001'))
		result.add(self.test_simple('foobar', status.OK, 'qwerty', "'foo'=5%;10", 'simple performance data 002'))
		result.add(self.test_simple('foobar', status.OK, 'qwerty', "'foo'=5%;10;23", 'simple performance data 003'))
		result.add(self.test_simple('foobar', status.OK, 'qwerty', "'foo'=5%;10;23;10;78", 'simple performance data 004'))
		result.add(self.test_simple('foobar', status.OK, 'qwerty', "'foo'=5%;10;23;10;78 'bar'=1k;2;3", 'simple performance data 005'))
		return result

	def install(self, arguments):
		conf = Settings.get()
		conf.set_string('/modules', 'pytest', 'PythonScript')

		conf.set_string('/settings/pytest/scripts', 'test_pb', 'test_pb.py')
		
		conf.save()
	
	def uninstall(self):
		None

	def help(self):
		None

	def init(self, plugin_id):
		None

	def shutdown(self):
		None