Ejemplo n.º 1
0
 def process_pong(self, args, handler_ctx):
   result = pong_result()
   try:
     self._handler.pong()
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'pong', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 2
0
 def process_echo(self, args, handler_ctx):
     result = echo_result()
     try:
         result.success = self._handler.echo(handler_ctx, args.input)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'echo', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 3
0
 def process_interact(self, args, handler_ctx):
     result = interact_result()
     try:
         self._handler.interact(handler_ctx, args.arg)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'interact', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 4
0
 def process_remove(self, args, handler_ctx):
     result = remove_result()
     try:
         result.success = self._handler.remove(handler_ctx, args.req)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'remove', ex)
         result = Thrift.TApplicationException(message=str(ex))
     return result
Ejemplo n.º 5
0
 def process_simple_rpc(self, args, handler_ctx):
     result = simple_rpc_result()
     try:
         self._handler.simple_rpc(handler_ctx)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'simple_rpc', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 6
0
 def then_sleep(self, args, handler_ctx):
   result = sleep_result()
   try:
     self._handler.future_sleep().result()
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'sleep', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 7
0
 def process_init(self, args, handler_ctx):
     result = init_result()
     try:
         result.success = self._handler.init(handler_ctx, args.int1)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'init', ex)
         result = Thrift.TApplicationException(message=str(ex))
     return result
Ejemplo n.º 8
0
 def process_has_arg_docs(self, args, handler_ctx):
   result = has_arg_docs_result()
   try:
     self._handler.has_arg_docs(handler_ctx, args.s, args.i)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'has_arg_docs', ex)
     result = Thrift.TApplicationException(message=repr(ex))
   return result
 def process_import(self, args, handler_ctx):
     result = import_result()
     try:
         result.success = self._handler.import_PY_RESERVED_KEYWORD()
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'import', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 10
0
 def process_func(self, args, handler_ctx):
     result = func_result()
     try:
         result.success = self._handler.func(args.arg1, args.arg2)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'func', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 11
0
 def process_init(self, args, handler_ctx):
   result = init_result()
   try:
     result.success = self._handler.init(args.int1, args.int2, args.int3, args.int4, args.int5, args.int6, args.int7, args.int8, args.int9, args.int10, args.int11, args.int12, args.int13, args.int14, args.int15, args.int16)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'init', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 12
0
 def process_authenticate(self, args, handler_ctx):
   result = authenticate_result()
   try:
     result.success = self._handler.authenticate(handler_ctx, args.username, args.password)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'authenticate', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 13
0
 def process_execute(self, args, handler_ctx):
   result = execute_result()
   try:
     result.success = self._handler.execute(handler_ctx, args.sessionId, args.stmt)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'execute', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 14
0
 def process_query(self, args, handler_ctx):
   result = query_result()
   try:
     self._handler.query(args.s, args.i)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'query', ex)
     result = Thrift.TApplicationException(message=repr(ex))
   return result
Ejemplo n.º 15
0
 def then_isPrime(self, args, handler_ctx):
   result = isPrime_result()
   try:
     result.success = self._handler.future_isPrime(args.num).result()
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'isPrime', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 16
0
 def then_getResult(self, args, handler_ctx):
   result = getResult_result()
   try:
     result.success = self._handler.future_getResult().result()
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'getResult', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 17
0
 def process_add(self, args, handler_ctx):
     result = add_result()
     try:
         result.success = self._handler.add(args.num1, args.num2)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'add', ex)
         result = Thrift.TApplicationException(message=str(ex))
     return result
Ejemplo n.º 18
0
 def process_bounce_map(self, args, handler_ctx):
     result = bounce_map_result()
     try:
         result.success = self._handler.bounce_map(handler_ctx, args.m)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'bounce_map', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 19
0
 def process_doBland(self, args, handler_ctx):
   result = doBland_result()
   try:
     self._handler.doBland(handler_ctx)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'doBland', ex)
     result = Thrift.TApplicationException(message=repr(ex))
   return result
