Esempio n. 1
0
    def test_update_manager(self):
        """
        Tests updating of managers in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for manager in system_data.get_managers_list():
            temp_manager = ManagerObjManager().deepcopy(manager)
            temp_manager.description = "new_manager_" + str(ctr + 1)
            system_data.update_manager(temp_manager)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for manager in system_data.get_managers_list():
            storage._update_manager(manager)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_managers_content(self, system_data.get_managers_list(),
                                 storage._system_data.get_managers_list())
    def test_update_profile(self):
        """
        Tests updating of profiles in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for profile in system_data.get_profiles_list():
            temp_profile = ManagerObjProfile().deepcopy(profile)
            temp_profile.name = "new_profile" + str(ctr + 1)

            system_data.update_profile(temp_profile)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for profile in system_data.get_profiles_list():
            storage._update_profile(profile)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_profiles_content(self, system_data.get_profiles_list(),
                                 storage._system_data.get_profiles_list())
Esempio n. 3
0
    def test_update_alert(self):
        """
        Tests updating of alerts in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for alert in system_data.get_alerts_list():
            temp_alert = ManagerObjAlert().deepcopy(alert)
            temp_alert.description = "new_alert_" + str(ctr + 1)
            temp_alert.clientAlertId = ctr
            # We started the alert levels in our test data with level 1.
            temp_alert.alertLevels = [
                (ctr % len(system_data.get_alert_levels_list())) + 1
            ]
            system_data.update_alert(temp_alert)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for alert in system_data.get_alerts_list():
            storage._update_alert(alert)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_alerts_content(self, system_data.get_alerts_list(),
                               storage._system_data.get_alerts_list())
Esempio n. 4
0
    def test_update_option(self):
        """
        Test Option object updating.
        """
        config_logging(logging.INFO)
        storage = self._create_options()

        # Create changes that should be copied to the stored object.
        new_options = []
        for i in range(len(self.options)):
            temp_option = Option().deepcopy(self.options[i])
            temp_option.value = i + 5
            new_options.append(temp_option)

        for i in range(len(new_options)):

            # Update store with new object data.
            temp_option = new_options[i]
            storage.update_option_by_obj(temp_option)

            gt_storage = []
            for j in range(i + 1):
                gt_storage.append(new_options[j])
            for j in range(i + 1, len(new_options)):
                gt_storage.append(self.options[j])

            stored_options = storage.get_options_list()
            self.assertIsNotNone(stored_options)

            compare_options_content(self, gt_storage, stored_options)
Esempio n. 5
0
    def test_single_communication(self):
        """
        Tests single request sending through the communication channel from the client to the server.
        """
        config_logging(logging.CRITICAL)

        comm_client, comm_server = create_simulated_communication()

        ping_msg = MsgBuilder.build_ping_msg()
        promise = comm_client.send_request("ping", ping_msg)

        msg_request = comm_server.recv_request()
        if msg_request is None:
            self.fail("Receiving message failed.")

        self.assertEqual(msg_request.state, MsgState.OK)

        if "ping" != msg_request.msg_dict["message"]:
            self.fail("Expected 'ping' message.")

        if not promise.is_finished(timeout=5.0):
            self.fail("Expected message to be sent.")

        if not promise.was_successful():
            self.fail("Sending message was not successful.")
Esempio n. 6
0
    def test_update_option(self):
        """
        Tests updating of options in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 5
        for option in system_data.get_options_list():
            temp_option = ManagerObjOption().deepcopy(option)
            temp_option.value = float(ctr)
            system_data.update_option(temp_option)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for option in system_data.get_options_list():
            storage._update_option(option)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_options_content(self, system_data.get_options_list(),
                                storage._system_data.get_options_list())
