def setUp(self):
     try:
         raise RuntimeError("error")
     except:
         self.exc = sys.exc_info()[1]
         self.traceback = sys.exc_info()[2]
         self.f = ImmediateExceptionFuture(self.exc, self.traceback)
Пример #2
0
    def test_heartbeat_on_failure(self):
        reactor = self.mock_reactor()
        self.mock_request_new_session()
        self.manager._request_heartbeat = MagicMock(
            return_value=ImmediateExceptionFuture(SessionExpiredError()))

        m = MagicMock(side_effect=self.manager.invalidate_session)
        self.manager.invalidate_session = m

        self.manager.acquire_session(self.raft_group_id, 1).result()
        time.sleep(2)
        self.manager.shutdown()
        reactor.shutdown()
        self.assertGreater(self.context.reactor.add_timer.call_count,
                           1)  # assert that the heartbeat task is executed
        m.assert_called_once_with(self.raft_group_id, self.session_id)
        self.assertEqual(0, len(self.manager._sessions))
    def get_or_connect(self, address, authenticator=None):
        """
        Gets the existing connection for a given address. If it does not exist, the system will try to connect
        asynchronously. In this case, it returns a Future. When the connection is established at some point in time, it
        can be retrieved by using the get_connection(:class:`~hazelcast.core.Address`) or from Future.

        :param address: (:class:`~hazelcast.core.Address`), the address to connect to.
        :param authenticator: (Function), function to be used for authentication (optional).
        :return: (:class:`~hazelcast.connection.Connection`), the existing connection or it returns a Future which includes asynchronously.
        """
        if address in self.connections:
            return ImmediateFuture(self.connections[address])
        else:
            with self._new_connection_mutex:
                if address in self._pending_connections:
                    return self._pending_connections[address]
                else:
                    authenticator = authenticator or self._cluster_authenticator
                    try:
                        translated_address = self._address_translator.translate(
                            address)
                        if translated_address is None:
                            raise ValueError(
                                "Address translator could not translate address: {}"
                                .format(address))
                        connection = self._new_connection_func(
                            translated_address,
                            self._client.config.network_config.
                            connection_timeout,
                            self._client.config.network_config.socket_options,
                            connection_closed_callback=self._connection_closed,
                            message_callback=self._client.invoker.
                            _handle_client_message,
                            network_config=self._client.config.network_config)
                    except IOError:
                        return ImmediateExceptionFuture(
                            sys.exc_info()[1],
                            sys.exc_info()[2])

                    future = authenticator(connection).continue_with(
                        self.on_auth, connection, address)
                    if not future.done():
                        self._pending_connections[address] = future
                    return future
Пример #4
0
    def release(self, permits=1):
        check_true(permits > 0, "Permits must be positive")
        session_id = self._get_session_id()
        if session_id == _NO_SESSION_ID:
            return ImmediateExceptionFuture(self._new_illegal_state_error())

        current_thread_id = thread_id()
        invocation_uuid = uuid.uuid4()

        def check_response(response):
            try:
                response.result()
            except SessionExpiredError as e:
                self._invalidate_session(session_id)
                raise self._new_illegal_state_error(e)
            finally:
                self._release_session(session_id, permits)

        return self._request_release(session_id, current_thread_id, invocation_uuid, permits).continue_with(
            check_response)
Пример #5
0
    def get_or_connect(self, address, authenticator=None):
        if address in self.connections:
            return ImmediateFuture(self.connections[address])
        else:
            with self._new_connection_mutex:
                if address in self._pending_connections:
                    return self._pending_connections[address]
                else:
                    authenticator = authenticator or self._cluster_authenticator
                    try:
                        connection = self._new_connection_func(address,
                                                               self._client.config.network_config.connection_timeout,
                                                               self._client.config.network_config.socket_options,
                                                               connection_closed_callback=self._connection_closed,
                                                               message_callback=self._client.invoker._handle_client_message)
                    except IOError:
                        return ImmediateExceptionFuture(sys.exc_info()[1], sys.exc_info()[2])

                    future = authenticator(connection).continue_with(self.on_auth, connection, address)
                    if not future.done():
                        self._pending_connections[address] = future
                    return future
 def mock(*_, **__):
     if called.get_and_increment() == 0 and first_call_err:
         return ImmediateExceptionFuture(first_call_err)
     return ImmediateFuture(result)