Ejemplo n.º 20
0
 def process_get200(self, args, handler_ctx):
   result = get200_result()
   try:
     result.success = self._handler.get200(handler_ctx)
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'get200', ex)
     result = Thrift.TApplicationException(message=repr(ex))
   return result
 def process_global(self, args, handler_ctx):
     result = global_result()
     try:
         result.success = self._handler.global_PY_RESERVED_KEYWORD(
             handler_ctx, args.raise_PY_RESERVED_KEYWORD)
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'global', ex)
         result = Thrift.TApplicationException(message=repr(ex))
     return result
Ejemplo n.º 22
0
 def process_count_activity_multi(self, args, handler_ctx):
   result = count_activity_multi_result()
   try:
     result.success = self._handler.count_activity_multi(handler_ctx, args.context_ids)
   except InvalidContextIDException as exc0:
     self._event_handler.handlerException(handler_ctx, 'count_activity_multi', exc0)
     result.invalid_context_id = exc0
   except:
     ex = sys.exc_info()[1]
     self._event_handler.handlerError(handler_ctx, 'count_activity_multi', ex)
     result = Thrift.TApplicationException(message=str(ex))
   return result
Ejemplo n.º 23
0
 def process_get500(self, args, handler_ctx):
     result = get500_result()
     try:
         result.success = self._handler.get500(handler_ctx)
     except Fiery as exc0:
         self._event_handler.handlerException(handler_ctx, 'get500', exc0)
         result.f = exc0
     except Banal as exc1:
         self._event_handler.handlerException(handler_ctx, 'get500', exc1)
         result.b = exc1
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'get500', ex)
         result = Thrift.TApplicationException(message=str(ex))
     return result
Ejemplo n.º 24
0
 def process_doRaise(self, args, handler_ctx):
     result = doRaise_result()
     try:
         self._handler.doRaise(handler_ctx)
     except Banal as exc0:
         self._event_handler.handlerException(handler_ctx, 'doRaise', exc0)
         result.b = exc0
     except Fiery as exc1:
         self._event_handler.handlerException(handler_ctx, 'doRaise', exc1)
         result.f = exc1
     except:
         ex = sys.exc_info()[1]
         self._event_handler.handlerError(handler_ctx, 'doRaise', ex)
         result = Thrift.TApplicationException(message=str(ex))
     return result
Ejemplo n.º 25
0
 def execute(self, param):
     print("server: execute failure")
     raise Thrift.TApplicationException(
         type=Thrift.TApplicationException.INTERNAL_ERROR,
         message="for execute",
     )
Ejemplo n.º 26
0
 def add(self, a, b):
     print("server: add failure")
     raise Thrift.TApplicationException(
         type=Thrift.TApplicationException.INTERNAL_ERROR,
         message="for add",
     )
Ejemplo n.º 27
0
 def poke(self):
     print("server: poke failure")
     raise Thrift.TApplicationException(
         type=Thrift.TApplicationException.INTERNAL_ERROR,
         message="for poke",
     )