Esempio n. 7
0
    def test_delete_node(self):
        """
        Tests deleting of nodes in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Delete object and check correct deletion.
        for node in system_data.get_nodes_list():
            storage._open_connection()
            storage._delete_node(node.nodeId)
            storage._conn.commit()

            system_data.delete_node_by_id(node.nodeId)

            storage.synchronize_database_to_system_data()
            compare_nodes_content(self, system_data.get_nodes_list(),
                                  storage._system_data.get_nodes_list())

            # Delete function of database also deletes all Alert, Manager, and Sensor objects.
            compare_alerts_content(self, system_data.get_alerts_list(),
                                   storage._system_data.get_alerts_list())
            compare_managers_content(self, system_data.get_managers_list(),
                                     storage._system_data.get_managers_list())
            compare_sensors_content(self, system_data.get_sensors_list(),
                                    storage._system_data.get_sensors_list())
Esempio n. 8
0
    def test_add_data(self):
        """
        Tests adding of system information to the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        # Create database objects.
        system_data = self._create_system_data()
        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          [])

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_nodes_content(self, system_data.get_nodes_list(),
                              storage._system_data.get_nodes_list())
        compare_alerts_content(self, system_data.get_alerts_list(),
                               storage._system_data.get_alerts_list())
        compare_managers_content(self, system_data.get_managers_list(),
                                 storage._system_data.get_managers_list())
        compare_sensors_content(self, system_data.get_sensors_list(),
                                storage._system_data.get_sensors_list())
    def test_update_server_info_duplicate_sensor_alerts(self):
        """
        Tests adding of sensor alerts to the database via update_server_information duplicates sensor alerts.
        """

        config_logging(logging.ERROR)

        storage = self._init_database()
        storage._sensor_alert_life_span = 2147483647  # max signed 32bit integer

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        sensor_list = system_data.get_sensors_list()
        for i in range(len(sensor_list)):
            target_sensor = sensor_list[i % len(sensor_list)]

            sensor_alert = ManagerObjSensorAlert()
            sensor_alert.sensorId = target_sensor.sensorId
            sensor_alert.state = (i % 2)
            sensor_alert.description = "Sensor Alert %d" % i
            sensor_alert.timeReceived = int(time.time())
            sensor_alert.alertLevels = list(target_sensor.alertLevels)
            sensor_alert.hasOptionalData = False
            sensor_alert.changeState = False
            sensor_alert.hasLatestData = False
            sensor_alert.dataType = SensorDataType.NONE

            system_data.add_sensor_alert(sensor_alert)

        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_profiles_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          system_data.get_sensor_alerts_list())

        self.assertEqual(len(system_data.get_sensor_alerts_list()),
                         len(sensor_list))

        # Add same list of sensor alerts again for duplication test.
        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_profiles_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          system_data.get_sensor_alerts_list())

        storage._open_connection()
        db_sensor_alerts = storage._get_sensor_alerts()
        storage._close_connection()

        compare_sensor_alerts_content(self,
                                      system_data.get_sensor_alerts_list(),
                                      db_sensor_alerts)
Esempio n. 10
0
    def test_add_option(self):
        """
        Tests adding of options to the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_options_content(self, system_data.get_options_list(),
                                storage._system_data.get_options_list())
Esempio n. 11
0
    def _create_option_executer(self) -> Tuple[OptionExecuter, GlobalData]:

        config_logging(logging.ERROR)

        global_data = GlobalData()
        global_data.logger = logging.getLogger("Option Test Case")
        global_data.storage = MockStorage()
        global_data.managerUpdateExecuter = MockManagerUpdateExecuter()

        internal_sensor = MockProfileChangeSensorSensor(global_data)
        global_data.internalSensors.append(internal_sensor)

        option_executer = OptionExecuter(global_data)
        option_executer.daemon = True
        option_executer.start()

        return option_executer, global_data
Esempio n. 12
0
    def test_update_node(self):
        """
        Tests updating of nodes in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for node in system_data.get_nodes_list():
            temp_node = ManagerObjNode().deepcopy(node)
            temp_node.hostname = "new_hostname_" + str(ctr + 1)
            temp_node.nodeType = ["alert", "manager", "sensor",
                                  "server"][ctr % 4]
            temp_node.instance = "new_instance_" + str(ctr + 1)
            temp_node.connected = (ctr % 2)
            temp_node.version = float(5 + ctr)
            temp_node.rev = ctr
            temp_node.username = "******" + str(ctr + 1)
            temp_node.persistent = (ctr % 2)
            system_data.update_node(temp_node)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for node in system_data.get_nodes_list():
            storage._update_node(node)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_nodes_content(self, system_data.get_nodes_list(),
                              storage._system_data.get_nodes_list())

        # Update function of database also deletes all Alert, Manager, and Sensor objects if node type changes.
        compare_alerts_content(self, system_data.get_alerts_list(),
                               storage._system_data.get_alerts_list())
        compare_managers_content(self, system_data.get_managers_list(),
                                 storage._system_data.get_managers_list())
        compare_sensors_content(self, system_data.get_sensors_list(),
                                storage._system_data.get_sensors_list())