Пример #7
0
class ImmediateExceptionFutureTest(unittest.TestCase):
    f = None

    def setUp(self):
        try:
            raise RuntimeError("error")
        except:
            self.exc = sys.exc_info()[1]
            self.traceback = sys.exc_info()[2]
            self.f = ImmediateExceptionFuture(self.exc, self.traceback)

    def test_result(self):
        with self.assertRaises(type(self.exc)):
            self.f.result()

    def test_exception(self):
        self.assertEqual(self.exc, self.f.exception())

    def test_traceback(self):
        self.assertEqual(self.traceback, self.f.traceback())

    def test_set_result(self):
        with self.assertRaises(NotImplementedError):
            self.f.set_result("done")

    def test_set_exception(self):
        with self.assertRaises(NotImplementedError):
            self.f.set_exception(RuntimeError())

    def test_is_succcess(self):
        self.assertFalse(self.f.is_success())

    def test_is_done(self):
        self.assertTrue(self.f.done())

    def test_is_not_running(self):
        self.assertFalse(self.f.running())

    def test_callback(self):
        n = [0]

        def callback(f):
            self.assertEqual(f, self.f)
            n[0] += 1

        self.f.add_done_callback(callback)

        self.assertEqual(n[0], 1)
Пример #8
0
 def mock(expected_round, invocation_uuid):
     if called_count.get_and_increment() < 2:
         return ImmediateExceptionFuture(OperationTimeoutError("xx"))
     return original(expected_round, invocation_uuid)
class ImmediateExceptionFutureTest(unittest.TestCase):
    f = None

    def setUp(self):
        try:
            raise RuntimeError("error")
        except:
            self.exc = sys.exc_info()[1]
            self.traceback = sys.exc_info()[2]
            self.f = ImmediateExceptionFuture(self.exc, self.traceback)

    def test_result(self):
        with self.assertRaises(type(self.exc)):
            self.f.result()

    def test_exception(self):
        self.assertEqual(self.exc, self.f.exception())

    def test_traceback(self):
        self.assertEqual(self.traceback, self.f.traceback())

    def test_set_result(self):
        with self.assertRaises(NotImplementedError):
            self.f.set_result("done")

    def test_set_exception(self):
        with self.assertRaises(NotImplementedError):
            self.f.set_exception(RuntimeError())

    def test_is_succcess(self):
        self.assertFalse(self.f.is_success())

    def test_is_done(self):
        self.assertTrue(self.f.done())

    def test_is_not_running(self):
        self.assertFalse(self.f.running())

    def test_callback(self):
        n = [0]

        def callback(f):
            self.assertEqual(f, self.f)
            n[0] += 1

        self.f.add_done_callback(callback)

        self.assertEqual(n[0], 1)
Пример #10
0
    def execute(self, sql, params, cursor_buffer_size, timeout,
                expected_result_type, schema):
        """Constructs a statement and executes it.

        Args:
            sql (str): SQL string.
            params (tuple): Query parameters.
            cursor_buffer_size (int): Cursor buffer size.
            timeout (float): Timeout of the query.
            expected_result_type (SqlExpectedResultType): Expected result type
                of the query.
            schema (str or None): The schema name.

        Returns:
            hazelcast.future.Future[SqlResult]: The execution result.
        """
        statement = _SqlStatement(sql, params, cursor_buffer_size, timeout,
                                  expected_result_type, schema)

        connection = None
        try:
            try:
                # Serialize the passed parameters.
                serialized_params = [
                    self._serialization_service.to_data(param)
                    for param in statement.parameters
                ]
            except SchemaNotReplicatedError as e:
                return self._send_schema_and_retry_fn(
                    e,
                    self.execute,
                    sql,
                    params,
                    cursor_buffer_size,
                    timeout,
                    expected_result_type,
                    schema,
                )

            connection = self._get_query_connection()
            # Create a new, unique query id.
            query_id = _SqlQueryId.from_uuid(connection.remote_uuid)

            request = sql_execute_codec.encode_request(
                statement.sql,
                serialized_params,
                # to_millis expects None to produce -1
                to_millis(None if statement.timeout ==
                          -1 else statement.timeout),
                statement.cursor_buffer_size,
                statement.schema,
                statement.expected_result_type,
                query_id,
                False,
            )

            invocation = Invocation(
                request,
                connection=connection,
                response_handler=sql_execute_codec.decode_response)
            self._invocation_service.invoke(invocation)
            return invocation.future.continue_with(lambda future: SqlResult(
                self,
                connection,
                query_id,
                statement.cursor_buffer_size,
                self._handle_execute_response(future, connection),
            ))
        except Exception as e:
            return ImmediateExceptionFuture(self.re_raise(e, connection))
 def read_many_mock(*_):
     if next(counter) == 0:
         return ImmediateExceptionFuture(error)
     return Future()
 def prepare_thread_id(self, thread_id, err=None):
     if err:
         value = ImmediateExceptionFuture(err)
     else:
         value = ImmediateFuture(thread_id)
     self.session_manager.get_or_create_unique_thread_id = MagicMock(return_value=value)