Beispiel #1
0
 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
Beispiel #2
0
 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))
Beispiel #3
0
	def serialize(self, string, filename):
		path = os.path.dirname(filename)
		if not os.path.exists(path):
			os.makedirs(path)
		f = open(filename,"w")
		f.write(string)
		f.close()
		log_debug('Writing file: %s'%filename)
Beispiel #4
0
	def log(self, prefix = '', indent = 0):
		start = '%s%s'%(prefix, ''.rjust(indent, ' '))
		if self.status:
			log_debug('%s%s'%(start, self))
		else:
			log_error('%s%s'%(start, self))
		for c in self.children:
			c.log(prefix, indent+1)
Beispiel #5
0
 def log(self, prefix="", indent=0):
     start = "%s%s" % (prefix, "".rjust(indent, " "))
     if self.status:
         log_debug("%s%s" % (start, self))
     else:
         log_error("%s%s" % (start, self))
     for c in self.children:
         c.log(prefix, indent + 1)
Beispiel #6
0
 def return_nagios(self):
     (total, ok) = self.count()
     log_debug(" | Test result log (only summary will be returned to query)")
     self.log(" | ")
     if total == ok:
         return (status.OK, "OK: %d test(s) successfull" % (total))
     else:
         return (status.CRITICAL, "ERROR: %d/%d test(s) failed" % (total - ok, total))
Beispiel #7
0
 def serialize(self, string, filename):
     path = os.path.dirname(filename)
     if not os.path.exists(path):
         os.makedirs(path)
     f = open(filename, "w")
     f.write(string)
     f.close()
     log_debug('Writing file: %s' % filename)
Beispiel #8
0
	def log(self, prefix = '', indent = 0):
		start = '%s%s'%(prefix, ''.rjust(indent, ' '))
		if self.status:
			log_debug('%s%s'%(start, self))
		else:
			log_error('%s%s'%(start, self))
		for c in self.children:
			c.log(prefix, indent+1)
Beispiel #9
0
	def return_nagios(self):
		(total, ok) = self.count()
		log_debug(' | Test result log (only summary will be returned to query)')
		self.log(' | ')
		if total == ok:
			return (status.OK, "OK: %d test(s) successfull"%(total))
		else:
			return (status.CRITICAL, "ERROR: %d/%d test(s) failed"%(total-ok, total))
Beispiel #10
0
	def generate_rst(self, input_dir, output_dir):
		root = self.get_info()
		i = 0
		
		env = Environment(extensions=["jinja2.ext.do",])
		env.filters['firstline'] = first_line
		env.filters['rst_link'] = make_rst_link
		env.filters['rst_table'] = render_rst_table
		env.filters['rst_csvtable'] = render_rst_csv_table
		env.filters['rst_heading'] = render_rst_heading
		env.filters['extract_value'] = extract_value
		env.filters['block_pad'] = block_pad
		env.filters['common_head'] = calculate_common_head
		env.filters['as_text'] = as_text
		
		for (module,minfo) in root.plugins.iteritems():
			out_base_path = '%s/reference/'%output_dir
			sample_base_path = '%s/samples/'%output_dir
			if minfo.namespace:
				out_base_path = '%s/reference/%s/'%(output_dir, minfo.namespace)
			hash = root.get_hash()
			minfo.key = module
			minfo.queries = {}
			for (c,cinfo) in sorted(root.commands.iteritems()):
				if module in cinfo.info.plugin:
					more_info = self.fetch_command(c,cinfo)
					if more_info:
						cinfo = more_info
					sfile = '%s%s_%s_samples.inc'%(sample_base_path, module, c)
					if os.path.exists(sfile):
						cinfo.sample = os.path.basename(sfile)
						#all_samples.append((module, command, sfile))
					cinfo.key = c
					minfo.queries[c] = cinfo
			minfo.aliases = {}
			for (c,cinfo) in sorted(root.aliases.iteritems()):
				if module in cinfo.info.plugin:
					cinfo.key = c
					minfo.aliases[c] = cinfo
					
			minfo.paths = {}
			for (c,cinfo) in sorted(root.paths.iteritems()):
				if module in cinfo.info.plugin:
					cinfo.key = c
					minfo.paths[c] = cinfo

			hash['module'] = minfo
			i=i+1
			log_debug('Processing module: %d of %d [%s]'%(i, len(root.plugins), module))

			template = env.from_string(module_template)
			render_template(hash, template, '%s/%s.rst'%(out_base_path, module))

		log_debug('%s/samples/index.rst'%output_dir)
		hash = root.get_hash()
		template = env.from_string(samples_template)
		render_template(hash, template, '%s/samples/index.rst'%output_dir)