Esempio n. 13
0
    def test_delete_profile(self):
        """
        Tests deleting of profiles in system information data in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        # Create database objects.
        system_data = self._create_system_data()
        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_profiles_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          [])

        # Delete profile objects and check correct deletion.
        for profile in system_data.get_profiles_list():
            system_data.delete_profile_by_id(profile.profileId)

            storage.update_server_information(
                0, system_data.get_options_list(),
                system_data.get_profiles_list(), system_data.get_nodes_list(),
                system_data.get_sensors_list(), system_data.get_alerts_list(),
                system_data.get_managers_list(),
                system_data.get_alert_levels_list(), [])

            storage.synchronize_database_to_system_data()
            compare_profiles_content(self, system_data.get_profiles_list(),
                                     storage._system_data.get_profiles_list())
            compare_nodes_content(self, system_data.get_nodes_list(),
                                  storage._system_data.get_nodes_list())
            compare_alerts_content(self, system_data.get_alerts_list(),
                                   storage._system_data.get_alerts_list())
            compare_managers_content(self, system_data.get_managers_list(),
                                     storage._system_data.get_managers_list())
            compare_sensors_content(self, system_data.get_sensors_list(),
                                    storage._system_data.get_sensors_list())
            compare_alert_levels_content(
                self, system_data.get_alert_levels_list(),
                storage._system_data.get_alert_levels_list())
Esempio n. 14
0
    def test_disconnect_communication(self):
        """
        Tests requests sending if the communication channel is disconnected and if they are transfered as soon
        as the channel is available.
        """
        config_logging(logging.CRITICAL)
        num_msgs = 5

        comm_client, comm_server = create_simulated_communication()

        # Disconnect client from server.
        comm_client._has_channel = False

        # Send messages.
        promises = list()
        for i in range(num_msgs):
            ping_msg = MsgBuilder.build_ping_msg()
            ping_dict = json.loads(ping_msg)
            ping_dict["num_msg"] = i
            promises.append(
                comm_client.send_request("ping", json.dumps(ping_dict)))

        for i in range(num_msgs):
            promise = promises[i]
            self.assertFalse(promise.is_finished(timeout=1.0))

        # Connect client.
        self.assertTrue(comm_client.connect())
        comm_client.set_connected()

        # Receive and check messages.
        Timer.start_timer(self, "receive_msgs", 10)
        for i in range(num_msgs):
            msg_request = comm_server.recv_request()

            self.assertIsNotNone(msg_request)
            self.assertEqual(msg_request.state, MsgState.OK)
            self.assertEqual(msg_request.msg_dict["message"], "ping")
            self.assertEqual(msg_request.msg_dict["num_msg"], i)

            promise = promises[i]
            self.assertTrue(promise.is_finished(timeout=5.0))
            self.assertTrue(promise.was_successful())
        Timer.stop_timer("receive_msgs")
    def test_add_sensor_alert(self):
        """
        Tests adding of sensor alerts to the database.
        """

        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        sensor_list = system_data.get_sensors_list()
        for i in range(len(sensor_list)):
            target_sensor = sensor_list[i % len(sensor_list)]

            sensor_alert = ManagerObjSensorAlert()
            sensor_alert.sensorId = target_sensor.sensorId
            sensor_alert.state = (i % 2)
            sensor_alert.description = "Sensor Alert %d" % i
            sensor_alert.timeReceived = int(time.time())
            sensor_alert.alertLevels = list(target_sensor.alertLevels)
            sensor_alert.hasOptionalData = False
            sensor_alert.changeState = False
            sensor_alert.hasLatestData = False
            sensor_alert.dataType = SensorDataType.NONE

            system_data.add_sensor_alert(sensor_alert)

        storage._open_connection()
        for sensor_alert in system_data.get_sensor_alerts_list():
            storage._add_sensor_alert(sensor_alert)
        storage._conn.commit()
        storage._close_connection()

        storage._open_connection()
        db_sensor_alerts = storage._get_sensor_alerts()
        storage._close_connection()

        compare_sensor_alerts_content(self,
                                      system_data.get_sensor_alerts_list(),
                                      db_sensor_alerts)
Esempio n. 16
0
    def test_recv_future(self):
        """
        Tests communication expired handling by letting the client send a ping request to the server
        which has a message time in the future.
        """
        config_logging(logging.WARNING)

        comm_client, comm_server = create_simulated_communication()

        ping_msg = MsgBuilder.build_ping_msg()
        json_msg = json.loads(ping_msg)
        json_msg["msgTime"] = int(
            time.time()) + comm_server._msg_expiration + 5
        promise = comm_client.send_request("ping", json.dumps(json_msg))

        msg_request = comm_server.recv_request()
        self.assertIsNotNone(msg_request)
        self.assertEqual(msg_request.state, MsgState.EXPIRED)
        self.assertEqual(msg_request.msg_dict["message"], "ping")
        self.assertTrue(promise.is_finished(timeout=5.0))
        self.assertFalse(promise.was_successful())
Esempio n. 17
0
    def _create_server(self) -> Tuple[ThreadedUnixStreamServer, GlobalData]:
        config_logging(logging.ERROR)

        global_data = GlobalData()

        dir = tempfile.mkdtemp()
        global_data.unixSocketFile = os.path.join(dir, "test_socket")

        global_data.serverComm = MockServerCommunication()

        server = ThreadedUnixStreamServer(global_data,
                                          global_data.unixSocketFile,
                                          LocalServerSession)

        server_thread = threading.Thread(target=server.serve_forever,
                                         daemon=True)
        server_thread.start()

        self.addCleanup(self._destroy_server, server, global_data)

        return server, global_data
Esempio n. 18
0
    def test_update_sensor(self):
        """
        Tests updating of sensors in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for sensor in system_data.get_sensors_list():
            temp_sensor = ManagerObjSensor().deepcopy(sensor)
            temp_sensor.description = "new_sensor_" + str(ctr + 1)
            temp_sensor.clientSensorId = ctr
            temp_sensor.alertDelay = ctr + 10
            temp_sensor.lastStateUpdated = ctr + 10
            temp_sensor.state = ctr % 2
            temp_sensor.dataType = SensorDataType.INT
            temp_sensor.data = ctr
            # We started the alert levels in our test data with level 1.
            temp_sensor.alertLevels = [
                (ctr % len(system_data.get_alert_levels_list())) + 1
            ]
            system_data.update_sensor(temp_sensor)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for sensor in system_data.get_sensors_list():
            storage._update_sensor(sensor)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_sensors_content(self, system_data.get_sensors_list(),
                                storage._system_data.get_sensors_list())
