示例#1
0
    def test_intercept_handler_exception(self):
        current_span = mock.Mock()
        mock_tracer = MockTracer(None, None, None)
        patch = mock.patch(
            'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
            MockTracer)
        interceptor = server_interceptor.OpenCensusServerInterceptor(
            None, None)
        mock_context = mock.Mock()
        mock_context.invocation_metadata = mock.Mock(return_value=None)
        mock_continuation = mock.Mock()
        mock_continuation.unary_unary = mock.Mock(
            side_effect=Exception('Test'))
        with patch:
            # patch the wrapper's handler to return an exception
            rpc_wrapper = interceptor.intercept_handler(
                mock.Mock(), mock.Mock())
            rpc_wrapper.handler.unary_unary = mock.Mock(
                side_effect=Exception('Test'))
            with self.assertRaises(Exception):
                rpc_wrapper.unary_unary(mock.Mock(), mock_context)

        expected_attributes = {'/component': 'grpc', '/error/message': 'Test'}

        self.assertEqual(
            execution_context.get_opencensus_tracer().current_span.attributes,
            expected_attributes)
 def test_intercept_service(self):
     interceptor = server_interceptor.OpenCensusServerInterceptor(
         None, None)
     mock_handler = mock.Mock()
     interceptor.intercept_handler = mock_handler
     interceptor.intercept_service(None, None)
     self.assertTrue(mock_handler.called)
 def test_constructor(self):
     sampler = mock.Mock()
     exporter = mock.Mock()
     interceptor = server_interceptor.OpenCensusServerInterceptor(
         sampler=sampler, exporter=exporter)
     self.assertEqual(interceptor.sampler, sampler)
     self.assertEqual(interceptor.exporter, exporter)
    def test_intercept_service(self):
        test_dimensions = [
            ['unary_unary', False, False],
            ['unary_stream', False, True],
            ['stream_unary', True, False],
            ['stream_stream', True, True],
        ]
        for rpc_fn_name, request_streaming, response_streaming in test_dimensions:
            patch = mock.patch(
                'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
                MockTracer)
            mock_context = mock.Mock()
            mock_context.invocation_metadata = mock.Mock(
                return_value=(('test_key', b'test_value'), ))
            mock_handler = mock.Mock()
            mock_handler.request_streaming = request_streaming
            mock_handler.response_streaming = response_streaming
            mock_continuation = mock.Mock(return_value=mock_handler)

            mock_context._rpc_event.call_details.method = 'hello'
            interceptor = server_interceptor.OpenCensusServerInterceptor(
                None, None)

            with patch:
                handler = interceptor.intercept_service(
                    mock_continuation, mock.Mock())
                getattr(handler, rpc_fn_name)(mock.Mock(), mock_context)

            expected_attributes = {
                '/component': 'grpc',
            }

            self.assertEqual(
                execution_context.get_opencensus_tracer().current_span().
                attributes, expected_attributes)
    def test_intercept_service_no_metadata(self):
        patch = mock.patch(
            'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
            MockTracer)
        mock_context = mock.Mock()
        mock_context.invocation_metadata = mock.Mock(return_value=None)
        mock_context._rpc_event.call_details.method = 'hello'
        interceptor = server_interceptor.OpenCensusServerInterceptor(
            None, None)
        mock_handler = mock.Mock()
        mock_handler.request_streaming = False
        mock_handler.response_streaming = False
        mock_continuation = mock.Mock(return_value=mock_handler)

        with patch:
            interceptor.intercept_service(mock_continuation,
                                          mock.Mock()).unary_unary(
                                              mock.Mock(), mock_context)

        expected_attributes = {
            '/component': 'grpc',
        }

        self.assertEqual(
            execution_context.get_opencensus_tracer().current_span().
            attributes, expected_attributes)
    def test_intercept_handler_exception(self):
        test_dimensions = [
            ['unary_unary', False, False],
            ['unary_stream', False, True],
            ['stream_unary', True, False],
            ['stream_stream', True, True],
        ]
        for rpc_fn_name, request_streaming, response_streaming in test_dimensions:
            patch = mock.patch(
                'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
                MockTracer)
            interceptor = server_interceptor.OpenCensusServerInterceptor(
                None, None)
            mock_context = mock.Mock()
            mock_context.invocation_metadata = mock.Mock(return_value=None)
            mock_context._rpc_event.call_details.method = 'hello'
            mock_handler = mock.Mock()
            mock_handler.request_streaming = request_streaming
            mock_handler.response_streaming = response_streaming
            setattr(mock_handler, rpc_fn_name,
                    mock.Mock(side_effect=Exception('Test')))
            mock_continuation = mock.Mock(return_value=mock_handler)

            # mock_continuation.unary_unary = mock.Mock())
            with patch:
                # patch the wrapper's handler to return an exception
                handler = interceptor.intercept_service(
                    mock_continuation, mock.Mock())
                with self.assertRaises(Exception):
                    getattr(handler, rpc_fn_name)(mock.Mock(), mock_context)

            expected_attributes = {
                '/component': 'grpc',
                '/error/message': 'Test'
            }

            current_span = execution_context.get_opencensus_tracer(
            ).current_span()
            self.assertEqual(
                execution_context.get_opencensus_tracer().current_span().
                attributes, expected_attributes)

            self.assertEqual(current_span.span_kind,
                             span_module.SpanKind.SERVER)

            # check that the stack trace is attached to the current span
            self.assertIsNotNone(current_span.stack_trace)
            self.assertIsNotNone(current_span.stack_trace.stack_trace_hash_id)
            self.assertNotEqual(current_span.stack_trace.stack_frames, [])

            # check that the status obj is attached to the current span
            self.assertIsNotNone(current_span.status)
            self.assertEqual(current_span.status.code, code_pb2.UNKNOWN)
            self.assertEqual(current_span.status.message, 'Test')