Ejemplo n.º 28
0
    def send(self, *args, **kwargs):
        params = inspect.getcallargs(
            getattr(service_module.Iface, method_name), self, *args, **kwargs
        )
        params.pop('self')  # self is already known

        # $methodName_args is the implicit struct containing the various
        # method parameters.
        call_args = args_type()
        for name, value in params.items():
            setattr(call_args, name, value)

        tracer = tracing.ClientTracer(channel=self.tchannel)
        span, headers = tracer.start_span(
            service=service_name, endpoint=method_name, headers={}
        )

        body = serializer.serialize_body(call_args)
        header = serializer.serialize_header(headers)

        # Glue for old API.
        if hasattr(self.tchannel, 'request'):
            tracing.apply_trace_flag(span, self.trace, True)
            with span:
                response = yield self.tchannel.request(
                    hostport=self.hostport, service=self.service
                ).send(
                    arg1=endpoint,
                    arg2=header,
                    arg3=body,  # body
                    headers=self.protocol_headers,
                )
                body = yield response.get_body()
        else:
            with span:
                response = yield self.tchannel.call(
                    scheme=schemes.THRIFT,
                    service=self.service,
                    arg1=endpoint,
                    arg2=header,
                    arg3=body,
                    hostport=self.hostport,
                    trace=self.trace,
                    tracing_span=span
                    # TODO: Need to handle these!
                    # headers=self.protocol_headers,
                )
                body = response.body

        call_result = serializer.deserialize_body(body)

        if not result_spec:
            # void return type and no exceptions allowed
            raise gen.Return(None)

        for exc_spec in result_spec[1:]:
            # May have failed with an exception
            exc = getattr(call_result, exc_spec[2])
            if exc is not None:
                raise exc

        if result_spec[0]:
            # Non-void return type. Return the result.
            success = getattr(call_result, result_spec[0][2])
            if success is not None:
                raise gen.Return(success)
        else:
            # No return type specified and no exceptions raised.
            raise gen.Return(None)

        # Expected a result but nothing was present in the object. Something
        # went wrong.
        from thrift import Thrift
        raise Thrift.TApplicationException(
            Thrift.TApplicationException.MISSING_RESULT,
            '%s failed: did not receive a result as expected' % method_name
        )
Ejemplo n.º 29
0
        closed = []
        try:
            raw_server.transport = Generic()
            raw_server.transport.close = lambda: closed.append(True)
            with self.client.get_client() as clt:
                raise Thrift.TException("Cleese")
        except ErrorThriftMessage, exc:
            self.assert_(len(closed) == 1)
            self.assert_(exc.args[0] == "Cleese")

        closed = []
        try:
            raw_server.transport = Generic()
            raw_server.transport.close = lambda: closed.append(True)
            with self.client.get_client() as clt:
                raise Thrift.TException()
        except Exception, exc:
            self.assert_(len(closed) == 1)
            self.assert_(exc.args[0] != "")

        # Cassandra exceptions - no open/close, added info
        excs = ((NotFoundException, UnavailableException,
                 InvalidRequestException))
        for exc_ in excs:
            try:
                with self.client.get_client() as clt:
                    raise exc_("John Cleese")
                self.fail_("Exception gobbled.")
            except (exc_), ex:
                self.assert_(len(ex.args) > 1)
                server = self.client._servers[self.client._current_server]