Esempio n. 19
0
    def test_delete_option(self):
        """
        Tests deleting of options in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Delete object and check correct deletion.
        for option in system_data.get_options_list():
            storage._open_connection()
            storage._delete_option(option.type)
            storage._conn.commit()

            system_data.delete_option_by_type(option.type)

            storage.synchronize_database_to_system_data()
            compare_options_content(self, system_data.get_options_list(),
                                    storage._system_data.get_options_list())
Esempio n. 20
0
    def test_delete_profile(self):
        """
        Tests deleting of profiles in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Delete object and check correct deletion.
        for profile in system_data.get_profiles_list():
            storage._open_connection()
            storage._delete_profile(profile.profileId)
            storage._conn.commit()

            system_data.delete_profile_by_id(profile.profileId)

            storage.synchronize_database_to_system_data()
            compare_profiles_content(self, system_data.get_profiles_list(),
                                     storage._system_data.get_profiles_list())
Esempio n. 21
0
    def test_update_alert_level(self):
        """
        Tests updating of alert levels in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Update local objects.
        ctr = 0
        for alert_level in system_data.get_alert_levels_list():
            temp_alert_level = ManagerObjAlertLevel().deepcopy(alert_level)
            temp_alert_level.name = "new_alert_level" + str(ctr + 1)
            temp_alert_level.triggerAlways = (ctr % 2)
            temp_alert_level.instrumentation_active = (((ctr + 1) % 2) == 0)

            if temp_alert_level.instrumentation_active:
                temp_alert_level.instrumentation_cmd = "new_alert_level_instrumentation_" + str(
                    ctr + 1)
                temp_alert_level.instrumentation_timeout = 543 + ctr

            system_data.update_alert_level(temp_alert_level)
            ctr += 1

        # Update database objects.
        storage._open_connection()
        for alert_level in system_data.get_alert_levels_list():
            storage._update_alert_level(alert_level)
        storage._conn.commit()

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_alert_levels_content(
            self, system_data.get_alert_levels_list(),
            storage._system_data.get_alert_levels_list())
Esempio n. 22
0
    def test_delete_alert_level(self):
        """
        Tests deleting of alert levels in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        system_data = self._create_system_data()
        self._create_objects(storage, system_data)

        # Delete object and check correct deletion.
        for alert_level in system_data.get_alert_levels_list():
            storage._open_connection()
            storage._delete_alert_level(alert_level.level)
            storage._conn.commit()

            system_data.delete_alert_level_by_level(alert_level.level)

            storage.synchronize_database_to_system_data()
            compare_alert_levels_content(
                self, system_data.get_alert_levels_list(),
                storage._system_data.get_alert_levels_list())
    def test_stress_communication(self):
        """
        Stress tests communication by letting client and server trying to send
        X messages to each other at the same time. Checks order of the send/received messages
        as well as not to take too long to send messages.
        """

        count = 30

        config_logging(logging.CRITICAL)

        comm_client, comm_server = create_simulated_communication()

        receiving_sync = threading.Event()
        receiving_sync.clear()

        msg_requests_server = []
        kwargs = {
            "count": count,
            "comm": comm_server,
            "msg_requests": msg_requests_server,
            "sync": receiving_sync
        }
        server_receiver = threading.Thread(target=msg_receiver,
                                           kwargs=kwargs,
                                           daemon=True)
        server_receiver.start()

        msg_requests_client = []
        kwargs = {
            "count": count,
            "comm": comm_client,
            "msg_requests": msg_requests_client,
            "sync": receiving_sync
        }
        client_receiver = threading.Thread(target=msg_receiver,
                                           kwargs=kwargs,
                                           daemon=True)
        client_receiver.start()

        start_timer = time.time()
        receiving_sync.set()

        # Send requests from client to server.
        requests_client = []
        for i in range(count):
            ping_msg = MsgBuilder.build_ping_msg()
            ping_dict = json.loads(ping_msg)
            # Insert bogus field to uniquely identify messages on the other side.
            ping_dict["test_msg_name"] = "client_" + str(i)
            ping_msg = json.dumps(ping_dict)
            promise = comm_client.send_request("ping", ping_msg)
            requests_client.append(promise)

        # Send requests from server to client.
        requests_server = []
        for i in range(count):
            ping_msg = MsgBuilder.build_ping_msg()
            ping_dict = json.loads(ping_msg)
            # Insert bogus field to uniquely identify messages on the other side.
            ping_dict["test_msg_name"] = "server_" + str(i)
            ping_msg = json.dumps(ping_dict)
            promise = comm_server.send_request("ping", ping_msg)
            requests_server.append(promise)

        # Give each message 5 seconds time
        # ("count" messages sent by client and "count" messages sent by server).
        for _ in range(count * 2 * 5):
            if client_receiver.isAlive():
                client_receiver.join(timeout=1.0)
            elif server_receiver.isAlive():
                server_receiver.join(timeout=1.0)
            else:
                break
        if client_receiver.isAlive():
            self.fail("Client timed out while receiving messages.")
        if server_receiver.isAlive():
            self.fail("Server timed out while receiving messages.")

        if len(requests_client) != len(msg_requests_server):
            self.fail(
                "Client requests differ from messages received by server.")

        if len(requests_server) != len(msg_requests_client):
            self.fail(
                "Server requests differ from messages received by client.")

        # Check requests send by the client.
        for i in range(len(requests_client)):
            promise = requests_client[i]
            send_msg = json.loads(promise.msg)
            msg_request = msg_requests_server[i]

            self.assertIsNotNone(msg_request)
            self.assertEqual(msg_request.state, MsgState.OK)

            if promise.msg_type != msg_request.msg_dict["message"]:
                self.fail(
                    "Message type from send and receive different (client -> server)."
                )

            if send_msg["test_msg_name"] != msg_request.msg_dict[
                    "test_msg_name"]:
                self.fail(
                    "Messages sent and received different or different order (client -> server)."
                )

        # Check requests send by the server.
        for i in range(len(requests_client)):
            promise = requests_server[i]
            send_msg = json.loads(promise.msg)
            msg_request = msg_requests_client[i]

            self.assertIsNotNone(msg_request)
            self.assertEqual(msg_request.state, MsgState.OK)

            if promise.msg_type != msg_request.msg_dict["message"]:
                self.fail(
                    "Message type from send and receive different (server -> client)."
                )

            if send_msg["test_msg_name"] != msg_request.msg_dict[
                    "test_msg_name"]:
                self.fail(
                    "Messages sent and received different or different order (server -> client)."
                )

        time_elapsed = time.time() - start_timer
        logging.info("Needed %.2f seconds to send/receive messages." %
                     time_elapsed)
