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 log(self, show_all = False, prefix = '', indent = 0): if self.status: if show_all: log('%s%s%s'%(prefix, ''.rjust(indent, ' '), self)) log_debug('%s%s%s'%(prefix, ''.rjust(indent, ' '), self)) else: log_error('%s%s%s'%(prefix, ''.rjust(indent, ' '), self))
def delete_file(self, name, path = ''): (folder, file_name) = self.get_real_filename(name, path) if os.path.exists(file_name): try: os.remove(file_name) except OSError, (errno, strerror): log('Failed to delete: %s'%file_name)
def setup(self, plugin_id, prefix): self.reg = Registry.get(plugin_id) self.temp_path = self.core.expand_path('${temp}') log('Temp: %s'%self.temp_path) self.work_path = os.path.join(self.temp_path, '%s.txt'%uuid.uuid4()) log('Work: %s'%self.work_path) create_test_data(self.work_path)
def setup(self, plugin_id, prefix): self.reg = Registry.get(plugin_id) self.temp_path = self.core.expand_path("${temp}") log("Temp: %s" % self.temp_path) self.work_path = os.path.join(self.temp_path, "%s.txt" % uuid.uuid4()) log("Work: %s" % self.work_path) create_test_data(self.work_path)
def init(pid, plugin_alias, script_alias): global world_status, plugin_id plugin_id = pid conf = Settings.get(plugin_id) conf.register_path('/settings/cool script', "Sample script config", "This is a sample script which demonstrates how to interact with NSClient++") conf.register_key('/settings/cool script', 'world', 'string', "A key", "Never ever change this key: or the world will break", "safe") world_status = conf.get_string('/settings/cool script', 'world', 'true') if world_status != 'safe': log('My god: its full of stars: %s'%world_status) log('Adding a simple function/cmd line') reg = Registry.get(plugin_id) reg.simple_cmdline('help', get_help) reg.simple_function('check_world', check_world, 'Check if the world is safe') reg.simple_function('break_world', break_world, 'Break the world') reg.simple_function('fix_world', fix_world, 'Fix the world') reg.simple_function('save_world', save_world, 'Save the world') reg.simple_function('show_metrics', fun_show_metrics, 'Enable displaying metrics or not') reg.submit_metrics(submit_metrics) reg.fetch_metrics(fetch_metrics)
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 upsert(path, data): r = requests.post(icinga_url+path, data=data, verify=False, headers=icinga_header, auth=icinga_auth) if r.status_code == 404: r = requests.put(icinga_url+path, data=data, verify=False, headers=icinga_header, auth=icinga_auth) if r.status_code == 500: log("Failed to upsert: %s: %s"%(path, r.text)) return r
def install_module(module): m = None try: m = importlib.import_module('modules.%s'%module) except Exception,e: log("Failed to load %s: %s"%(module, e)) return
def test_one_crypto(self, crypto, length=512): log('Testing: %s %d'%(crypto, length)) 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 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 setup(self, plugin_id, prefix): self.reg = Registry.get(plugin_id) self.temp_path = core.expand_path('${temp}') log('Temp: %s'%self.temp_path) self.work_path = os.path.join(self.temp_path, '%s'%uuid.uuid4()) log('Work: %s'%self.work_path) os.mkdir(self.work_path)
def check_bound(self, filter, warn, crit, expected): alias = "%s/%s/%s" % (filter, warn, crit) result = TestResult("Checking %s" % alias) args = ["file=%s" % self.work_path, "column-split=,", "filter=%s" % filter, "warn=%s" % warn, "crit=%s" % crit] # log("Command: %s"%args) (ret, msg, perf) = self.core.simple_query("check_logfile", args) log("%s : %s -- %s" % (filter, msg, perf)) result.add_message(ret == expected, "Check status", "Invalid check status: %s" % ret) return result
def inbox_handler_wrapped(self, channel, request): message = plugin_pb2.SubmitRequestMessage() message.ParseFromString(request) 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 simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf): log('Got simple 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 check_bound(self, filter, warn, crit, expected): alias = '%s/%s/%s'%(filter, warn, crit) result = TestResult('Checking %s'%alias) args = ['file=%s'%self.work_path, 'column-split=,', 'filter=%s'%filter, 'warn=%s'%warn, 'crit=%s'%crit] #log("Command: %s"%args) (ret, msg, perf) = self.core.simple_query('check_logfile', args) log("Messge: %s"%msg) log("Perf: %s"%perf) result.add_message(ret == expected, 'Check status', 'Invalid check status: %s'%ret) return result
def log(self, show_all = False, prefix = '', indent = 0): start = '%s%s'%(prefix, ''.rjust(indent, ' ')) if self.status: if show_all: log('%s%s'%(start, self)) log_debug('%s%s'%(start, self)) else: log_error('%s%s'%(start, self)) for c in self.children: c.log(show_all, prefix, indent+1)
def submit_payload(self, alias, ssl, length, source, status, msg, perf, target): message = plugin_pb2.QueryRequestMessage() message.header.destination_id = target message.header.command = 'nrpe_forward' 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('ignored', 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 and len(response_message.payload[0].lines) == 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].lines[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 simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf): message = unicodedata.normalize('NFKD', message).encode('ascii','ignore') log('Got simple message %s on %s'%(command, channel)) self.got_simple_response = True self.last_source = source self.last_command = command self.last_status = status self.last_message = message self.message_count = self.message_count + 1 self.last_perfdata = perf return True
def cleanup_files(self): for data in self.test_data: self.delete_file(data[0], data[3]) for data in self.test_data: self.delete_file(data[0], data[3]) if os.path.exists(self.work_path): try: os.rmdir(self.work_path) except OSError, (errno, strerror): log('Failed to delete folder: %s'%self.work_path) log('Failed to delete folder: %s'%errno)
def add_host(server_name, address, os_version): payload = { "attrs": { "address": address, "check_command": "hostalive", "vars.os": "Windows", "vars.version": os_version } } r = upsert('/v1/objects/hosts/%s'%server_name, json.dumps(payload)) log("Host for %s created: %d: %s"%(address, r.status_code, r.text))
def setup(self, plugin_id, prefix): t = datetime.datetime.fromtimestamp(time.mktime(time.localtime())) t = t + datetime.timedelta(seconds=60) tm = time.strftime("%H:%M", t.timetuple()) folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) log("Adding scheduled tasks") for state in ['OK', 'WARN', 'CRIT', 'LONG']: cmd = "schtasks.exe /Create /SC DAILY /TN NSCPSample_%s /TR \"%s\\check_test.bat %s\" /ST %s /F"%(state, folder, state, tm) log_debug(cmd) check_output(cmd) log("Waiting 1 minute (for tasks to run)") time.sleep(60)
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 __main__(args): global plugin_id # List all namespaces recursivly core = Core.get(plugin_id) (ret, ns_msgs) = core.simple_exec('CheckWMI', 'wmi', ['--list-all-ns']) if len(ns_msgs) == 0: log_error("Failed to execute WMI command is CheckWMI enabled?") else: for ns in ns_msgs[0].splitlines(): # List all classes in each namespace (ret, cls_msgs) = core.simple_exec('any', 'wmi', ['--list-classes', '--simple', '--namespace', ns]) for cls in cls_msgs[0].splitlines(): log( '%s : %s'%(ns, cls))
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 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)
def add_nrpe_service(server_name, service_name, command, description, args = []): payload = { "display_name": description, "host_name": server_name, "attrs": { "check_command": "nrpe", "check_interval": "60", "retry_interval": "15", "vars.nrpe_command": command, "vars.nrpe_arguments": args } } r = upsert('/v1/objects/services/%s!%s'%(server_name, service_name), json.dumps(payload)) log("Service created: %s!%s %d: %s"%(server_name, service_name, r.status_code, r.text))
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 main(self, args): parser = OptionParser(prog="") parser.add_option("-f", "--format", help="Generate format") parser.add_option("-o", "--output", help="write report to FILE(s)") parser.add_option("-i", "--input", help="Reference folder") (options, args) = parser.parse_args(args=args) if not options.format: options.format = "rst" if options.format in ["rst"]: self.generate_rst(options.input, options.output) else: log("Help%s"%parser.print_help()) log("Invalid format: %s"%options.format) return
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 main(self, args): parser = OptionParser(prog="") parser.add_option("-f", "--format", help="Generate format") parser.add_option("-o", "--output", help="write report to FILE(s)") parser.add_option("--trac-path", help="The path to track (used for importing wikis)") (options, args) = parser.parse_args(args=args) #if options.format in ["trac"]: # self.generate_trac(options.output, options.trac_path) if options.format in ["rst"]: self.generate_rst(options.output) else: log("Help%s" % parser.print_help()) log("Invalid format: %s" % options.format) return
def install(self, arguments): t = datetime.datetime.fromtimestamp(time.mktime(time.localtime())) t = t + datetime.timedelta(seconds=60) tm = time.strftime("%H:%M", t.timetuple()) folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) log("Adding scheduled tasks") for state in ['OK', 'WARN', 'CRIT', 'LONG']: cmd = "SchTasks /Create /SC DAILY /TN NSCPSample_%s /TR \"%s\\check_test.bat %s\" /ST %s /F"%(state, folder, state, tm) log_debug(cmd) check_output(cmd) log("Waiting 1 minute (for tasks to run)") time.sleep(60) conf = self.conf conf.set_string('/modules', 'test_tsch', 'CheckTaskSched') conf.set_string('/modules', 'pytest', 'PythonScript') conf.set_string('/settings/pytest/scripts', 'test_w32_tsch', __file__) conf.save()
def check_files(self, filter, text, expected): alias = '%s: %s' % (text, filter) result = TestResult('Checking %s' % alias) args = [ 'file=%s' % self.work_path, 'column-split=,', 'filter=%s' % filter, 'warn=count gt %d' % expected, 'crit=count gt %d' % expected ] #log("Command: %s"%args) (ret, msg, perf) = self.core.simple_query('check_logfile', args) log("%s : %s -- %s" % (filter, msg, perf)) count = self.get_count(perf) result.add_message(count == expected, '%s - number of files' % filter, 'got %s expected %s' % (count, expected)) result.add_message(ret == status.OK, '%s -- status', 'got %s expected OK' % ret) return result
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 run_test_proc(self): result = TestResult('Checking CheckProcState') for j in range(0, 3): result.append(self.test_one_proc_int('notepad.exe', 0, j)) pids = [] for i in range(1, 4): log('Starting notepad...') handle = subprocess.Popen('notepad.exe', shell=False) sleep(500) pids.append(handle.pid) for j in range(0, 3): result.append(self.test_one_proc_int('notepad.exe', i, j)) for p in pids: subprocess.Popen("taskkill /F /T /PID %i" % p, shell=True) return result
def init(pid, plugin_alias, script_alias): global prefix global plugin_id plugin_id = pid if script_alias: prefix = '%s_'%script_alias conf = Settings.get() #val = conf.get_string('/modules', 'PythonScript', 'foo') #log('Got it: %s'%val) log('Testing to register a function') reg = Registry.get(plugin_id) reg.simple_cmdline('help', get_help) reg.simple_cmdline('install_python_test', install_test) reg.simple_function('%stest'%prefix, test, 'Run python unittest')
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)
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 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 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_proc(self): master = TestResult('Checking check_process') result = TestResult('0 notepads running') for j in range(0, 3): result.append(self.test_one_proc_int('notepad.exe', 0, j)) master.add(result) pids = [] for i in range(1, 4): result = TestResult('%d notepads running' % i) log('Starting notepad...') handle = subprocess.Popen('notepad.exe', shell=False) sleep(500) pids.append(handle.pid) for j in range(0, 3): result.append(self.test_one_proc_int('notepad.exe', i, j)) master.add(result) for p in pids: subprocess.Popen("taskkill /F /T /PID %i" % p, shell=True) return master
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 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 uninstall(self): log("Removing scheduled tasks") for state in ['OK', 'WARN', 'CRIT', 'LONG']: log_debug("SchTasks /Delete /TN NSCPSample_%s /F"%state) check_output("SchTasks /Delete /TN NSCPSample_%s /F"%state)
def shutdown(): log('Unloading script...')
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)
def install(self, arguments = []): boot = False for suite in self.suites: instance = suite.getInstance() instance.install(arguments) if instance.require_boot(): boot = True #core = Core.get() #core.reload('service') #(code, msg, perf) = core.simple_query('py_unittest', []) log('-+---==(TEST INSTALLER)==---------------------------------------------------+-') log(' | Setup nessecary configuration for running test |') log(' | This includes: Loading the PythonScript module at startup |') log(' | To use this please run nsclient++ in "test mode" like so: |') if boot: log(' | nscp client --boot --query py_unittest |') else: log(' | nscp client --query py_unittest |') log('-+--------------------------------------------------------==(DAS ENDE!)==---+-')
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 submit_metrics(list, request): global show_metrics if show_metrics: for k, v in list.iteritems(): log("Got metrics: %s = %s" % (k, v))
def remove(path): r = requests.delete(icinga_url+path, verify=False, headers=icinga_header, auth=icinga_auth) if r.status_code == 500: log("Failed to delete: %s: %s"%(path, r.text)) return r
def install_test(arguments): log('-+---==(TEST INSTALLER)==---------------------------------------------------+-') log(' | Setup nessecary configuration for running test |') log(' | This includes: Loading the PythonScript module at startup |') log(' | To use this please run nsclient++ in "test mode" like so: |') log(' | nscp --test |') log(' | Then start the pytest_test command by typing it and press enter like so: |') log(' | pytest_test |') log(' | Lastly exit by typing exit like so: |') log(' | exit |') log('-+--------------------------------------------------------==(DAS ENDE!)==---+-') conf = Settings.get() conf.set_string('/modules', 'pytest', 'PythonScript') conf.set_string('/settings/pytest/scripts', 'pytest', 'test.py') conf.save()
def post(path, data): r = requests.post(icinga_url+path, data=data, verify=False, headers=icinga_header, auth=icinga_auth) if r.status_code == 500: log("Failed to upsert: %s: %s"%(path, r.text)) return r
def shutdown(): global server_name log('Removing host: %s...'%server_name) remove('/v1/objects/hosts/%s?cascade=1'%server_name)
def get_help(arguments): if arguments: log("Wicked: we got some args") return (status.OK, 'Need help? Sorry, Im not help full my friend...')
"vars.nrpe_arguments": args } } r = upsert('/v1/objects/services/%s!%s'%(server_name, service_name), json.dumps(payload)) log("Service created: %s!%s %d: %s"%(server_name, service_name, r.status_code, r.text)) def install_module(module): m = None try: m = importlib.import_module('modules.%s'%module) except Exception,e: log("Failed to load %s: %s"%(module, e)) return try: log('Detected %s: enabling %s'%(m.desc(), module)) m.set_plugin_id(plugin_id) m.install() for s in m.get_services(): add_nrpe_service(server_name, s['name'], s['command'], s['desc'], s['args']) except Exception,e: log("Failed to install %s: %s"%(module, e)) log("Module %s installed successfully."%module) def on_event(event, data): if 'exe' in data and data['exe'] == 'notepad.exe': install_module('notepad') if 'exe' in data and data['exe'] == 'nscp.exe': install_module('nscp') nics = []
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 shutdown(): log("shutdown") shutdown_testcases()
def delete_file(file): if os.path.exists(file): try: os.remove(file) except OSError, (errno, strerror): log('Failed to delete: %s' % file)