Ejemplo n.º 30
0
class TestClient(ConnectionTest):
    def setUp(self):
        super(TestClient, self).setUp()
        self.client = MockClient('Keyspace1',
                                 ['localhost:1234', 'localhost:5678'])

    def test_init(self):
        pass

    def test_build_server(self):

        exc_classes = (InvalidRequestException, UnavailableException,
                       Thrift.TException)

        cls = Cassandra.Client
        srv = self.client._build_server(cls, 'localhost', 1234)
        self.assert_(isinstance(srv, Cassandra.Client))

        self.client._timeout = 250
        srv = self.client._build_server(cls, 'localhost', 1234)
        self.assert_(srv._iprot.trans._TFramedTransport__trans._timeout ==
                     self.client._timeout * .001)
        self.assert_(isinstance(srv, Cassandra.Client))

        with save(conn.TSocket, ('TSocket', )):
            for exc_class in exc_classes:
                conn.TSocket.TSocket = raises(exc_class)
                self.assert_(
                    self.client._build_server(cls, 'localhost', 1234) is None)

    def test_get_server(self):
        # Zero clients
        real = self.client._clients
        bad = (None, [])
        for clts in bad:
            self.client._clients = clts
            self.assertRaises(ErrorCassandraNoServersConfigured,
                              self.client._get_server)

        # Round-robin
        fake = ['eggs', 'bacon', 'spam']
        self.client._clients = fake
        self.client._current_server = 0
        for exp in 2 * fake:
            srv = self.client._get_server()
            self.assert_(srv == exp)

    def test_list_servers(self):
        servers = self.client.list_servers()
        self.assert_(servers.__class__ == list)
        self.assert_(self.client._clients == servers)

    def test_connect(self):
        client = self.client._get_server()
        self.client._get_server = lambda: client

        # Already connected
        client.transport = _MockTransport()
        client.transport.isOpen = lambda: True
        self.assert_(self.client._connect())

        # Not connected, no error
        nopens = client.transport.calls['open']
        with save(client.transport, ('isOpen', )):
            client.transport.isOpen = lambda: False
            self.assert_(self.client._connect())
            self.assert_(client.transport.calls['open'] == nopens + 1)

        # Thrift Exception on connect - trapped
        ncloses = client.transport.calls['close']
        with save(client.transport, ('isOpen', 'open')):
            client.transport.isOpen = lambda: False
            client.transport.open = raises(TTransportException)
            self.assertRaises(ErrorThriftMessage, self.client._connect)
            self.assert_(client.transport.calls['close'] == ncloses + 1)

        # Other exception on connect should be ignored
        with save(client.transport, ('isOpen', 'open')):
            client.transport.isOpen = lambda: False
            client.transport.open = raises(Exception)
            ncloses = client.transport.calls['close']
            self.assertRaises(Exception, self.client._connect)

        # Connection recycling - reuse same connection
        nopens = client.transport.calls['open']
        ncloses = client.transport.calls['close']
        conn = self.client._connect()
        self.client._recycle = 60
        client.connect_time = time.time()
        self.assert_(conn is self.client._connect())
        self.assert_(client.transport.calls['open'] == nopens)
        self.assert_(client.transport.calls['open'] == ncloses)

        # Recycling - reconnect
        nopens = client.transport.calls['open']
        ncloses = client.transport.calls['close']
        conn = self.client._connect()
        self.client._recycle = 60
        client.connect_time = 0
        self.assert_(conn is self.client._connect())
        self.assert_(client.transport.calls['open'] == nopens + 1)
        self.assert_(client.transport.calls['close'] == ncloses + 1)

    def test_methods(self):
        """Test the various client methods."""

        methods = filter(lambda m: m[0] != '_', dir(Cassandra.Iface))

        real_client = Generic()

        @contextmanager
        def get_client():
            yield real_client

        client = self._client('Keyspace1', ['127.0.0.1:9160'])
        client.get_client = get_client
        dummy = lambda *args, **kwargs: (True, args, kwargs)

        for method in methods:
            self.assert_(hasattr(client, method),
                         "Lazyboy client lacks interface method %s" % method)
            self.assert_(callable(getattr(client, method)))
            setattr(real_client, method, dummy)
            res = getattr(client, method)('cleese', gilliam="Terry")
            self.assert_(isinstance(res, tuple),
                         "%s method failed: %s" % (method, res))
            self.assert_(res[0] is True)
            self.assert_(res[1] == ('cleese', ))
            self.assert_(res[2] == {'gilliam': "Terry"})

    def test_get_client(self):
        """Test get_client."""
        cass_client = Generic()
        raw_server = Generic()
        self.client._get_server = lambda: raw_server
        self.client._connect = lambda: raw_server
        self.client._servers = [raw_server]
        self.client._current_server = 0

        transport = _MockTransport()
        raw_server.transport = transport

        with self.client.get_client() as clt:
            self.assert_(clt is raw_server)

        # Socket error handling
        ncloses = transport.calls['close']
        try:
            with self.client.get_client() as clt:
                raise socket.error(7, "Test error")
            self.fail_("Exception not raised.")
        except ErrorThriftMessage, exc:
            self.assert_(transport.calls['close'] == ncloses + 1)
            self.assert_(exc.args[1] == "Test error")

        closed = []
        try:
            raw_server.transport = Generic()
            raw_server.transport.close = lambda: closed.append(True)
            with self.client.get_client() as clt:
                raise Thrift.TException("Cleese")
        except ErrorThriftMessage, exc:
            self.assert_(len(closed) == 1)
            self.assert_(exc.args[0] == "Cleese")