Esempio n. 24
0
    def test_send_request_rts_error(self):
        """
        Tests communication error handling by letting the client send a ping request to the server
        and failing the rts message part the first time.
        """

        config_logging(logging.CRITICAL)

        comm_client, comm_server = create_simulated_error_communication()

        # Inject in first "rts" an error.
        comm_client._connection.sim_error_rts = True

        receiving_sync = threading.Event()
        receiving_sync.clear()

        msg_requests_server = []
        kwargs = {
            "count":
            2,  # we receive 2 messages: None because of the error and the ping
            "comm": comm_server,
            "msg_requests": msg_requests_server,
            "sync": receiving_sync
        }
        server_receiver = threading.Thread(target=msg_receiver,
                                           kwargs=kwargs,
                                           daemon=True)
        server_receiver.start()

        start_timer = time.time()
        receiving_sync.set()

        ping_msg = MsgBuilder.build_ping_msg()
        promise = comm_client.send_request("ping", ping_msg)

        # Give message 5 seconds time.
        reconnect_client_ctr = 0
        reconnect_server_ctr = 0
        for _ in range(5):
            if server_receiver.isAlive():

                # Re-connect channel if it is down (since we simulate an error we have to re-connect).
                if not comm_client.has_channel:
                    comm_client.set_connected()
                    reconnect_client_ctr += 1

                # Re-connect channel if it is down (since we simulate an error we have to re-connect).
                if not comm_server.has_channel:
                    comm_server.set_connected()
                    reconnect_server_ctr += 1

                server_receiver.join(timeout=1.0)

            else:
                break

        if server_receiver.isAlive():
            self.fail("Server timed out while receiving messages.")

        if reconnect_client_ctr > 1:
            self.fail("Client had to re-connect more than once to server.")

        if reconnect_server_ctr > 1:
            self.fail("Server had to re-connect more than once with client.")

        if not msg_requests_server:
            self.fail("Received no message.")

        if len(msg_requests_server) != 2:
            self.fail("Expected two messages.")

        if msg_requests_server[0] is not None:
            self.fail("Expected None as first received message.")

        msg_request = msg_requests_server[1]
        if msg_request is None:
            self.fail("Receiving message failed.")

        self.assertEqual(msg_request.state, MsgState.OK)

        if "ping" != msg_request.msg_dict["message"]:
            self.fail("Expected 'ping' message.")

        if not promise.is_finished(timeout=5.0):
            self.fail("Expected message to be sent.")

        if not promise.was_successful():
            self.fail("Sending message was not successful.")

        time_elapsed = time.time() - start_timer
        logging.info("Needed %.2f seconds to send/receive messages." %
                     time_elapsed)