Beispiel #11
0
	def simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf):
		log_debug('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
Beispiel #12
0
 def get_paths(self):
     (code, data) = self.conf.query(self.build_inventory_request())
     if code == 1:
         message = plugin_pb2.SettingsResponseMessage()
         message.ParseFromString(data)
         for payload in message.payload:
             if payload.inventory:
                 log_debug('Found %d paths' % len(payload.inventory))
                 return payload.inventory
     return []
Beispiel #13
0
	def get_paths(self):
		(code, data) = self.conf.query(self.build_inventory_request())
		if code == 1:
			message = plugin_pb2.SettingsResponseMessage()
			message.ParseFromString(data)
			for payload in message.payload:
				if payload.inventory:
					log_debug('Found %d paths'%len(payload.inventory))
					return payload.inventory
		return []
Beispiel #14
0
 def get_keys(self, path):
     (code, data) = self.conf.query(self.build_inventory_request(path, False, True))
     if code == 1:
         message = plugin_pb2.SettingsResponseMessage()
         message.ParseFromString(data)
         for payload in message.payload:
             if payload.inventory:
                 log_debug('Found %d keys for %s'%(len(payload.inventory), path))
                 return payload.inventory
     return []
Beispiel #15
0
	def get_keys(self, path):
		(code, data) = self.conf.query(self.build_inventory_request(path, False, True))
		if code == 1:
			message = plugin_pb2.SettingsResponseMessage()
			message.ParseFromString(data)
			for payload in message.payload:
				if payload.inventory:
					log_debug('Found %d keys for %s'%(len(payload.inventory), path))
					return payload.inventory
		return []
Beispiel #16
0
 def get_plugins(self):
     (code, data) = self.registry.query(self.build_command_request(4))
     if code == 1:
         message = plugin_pb2.RegistryResponseMessage()
         message.ParseFromString(data)
         for payload in message.payload:
             if payload.inventory:
                 log_debug('Found %d plugins' % len(payload.inventory))
                 return payload.inventory
     log_error('No plugins')
     return []
Beispiel #17
0
	def get_plugins(self):
		(code, data) = self.registry.query(self.build_command_request(4))
		if code == 1:
			message = plugin_pb2.RegistryResponseMessage()
			message.ParseFromString(data)
			for payload in message.payload:
				if payload.inventory:
					log_debug('Found %d plugins'%len(payload.inventory))
					return payload.inventory
		log_error('No plugins')
		return []
Beispiel #18
0
 def simple_inbox_handler_wrapped(self, channel, source, command, status,
                                  message, perf):
     log_debug('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
Beispiel #19
0
 def get_query_aliases(self):
     log_debug('Fetching aliases...')
     (code, data) = self.registry.query(self.build_command_request(5))
     if code == 1:
         message = plugin_pb2.RegistryResponseMessage()
         message.ParseFromString(data)
         for payload in message.payload:
             if payload.inventory:
                 log_debug('Found %d aliases' % len(payload.inventory))
                 return payload.inventory
     log_error('No aliases found')
     return []
Beispiel #20
0
	def get_query_aliases(self):
		log_debug('Fetching aliases...')
		(code, data) = self.registry.query(self.build_command_request(5))
		if code == 1:
			message = plugin_pb2.RegistryResponseMessage()
			message.ParseFromString(data)
			for payload in message.payload:
				if payload.inventory:
					log_debug('Found %d aliases'%len(payload.inventory))
					return payload.inventory
		log_error('No aliases found')
		return []
Beispiel #21
0
 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)
Beispiel #22
0
    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_debug('Got message %s on %s' % (command, channel))

        msg = NSCAMessage(command)
        msg.got_response = True
        self.set_response(msg)
        return None
Beispiel #23
0
 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)
