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_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_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_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 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()
예제 #7
0
    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)

        test_dir = os.path.dirname(os.path.realpath(__file__))
        print(("Current test directory: %s" % test_dir))

        print(("Feeding Alignak backend... %s" % test_dir))
        exit_code = subprocess.call(
            shlex.split(
                'alignak-backend-import --delete %s/cfg/default/_main.cfg' % test_dir)
        )
        assert exit_code == 0

        # Start arbiter 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 setUpClass(cls):
        # Set test mode for alignak backend
        # Uncomment to log the bakend REST API
        # 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']

        # Get admin user
        users = cls.backend.get_all('user')
        for user in users['_items']:
            if user['name'] == 'admin':
                cls.user_admin = user

        # 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)
        cls.ping_cmd = data_cmd_http['_id']

        # add 1 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 arbiter module
        modconf = Module()
        modconf.module_alias = "backend_arbiter"
        modconf.username = "******"
        modconf.password = "******"
        modconf.api_url = 'http://127.0.0.1:5000'

        # Update default check timers
        # check every x min if config in backend changed, if yes it will reload it
        # Default, every 5 minutes
        modconf.verify_modification = 1
        # verify_modification     5

        cls.arbmodule = AlignakBackendArbiter(modconf)
        cls.objects = cls.arbmodule.get_objects()
    def test_delete_host_service_detection(self):
        """Test if the hook detect we have deleted an host / service in the backend
        """
        class Arbiter(object):
            conf = Config()
            pidfile = '/tmp/arbiter.pid'

        arb = Arbiter()

        if os.path.exists('/tmp/arbiter.pid'):
            os.remove('/tmp/arbiter.pid')

        now = timegm(datetime.utcnow().utctimetuple())

        # add 1 host
        data = json.loads(open('cfg/host_srv001.json').read())
        data['check_command'] = self.ping_cmd
        data['name'] = 'srv002'
        del data['realm']
        data['_realm'] = self.realm_all
        srv002 = self.data_host = self.backend.post("host", data)

        # Get our existing host
        hosts = self.backend.get_all('host')
        self.assertEqual(len(hosts['_items']), 3)

        # Start arbiter module
        modconf = Module()
        modconf.module_alias = "backend_arbiter"
        modconf.username = "******"
        modconf.password = "******"
        modconf.api_url = 'http://127.0.0.1:5000'

        # Update default check timers
        # check every x min if config in backend changed, if yes it will reload it
        # Default, every 5 minutes
        modconf.verify_modification = 1
        # verify_modification     5

        self.arbmodule = AlignakBackendArbiter(modconf)
        self.objects = self.arbmodule.get_objects()

        # No configuration check is done ... because it is not yet the moment to check.
        print("No configuration check")
        next_check = self.arbmodule.next_check
        print("Next check: %s" % (next_check))
        assert self.arbmodule.configuration_reload_required is False
        assert self.arbmodule.configuration_reload_changelog == []
        self.arbmodule.hook_tick(arb)
        print("Next check: %s / %s" % (next_check, self.arbmodule.next_check))
        assert self.arbmodule.next_check == next_check
        assert self.arbmodule.configuration_reload_required is False
        assert self.arbmodule.configuration_reload_changelog == []

        # delete the last host
        headers = {
            'Content-Type': 'application/json',
            'If-Match': srv002['_etag']
        }
        self.backend.delete('host/%s' % srv002['_id'], headers)
        hosts = self.backend.get_all('host')
        self.assertEqual(len(hosts['_items']), 2)

        # Set next check in the past to force a configuration check
        # Set check date in the future
        # And configuration has changed...
        print("Configuration check - a host has been deleted changed")
        self.arbmodule.next_check = now - 1
        self.arbmodule.time_loaded_conf = datetime.utcfromtimestamp(
            now + 1).strftime(self.arbmodule.backend_date_format)
        print("Next check: %s" % (next_check))
        assert self.arbmodule.configuration_reload_required is False
        assert self.arbmodule.configuration_reload_changelog == []
        self.arbmodule.hook_tick(arb)
        print("Next check: %s / %s" % (next_check, self.arbmodule.next_check))
        assert self.arbmodule.next_check > now
        assert self.arbmodule.configuration_reload_required is True
        assert len(self.arbmodule.configuration_reload_changelog) > 0
    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 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 some realms
        data = {'name': 'All-A', '_parent': cls.realm_all}
        realm_a = cls.backend.post("realm", data)
        cls.realm_all_a = realm_a['_id']
        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)

        # Get admin user
        resp = cls.backend.get_all('user')
        cls.user_admin = resp['_items'][0]

        # Add user
        # User 1
        data = {
            'name':
            'user1',
            'password':
            '******',
            'back_role_super_admin':
            False,
            'host_notification_period':
            cls.user_admin['host_notification_period'],
            'service_notification_period':
            cls.user_admin['service_notification_period'],
            '_realm':
            realm_a['_id'],
            '_sub_realm':
            False
        }
        user1 = cls.backend.post('user', data)

        data = {
            'user': user1['_id'],
            'realm': realm_a['_id'],
            'resource': '*',
            'crud': ['create', 'read', 'update', 'delete']
        }
        cls.backend.post('userrestrictrole', 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)

        modconf2 = Module()
        modconf2.module_alias = "backend_arbiter"
        modconf2.username = "******"
        modconf2.password = "******"
        modconf2.api_url = 'http://127.0.0.1:5000'
        cls.arbmodule2 = AlignakBackendArbiter(modconf2)
    def setUpClass(cls):
        """This method:
          * deletes mongodb database
          * starts the backend with uwsgi
          * logs in the backend and gets the token

        :return: None
        """
        # 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['name'] = 'other-ping'
        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)

        # Get admin user
        users = cls.backend.get_all('user')
        cls.user_id = users['_items'][0]['_id']

        # Start scheduler 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()
예제 #13
0
    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 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()
예제 #15
0
    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()
예제 #16
0
    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)