Esempio n. 25
0
    def test_update(self):
        """
        Tests updating of system information in the database.
        """
        config_logging(logging.ERROR)

        storage = self._init_database()

        # Create database objects.
        system_data = self._create_system_data()
        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          [])

        # Update local objects.
        ctr = 0
        for option in system_data.get_options_list():
            temp_option = ManagerObjOption().deepcopy(option)
            temp_option.value = float(ctr)
            system_data.update_option(temp_option)
            ctr += 1

        for alert_level in system_data.get_alert_levels_list():
            temp_alert_level = ManagerObjAlertLevel().deepcopy(alert_level)
            temp_alert_level.name = "new_alert_level_" + str(ctr + 1)
            temp_alert_level.triggerAlways = (ctr % 2)
            temp_alert_level.instrumentation_active = (ctr % 2) == 0

            if temp_alert_level.instrumentation_active:
                temp_alert_level.instrumentation_cmd = "alert_level_instrumentation_" + str(
                    ctr + 1)
                temp_alert_level.instrumentation_timeout = 123 + ctr

            system_data.update_alert_level(temp_alert_level)
            ctr += 1

        for node in system_data.get_nodes_list():
            temp_node = ManagerObjNode().deepcopy(node)
            temp_node.hostname = "new_hostname_" + str(ctr + 1)
            temp_node.nodeType = ["alert", "manager", "sensor",
                                  "server"][ctr % 4]
            temp_node.instance = "new_instance_" + str(ctr + 1)
            temp_node.connected = (ctr % 2)
            temp_node.version = float(5 + ctr)
            temp_node.rev = ctr
            temp_node.username = "******" + str(ctr + 1)
            temp_node.persistent = (ctr % 2)
            system_data.update_node(temp_node)
            ctr += 1

        for alert in system_data.get_alerts_list():
            temp_alert = ManagerObjAlert().deepcopy(alert)
            temp_alert.description = "new_alert_" + str(ctr + 1)
            temp_alert.remoteAlertId = ctr
            # We started the alert levels in our test data with level 1.
            temp_alert.alertLevels = [
                (ctr % len(system_data.get_alert_levels_list())) + 1
            ]
            system_data.update_alert(temp_alert)
            ctr += 1

        for manager in system_data.get_managers_list():
            temp_manager = ManagerObjManager().deepcopy(manager)
            temp_manager.description = "new_manager_" + str(ctr + 1)
            system_data.update_manager(temp_manager)
            ctr += 1

        for sensor in system_data.get_sensors_list():
            temp_sensor = ManagerObjSensor().deepcopy(sensor)
            temp_sensor.description = "new_sensor_" + str(ctr + 1)
            temp_sensor.remoteSensorId = ctr
            temp_sensor.alertDelay = ctr + 10
            temp_sensor.lastStateUpdated = ctr + 10
            temp_sensor.state = ctr % 2
            temp_sensor.dataType = SensorDataType.INT
            temp_sensor.data = ctr
            # We started the alert levels in our test data with level 1.
            temp_sensor.alertLevels = [
                (ctr % len(system_data.get_alert_levels_list())) + 1
            ]
            system_data.update_sensor(temp_sensor)
            ctr += 1

        # Update database objects.
        storage.update_server_information(0, system_data.get_options_list(),
                                          system_data.get_nodes_list(),
                                          system_data.get_sensors_list(),
                                          system_data.get_alerts_list(),
                                          system_data.get_managers_list(),
                                          system_data.get_alert_levels_list(),
                                          [])

        storage._system_data = SystemData()
        storage.synchronize_database_to_system_data()

        compare_nodes_content(self, system_data.get_nodes_list(),
                              storage._system_data.get_nodes_list())
        compare_alerts_content(self, system_data.get_alerts_list(),
                               storage._system_data.get_alerts_list())
        compare_managers_content(self, system_data.get_managers_list(),
                                 storage._system_data.get_managers_list())
        compare_sensors_content(self, system_data.get_sensors_list(),
                                storage._system_data.get_sensors_list())
        compare_alert_levels_content(
            self, system_data.get_alert_levels_list(),
            storage._system_data.get_alert_levels_list())