Beispiel #24
0
	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_debug('Got message %s on %s'%(command, channel))
		
		msg = NSCAMessage(command)
		msg.got_response = True
		self.set_response(msg)
		return None
Beispiel #25
0
	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_debug('Waiting for %s (%d/10)'%(uuid, i+1))
				sleep(200)
			else:
				log_debug('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_debug('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_debug('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
Beispiel #26
0
 def check_ts_query(self, task, code):
     result = TestResult('Checking task %s'%task)
     for i in [0, 1, 2, 3, 4]:
         # check_tasksched "filter=title = 'NSCPSample_CRIT'" "warn=exit_code != 3"
         args = ["filter=title = 'NSCPSample_%s'"%task, 
             "warn=exit_code = %d"%i]
         log_debug(', '.join(args))
         (ret, msg, perf) = self.core.simple_query('check_tasksched', args)
         
         if i == code:
             result.assert_equals(ret, status.WARNING, 'Verify WARN result: %s'%msg)
         else:
             result.assert_equals(ret, status.OK, 'Verify OK result: %s'%msg)
         
     return result
Beispiel #27
0
 def check_ts_query(self, task, code):
     result = TestResult('Checking task %s'%task)
     for i in [0, 1, 2, 3, 4]:
         # check_tasksched "filter=title = 'NSCPSample_CRIT'" "warn=exit_code != 3"
         args = ["filter=title = 'NSCPSample_%s'"%task, 
             "warn=exit_code = %d"%i]
         log_debug(', '.join(args))
         (ret, msg, perf) = self.core.simple_query('check_tasksched', args)
         
         if i == code:
             result.assert_equals(ret, status.WARNING, 'Verify WARN result: %s'%msg)
         else:
             result.assert_equals(ret, status.OK, 'Verify OK result: %s'%msg)
         
     return result
Beispiel #28
0
 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()
Beispiel #29
0
def render_template(hash, template, filename):
	data = template.render(hash).encode('utf8')
	
	path = os.path.dirname(filename)
	if not os.path.exists(path):
		os.makedirs(path)

	if os.path.exists(filename):
		m1 = hashlib.sha256()
		m1.update(data)
		sha1 = m1.digest()
		with open(filename) as f:
			m2 = hashlib.sha256()
			m2.update(f.read())
			sha2 = m2.digest()
		if sha1 == sha2:
			log_debug("no changes detected in: %s"%filename)
			return

	log_debug('Writing file: %s'%filename)
	f = open(filename,"wb")
	f.write(data)
	f.close()
Beispiel #30
0
def render_template(hash, template, filename):
    data = template.render(hash).encode('utf8')

    path = os.path.dirname(filename)
    if not os.path.exists(path):
        os.makedirs(path)

    if os.path.exists(filename):
        m1 = hashlib.sha256()
        m1.update(data)
        sha1 = m1.digest()
        with open(filename) as f:
            m2 = hashlib.sha256()
            m2.update(f.read())
            sha2 = m2.digest()
        if sha1 == sha2:
            log_debug("no changes detected in: %s" % filename)
            return

    log_debug('Writing file: %s' % filename)
    f = open(filename, "wb")
    f.write(data)
    f.close()
Beispiel #31
0
    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_debug('Waiting for %s (%d/10)' % (uuid, i + 1))
                sleep(200)
            else:
                log_debug('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_debug(
                    '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_debug('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
Beispiel #32
0
	def install(self, arguments):
		global is_windows, route_via_python, route_via_nsca, use_threads

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

		if route_via_nsca:
			self.conf.set_string('/modules', self.nsca_server_alias, 'NSCAServer')
			self.conf.set_string('/modules', self.nsca_client_alias, 'NSCAClient')
			
			# Configure NSCA Server
			self.conf.set_string('/settings/NSCA/%s'%self.nsca_server_alias, 'port', '%d'%self.nsca_port)
			self.conf.set_string('/settings/NSCA/%s'%self.nsca_server_alias, 'inbox', self.python_channel)
			self.conf.set_string('/settings/NSCA/%s'%self.nsca_server_alias, 'encryption', 'xor')
			self.conf.set_string('/settings/NSCA/%s'%self.nsca_server_alias, 'password', 'HelloWorld')

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

		if route_via_nrpe:
			self.conf.set_string('/modules', self.nrpe_server_alias, 'NRPEServer')
			self.conf.set_string('/modules', self.nrpe_client_alias, 'NRPEClient')
			
			# Configure NRPE Server
			self.conf.set_string('/settings/NRPE/%s'%self.nrpe_server_alias, 'port', '%d'%self.nrpe_port)
			self.conf.set_string('/settings/NRPE/%s'%self.nrpe_server_alias, 'allow arguments', 'true')

			# Configure NRPE Client
			self.conf.set_string('/settings/NRPE/%s/targets/default'%self.nsca_client_alias, 'address', 'nrpe://127.0.0.1:%d'%self.nrpe_port)
			
		# Configure python
		self.conf.set_string('/settings/pytest/scripts', 'test_stress', 'test_stress.py')
		
		# Configure Scheduler
		if route_via_python:
			self.conf.set_string(self.sched_base_path, 'threads', '0')
		else:
			self.conf.set_string(self.sched_base_path, 'threads', '50')

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

		self.conf.set_string(default_path, 'alias', 'stress')
		#self.conf.set_string(default_path, 'target', 'stress_001')
		
		use_command = self.command
		if not route_via_python:
			if route_via_nrpe:
				use_command = 'nrpe_query host=127.0.0.1 port=%d command=CheckOK'%self.nrpe_port
			else:
				use_command = 'CheckOK'
		
		self.conf.set_string(default_path, 'command', use_command)
		self.conf.set_string(default_path, 'interval', '5s')
		log_debug('Adding %d checks'%int(check_per_second*5))
		for i in range(1, int(check_per_second*5)+1):
			
			alias = 'stress_python_%i'%i
			self.conf.set_string('%s/schedules'%(self.sched_base_path), alias, use_command)

		self.conf.save()
Beispiel #33
0
 def log(self, prefix="", indent=0):
     if self.status:
         log_debug("%s%s%s" % (prefix, "".rjust(indent, " "), self))
     else:
         log_error("%s%s%s" % (prefix, "".rjust(indent, " "), self))
Beispiel #34
0
    def generate_rst(self, input_dir, output_dir):
        root = self.get_info()
        i = 0

        env = Environment(extensions=[
            "jinja2.ext.do",
        ])
        env.filters['firstline'] = first_line
        env.filters['rst_link'] = make_rst_link
        env.filters['rst_table'] = render_rst_table
        env.filters['rst_csvtable'] = render_rst_csv_table
        env.filters['rst_heading'] = render_rst_heading
        env.filters['extract_value'] = extract_value
        env.filters['block_pad'] = block_pad
        env.filters['common_head'] = calculate_common_head
        env.filters['as_text'] = as_text

        for (module, minfo) in root.plugins.iteritems():
            out_base_path = '%s/reference/' % output_dir
            sample_base_path = '%s/samples/' % output_dir
            if minfo.namespace:
                out_base_path = '%s/reference/%s/' % (output_dir,
                                                      minfo.namespace)
            hash = root.get_hash()
            minfo.key = module
            minfo.queries = {}
            for (c, cinfo) in sorted(root.commands.iteritems()):
                if module in cinfo.info.plugin:
                    more_info = self.fetch_command(c, cinfo)
                    if more_info:
                        cinfo = more_info
                    sfile = '%s%s_%s_samples.inc' % (sample_base_path, module,
                                                     c)
                    if os.path.exists(sfile):
                        cinfo.sample = os.path.basename(sfile)
                        #all_samples.append((module, command, sfile))
                    cinfo.key = c
                    minfo.queries[c] = cinfo
            minfo.aliases = {}
            for (c, cinfo) in sorted(root.aliases.iteritems()):
                if module in cinfo.info.plugin:
                    cinfo.key = c
                    minfo.aliases[c] = cinfo

            minfo.paths = {}
            for (c, cinfo) in sorted(root.paths.iteritems()):
                if module in cinfo.info.plugin:
                    cinfo.key = c
                    minfo.paths[c] = cinfo

            hash['module'] = minfo
            i = i + 1
            log_debug('Processing module: %d of %d [%s]' %
                      (i, len(root.plugins), module))

            template = env.from_string(module_template)
            render_template(hash, template,
                            '%s/%s.rst' % (out_base_path, module))

        log_debug('%s/samples/index.rst' % output_dir)
        hash = root.get_hash()
        template = env.from_string(samples_template)
        render_template(hash, template, '%s/samples/index.rst' % output_dir)
Beispiel #35
0
    def generate_rst(self, dir):
        renderer = self.renderer
        docs = {}
        root = self.get_info()
        import_commands = []
        import_config = ""

        i = 0
        commands = []
        for (module, minfo) in root.plugins.iteritems():
            i = i + 1
            log_debug('Processing module: %d of %d [%s]' %
                      (i, len(root.plugins), module))
            string = renderer.page_header('module', module)
            string += renderer.obj_anchor('module', module,
                                          minfo.info.description)
            string += renderer.title(
                0, ':module:`%s` --- %s' % (module, minfo.info.title))
            string += renderer.para(minfo.info.description)

            queries = []
            for (c, cinfo) in sorted(root.commands.iteritems()):
                if module in cinfo.info.plugin:
                    queries.append([
                        renderer.obj_link('query', c),
                        cinfo.info.description.split('\n')[0]
                    ])
            if queries:
                queries.insert(0, ['Command', 'Description'])
                string += renderer.heading(
                    'Queries (Overview)',
                    'A list of all avalible queries (check commands)')
                string += renderer.table(queries)

            table = []
            for (c, cinfo) in sorted(root.aliases.iteritems()):
                if module in cinfo.info.plugin:
                    if cinfo.info.description.startswith(
                            'Alternative name for:'):
                        command = cinfo.info.description[22:]
                        table.append([
                            c,
                            renderer.obj_link('query', command),
                            cinfo.info.title
                        ])
                    else:
                        table.append([c, '', cinfo.info.title])
            if table:
                table.insert(0, ['Alias', 'Command', 'Description'])
                string += renderer.heading(
                    'Aliases',
                    'A list of all short hand aliases for queries (check commands)'
                )
                string += renderer.table(table)

            string += renderer.para('Commands (executable)',
                                    "**TODO:** Add command list")

            config_table = self.generate_rst_config_table(root.paths, module)
            if config_table:
                string += renderer.heading(
                    'Configuration (Overview)',
                    'A list of all configuration options')
                string += config_table

            if queries:
                string += renderer.title(1, 'Queries')
                string += renderer.para(
                    'A quick reference for all avalible queries (check commands) in the %s module.'
                    % module)
                for (c, cinfo) in root.commands.iteritems():
                    if module in cinfo.info.plugin:
                        string += self.generate_rst_command_details(
                            c, cinfo, module)

            if config_table:
                string += renderer.title(1, 'Configuration')
                string += renderer.para(
                    'A quick reference for all avalible configuration options in the %s module.'
                    % module)
                string += self.generate_rst_config_details(root.paths, module)

            renderer.serialize(string, '%s/reference/%s.rst' % (dir, module))
            commands.append('%s.rst' % module)

        all_config = self.generate_rst_config_table(root.paths)
        #renderer.serialize(all_config, '%s/reference/config.rst'%dir)

        string = """Modules
=======

Contents:

.. toctree::
   :maxdepth: 3

"""
        for c in sorted(commands):
            string += '   %s\n' % c
        renderer.serialize(string, '%s/reference/index.rst' % dir)
Beispiel #36
0
    def install(self, arguments):
        global is_windows, route_via_python, route_via_nsca, use_threads

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

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

            # Configure NSCA Server
            self.conf.set_string("/settings/NSCA/%s" % self.nsca_server_alias, "port", "%d" % self.nsca_port)
            self.conf.set_string("/settings/NSCA/%s" % self.nsca_server_alias, "inbox", self.python_channel)
            self.conf.set_string("/settings/NSCA/%s" % self.nsca_server_alias, "encryption", "xor")
            self.conf.set_string("/settings/NSCA/%s" % self.nsca_server_alias, "password", "HelloWorld")

            # Configure NSCA Client
            self.conf.set_string(
                "/settings/NSCA/%s/targets/default" % self.nsca_client_alias,
                "address",
                "nsca://127.0.0.1:%d" % self.nsca_port,
            )
            self.conf.set_string("/settings/NSCA/%s/targets/default" % self.nsca_client_alias, "encryption", "xor")
            self.conf.set_string("/settings/NSCA/%s/targets/default" % self.nsca_client_alias, "password", "HelloWorld")
            self.conf.set_string("/settings/NSCA/%s" % self.nsca_client_alias, "channel", self.nsca_channel)

        if route_via_nrpe:
            self.conf.set_string("/modules", self.nrpe_server_alias, "NRPEServer")
            self.conf.set_string("/modules", self.nrpe_client_alias, "NRPEClient")

            # Configure NRPE Server
            self.conf.set_string("/settings/NRPE/%s" % self.nrpe_server_alias, "port", "%d" % self.nrpe_port)
            self.conf.set_string("/settings/NRPE/%s" % self.nrpe_server_alias, "allow arguments", "true")

            # Configure NRPE Client
            self.conf.set_string(
                "/settings/NRPE/%s/targets/default" % self.nsca_client_alias,
                "address",
                "nrpe://127.0.0.1:%d" % self.nrpe_port,
            )

            # Configure python
        self.conf.set_string("/settings/pytest/scripts", "test_stress", "test_stress.py")

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

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

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

        use_command = self.command
        if not route_via_python:
            if route_via_nrpe:
                use_command = "nrpe_query host=127.0.0.1 port=%d command=CheckOK" % self.nrpe_port
            else:
                use_command = "CheckOK"

        self.conf.set_string(default_path, "command", use_command)
        self.conf.set_string(default_path, "interval", "5s")
        log_debug("Adding %d checks" % int(check_per_second * 5))
        for i in range(1, int(check_per_second * 5) + 1):

            alias = "stress_python_%i" % i
            self.conf.set_string("%s/schedules" % (self.sched_base_path), alias, use_command)

        self.conf.save()
Beispiel #37
0
 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)
Beispiel #38
0
	def generate_rst(self, dir):
		global all_samples
		renderer = self.renderer
		docs = {}
		root = self.get_info()
		import_commands = []
		import_config = ""
		
		i = 0
		commands = []
		for (module,minfo) in root.plugins.iteritems():
			i=i+1
			log_debug('Processing module: %d of %d [%s]'%(i, len(root.plugins), module))
			string = renderer.page_header('module', module)
			string += renderer.obj_anchor('module', module, minfo.info.description)
			string += renderer.title(0, ':module:`%s` --- %s'%(module, minfo.info.title))
			string += renderer.para(minfo.info.description)

			queries = []
			for (c,cinfo) in sorted(root.commands.iteritems()):
				if module in cinfo.info.plugin:
					queries.append([renderer.obj_link('query', c), cinfo.info.description.split('\n')[0]])
			if queries:
				queries.insert(0, ['Command', 'Description'])
				string += renderer.heading('Queries (Overview)', 'A list of all avalible queries (check commands)')
				string += renderer.table(queries)
				
			table = []
			for (c,cinfo) in sorted(root.aliases.iteritems()):
				if module in cinfo.info.plugin:
					if cinfo.info.description.startswith('Alternative name for:'):
						command = cinfo.info.description[22:]
						table.append([c, renderer.obj_link('query', command), cinfo.info.title])
					else:
						table.append([c, '', cinfo.info.title])
			if table:
				table.insert(0, ['Alias', 'Command', 'Description'])
				string += renderer.heading('Aliases', 'A list of all short hand aliases for queries (check commands)')
				string += renderer.table(table)

			string += renderer.para('Commands (executable)', "**TODO:** Add command list")

			config_table = self.generate_rst_config_table(root.paths, module)
			if config_table:
				string += renderer.heading('Configuration (Overview)', 'A list of all configuration options')
				string += config_table
				
			if queries:
				string += renderer.title(1, 'Queries')
				string += renderer.para('A quick reference for all avalible queries (check commands) in the %s module.'%module)
				for (c,cinfo) in root.commands.iteritems():
					if module in cinfo.info.plugin:
						string += self.generate_rst_command_details(c, cinfo, module, '%s/reference/%s'%(dir, module))

			if config_table:
				string += renderer.title(1, 'Configuration')
				string += renderer.para('A quick reference for all avalible configuration options in the %s module.'%module)
				string += self.generate_rst_config_details(root.paths, module)
			
			renderer.serialize(string, '%s/reference/%s.rst'%(dir, module))
			commands.append('%s.rst'%module)

		string = renderer.page_header('samples', 'TODO')
		string += renderer.title(0, 'All samples')
		string += renderer.para('All samples')
		mods = set(map(lambda (m, c, f):m, all_samples))
		for m1 in mods:
			string += renderer.title(1, m1)
			string += renderer.para('All samples for module: :module:`%s`'%m1)
			for (m2, c, f) in all_samples:
				if m1 == m2:
					string += renderer.title(2, c)
					string += renderer.para('All samples for command: :query:`%s.%s`'%(m1, c))
					string += ".. include:: %s\n\n"%f
		renderer.serialize(string, '%s/reference/all_samples.rst'%dir)
		
		
		all_config = self.generate_rst_config_table(root.paths)
		#renderer.serialize(all_config, '%s/reference/config.rst'%dir)
			
		string = """Modules
=======

Contents:

.. toctree::
   :maxdepth: 3

"""
		for c in sorted(commands):
			string += '   %s\n'%c
		string += '   all_samples.rst\n'
		renderer.serialize(string, '%s/reference/index.rst'%dir)
Beispiel #39
0
 def teardown(self):
     for state in ['OK', 'WARN', 'CRIT', 'LONG']:
         log_debug("schtasks.exe /Delete /TN NSCPSample_%s /F"%state)
         check_output("schtasks.exe /Delete /TN NSCPSample_%s /F"%state)
Beispiel #40
0
 def stress_handler(channel, source, command, code, message, perf):
     instance = PythonTest.getInstance()
     instance.stress_count = instance.stress_count + 1
     log_debug('Got message %d/%d on %s' %
               (instance.stress_count, instance.noop_count, channel))
Beispiel #41
0
	def stress_handler(channel, source, command, code, message, perf):
		instance = PythonTest.getInstance()
		instance.stress_count = instance.stress_count + 1
		log_debug('Got message %d/%d on %s'%(instance.stress_count, instance.noop_count, channel))
Beispiel #42
0
    def install(self, arguments):
        global is_windows, route_via_python, route_via_nsca, use_threads

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

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

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

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

        if route_via_nrpe:
            self.conf.set_string('/modules', self.nrpe_server_alias,
                                 'NRPEServer')
            self.conf.set_string('/modules', self.nrpe_client_alias,
                                 'NRPEClient')

            # Configure NRPE Server
            self.conf.set_string('/settings/NRPE/%s' % self.nrpe_server_alias,
                                 'port', '%d' % self.nrpe_port)
            self.conf.set_string('/settings/NRPE/%s' % self.nrpe_server_alias,
                                 'allow arguments', 'true')

            # Configure NRPE Client
            self.conf.set_string(
                '/settings/NRPE/%s/targets/default' % self.nsca_client_alias,
                'address', 'nrpe://127.0.0.1:%d' % self.nrpe_port)

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

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

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

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

        use_command = self.command
        if not route_via_python:
            if route_via_nrpe:
                use_command = 'nrpe_query host=127.0.0.1 port=%d command=CheckOK' % self.nrpe_port
            else:
                use_command = 'CheckOK'

        self.conf.set_string(default_path, 'command', use_command)
        self.conf.set_string(default_path, 'interval', '5s')
        log_debug('Adding %d checks' % int(check_per_second * 5))
        for i in range(1, int(check_per_second * 5) + 1):

            alias = 'stress_python_%i' % i
            self.conf.set_string('%s/schedules' % (self.sched_base_path),
                                 alias, use_command)

        self.conf.save()
Beispiel #43
0
	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
Beispiel #44
0
 def teardown(self):
     for state in ['OK', 'WARN', 'CRIT', 'LONG']:
         log_debug("schtasks.exe /Delete /TN NSCPSample_%s /F" % state)
         check_output("schtasks.exe /Delete /TN NSCPSample_%s /F" % state)