示例#7
0
    def _instance(self):
        sampler = always_on.AlwaysOnSampler()
        exporter = print_exporter.PrintExporter(
            transport=background_thread.BackgroundThreadTransport)
        # exporter = stackdriver_exporter.StackdriverExporter(project_id="")
        tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(
            sampler, exporter)
        server = grpc.server(
            futures.ThreadPoolExecutor(max_workers=self.max_workers),
            interceptors=(tracer_interceptor, ))
        ouroboros_pb2_grpc.add_OuroborosServicer_to_server(
            OuroborosServicer(), server)
        server.add_insecure_port(f"{self.host}:{self.port}")

        return server
示例#8
0
def serve():
    sampler = always_on.AlwaysOnSampler()
    exporter = stackdriver_exporter.StackdriverExporter()
    tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(
        sampler, exporter)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         interceptors=(tracer_interceptor, ))
    hello_world_pb2_grpc.add_GreeterServicer_to_server(HelloWorld(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
def main():
    # Setup and start the gRPC server with the OpenCensus integration/interceptor
    tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(
        always_on.AlwaysOnSampler(), stackdriverExporter)

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         interceptors=(tracer_interceptor, ))
    proto.add_FetchServicer_to_server(CapitalizeServer(), server)
    server.add_insecure_port('[::]:9778')
    server.start()

    try:
        while True:
            time.sleep(60 * 60)
    except KeyboardInterrupt:
        server.stop(0)
def serve_grpc_binary(port=pb2.PYTHON_GRPC_BINARY_PROPAGATION_PORT):
    """Run the GRPC/binary server, shut down on exiting context."""
    interceptor = server_interceptor.OpenCensusServerInterceptor(
        always_on.AlwaysOnSampler(),
        trace_exporter.TraceExporter(SERVICE_NAME))
    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=GRPC_TPE_WORKERS),
        interceptors=(interceptor, ))
    pb2_grpc.add_TestExecutionServiceServicer_to_server(
        GRPCBinaryTestServer(), server)
    server.add_insecure_port('[::]:{}'.format(port))
    try:
        server.start()
        yield server
    finally:
        server.stop(0)
    logger.debug("Shut down grpc server")
    def test_intercept_handler_no_metadata(self):
        patch = mock.patch(
            'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
            MockTracer)
        mock_context = mock.Mock()
        mock_context.invocation_metadata = mock.Mock(return_value=None)
        interceptor = server_interceptor.OpenCensusServerInterceptor(
            None, None)

        with patch:
            interceptor.intercept_handler(
                mock.Mock(), mock.Mock()
            ).unary_unary(mock.Mock(), mock_context)

        expected_attributes = {
            '/component': 'grpc',
        }

        self.assertEqual(
            execution_context.get_opencensus_tracer().current_span().attributes,
            expected_attributes)
    def test_intercept_handler(self):
        current_span = mock.Mock()
        mock_tracer = MockTracer(None, None, None)
        patch = mock.patch(
            'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
            MockTracer)
        mock_details = mock.Mock()
        mock_details.invocation_metadata = (('test_key', b'test_value'), )
        interceptor = server_interceptor.OpenCensusServerInterceptor(
            None, None)

        with patch:
            interceptor.intercept_handler(mock.Mock(), mock_details)

        expected_attributes = {
            '/component': 'grpc',
        }

        self.assertEqual(
            execution_context.get_opencensus_tracer().current_span.attributes,
            expected_attributes)
    def test_intercept_handler_exception(self):
        patch = mock.patch(
            'opencensus.trace.ext.grpc.server_interceptor.tracer_module.Tracer',
            MockTracer)
        interceptor = server_interceptor.OpenCensusServerInterceptor(
            None, None)
        mock_context = mock.Mock()
        mock_context.invocation_metadata = mock.Mock(return_value=None)
        mock_continuation = mock.Mock()
        mock_continuation.unary_unary = mock.Mock(side_effect=Exception('Test'))
        with patch:
            # patch the wrapper's handler to return an exception
            rpc_wrapper = interceptor.intercept_handler(
                mock.Mock(), mock.Mock())
            rpc_wrapper.handler.unary_unary = mock.Mock(
                side_effect=Exception('Test'))
            with self.assertRaises(Exception):
                rpc_wrapper.unary_unary(mock.Mock(), mock_context)

        expected_attributes = {
            '/component': 'grpc',
            '/error/message': 'Test'
        }

        current_span = execution_context.get_opencensus_tracer().current_span()
        self.assertEqual(
            execution_context.get_opencensus_tracer().current_span().attributes,
            expected_attributes)

        # check that the stack trace is attached to the current span
        self.assertIsNotNone(current_span.stack_trace)
        self.assertIsNotNone(current_span.stack_trace.stack_trace_hash_id)
        self.assertNotEqual(current_span.stack_trace.stack_frames, [])

        # check that the status obj is attached to the current span
        self.assertIsNotNone(current_span.status)
        self.assertEqual(current_span.status.code, code_pb2.UNKNOWN)
        self.assertEqual(current_span.status.message, 'Test')
示例#14
0
            logger.info("Profiler enabled.")
            initStackdriverProfiling()
    except KeyError:
        logger.info("Profiler disabled.")

    tracer = None
    try:
        if "DISABLE_TRACING" in os.environ:
            raise KeyError()
        else:
            logger.info("Tracing enabled.")
            sampler = always_on.AlwaysOnSampler()
            exporter = stackdriver_exporter.StackdriverExporter(
                project_id=os.environ.get('GCP_PROJECT_ID'),
                transport=AsyncTransport)
            tracer_interceptor = server_interceptor.OpenCensusServerInterceptor(
                sampler, exporter)
            tracer = Tracer(exporter=exporter)

    except (KeyError, DefaultCredentialsError):
        logger.info("Tracing disabled.")
        tracer_interceptor = server_interceptor.OpenCensusServerInterceptor()

    try:
        if "DISABLE_DEBUGGER" in os.environ:
            raise KeyError()
        else:
            logger.info("Debugger enabled.")
            try:
                googleclouddebugger.enable(module='recommendationserver',
                                           version='1.0.0')
            except Exception, err: