def test_send_to_backend_liveservice(self): modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) module.ref_live = { 'service': { '55d113586376e9835e1b2fe8': { '_etag': '694909e730bf5da80f10ee386eea03d73ab9ec80', '_id': '55d46d5e6376e91e9212230e' } } } module.mapping = { 'service': {'srv1check alive': '55d113586376e9835e1b2fe8'} } data = { 'state': 'OK', 'state_type': 'HARD', 'last_check': 1440976938, 'output': 'TCP OK - 0.033 second response time on 93.93.47.83 port 22', 'long_output': '', 'perf_data': 'time=0.032536s;;;0.000000;3.000000', 'acknowledged': False, } with HTTMock(server_responses): response = module.send_to_backend('liveservice', 'srv1check alive', data) self.assertTrue(response) self.assertEqual('86bc21287a2b98708d6e3b5d148ff9b1c7cbefc5', module.ref_live['service']['55d113586376e9835e1b2fe8']['_etag'])
def test_update_service(self): data = { 'state': 'OK', 'state_type': 'HARD', 'last_chk': 1440976938, 'output': 'TCP OK - 0.033 second response time on 93.93.47.83 port 22', 'long_output': '', 'perf_data': 'time=0.032536s;;;0.000000;3.000000', 'problem_has_been_acknowledged': False, 'service_description': 'check disk', 'host_name': 'server1' } modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) with HTTMock(server_responses): # get livehosts module.get_refs('livehost') # get liveservices module.get_refs('liveservice') with HTTMock(server_responses): ret = module.update(data, 'service') reference = { 'livehost': 0, 'liveservice': 1, 'loghost': 0, 'logservice': 1 } self.assertEqual(reference, ret)
def init_livestatus(self, modconf=None, dbmodconf=None, needcache=False): self.livelogs = 'tmp/livelogs.db' + self.testid if modconf is None: modconf = Module({'module_name': 'LiveStatus', 'module_type': 'livestatus', 'port': str(50000 + os.getpid()), 'pnp_path': 'tmp/pnp4nagios_test' + self.testid, 'host': '127.0.0.1', 'socket': 'live', 'name': 'test', #? }) if dbmodconf is None: dbmodconf = Module({'module_name': 'LogStore', 'module_type': 'logstore_sqlite', 'use_aggressive_sql': "0", 'database_file': self.livelogs, 'archive_path': os.path.join(os.path.dirname(self.livelogs), 'archives'), }) modconf.modules = [dbmodconf] self.livestatus_broker = LiveStatus_broker(modconf) self.livestatus_broker.create_queues() #--- livestatus_broker.main self.livestatus_broker.log = logger # this seems to damage the logger so that the scheduler can't use it #self.livestatus_broker.log.load_obj(self.livestatus_broker) self.livestatus_broker.debug_output = [] self.livestatus_broker.modules_manager = ModulesManager('livestatus', modules_dir, []) self.livestatus_broker.modules_manager.set_modules(self.livestatus_broker.modules) # We can now output some previouly silented debug ouput self.livestatus_broker.do_load_modules() for inst in self.livestatus_broker.modules_manager.instances: if inst.properties["type"].startswith('logstore'): f = getattr(inst, 'load', None) if f and callable(f): f(self.livestatus_broker) # !!! NOT self here !!!! break for s in self.livestatus_broker.debug_output: print "errors during load", s del self.livestatus_broker.debug_output self.livestatus_broker.rg = LiveStatusRegenerator() self.livestatus_broker.datamgr = datamgr datamgr.load(self.livestatus_broker.rg) self.livestatus_broker.query_cache = LiveStatusQueryCache() if not needcache: self.livestatus_broker.query_cache.disable() self.livestatus_broker.rg.register_cache(self.livestatus_broker.query_cache) #--- livestatus_broker.main self.livestatus_broker.init() self.livestatus_broker.db = self.livestatus_broker.modules_manager.instances[0] self.livestatus_broker.livestatus = LiveStatus(self.livestatus_broker.datamgr, self.livestatus_broker.query_cache, self.livestatus_broker.db, self.livestatus_broker.pnp_path, self.livestatus_broker.from_q) #--- livestatus_broker.do_main self.livestatus_broker.db.open() if hasattr(self.livestatus_broker.db, 'prepare_log_db_table'): self.livestatus_broker.db.prepare_log_db_table()
def setUpClass(cls): # Set test mode for alignak backend os.environ['TEST_ALIGNAK_BACKEND'] = '1' os.environ['ALIGNAK_BACKEND_MONGO_DBNAME'] = 'alignak-module-backend-test' # Delete used mongo DBs print ("Deleting Alignak backend DB...") exit_code = subprocess.call( shlex.split( 'mongo %s --eval "db.dropDatabase()"' % os.environ['ALIGNAK_BACKEND_MONGO_DBNAME']) ) assert exit_code == 0 cls.p = subprocess.Popen(['uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid']) time.sleep(3) print ("Feeding backend...") exit_code = subprocess.call( shlex.split('alignak-backend-import --delete cfg/default/_main.cfg') ) assert exit_code == 0 # Start broker module modconf = Module() modconf.module_alias = "alignakbackendarbit" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.arbmodule = AlignakBackendArbiter(modconf) cls.objects = cls.arbmodule.get_objects()
def setUpClass(cls): # Set test mode for alignak backend os.environ['TEST_ALIGNAK_BACKEND'] = '1' os.environ['ALIGNAK_BACKEND_MONGO_DBNAME'] = 'alignak-module-backend-test' # Delete used mongo DBs print ("Deleting Alignak backend DB...") exit_code = subprocess.call( shlex.split( 'mongo %s --eval "db.dropDatabase()"' % os.environ[ 'ALIGNAK_BACKEND_MONGO_DBNAME']) ) assert exit_code == 0 cls.p = subprocess.Popen(['uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid']) time.sleep(3) cls.backend = Backend('http://127.0.0.1:5000') cls.backend.login("admin", "admin", "force") realms = cls.backend.get_all('realm') for cont in realms['_items']: cls.realm_all = cont['_id'] # add commands data = json.loads(open('cfg/command_ping.json').read()) data['_realm'] = cls.realm_all data_cmd_ping = cls.backend.post("command", data) data = json.loads(open('cfg/command_http.json').read()) data['_realm'] = cls.realm_all data_cmd_http = cls.backend.post("command", data) # add host data = json.loads(open('cfg/host_srv001.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all cls.data_host = cls.backend.post("host", data) # add 2 services data = json.loads(open('cfg/service_srv001_ping.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all cls.data_srv_ping = cls.backend.post("service", data) data = json.loads(open('cfg/service_srv001_http.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_http['_id'] data['_realm'] = cls.realm_all cls.data_srv_http = cls.backend.post("service", data) # Start broker module modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.brokmodule = AlignakBackendBroker(modconf)
def test_get_endpoint(self): modconf = Module() modconf.module_name = "alignakbackend" modconf.api_url = 'http://www.alignak.local:5000' module = AlignakBackendBrok(modconf) self.assertEqual('http://www.alignak.local:5000', module.url) endp = module.endpoint('liveservice?embedded={"service_description":1}') self.assertEqual('http://www.alignak.local:5000/liveservice?embedded={"service_description":1}', endp)
def test_01_connection_refused(self): # Start broker module with not allowed user modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' broker_module = AlignakBackendBroker(modconf) self.assertFalse(broker_module.backendConnection()) self.assertFalse(broker_module.logged_in)
def test_00_connection_accepted(self): # Start broker module with admin user modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' broker_module = AlignakBackendBroker(modconf) self.assertTrue(broker_module.backendConnection()) self.assertTrue(broker_module.logged_in)
def test_send_to_backend_loghost(self): modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) module.mapping = { 'host': {'srv1': '55d113586376e9835e1b2fe6'} } data = { 'state': 'OK', 'state_type': 'HARD', 'last_check': 1440976938, 'output': 'TCP OK - 0.033 second response time on 93.93.47.83 port 22', 'long_output': '', 'perf_data': 'time=0.032536s;;;0.000000;3.000000', 'acknowledged': False, } with HTTMock(server_responses): response = module.send_to_backend('loghost', 'srv1', data) self.assertTrue(response)
def test_get_refs_liveservice(self): """ Get all services :return: None """ modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) with HTTMock(server_responses): module.get_refs('liveservice') ref = { '55d4f7b26376e946db235fc4': { '_id': '55d4f8746376e946db235fc8', '_etag': 'fbf6c05750113eca669aece45198affb567ac550' }, '55d4f7be6376e946db235fc5': { '_id': '55d4f8876376e946db235fc9', '_etag': '3ed23c329f07c92fabeee465e5c4e59bc5f575f0' }, '55d4f7cc6376e946db235fc6': { '_id': '55d4faa26376e946db235fca', '_etag': 'b7c4a2563f7382ed86dac2dc975759e20be778fc' }, '55d4f7d76376e946db235fc7': { '_id': '55d4fabd6376e946db235fcb', '_etag': '9ab70e496605b755836be976d676be17a4bc6fea' } } self.assertEqual(module.ref_live['service'], ref) mapping_ref = { 'server1check disk': '55d4f7b26376e946db235fc4', 'server2check disk': '55d4f7be6376e946db235fc5', 'server3check disk': '55d4f7cc6376e946db235fc6', 'server4check disk': '55d4f7d76376e946db235fc7' } self.assertEqual(module.mapping['service'], mapping_ref)
def test_manage_brok_service_check_result(self): modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) data = { 'state': 'OK', 'state_type': 'HARD', 'last_chk': 1440976938, 'output': 'TCP OK - 0.033 second response time on 93.93.47.83 port 22', 'long_output': '', 'perf_data': 'time=0.032536s;;;0.000000;3.000000', 'problem_has_been_acknowledged': False, 'service_description': 'check disk', 'host_name': 'server1' } brok = Brok(_type='service_check_result', data=data) brok.prepare() with HTTMock(server_responses): module.manage_brok(brok) reference = { '55d4f7b26376e946db235fc4': { '_id': '55d4f8746376e946db235fc8', '_etag': 'fff582e398e47bce29e7317f25eb5068aaac3c4b' }, '55d4f7be6376e946db235fc5': { '_id': '55d4f8876376e946db235fc9', '_etag': '3ed23c329f07c92fabeee465e5c4e59bc5f575f0' }, '55d4f7cc6376e946db235fc6': { '_id': '55d4faa26376e946db235fca', '_etag': 'b7c4a2563f7382ed86dac2dc975759e20be778fc' }, '55d4f7d76376e946db235fc7': { '_id': '55d4fabd6376e946db235fcb', '_etag': '9ab70e496605b755836be976d676be17a4bc6fea' } } self.assertEqual(reference, module.ref_live['service'])
def test_manage_brok_host_check_result(self): modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) data = { 'state': 'OK', 'state_type': 'HARD', 'last_chk': 1440976938, 'output': 'TCP OK - 0.033 second response time on 93.93.47.83 port 22', 'long_output': '', 'perf_data': 'time=0.032536s;;;0.000000;3.000000', 'problem_has_been_acknowledged': False, 'host_name': 'server1' } brok = Brok(_type='host_check_result', data=data) brok.prepare() with HTTMock(server_responses): module.manage_brok(brok) reference = { '55d4a5246376e946db235fbc': { '_etag': 'fff582e398e47bce29e7317f25eb5068aaac3c4a', '_id': '55d4e5626376e946db235fc0' }, '55d4a5276376e946db235fbd': { '_etag': '3524b87876c1d457bdca7492b9bfc503f3f13b1e', '_id': '55d4e57d6376e946db235fc1' }, '55d4a52a6376e946db235fbe': { '_etag': 'a457e78fe0dc28c1b427d9b0696096fee73f4a29', '_id': '55d4e7d36376e946db235fc2' }, '55d4a52d6376e946db235fbf': { '_etag': '2b45425c497d5593bad8ef5413c84e6a0d61cc41', '_id': '55d4e8126376e946db235fc3' } } self.assertEqual(reference, module.ref_live['host'])
def test_get_refs_livehost(self): modconf = Module() modconf.module_name = "alignakbackend" module = AlignakBackendBrok(modconf) with HTTMock(server_responses): module.get_refs('livehost') ref = { '55d4a5246376e946db235fbc': { '_id': '55d4e5626376e946db235fc0', '_etag': '78462b947415c0703d5bb747e8bc1fdb0e088a3b' }, '55d4a5276376e946db235fbd': { '_id': '55d4e57d6376e946db235fc1', '_etag': '3524b87876c1d457bdca7492b9bfc503f3f13b1e' }, '55d4a52a6376e946db235fbe': { '_id': '55d4e7d36376e946db235fc2', '_etag': 'a457e78fe0dc28c1b427d9b0696096fee73f4a29' }, '55d4a52d6376e946db235fbf': { '_id': '55d4e8126376e946db235fc3', '_etag': '2b45425c497d5593bad8ef5413c84e6a0d61cc41' } } self.assertEqual(module.ref_live['host'], ref) mapping_ref = { 'server1': '55d4a5246376e946db235fbc', 'server2': '55d4a5276376e946db235fbd', 'server3': '55d4a52a6376e946db235fbe', 'server4': '55d4a52d6376e946db235fbf' } self.assertEqual(module.mapping['host'], mapping_ref)
def test_module_zzz_service_livestate(self): """Test the module /host API - service creation and livestate :return: """ self.print_header() # Obliged to call to get a self.logger... self.setup_with_file('cfg/cfg_default.cfg') self.assertTrue(self.conf_is_correct) # ----- # Provide parameters - logger configuration file (exists) # ----- # Clear logs self.clear_logs() # Create an Alignak module mod = Module({ 'module_alias': 'web-services', 'module_types': 'web-services', 'python_name': 'alignak_module_ws', # Alignak backend 'alignak_backend': 'http://127.0.0.1:5000', 'username': '******', 'password': '******', # Do not set a timestamp in the built external commands 'set_timestamp': '0', # Send a log_check_result to the alignak backend 'alignak_backend_old_lcr': '1', # Do not give feedback data 'give_feedback': '0', 'give_result': '1', # Set Arbiter address as empty to not poll the Arbiter else the test will fail! 'alignak_host': '', 'alignak_port': 7770, # Allow host/service creation 'allow_host_creation': '1', 'allow_service_creation': '1' }) # Create the modules manager for a daemon type self.modulemanager = ModulesManager('receiver', None) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) my_module = self.modulemanager.instances[0] # Clear logs self.clear_logs() # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_log_match("Trying to initialize module: web-services", 0) self.assert_log_match("Starting external module web-services", 1) self.assert_log_match( "Starting external process for module web-services", 2) self.assert_log_match("web-services is now started", 3) # Check alive self.assertIsNotNone(my_module.process) self.assertTrue(my_module.process.is_alive()) time.sleep(1) # Alignak backend # --- self.endpoint = 'http://127.0.0.1:5000' headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} # get token response = requests.post(self.endpoint + '/login', json=params, headers=headers) resp = response.json() self.token = resp['token'] self.auth = requests.auth.HTTPBasicAuth(self.token, '') # Do not allow GET request on /host - not authorized response = requests.get('http://127.0.0.1:8888/host') self.assertEqual(response.status_code, 401) session = requests.Session() # Login with username/password (real backend login) headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} response = session.post('http://127.0.0.1:8888/login', json=params, headers=headers) assert response.status_code == 200 resp = response.json() # Request to create an host - create a new host headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "template": { "_realm": 'All', "check_command": "_internal_host_up" } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested host 'new_host_for_services_0' does not exist.", u"Requested host 'new_host_for_services_0' created." ] }) # No errors! # Get new host in the backend response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_for_services_0'})}) resp = response.json() new_host_for_services_0 = resp['_items'][0] self.assertEqual('new_host_for_services_0', new_host_for_services_0['name']) # Get backend check results - no check result sent to the backend response = requests.get(self.endpoint + '/logcheckresult', auth=self.auth) resp = response.json() rl = resp['_items'] self.assertEqual(len(rl), 0) # Request to create an host - create a new service without any template data headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "services": [{ "name": "test_empty_0", # "template": { # "_realm": 'All', # "check_command": "_echo" # }, "livestate": { "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", }, "variables": { 'test1': 'string', 'test2': 1, 'test3': 5.0 }, }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested service 'new_host_for_services_0/test_empty_0' does not exist.", u"Requested service 'new_host_for_services_0/test_empty_0' created.", u"PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_empty_0;0;Output...|'counter'=1\nLong output...", u"Service 'new_host_for_services_0/test_empty_0' updated", ] }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_for_services_0'})}) resp = response.json() new_host_for_services_0 = resp['_items'][0] self.assertEqual('new_host_for_services_0', new_host_for_services_0['name']) # Get services data to confirm update response = requests.get(self.endpoint + '/service', auth=self.auth, params={ 'where': json.dumps({ 'host': new_host_for_services_0['_id'], 'name': 'test_empty_0' }) }) resp = response.json() service = resp['_items'][0] expected = {u'_TEST3': 5.0, u'_TEST2': 1, u'_TEST1': u'string'} self.assertEqual(expected, service['customs']) # Send a service livestate, no timestamp headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "services": [{ "name": "test_empty_0", "livestate": { # No timestamp in the livestate "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", } }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_empty_0;0;Output...|'counter'=1\nLong output...", ] }) # No errors! # Get backend check results - no check result sent to the backend response = requests.get(self.endpoint + '/logcheckresult', auth=self.auth) resp = response.json() rl = resp['_items'] self.assertEqual(len(rl), 0) # Send a service livestate, timestamp in the past headers = {'Content-Type': 'application/json'} now = int(time.time()) - 3600 data = { "name": "new_host_for_services_0", "services": [{ "name": "test_empty_0", "livestate": { # Timestamp in the past "timestamp": now, "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", } }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"[%d] PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_empty_0;0;Output...|'counter'=1\nLong output..." % now, ] }) # No errors! # Get backend check results - a check result was recorded in the backend response = requests.get(self.endpoint + '/logcheckresult', auth=self.auth) resp = response.json() rl = resp['_items'] # A log check result was recorded... self.assertEqual(len(rl), 1) rl = resp['_items'][0] print("LCR: %s" % rl) # ...with the correct timestamp self.assertEqual(rl['host_name'], "new_host_for_services_0") self.assertEqual(rl['service_name'], "test_empty_0") self.assertEqual(rl['last_check'], now) # Send a service livestate with a timestamp in the past but sooner than the former one now = now + 1800 data = { "name": "new_host_for_services_0", "services": [{ "name": "test_empty_0", "livestate": { # Timestamp in the past "timestamp": now, "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", } }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"[%d] PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_empty_0;0;Output...|'counter'=1\nLong output..." % now, ] }) # No errors! # Get backend check results - a check result was recorded in the backend response = requests.get(self.endpoint + '/logcheckresult', auth=self.auth) resp = response.json() rl = resp['_items'] # A log check result was recorded... self.assertEqual(len(rl), 2) rl = resp['_items'][1] print("LCR: %s" % rl) # ...with the correct timestamp self.assertEqual(rl['host_name'], "new_host_for_services_0") self.assertEqual(rl['service_name'], "test_empty_0") self.assertEqual(rl['last_check'], now) # Logout response = session.get('http://127.0.0.1:8888/logout') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'OK') self.assertEqual(result['_result'], 'Logged out') self.modulemanager.stop_all()
# Special Livestatus module opening since the module rename #from alignak.modules.livestatus import module as livestatus_broker livestatus_broker = modulesctx.get_module('livestatus') LiveStatus_broker = livestatus_broker.LiveStatus_broker LiveStatus = livestatus_broker.LiveStatus LiveStatusRegenerator = livestatus_broker.LiveStatusRegenerator LiveStatusQueryCache = livestatus_broker.LiveStatusQueryCache LiveStatusClientThread = livestatus_broker.LiveStatusClientThread Logline = livestatus_broker.Logline LiveStatusLogStoreMongoDB = modulesctx.get_module('logstore-mongodb').LiveStatusLogStoreMongoDB LiveStatusLogStoreSqlite = modulesctx.get_module('logstore-sqlite').LiveStatusLogStoreSqlite livestatus_modconf = Module() livestatus_modconf.module_name = "livestatus" livestatus_modconf.module_type = livestatus_broker.properties['type'] livestatus_modconf.properties = livestatus_broker.properties.copy() class AlignakModulesTest(AlignakTest): def do_load_modules(self): self.modules_manager.load_and_init() self.log.log("I correctly loaded the modules: [%s]" % (','.join([inst.get_name() for inst in self.modules_manager.instances]))) def update_broker(self, dodeepcopy=False): # The brok should be manage in the good order ids = self.sched.brokers['Default-Broker']['broks'].keys()
def setUpClass(cls): # Set test mode for alignak backend os.environ['TEST_ALIGNAK_BACKEND'] = '1' os.environ['ALIGNAK_BACKEND_MONGO_DBNAME'] = 'alignak-module-backend-test' # Delete used mongo DBs print ("Deleting Alignak backend DB...") exit_code = subprocess.call( shlex.split( 'mongo %s --eval "db.dropDatabase()"' % os.environ['ALIGNAK_BACKEND_MONGO_DBNAME']) ) assert exit_code == 0 cls.p = subprocess.Popen(['uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid']) time.sleep(3) cls.backend = Backend('http://127.0.0.1:5000') cls.backend.login("admin", "admin", "force") realms = cls.backend.get_all('realm') for cont in realms['_items']: cls.realm_all = cont['_id'] timeperiods = cls.backend.get_all('timeperiod') for tp in timeperiods['_items']: if tp['name'] == '24x7': timeperiods_id = tp['_id'] # add commands data = json.loads(open('cfg/command_ping.json').read()) data['_realm'] = cls.realm_all data_cmd_ping = cls.backend.post("command", data) data = json.loads(open('cfg/command_http.json').read()) data['_realm'] = cls.realm_all data_cmd_http = cls.backend.post("command", data) # add user data = {'name': 'jeronimo', 'host_notification_period': timeperiods_id, 'service_notification_period': timeperiods_id, '_realm': cls.realm_all} data_user_jeronimo = cls.backend.post("user", data) # add usergroup data = {'name': 'admins', '_realm': cls.realm_all, 'users': [data_user_jeronimo['_id']]} data_usergroup = cls.backend.post("usergroup", data) # add host template data = json.loads(open('cfg/host_srvtemplate.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all cls.data_host = cls.backend.post("host", data) # add host data = json.loads(open('cfg/host_srv001.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_host = cls.backend.post("host", data) # add service ping data = json.loads(open('cfg/service_srv001_ping.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_srv_ping = cls.backend.post("service", data) # Add hostgroup data = {'name': 'allmyhosts', '_realm': cls.realm_all, 'hosts': [cls.data_host['_id']]} cls.backend.post("hostgroup", data) # add service http data = json.loads(open('cfg/service_srv001_http.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_http['_id'] data['_realm'] = cls.realm_all data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_srv_http = cls.backend.post("service", data) # Add some realms data = { 'name': 'All-A', '_parent': cls.realm_all } realm_a = cls.backend.post("realm", data) data = { 'name': 'All-B', '_parent': cls.realm_all } cls.backend.post("realm", data) data = { 'name': 'All-A-1', '_parent': realm_a['_id'] } cls.backend.post("realm", data) # Start broker module modconf = Module() modconf.module_alias = "alignakbackendarbit" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.arbmodule = AlignakBackendArbiter(modconf) cls.objects = cls.arbmodule.get_objects()
def setUpClass(cls): # Set test mode for alignak backend os.environ['TEST_ALIGNAK_BACKEND'] = '1' os.environ[ 'ALIGNAK_BACKEND_MONGO_DBNAME'] = 'alignak-module-backend-test' # Delete used mongo DBs print("Deleting Alignak backend DB...") exit_code = subprocess.call( shlex.split('mongo %s --eval "db.dropDatabase()"' % os.environ['ALIGNAK_BACKEND_MONGO_DBNAME'])) assert exit_code == 0 cls.p = subprocess.Popen([ 'uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid' ]) time.sleep(3) cls.backend = Backend('http://127.0.0.1:5000') cls.backend.login("admin", "admin", "force") realms = cls.backend.get_all('realm') for cont in realms['_items']: cls.realm_all = cont['_id'] # add commands data = json.loads(open('cfg/command_ping.json').read()) data['_realm'] = cls.realm_all data_cmd_ping = cls.backend.post("command", data) data = json.loads(open('cfg/command_http.json').read()) data['_realm'] = cls.realm_all data_cmd_http = cls.backend.post("command", data) # add host data = json.loads(open('cfg/host_srv001.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all cls.data_host = cls.backend.post("host", data) # add 2 services data = json.loads(open('cfg/service_srv001_ping.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all cls.data_srv_ping = cls.backend.post("service", data) data = json.loads(open('cfg/service_srv001_http.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_http['_id'] data['_realm'] = cls.realm_all cls.data_srv_http = cls.backend.post("service", data) users = cls.backend.get_all('user') cls.user_id = users['_items'][0]['_id'] # Start broker module modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.brokmodule = AlignakBackendBroker(modconf)
def test_module_zzz_service_creation(self): """Test the module /host API - service creation :return: """ self.print_header() # Obliged to call to get a self.logger... self.setup_with_file('cfg/cfg_default.cfg') self.assertTrue(self.conf_is_correct) # ----- # Provide parameters - logger configuration file (exists) # ----- # Clear logs self.clear_logs() # Create an Alignak module mod = Module({ 'module_alias': 'web-services', 'module_types': 'web-services', 'python_name': 'alignak_module_ws', # Alignak backend 'alignak_backend': 'http://127.0.0.1:5000', 'username': '******', 'password': '******', # Do not set a timestamp in the built external commands 'set_timestamp': '0', 'give_result': '1', 'give_feedback': '1', # Errors for unknown host/service 'ignore_unknown_host': '0', 'ignore_unknown_service': '0', # Set Arbiter address as empty to not poll the Arbiter else the test will fail! 'alignak_host': '', 'alignak_port': 7770, # Allow host/service creation 'allow_host_creation': '1', 'allow_service_creation': '1' }) # Create the modules manager for a daemon type self.modulemanager = ModulesManager('receiver', None) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) my_module = self.modulemanager.instances[0] # Clear logs self.clear_logs() # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_log_match("Trying to initialize module: web-services", 0) self.assert_log_match("Starting external module web-services", 1) self.assert_log_match( "Starting external process for module web-services", 2) self.assert_log_match("web-services is now started", 3) # Check alive self.assertIsNotNone(my_module.process) self.assertTrue(my_module.process.is_alive()) time.sleep(1) # Do not allow GET request on /host - not authorized response = requests.get('http://127.0.0.1:8888/host') self.assertEqual(response.status_code, 401) session = requests.Session() # Login with username/password (real backend login) headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} response = session.post('http://127.0.0.1:8888/login', json=params, headers=headers) assert response.status_code == 200 resp = response.json() # Request to create an host - create a new host headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "template": { "_realm": 'All', "check_command": "_internal_host_up" } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested host 'new_host_for_services_0' does not exist.", u"Requested host 'new_host_for_services_0' created." ], u'_feedback': { u'name': u'new_host_for_services_0' } }) # No errors! # Request to create an host - create a new service without any template data headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "services": [{ "name": "test_empty_0", # "template": { # "_realm": 'All', # "check_command": "_echo" # }, "livestate": { "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", }, "variables": { 'test1': 'string', 'test2': 1, 'test3': 5.0 }, }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested service 'new_host_for_services_0/test_empty_0' does not exist.", u"Requested service 'new_host_for_services_0/test_empty_0' created.", u"PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_empty_0;0;Output...|'counter'=1\nLong output...", u"Service 'new_host_for_services_0/test_empty_0' updated", ], u'_feedback': { u'name': u'new_host_for_services_0' } }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_for_services_0'})}) resp = response.json() new_host_for_services_0 = resp['_items'][0] self.assertEqual('new_host_for_services_0', new_host_for_services_0['name']) self.assertEqual([], new_host_for_services_0['_templates']) self.assertEqual({}, new_host_for_services_0['customs']) # Get services data to confirm update response = requests.get(self.endpoint + '/service', auth=self.auth, params={ 'where': json.dumps({ 'host': new_host_for_services_0['_id'], 'name': 'test_empty_0' }) }) resp = response.json() service = resp['_items'][0] # The service still had a variable _CUSTNAME and it inherits from the host variables expected = {u'_TEST3': 5.0, u'_TEST2': 1, u'_TEST1': u'string'} self.assertEqual(expected, service['customs']) # Request to create an host - create a new service for the new host headers = {'Content-Type': 'application/json'} data = { "name": "new_host_for_services_0", "services": [{ "name": "test_ok_0", "template": { "_realm": 'All', "check_command": "_echo", "alias": "My service...", "check_period": "24x7" }, "livestate": { "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", }, "variables": { 'test1': 'string', 'test2': 1, 'test3': 5.0 }, }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested service 'new_host_for_services_0/test_ok_0' does not exist.", u"Requested service 'new_host_for_services_0/test_ok_0' created.", u"PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_ok_0;0;Output...|'counter'=1\nLong output...", u"Service 'new_host_for_services_0/test_ok_0' updated", ], u'_feedback': { u'name': u'new_host_for_services_0' } }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_for_services_0'})}) resp = response.json() new_host_for_services_0 = resp['_items'][0] self.assertEqual('new_host_for_services_0', new_host_for_services_0['name']) self.assertEqual([], new_host_for_services_0['_templates']) self.assertEqual({}, new_host_for_services_0['customs']) # Get services data to confirm update response = requests.get(self.endpoint + '/service', auth=self.auth, params={ 'where': json.dumps({ 'host': new_host_for_services_0['_id'], 'name': 'test_ok_0' }) }) resp = response.json() service = resp['_items'][0] # The service still had a variable _CUSTNAME and it inherits from the host variables expected = {u'_TEST3': 5.0, u'_TEST2': 1, u'_TEST1': u'string'} self.assertEqual(expected, service['customs']) # Create a new service with a template and update service livestate and data data = { "name": "new_host_for_services_0", "services": [{ "name": "test_ok_1", "template": { "_realm": 'All', "check_command": "_echo", "_templates": ["generic-service"] }, "livestate": { "state": "OK", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", }, "variables": { 'test1': 'string', 'test2': 1, 'test3': 5.0 }, }] } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_for_services_0 is alive :)', u"Requested service 'new_host_for_services_0/test_ok_1' does not exist.", u"Requested service 'new_host_for_services_0/test_ok_1' created.", u"PROCESS_SERVICE_CHECK_RESULT;new_host_for_services_0;test_ok_1;0;Output...|'counter'=1\nLong output...", u"Service 'new_host_for_services_0/test_ok_1' updated", ], u'_feedback': { u'name': u'new_host_for_services_0' } }) # No errors! # Get new service to confirm creation response = session.get( 'http://127.0.0.1:5000/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_for_services_0'})}) resp = response.json() new_host_for_services_0 = resp['_items'][0] self.assertEqual('new_host_for_services_0', new_host_for_services_0['name']) self.assertEqual([], new_host_for_services_0['_templates']) self.assertEqual({}, new_host_for_services_0['customs']) # Get services data to confirm update response = requests.get('http://127.0.0.1:5000/service', auth=self.auth, params={ 'where': json.dumps({ 'host': new_host_for_services_0['_id'], 'name': 'test_ok_1' }) }) resp = response.json() service = resp['_items'][0] # The service still had a variable _CUSTNAME and it inherits from the host variables expected = {u'_TEST3': 5.0, u'_TEST2': 1, u'_TEST1': u'string'} self.assertEqual(expected, service['customs']) # Logout response = session.get('http://127.0.0.1:8888/logout') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'OK') self.assertEqual(result['_result'], 'Logged out') self.modulemanager.stop_all()
def test_module_zzz_host_creation(self): """Test the module /host API - host creation :return: """ self.print_header() # Obliged to call to get a self.logger... self.setup_with_file('cfg/cfg_default.cfg') self.assertTrue(self.conf_is_correct) # ----- # Provide parameters - logger configuration file (exists) # ----- # Clear logs self.clear_logs() # Create an Alignak module mod = Module({ 'module_alias': 'web-services', 'module_types': 'web-services', 'python_name': 'alignak_module_ws', # Alignak backend 'alignak_backend': 'http://127.0.0.1:5000', 'username': '******', 'password': '******', # Do not set a timestamp in the built external commands 'set_timestamp': '0', 'give_result': '1', 'give_feedback': '1', # Errors for unknown host/service 'ignore_unknown_host': '0', 'ignore_unknown_service': '0', # Set Arbiter address as empty to not poll the Arbiter else the test will fail! 'alignak_host': '', 'alignak_port': 7770, # Allow host/service creation 'allow_host_creation': '1', 'allow_service_creation': '1' }) # Create the modules manager for a daemon type self.modulemanager = ModulesManager('receiver', None) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) my_module = self.modulemanager.instances[0] # Clear logs self.clear_logs() # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_log_match("Trying to initialize module: web-services", 0) self.assert_log_match("Starting external module web-services", 1) self.assert_log_match( "Starting external process for module web-services", 2) self.assert_log_match("web-services is now started", 3) # Check alive self.assertIsNotNone(my_module.process) self.assertTrue(my_module.process.is_alive()) time.sleep(1) # Do not allow GET request on /host - not authorized response = requests.get('http://127.0.0.1:8888/host') self.assertEqual(response.status_code, 401) session = requests.Session() # Login with username/password (real backend login) headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} response = session.post('http://127.0.0.1:8888/login', json=params, headers=headers) assert response.status_code == 200 resp = response.json() # Request to create an host - no provided data headers = {'Content-Type': 'application/json'} data = { "name": "new_host_10", } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_10 is alive :)', u"Requested host 'new_host_10' does not exist.", u"Requested host 'new_host_10' created." ], u'_feedback': { u'name': u'new_host_10' } }) # Host created with default check_command and in default user realm # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_10'})}) resp = response.json() new_host_10 = resp['_items'][0] self.assertEqual('new_host_10', new_host_10['name']) self.assertEqual([], new_host_10['_templates']) self.assertEqual({}, new_host_10['customs']) # Request to create an host - host still existing headers = {'Content-Type': 'application/json'} data = { "name": "new_host_10", } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [u'new_host_10 is alive :)'], u'_feedback': { u'name': u'new_host_10' } }) # The host already exists, returns an host alive ;) # Request to create an host headers = {'Content-Type': 'application/json'} data = { "name": "new_host_1", "template": { # "_realm": 'All', # "check_command": "unknown" "alias": "My host...", "check_period": "24x7" } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_1 is alive :)', u"Requested host 'new_host_1' does not exist.", u"Requested host 'new_host_1' created." ], u'_feedback': { u'name': u'new_host_1' } }) # Host created, even if check_command does not exist, it uses the default check_command! # Request to create an host - host created with specified realm and check_command headers = {'Content-Type': 'application/json'} data = { "name": "new_host_2", "template": { "_realm": 'All', "check_command": "_internal_host_up" } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_2 is alive :)', u"Requested host 'new_host_2' does not exist.", u"Requested host 'new_host_2' created." ], u'_feedback': { u'name': u'new_host_2' } }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_2'})}) resp = response.json() new_host_2 = resp['_items'][0] self.assertEqual('new_host_2', new_host_2['name']) self.assertEqual([], new_host_2['_templates']) self.assertEqual({}, new_host_2['customs']) # Create a new host with a template and Update host livestate (heartbeat / host is alive): livestate data = { "name": "new_host_3", "template": { "_realm": 'All', "check_command": "_internal_host_up", "_templates": ["generic-host"] }, "livestate": { "state": "UP", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_3 is alive :)', u"Requested host 'new_host_3' does not exist.", u"Requested host 'new_host_3' created.", u"PROCESS_HOST_CHECK_RESULT;new_host_3;0;Output...|'counter'=1\nLong output...", ], u'_feedback': { u'name': u'new_host_3' } }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_3'})}) resp = response.json() new_host_3 = resp['_items'][0] self.assertEqual('new_host_3', new_host_3['name']) self.assertNotEqual([], new_host_3['_templates']) self.assertEqual({'_TEMPLATE': 'generic'}, new_host_3['customs']) # Create a new host with a template and no _realm and Update host livestate (heartbeat / host is alive): livestate data = { "name": "new_host_4", "template": { "_templates": ["generic-host"] }, "livestate": { "state": "UP", "output": "Output...", "long_output": "Long output...", "perf_data": "'counter'=1", } } self.assertEqual(my_module.received_commands, 0) response = session.patch('http://127.0.0.1:8888/host', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { u'_status': u'OK', u'_result': [ u'new_host_4 is alive :)', u"Requested host 'new_host_4' does not exist.", u"Requested host 'new_host_4' created.", u"PROCESS_HOST_CHECK_RESULT;new_host_4;0;Output...|'counter'=1\nLong output...", ], u'_feedback': { u'name': u'new_host_4' } }) # No errors! # Get new host to confirm creation response = requests.get( self.endpoint + '/host', auth=self.auth, params={'where': json.dumps({'name': 'new_host_4'})}) resp = response.json() new_host_4 = resp['_items'][0] self.assertEqual('new_host_4', new_host_4['name']) self.assertNotEqual([], new_host_4['_templates']) self.assertEqual({'_TEMPLATE': 'generic'}, new_host_4['customs']) # Logout response = session.get('http://127.0.0.1:8888/logout') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'OK') self.assertEqual(result['_result'], 'Logged out') self.modulemanager.stop_all()
def test_modulemanager(self): """ Module manager manages its modules Test if the module manager manages correctly all the modules :return: """ self.print_header() self.setup_with_file('cfg/cfg_default_with_modules.cfg') assert self.conf_is_correct time_hacker.set_real_time() # Create an Alignak module mod = Module({ 'module_alias': 'mod-example', 'module_types': 'example', 'python_name': 'alignak_module_example' }) # Create the modules manager for a daemon type self.modulemanager = ModulesManager('receiver', None) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) # Loading module logs self.assert_any_log_match( re.escape( "Importing Python module 'alignak_module_example' for Example..." )) self.assert_any_log_match( re.escape( "Module properties: {'daemons': ['arbiter', 'broker', 'scheduler', 'poller', " "'receiver', 'reactionner'], 'phases': ['configuration', 'late_configuration', " "'running', 'retention'], 'type': 'example', 'external': True}" )) self.assert_any_log_match( re.escape("Imported 'alignak_module_example' for Example")) self.assert_any_log_match( re.escape( "Give an instance of alignak_module_example for alias: Example" )) self.assert_any_log_match( re.escape("I correctly loaded my modules: [Example]")) my_module = self.modulemanager.instances[0] assert my_module.is_external # Get list of not external modules assert [] == self.modulemanager.get_internal_instances() for phase in [ 'configuration', 'late_configuration', 'running', 'retention' ]: assert [] == self.modulemanager.get_internal_instances(phase) # Get list of external modules assert [my_module] == self.modulemanager.get_external_instances() for phase in [ 'configuration', 'late_configuration', 'running', 'retention' ]: assert [my_module ] == self.modulemanager.get_external_instances(phase) # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_any_log_match( re.escape("Starting external module mod-example")) self.assert_any_log_match( re.escape("Starting external process for module mod-example")) self.assert_any_log_match( re.escape("mod-example is now started (pid=")) # Check alive assert my_module.process is not None assert my_module.process.is_alive() # Kill the external module (normal stop is .stop_process) my_module.kill() time.sleep(0.1) # Should be dead (not normally stopped...) but we still know a process for this module! assert my_module.process is not None # Stopping module logs self.assert_any_log_match(re.escape("Killing external module ")) self.assert_any_log_match(re.escape("External module killed")) # Nothing special ... self.modulemanager.check_alive_instances() # Try to restart the dead modules self.modulemanager.try_to_restart_deads() # In fact it's too early, so it won't do it # Here the inst should still be dead assert not my_module.process.is_alive() # So we lie my_module.last_init_try = -5 self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() # In fact it's too early, so it won't do it # Here the inst should be alive again assert my_module.process.is_alive() # should be nothing more in to_restart of # the module manager assert [] == self.modulemanager.to_restart # Now we look for time restart so we kill it again my_module.kill() time.sleep(0.2) assert not my_module.process.is_alive() # Should be too early self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() assert not my_module.process.is_alive() # We lie for the test again my_module.last_init_try = -5 self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() # Here the inst should be alive again assert my_module.process.is_alive() # And we clear all now self.modulemanager.stop_all() # Stopping module logs self.assert_any_log_match(re.escape("I'm stopping module "))
def setUp(self): from alignak.objects.module import Module self.item = Module()
def test_module_zzz_event(self): """Test the module /event endpoint :return: """ self.print_header() # Obliged to call to get a self.logger... self.setup_with_file('cfg/cfg_default.cfg') self.assertTrue(self.conf_is_correct) # ----- # Provide parameters - logger configuration file (exists) # ----- # Clear logs self.clear_logs() # Create an Alignak module mod = Module({ 'module_alias': 'web-services', 'module_types': 'web-services', 'python_name': 'alignak_module_ws', # Alignak backend 'alignak_backend': 'http://127.0.0.1:5000', 'username': '******', 'password': '******', # Set Arbiter address as empty to not poll the Arbiter else the test will fail! 'alignak_host': '', 'alignak_port': 7770, }) # Create the modules manager for a daemon type self.modulemanager = ModulesManager('receiver', None) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) my_module = self.modulemanager.instances[0] # Clear logs self.clear_logs() # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_log_match("Trying to initialize module: web-services", 0) self.assert_log_match("Starting external module web-services", 1) self.assert_log_match( "Starting external process for module web-services", 2) self.assert_log_match("web-services is now started", 3) # Check alive self.assertIsNotNone(my_module.process) self.assertTrue(my_module.process.is_alive()) time.sleep(1) # --- # Prepare the backend content... self.endpoint = 'http://127.0.0.1:5000' headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} # get token response = requests.post(self.endpoint + '/login', json=params, headers=headers) resp = response.json() self.token = resp['token'] self.auth = requests.auth.HTTPBasicAuth(self.token, '') # Get default realm response = requests.get(self.endpoint + '/realm', auth=self.auth) resp = response.json() self.realm_all = resp['_items'][0]['_id'] # --- # Do not allow GET request on /event - not yet authorized response = requests.get('http://127.0.0.1:8888/event') self.assertEqual(response.status_code, 401) session = requests.Session() # Login with username/password (real backend login) headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} response = session.post('http://127.0.0.1:8888/login', json=params, headers=headers) assert response.status_code == 200 resp = response.json() # Do not allow GET request on /event response = session.get('http://127.0.0.1:8888/event') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'ERR') self.assertEqual(result['_issues'], ['You must only POST on this endpoint.']) self.assertEqual(my_module.received_commands, 0) # You must have parameters when POSTing on /event headers = {'Content-Type': 'application/json'} data = {} response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'ERR') self.assertEqual(result['_issues'], ['You must POST parameters on this endpoint.']) self.assertEqual(my_module.received_commands, 0) # Notify an host event - missing host or service headers = {'Content-Type': 'application/json'} data = {"fake": ""} self.assertEqual(my_module.received_commands, 0) response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'ERR', '_issues': ['Missing host and/or service parameter.'] }) # Notify an host event - missing comment headers = {'Content-Type': 'application/json'} data = { "host": "test_host", } response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'ERR', '_issues': [ 'Missing comment. If you do not have any comment, ' 'do not comment ;)' ] }) # Notify an host event - default author headers = {'Content-Type': 'application/json'} data = {"host": "test_host", "comment": "My comment"} response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'OK', '_result': [u'ADD_HOST_COMMENT;test_host;1;' u'Alignak WS;My comment'] }) # Notify an host event - default author and timestamp headers = {'Content-Type': 'application/json'} data = { "timestamp": 1234567890, "host": "test_host", "author": "Me", "comment": "My comment" } response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'OK', '_result': [ u'[1234567890] ADD_HOST_COMMENT;test_host;1;' u'Me;My comment' ] }) # Notify a service event - default author headers = {'Content-Type': 'application/json'} data = { "host": "test_host", "service": "test_service", "comment": "My comment" } response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'OK', '_result': [ u'ADD_SVC_COMMENT;test_host;test_service;1;' u'Alignak WS;My comment' ] }) # Notify a service event - default author and timestamp headers = {'Content-Type': 'application/json'} data = { "timestamp": 1234567890, "host": "test_host", "service": "test_service", "author": "Me", "comment": "My comment" } response = session.post('http://127.0.0.1:8888/event', json=data, headers=headers) self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual( result, { '_status': 'OK', '_result': [ u'[1234567890] ADD_SVC_COMMENT;test_host;test_service;' u'1;Me;My comment' ] }) # Get history to confirm that backend is ready # --- response = session.get(self.endpoint + '/history', auth=self.auth, params={ "sort": "-_id", "max_results": 25, "page": 1 }) resp = response.json() print("Response: %s" % resp) for item in resp['_items']: assert item['type'] in ['webui.comment'] # Got 4 notified events, so we get 4 comments in the backend self.assertEqual(len(resp['_items']), 4) # --- # Logout response = session.get('http://127.0.0.1:8888/logout') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'OK') self.assertEqual(result['_result'], 'Logged out') self.modulemanager.stop_all()
def _get_history(self, username, password): # Create an Alignak module mod = Module({ 'module_alias': 'web-services', 'module_types': 'web-services', 'python_name': 'alignak_module_ws', # Set Arbiter address as empty to not poll the Arbiter else the test will fail! 'alignak_host': '', 'alignak_port': 7770, # Alignak backend URL 'alignak_backend': 'http://127.0.0.1:5000', 'username': '******', 'password': '******', # Set module to listen on all interfaces 'host': '0.0.0.0', 'port': 8888, # Activate CherryPy file logs 'log_access': '/tmp/alignak-module-ws-access.log', 'log_error': '/tmp/alignak-module-ws-error.log', 'log_level': 'DEBUG' }) # Create a receiver daemon args = {'env_file': '', 'daemon_name': 'receiver-master'} self._receiver_daemon = Receiver(**args) # Create the modules manager for the daemon self.modulemanager = ModulesManager(self._receiver_daemon) # Load an initialize the modules: # - load python module # - get module properties and instances self.modulemanager.load_and_init([mod]) my_module = self.modulemanager.instances[0] # Clear logs self.clear_logs() # Start external modules self.modulemanager.start_external_instances() # Starting external module logs self.assert_log_match("Trying to initialize module: web-services", 0) self.assert_log_match("Starting external module web-services", 1) self.assert_log_match( "Starting external process for module web-services", 2) self.assert_log_match("web-services is now started", 3) time.sleep(1) # Check alive self.assertIsNotNone(my_module.process) self.show_logs() print("Instances: %s" % self.modulemanager.instances) print("My module: %s" % my_module.__dict__) # This test if raising an error whereas the module is really living ! # self.assertTrue(my_module.process.is_alive()) time.sleep(1) # --- # Prepare the backend content... self.endpoint = 'http://127.0.0.1:5000' headers = {'Content-Type': 'application/json'} params = {'username': '******', 'password': '******'} # get token response = requests.post(self.endpoint + '/login', json=params, headers=headers) resp = response.json() self.token = resp['token'] self.auth = requests.auth.HTTPBasicAuth(self.token, '') # Get default realm response = requests.get(self.endpoint + '/realm', auth=self.auth) resp = response.json() self.realm_all = resp['_items'][0]['_id'] # --- # ------------------------------------------- # Add a check result for an host data = { "last_check": 1496332753, "host": self.rh[0]['_id'], "service": None, 'acknowledged': False, 'state_id': 0, 'state': 'UP', 'state_type': 'HARD', 'last_state_id': 0, 'last_state': 'UP', 'last_state_type': 'HARD', 'state_changed': False, 'latency': 0, 'execution_time': 0.12, 'output': 'Check output', 'long_output': 'Check long_output', 'perf_data': 'perf_data', "_realm": self.realm_all } response = requests.post(self.endpoint + '/logcheckresult', json=data, headers=headers, auth=self.auth) resp = response.json() self.assertEqual(resp['_status'], 'OK') # ------------------------------------------- # Add a check result for a service data = { "last_check": 1496332754, "host": self.rh[0]['_id'], "service": self.rs[0]['_id'], 'acknowledged': False, 'state_id': 0, 'state': 'UP', 'state_type': 'HARD', 'last_state_id': 0, 'last_state': 'UP', 'last_state_type': 'HARD', 'state_changed': False, 'latency': 0, 'execution_time': 0.12, 'output': 'Check output', 'long_output': 'Check long_output', 'perf_data': 'perf_data', "_realm": self.realm_all } response = requests.post(self.endpoint + '/logcheckresult', json=data, headers=headers, auth=self.auth) resp = response.json() self.assertEqual(resp['_status'], 'OK') # Add an history event data = { "host_name": "chazay", "service_name": "Processus", "user_name": "Alignak", "type": "check.result", "message": "OK[HARD] (False,False): All is ok", "_realm": self.realm_all, "_sub_realm": True } time.sleep(1) requests.post(self.endpoint + '/history', json=data, headers=headers, auth=self.auth) # Add an history event time.sleep(1) data = { "host_name": "denice", "service_name": "Zombies", "user_name": "Alignak", "type": "check.result", "message": "OK[HARD] (False,False): All is ok", "_realm": self.realm_all, "_sub_realm": True } requests.post(self.endpoint + '/history', json=data, headers=headers, auth=self.auth) # Add an history event time.sleep(1) data = { "host_name": "denice", "user_name": "Me", "type": "monitoring.alert", "message": "HOST ALERT ....", "_realm": self.realm_all, "_sub_realm": True } requests.post(self.endpoint + '/history', json=data, headers=headers, auth=self.auth) # --- # --- # Get history to confirm that backend is ready # --- response = requests.get(self.endpoint + '/history', auth=self.auth, params={ "sort": "-_id", "max_results": 25, "page": 1, 'embedded': json.dumps({"logcheckresult": 1}) }) resp = response.json() pprint(resp['_items']) self.assertEqual(len(resp['_items']), 5) # Backend real history # The commented fields are the one existing in the backend but filtered by the WS backend_real_history = [ { '_created': 'Thu, 01 Jun 2017 15:59:16 GMT', # u'_etag': u'9f07c7285b37bb3d336a96ede3d3fd2a774c4c4c', '_id': '593039d406fd4b3bf0e27d9f', # u'_links': {u'self': {u'href': u'history/593039d406fd4b3bf0e27d9f', # u'title': u'History'}}, # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:16 GMT', 'host_name': 'denice', 'message': 'HOST ALERT ....', 'type': 'monitoring.alert', 'user_name': 'Me' }, { '_created': 'Thu, 01 Jun 2017 15:59:15 GMT', # u'_etag': u'24cd486a1a28859a0177fbe15d1ead61f78f7b2c', '_id': '593039d306fd4b3bf0e27d9e', # u'_links': {u'self': {u'href': u'history/593039d306fd4b3bf0e27d9e', # u'title': u'History'}}, # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:15 GMT', 'host_name': 'denice', 'message': 'OK[HARD] (False,False): All is ok', 'service_name': 'Zombies', 'type': 'check.result', 'user_name': 'Alignak' }, { '_created': 'Thu, 01 Jun 2017 15:59:14 GMT', # u'_etag': u'4c4ee43a4fac0b91dcfddb011619007dedb1cd95', '_id': '593039d206fd4b3bf0e27d9d', # u'_links': {u'self': {u'href': u'history/593039d206fd4b3bf0e27d9d', # u'title': u'History'}}, # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:14 GMT', 'host_name': 'chazay', 'message': 'OK[HARD] (False,False): All is ok', 'service_name': 'Processus', 'type': 'check.result', 'user_name': 'Alignak' }, { '_created': 'Thu, 01 Jun 2017 15:59:13 GMT', # u'_etag': u'76dd35f575244848dd41f67ad3109cf6f1f9a33c', '_id': '593039d106fd4b3bf0e27d9c', # u'_links': {u'self': {u'href': u'history/593039d106fd4b3bf0e27d9c', # u'title': u'History'}}, # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:13 GMT', # u'host': u'593039cc06fd4b3bf0e27d90', 'host_name': 'srv001', 'logcheckresult': { '_created': 'Thu, 01 Jun 2017 15:59:13 GMT', # u'_etag': u'10a3935b1158fe4c8f62962a14b1050fef32df4b', # u'_id': u'593039d106fd4b3bf0e27d9b', # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:13 GMT', 'acknowledged': False, 'acknowledgement_type': 1, 'downtimed': False, 'execution_time': 0.12, # u'host': u'593039cc06fd4b3bf0e27d90', # u'host_name': u'srv001', 'last_check': 1496332753, 'last_state': 'UP', 'last_state_changed': 0, 'last_state_id': 0, 'last_state_type': 'HARD', 'latency': 0.0, 'long_output': 'Check long_output', 'output': 'Check output', 'passive_check': False, 'perf_data': 'perf_data', # u'service': u'593039cf06fd4b3bf0e27d98', # u'service_name': u'ping', 'state': 'UP', 'state_changed': False, 'state_id': 0, 'state_type': 'HARD' }, 'message': 'UP[HARD] (False/False): Check output', # u'service': u'593039cf06fd4b3bf0e27d98', 'service_name': 'ping', 'type': 'check.result', # u'user': None, 'user_name': 'Alignak' }, { '_created': 'Thu, 01 Jun 2017 15:59:13 GMT', # u'_etag': u'c3cd29587ad328325dc48af677b3a36157361a84', '_id': '593039d106fd4b3bf0e27d9a', # u'_links': {u'self': {u'href': u'history/593039d106fd4b3bf0e27d9a', # u'title': u'History'}}, # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:13 GMT', # u'host': u'593039cc06fd4b3bf0e27d90', 'host_name': 'srv001', 'logcheckresult': { '_created': 'Thu, 01 Jun 2017 15:59:13 GMT', # u'_etag': u'0ea4c16f1e651a02772aa2bfa83070b47e7f6531', # u'_id': u'593039d106fd4b3bf0e27d99', # u'_realm': u'593039cc06fd4b3bf0e27d88', # u'_sub_realm': True, # u'_updated': u'Thu, 01 Jun 2017 15:59:13 GMT', 'acknowledged': False, 'acknowledgement_type': 1, 'downtimed': False, 'execution_time': 0.12, # u'host': u'593039cc06fd4b3bf0e27d90', # u'host_name': u'srv001', 'last_check': 1496332754, 'last_state': 'UP', 'last_state_changed': 0, 'last_state_id': 0, 'last_state_type': 'HARD', 'latency': 0.0, 'long_output': 'Check long_output', 'output': 'Check output', 'passive_check': False, 'perf_data': 'perf_data', # u'service': None, # u'service_name': u'', 'state': 'UP', 'state_changed': False, 'state_id': 0, 'state_type': 'HARD' }, 'message': 'UP[HARD] (False/False): Check output', # u'service': None, 'service_name': '', 'type': 'check.result', # u'user': None, 'user_name': 'Alignak' } ] # --- # --- # # Directly call the module function # search = { # 'page': 1, # 'max_results': 25 # } # result = my_module.getBackendHistory(search) # print(result) # print("Page: %d, got: %d items" % (search["page"], len(result['items']))) # for item in result['items']: # print(item) # assert len(result['items']) == 5 # --- # Do not allow GET request on /alignak_logs - not yet authorized! response = requests.get(self.ws_endpoint + '/alignak_logs') self.assertEqual(response.status_code, 401) session = requests.Session() # Login with username/password (real backend login) headers = {'Content-Type': 'application/json'} params = {'username': username, 'password': password} response = session.post(self.ws_endpoint + '/login', json=params, headers=headers) assert response.status_code == 200 resp = response.json() # --- # Get the alignak default history response = session.get(self.ws_endpoint + '/alignak_logs') self.assertEqual(response.status_code, 200) result = response.json() # Remove fields that will obviously be different! for item in result['items']: del (item['_id']) del (item['_created']) # if 'logcheckresult' in item: # del (item['logcheckresult']['_created']) for item in backend_real_history: del (item['_id']) del (item['_created']) if 'logcheckresult' in item: del (item['logcheckresult']['_created']) self.assertEqual(len(result['items']), 5) # Too complex comparison!!! # self.assertEqual(backend_real_history, result['items']) # assert cmp(backend_real_history, result['items']) == 0 # --- # --- # Get the alignak default history, filter to get only check.result response = session.get(self.ws_endpoint + '/alignak_logs?search=type:check.result') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 4) # --- # --- # Get the alignak default history, filter to get only for a user response = session.get(self.ws_endpoint + '/alignak_logs?search=user_name:Alignak') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 4) response = session.get(self.ws_endpoint + '/alignak_logs?search=user_name:Me') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) # --- # --- # Get the alignak default history, filter to get only for an host response = session.get(self.ws_endpoint + '/alignak_logs?search=host_name:chazay') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(len(result['items']), 1) # Implicit host_name response = session.get(self.ws_endpoint + '/alignak_logs?search=chazay') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(len(result['items']), 1) # Unknown search field response = session.get(self.ws_endpoint + '/alignak_logs?search=name:chazay') self.assertEqual(response.status_code, 200) result = response.json() # All history items because name is not aknown search field! So we get all items... self.assertEqual(len(result['items']), 5) # Some other hosts... response = session.get(self.ws_endpoint + '/alignak_logs?search=host_name:denice') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(len(result['items']), 2) response = session.get(self.ws_endpoint + '/alignak_logs?search=host_name:srv001') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(len(result['items']), 2) # Several hosts... response = session.get( self.ws_endpoint + '/alignak_logs?search=host_name:denice host_name:srv001') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(len(result['items']), 4) # 2 for each host # Not an host... # TODO: looks that ths criteria is not correctly implemented :( # response = session.get(self.ws_endpoint + '/alignak_logs?search=host_name:!denice') # self.assertEqual(response.status_code, 200) # result = response.json() # self.assertEqual(len(result['items']), 3) # --- # --- # Get the alignak default history, NOT for an host # todo: temporarily skipped # response = requests.get(self.ws_endpoint + '/alignak_logs?search=host_name:!Chazay') # self.assertEqual(response.status_code, 200) # result = response.json() # for item in result['items']: # print(item) # self.assertEqual(len(result['items']), 2) # --- # --- # Get the alignak default history, only for a service response = session.get(self.ws_endpoint + '/alignak_logs?search=service_name:Processus') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) # --- # --- # Get the alignak default history, for an host and a service # todo multi search query to be improved! # response = session.get(self.ws_endpoint + '/alignak_logs?search="host_name:chazay service_name=Processus"') # self.assertEqual(response.status_code, 200) # result = response.json() # for item in result['items']: # print(item) # self.assertEqual(len(result['items']), 3) # --- # --- # Get the alignak default history, unknown event type response = session.get(self.ws_endpoint + '/alignak_logs?search=type:XXX') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 0) # --- # --- # Get the alignak default history, page count response = session.get(self.ws_endpoint + '/alignak_logs?start=0&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) response = session.get(self.ws_endpoint + '/alignak_logs?start=1&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) response = session.get(self.ws_endpoint + '/alignak_logs?start=2&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) response = session.get(self.ws_endpoint + '/alignak_logs?start=3&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) response = session.get(self.ws_endpoint + '/alignak_logs?start=4&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 1) # Over the limits ! response = session.get(self.ws_endpoint + '/alignak_logs?start=5&count=1') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 0) response = session.get(self.ws_endpoint + '/alignak_logs?start=50&count=50') self.assertEqual(response.status_code, 200) result = response.json() for item in result['items']: print(item) self.assertEqual(len(result['items']), 0) # --- # --- # Get the alignak history, page count greater than the number of items response = session.get(self.ws_endpoint + '/alignak_logs?start=1&count=25') self.assertEqual(response.status_code, 200) result = response.json() pprint(result) self.assertEqual(len(result['items']), 5) # Got 5 items self.assertEqual(result['_meta']['max_results'], 25) self.assertEqual(result['_meta']['page'], 1) self.assertEqual(result['_meta']['total'], 5) response = session.get(self.ws_endpoint + '/alignak_logs?start=0&count=50') self.assertEqual(response.status_code, 200) result = response.json() pprint(result) self.assertEqual(len(result['items']), 5) # Got 5 items self.assertEqual(result['_meta']['max_results'], 50) self.assertEqual(result['_meta']['page'], 1) self.assertEqual(result['_meta']['total'], 5) # --- # Logout response = session.get(self.ws_endpoint + '/logout') self.assertEqual(response.status_code, 200) result = response.json() self.assertEqual(result['_status'], 'OK') self.assertEqual(result['_result'], 'Logged out')
def test_alignak_configuration(self): """Test alignak configuration reading :return: """ # Start broker module modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' self.brokmodule = AlignakBackendBroker(modconf) # Get a program status brok brok_data = { # Some general information 'alignak_name': 'my_alignak', 'instance_id': '176064a1b30741d39452415097807ab0', 'instance_name': 'scheduler-master', # Some running information 'program_start': 1493969754, 'daemon_mode': 1, 'pid': 68989, 'last_alive': 1493970641, 'last_command_check': 1493970641, 'last_log_rotation': 1493970641, 'is_running': 1, # Some configuration parameters 'process_performance_data': True, 'passive_service_checks_enabled': True, 'event_handlers_enabled': True, 'command_file': '', 'global_host_event_handler': None, 'interval_length': 60, 'modified_host_attributes': 0, 'check_external_commands': True, 'modified_service_attributes': 0, 'passive_host_checks_enabled': True, 'global_service_event_handler': None, 'notifications_enabled': True, 'check_service_freshness': True, 'check_host_freshness': True, 'flap_detection_enabled': True, 'active_service_checks_enabled': True, 'active_host_checks_enabled': True } brok = Brok({'type': 'update_program_status', 'data': brok_data}) brok.prepare() # ------- # Configure to manage this brok (default is to ignore...) ! self.brokmodule.manage_update_program_status = True # Send program status brok self.brokmodule.manage_brok(brok) # This has created an `alignak` resource... # Now we call the Arbiter hook function to get this created configuration # Will get all the `alignak` resources because no arbiter name is defined ... fake_arb = Arbiter() self.arbmodule.hook_read_configuration(fake_arb) configuration = self.arbmodule.get_alignak_configuration() print(("Configuration: %s" % configuration)) expected = brok_data.copy() print(("Expected: %s" % expected)) expected['name'] = expected.pop('alignak_name') # Some fields are valued as default by the backend configuration.pop('_created') configuration.pop('_updated') configuration.pop('_id') configuration.pop('_etag') configuration.pop('_realm') configuration.pop('_sub_realm') configuration.pop('_links') configuration.pop('schema_version') # TODO need add this new fields in alignak brok creation for field_name in ['use_timezone', 'illegal_macro_output_chars', 'illegal_object_name_chars', 'cleaning_queues_interval', 'max_plugins_output_length', 'enable_environment_macros', 'log_initial_states', 'log_active_checks', 'log_host_retries', 'log_service_retries', 'log_passive_checks', 'log_notifications', 'log_event_handlers', 'log_external_commands', 'log_flappings', 'log_snapshots', 'enable_notifications', 'notification_timeout', 'timeout_exit_status', 'execute_host_checks', 'max_host_check_spread', 'host_check_timeout', 'check_for_orphaned_hosts', 'execute_service_checks', 'max_service_check_spread', 'service_check_timeout', 'check_for_orphaned_services', 'flap_history', 'low_host_flap_threshold', 'high_host_flap_threshold', 'low_service_flap_threshold', 'high_service_flap_threshold', 'event_handler_timeout', 'no_event_handlers_during_downtimes', 'host_perfdata_command', 'service_perfdata_command', 'accept_passive_host_checks', 'host_freshness_check_interval', 'accept_passive_service_checks', 'service_freshness_check_interval', 'additional_freshness_latency']: configuration.pop(field_name) expected['alias'] = expected['name'] expected['notes'] = '' expected['notes_url'] = '' expected['global_host_event_handler'] = str(expected['global_host_event_handler']) expected['global_service_event_handler'] = 'None' self.assertEqual(configuration, expected) # Get another program status brok brok_data = { # Some general information 'alignak_name': 'my_alignak_2', 'instance_id': '176064a1b30741d39452415097807ab0', 'instance_name': 'scheduler-master', # Some running information 'program_start': 1493969754, 'daemon_mode': 1, 'pid': 68989, 'last_alive': 1493970641, 'last_command_check': 1493970641, 'last_log_rotation': 1493970641, 'is_running': 1, # Some configuration parameters 'process_performance_data': True, 'passive_service_checks_enabled': True, 'event_handlers_enabled': True, 'command_file': '', 'global_host_event_handler': 'None', 'interval_length': 60, 'modified_host_attributes': 0, 'check_external_commands': True, 'modified_service_attributes': 0, 'passive_host_checks_enabled': True, 'global_service_event_handler': 'None', 'notifications_enabled': True, 'check_service_freshness': True, 'check_host_freshness': True, 'flap_detection_enabled': True, 'active_service_checks_enabled': True, 'active_host_checks_enabled': True } brok = Brok({'type': 'update_program_status', 'data': brok_data}) brok.prepare() # Send program status brok self.brokmodule.manage_brok(brok) # This has created an `alignak` resource... # Now we call the Arbiter hook function to get this created configuration # Get the configuration for a specific arbiter / alignak # It will be the first one created fake_arb = Arbiter(arbiter_name='my_alignak') self.arbmodule.hook_read_configuration(fake_arb) configuration = self.arbmodule.get_alignak_configuration() # Some fields are valued as default by the backend configuration.pop('_created') configuration.pop('_updated') configuration.pop('_id') configuration.pop('_etag') configuration.pop('_realm') configuration.pop('_sub_realm') configuration.pop('_links') configuration.pop('schema_version') # TODO need add this new fields in alignak brok creation for field_name in ['use_timezone', 'illegal_macro_output_chars', 'illegal_object_name_chars', 'cleaning_queues_interval', 'max_plugins_output_length', 'enable_environment_macros', 'log_initial_states', 'log_active_checks', 'log_host_retries', 'log_service_retries', 'log_passive_checks', 'log_notifications', 'log_event_handlers', 'log_external_commands', 'log_flappings', 'log_snapshots', 'enable_notifications', 'notification_timeout', 'timeout_exit_status', 'execute_host_checks', 'max_host_check_spread', 'host_check_timeout', 'check_for_orphaned_hosts', 'execute_service_checks', 'max_service_check_spread', 'service_check_timeout', 'check_for_orphaned_services', 'flap_history', 'low_host_flap_threshold', 'high_host_flap_threshold', 'low_service_flap_threshold', 'high_service_flap_threshold', 'event_handler_timeout', 'no_event_handlers_during_downtimes', 'host_perfdata_command', 'service_perfdata_command', 'accept_passive_host_checks', 'host_freshness_check_interval', 'accept_passive_service_checks', 'service_freshness_check_interval', 'additional_freshness_latency']: configuration.pop(field_name) self.assertEqual(configuration, expected)
def setUpClass(cls): # Set test mode for alignak backend os.environ['TEST_ALIGNAK_BACKEND'] = '1' os.environ[ 'ALIGNAK_BACKEND_MONGO_DBNAME'] = 'alignak-module-backend-test' # Delete used mongo DBs print("Deleting Alignak backend DB...") exit_code = subprocess.call( shlex.split('mongo %s --eval "db.dropDatabase()"' % os.environ['ALIGNAK_BACKEND_MONGO_DBNAME'])) assert exit_code == 0 cls.p = subprocess.Popen([ 'uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid' ]) time.sleep(3) cls.backend = Backend('http://127.0.0.1:5000') cls.backend.login("admin", "admin", "force") realms = cls.backend.get_all('realm') for cont in realms['_items']: cls.realm_all = cont['_id'] timeperiods = cls.backend.get_all('timeperiod') for tp in timeperiods['_items']: if tp['name'] == '24x7': timeperiods_id = tp['_id'] # add commands data = json.loads(open('cfg/command_ping.json').read()) data['_realm'] = cls.realm_all data_cmd_ping = cls.backend.post("command", data) data = json.loads(open('cfg/command_http.json').read()) data['_realm'] = cls.realm_all data_cmd_http = cls.backend.post("command", data) # add user data = { 'name': 'jeronimo', 'customs': { '_OS': 'linux', 'licence': 'free ;)' }, 'host_notification_period': timeperiods_id, 'service_notification_period': timeperiods_id, '_realm': cls.realm_all } data_user_jeronimo = cls.backend.post("user", data) # add usergroup data = { 'name': 'admins', '_realm': cls.realm_all, 'users': [data_user_jeronimo['_id']] } data_usergroup = cls.backend.post("usergroup", data) # add host template data = json.loads(open('cfg/host_srvtemplate.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all cls.data_host = cls.backend.post("host", data) # add host data = json.loads(open('cfg/host_srv001.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all data['customs'] = {'_OS': 'linux', 'licence': 'free ;)'} data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_host = cls.backend.post("host", data) # Add hostgroup data = { 'name': 'allmyhosts', '_realm': cls.realm_all, 'hosts': [cls.data_host['_id']] } cls.data_hostgroup = cls.backend.post("hostgroup", data) # add service ping data = json.loads(open('cfg/service_srv001_ping.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_srv_ping = cls.backend.post("service", data) # add service pong data = json.loads(open('cfg/service_srv001_pong.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] data['hostgroups'] = [cls.data_hostgroup['_id']] cls.data_srv_pong = cls.backend.post("service", data) # add service http data = json.loads(open('cfg/service_srv001_http.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_http['_id'] data['_realm'] = cls.realm_all data['customs'] = {'_OS': 'linux', 'licence': 'free ;)'} data['users'] = [data_user_jeronimo['_id']] data['usergroups'] = [data_usergroup['_id']] cls.data_srv_http = cls.backend.post("service", data) # Add some realms data = {'name': 'All-A', '_parent': cls.realm_all} realm_a = cls.backend.post("realm", data) data = {'name': 'All-B', '_parent': cls.realm_all} cls.backend.post("realm", data) data = {'name': 'All-A-1', '_parent': realm_a['_id']} cls.backend.post("realm", data) # Start arbiter backend module modconf = Module() modconf.module_alias = "backend_arbiter" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.arbmodule = AlignakBackendArbiter(modconf) cls.objects = cls.arbmodule.get_objects()
def setUp(self): self.maxDiff = None # Start arbiter backend module modconf = Module() modconf.module_alias = "backend_arbiter" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' self.arbmodule = AlignakBackendArbiter(modconf) self.objects = self.arbmodule.get_objects() # Start broker module modconf = Module() modconf.module_alias = "backend_broker" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' self.brokmodule = AlignakBackendBroker(modconf) # Set up the broker module self.brokmodule.get_refs()
def setUpClass(cls): """ This method: * delete mongodb database * start the backend with uwsgi * log in the backend and get the token :return: None """ # Delete used mongo DBs exit_code = subprocess.call( shlex.split( 'mongo %s --eval "db.dropDatabase()"' % 'alignak-backend') ) assert exit_code == 0 cls.p = subprocess.Popen(['uwsgi', '--plugin', 'python', '-w', 'alignakbackend:app', '--socket', '0.0.0.0:5000', '--protocol=http', '--enable-threads', '--pidfile', '/tmp/uwsgi.pid']) time.sleep(3) cls.backend = Backend('http://127.0.0.1:5000') cls.backend.login("admin", "admin", "force") realms = cls.backend.get_all('realm') for cont in realms['_items']: cls.realm_all = cont['_id'] # add commands data = json.loads(open('cfg/command_ping.json').read()) data['_realm'] = cls.realm_all data_cmd_ping = cls.backend.post("command", data) data = json.loads(open('cfg/command_http.json').read()) data['_realm'] = cls.realm_all data_cmd_http = cls.backend.post("command", data) # add host data = json.loads(open('cfg/host_srv001.json').read()) data['check_command'] = data_cmd_ping['_id'] del data['realm'] data['_realm'] = cls.realm_all cls.data_host = cls.backend.post("host", data) # add 2 services data = json.loads(open('cfg/service_srv001_ping.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_ping['_id'] data['_realm'] = cls.realm_all cls.data_srv_ping = cls.backend.post("service", data) data = json.loads(open('cfg/service_srv001_http.json').read()) data['host'] = cls.data_host['_id'] data['check_command'] = data_cmd_http['_id'] data['_realm'] = cls.realm_all cls.data_srv_http = cls.backend.post("service", data) # Start broker module modconf = Module() modconf.module_alias = "backend_scheduler" modconf.username = "******" modconf.password = "******" modconf.api_url = 'http://127.0.0.1:5000' cls.schedmodule = AlignakBackendScheduler(modconf) class scheduler(object): """ Fake scheduler class used to save and load retention """ def __init__(self): self.data = None def get_retention_data(self): """ Get host and service data for save in backend :return: properties of host and services :rtype: dict """ all_data = {'hosts': {}, 'services': {}} all_data['hosts']['srv001'] = { 'latency': 0, 'last_state_type': 'HARD', 'state': 'UP', 'last_chk': 0, } all_data['hosts']['srv002'] = { 'latency': 0, 'last_state_type': 'HARD', 'state': 'UP', 'last_chk': 0, } all_data['services'][('srv001', 'check_http')] = { 'latency': 0, 'last_state_type': 'HARD', 'state': 'OK', 'last_chk': 0, } all_data['services'][('srv002', 'check_https')] = { 'latency': 0, 'last_state_type': 'HARD', 'state': 'WARNING', 'last_chk': 0, } return all_data def restore_retention_data(self, data): """ Load hoas and servcie from backend retention :param data: dict of hosts and service from retention backend :type data: dict """ self.data = data cls.sched = scheduler()
def test_modulemanager(self): mod = Module({ 'module_alias': 'mod-example', 'python_name': 'alignak_module_example' }) self.modulemanager = ModulesManager('broker', None) self.modulemanager.load_and_init([mod]) # And start external ones, like our LiveStatus self.modulemanager.start_external_instances() print "I correctly loaded the modules: %s " % ( [inst.get_name() for inst in self.modulemanager.instances]) print "*** First kill ****" # Now I will try to kill the livestatus module ls = self.modulemanager.instances[0] " :type: alignak.basemodule.BaseModule " ls.kill() time.sleep(0.1) print "Check alive?" print "Is alive?", ls.process.is_alive() # Should be dead self.assertFalse(ls.process.is_alive()) self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() # In fact it's too early, so it won't do it # Here the inst should still be dead print "Is alive?", ls.process.is_alive() self.assertFalse(ls.process.is_alive()) # So we lie ls.last_init_try = -5 self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() # In fact it's too early, so it won't do it # Here the inst should be alive again print "Is alive?", ls.process.is_alive() self.assertTrue(ls.process.is_alive()) # should be nothing more in to_restart of # the module manager self.assertEqual([], self.modulemanager.to_restart) # Now we look for time restart so we kill it again ls.kill() time.sleep(0.2) self.assertFalse(ls.process.is_alive()) # Should be too early self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() print "Is alive or not", ls.process.is_alive() self.assertFalse(ls.process.is_alive()) # We lie for the test again ls.last_init_try = -5 self.modulemanager.check_alive_instances() self.modulemanager.try_to_restart_deads() # Here the inst should be alive again print "Is alive?", ls.process.is_alive() self.assertTrue(ls.process.is_alive()) # And we clear all now print "Ask to die" self.modulemanager.stop_all() print "Died"