Search in sources :

Example 26 with ServerInterceptor

use of io.grpc.ServerInterceptor in project brave by openzipkin.

the class ITTracingServerInterceptor method init.

void init(@Nullable ServerInterceptor userInterceptor) throws Exception {
    stop();
    // tracing interceptor needs to go last
    ServerInterceptor tracingInterceptor = grpcTracing.newServerInterceptor();
    ServerInterceptor[] interceptors = userInterceptor != null ? new ServerInterceptor[] { userInterceptor, tracingInterceptor } : new ServerInterceptor[] { tracingInterceptor };
    server = ServerBuilder.forPort(PickUnusedPort.get()).addService(ServerInterceptors.intercept(new GreeterImpl(grpcTracing), interceptors)).build().start();
    client = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext(true).build();
}
Also used : ServerInterceptor(io.grpc.ServerInterceptor)

Example 27 with ServerInterceptor

use of io.grpc.ServerInterceptor in project brave by openzipkin.

the class ITTracingServerInterceptor method currentSpanVisibleToUserInterceptors.

/**
 * NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
 *
 * <p>Also notice that we are only making the current context available in the request side.
 */
@Test
public void currentSpanVisibleToUserInterceptors() throws Exception {
    AtomicReference<TraceContext> fromUserInterceptor = new AtomicReference<>();
    init(new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            testLogger.info("in span!");
            fromUserInterceptor.set(grpcTracing.tracing().currentTraceContext().get());
            return next.startCall(call, headers);
        }
    });
    GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
    assertThat(fromUserInterceptor.get()).isNotNull();
    spans.take();
}
Also used : ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata) TraceContext(brave.propagation.TraceContext) StrictCurrentTraceContext(brave.propagation.StrictCurrentTraceContext) ThreadContextCurrentTraceContext(brave.context.log4j2.ThreadContextCurrentTraceContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 28 with ServerInterceptor

use of io.grpc.ServerInterceptor in project pravega by pravega.

the class RPCTracingHelpersTest method testInterceptors.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testInterceptors() {
    String requestDescriptor = "createStream-myScope-myStream";
    long requestId = 1234L;
    ClientInterceptor clientInterceptor = RPCTracingHelpers.getClientInterceptor();
    RequestTracker requestTracker = new RequestTracker(true);
    // Mocking RPC elements.
    MethodDescriptor.Marshaller<Object> mockMarshaller = Mockito.mock(MethodDescriptor.Marshaller.class);
    ClientCall.Listener<Object> listener = Mockito.mock(ClientCall.Listener.class);
    ServerCall serverCall = Mockito.mock(ServerCall.class);
    ServerCallHandler serverCallHandler = Mockito.mock(ServerCallHandler.class);
    @Cleanup("shutdown") ManagedChannel channel = NettyChannelBuilder.forTarget("localhost").build();
    MethodDescriptor method = MethodDescriptor.newBuilder().setFullMethodName("createStream").setType(MethodDescriptor.MethodType.UNARY).setRequestMarshaller(mockMarshaller).setResponseMarshaller(mockMarshaller).build();
    Mockito.when(serverCall.getMethodDescriptor()).thenReturn(method);
    // Actual elements to work with.
    CallOptions callOptions = CallOptions.DEFAULT;
    Metadata headers = new Metadata();
    // Test that headers do not contain tracing-related key/values, as call options are not set.
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertFalse(headers.containsKey(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertFalse(headers.containsKey(RPCTracingHelpers.ID_HEADER));
    // Check that the server interceptor handles clients not sending tracing headers and that the cache remains clean.
    ServerInterceptor serverInterceptor = RPCTracingHelpers.getServerInterceptor(requestTracker);
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(0, requestTracker.getNumDescriptors());
    // Add call options and check that headers are correctly set.
    callOptions = callOptions.withOption(RPCTracingHelpers.REQUEST_DESCRIPTOR_CALL_OPTION, requestDescriptor).withOption(RPCTracingHelpers.REQUEST_ID_CALL_OPTION, String.valueOf(requestId));
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertEquals(requestDescriptor, headers.get(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertEquals(requestId, Long.parseLong(headers.get(RPCTracingHelpers.ID_HEADER)));
    // Test that the server interceptor correctly sets these headers in the cache for further tracking.
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(1, requestTracker.getNumDescriptors());
    assertEquals(requestId, requestTracker.getRequestIdFor(requestDescriptor));
}
Also used : ServerCallHandler(io.grpc.ServerCallHandler) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) RequestTracker(io.pravega.common.tracing.RequestTracker) MethodDescriptor(io.grpc.MethodDescriptor) Cleanup(lombok.Cleanup) ServerCall(io.grpc.ServerCall) ClientCall(io.grpc.ClientCall) ServerInterceptor(io.grpc.ServerInterceptor) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) Test(org.junit.Test)

Example 29 with ServerInterceptor

use of io.grpc.ServerInterceptor in project grpc-java by grpc.

the class XdsServerWrapperTest method buildInterceptor_inline.

@Test
@SuppressWarnings("unchecked")
public void buildInterceptor_inline() throws Exception {
    final SettableFuture<Server> start = SettableFuture.create();
    Executors.newSingleThreadExecutor().execute(new Runnable() {

        @Override
        public void run() {
            try {
                start.set(xdsServerWrapper.start());
            } catch (Exception ex) {
                start.setException(ex);
            }
        }
    });
    xdsClient.ldsResource.get(5, TimeUnit.SECONDS);
    RouteMatch routeMatch = RouteMatch.create(PathMatcher.fromPath("/FooService/barMethod", true), Collections.<HeaderMatcher>emptyList(), null);
    Filter filter = mock(Filter.class, withSettings().extraInterfaces(ServerInterceptorBuilder.class));
    when(filter.typeUrls()).thenReturn(new String[] { "filter-type-url" });
    filterRegistry.register(filter);
    FilterConfig f0 = mock(FilterConfig.class);
    FilterConfig f0Override = mock(FilterConfig.class);
    when(f0.typeUrl()).thenReturn("filter-type-url");
    final List<Integer> interceptorTrace = new ArrayList<>();
    ServerInterceptor interceptor0 = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            interceptorTrace.add(0);
            return next.startCall(call, headers);
        }
    };
    ServerInterceptor interceptor1 = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            interceptorTrace.add(1);
            return next.startCall(call, headers);
        }
    };
    when(((ServerInterceptorBuilder) filter).buildServerInterceptor(f0, null)).thenReturn(interceptor0);
    when(((ServerInterceptorBuilder) filter).buildServerInterceptor(f0, f0Override)).thenReturn(interceptor1);
    Route route = Route.forAction(routeMatch, null, ImmutableMap.<String, FilterConfig>of());
    VirtualHost virtualHost = VirtualHost.create("v1", Collections.singletonList("foo.google.com"), Arrays.asList(route), ImmutableMap.of("filter-config-name-0", f0Override));
    HttpConnectionManager hcmVirtual = HttpConnectionManager.forVirtualHosts(0L, Collections.singletonList(virtualHost), Arrays.asList(new NamedFilterConfig("filter-config-name-0", f0), new NamedFilterConfig("filter-config-name-1", f0)));
    EnvoyServerProtoData.FilterChain filterChain = createFilterChain("filter-chain-0", hcmVirtual);
    xdsClient.deliverLdsUpdate(Collections.singletonList(filterChain), null);
    start.get(5000, TimeUnit.MILLISECONDS);
    verify(mockServer).start();
    assertThat(selectorManager.getSelectorToUpdateSelector().getRoutingConfigs().size()).isEqualTo(1);
    ServerInterceptor realInterceptor = selectorManager.getSelectorToUpdateSelector().getRoutingConfigs().get(filterChain).get().interceptors().get(route);
    assertThat(realInterceptor).isNotNull();
    ServerCall<Void, Void> serverCall = mock(ServerCall.class);
    ServerCallHandler<Void, Void> mockNext = mock(ServerCallHandler.class);
    final ServerCall.Listener<Void> listener = new ServerCall.Listener<Void>() {
    };
    when(mockNext.startCall(any(ServerCall.class), any(Metadata.class))).thenReturn(listener);
    realInterceptor.interceptCall(serverCall, new Metadata(), mockNext);
    assertThat(interceptorTrace).isEqualTo(Arrays.asList(1, 0));
    verify(mockNext).startCall(eq(serverCall), any(Metadata.class));
}
Also used : XdsServingStatusListener(io.grpc.xds.XdsServerBuilder.XdsServingStatusListener) Server(io.grpc.Server) ServerCallHandler(io.grpc.ServerCallHandler) ArrayList(java.util.ArrayList) Metadata(io.grpc.Metadata) NamedFilterConfig(io.grpc.xds.Filter.NamedFilterConfig) ServerCall(io.grpc.ServerCall) FilterConfig(io.grpc.xds.Filter.FilterConfig) NamedFilterConfig(io.grpc.xds.Filter.NamedFilterConfig) ServerInterceptorBuilder(io.grpc.xds.Filter.ServerInterceptorBuilder) Route(io.grpc.xds.VirtualHost.Route) TimeoutException(java.util.concurrent.TimeoutException) StatusException(io.grpc.StatusException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) RouteMatch(io.grpc.xds.VirtualHost.Route.RouteMatch) ServerInterceptor(io.grpc.ServerInterceptor) FilterChain(io.grpc.xds.EnvoyServerProtoData.FilterChain) Test(org.junit.Test)

Example 30 with ServerInterceptor

use of io.grpc.ServerInterceptor in project grpc-java by grpc.

the class OrcaMetricReportingServerInterceptorTest method shareCallMetricRecorderInContext.

@Test
public void shareCallMetricRecorderInContext() throws IOException {
    final CallMetricRecorder callMetricRecorder = InternalCallMetricRecorder.newCallMetricRecorder();
    ServerStreamTracer.Factory callMetricRecorderSharingStreamTracerFactory = new ServerStreamTracer.Factory() {

        @Override
        public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) {
            return new ServerStreamTracer() {

                @Override
                public Context filterContext(Context context) {
                    return context.withValue(InternalCallMetricRecorder.CONTEXT_KEY, callMetricRecorder);
                }
            };
        }
    };
    final AtomicReference<CallMetricRecorder> callMetricRecorderCapture = new AtomicReference<>();
    SimpleServiceGrpc.SimpleServiceImplBase simpleServiceImpl = new SimpleServiceGrpc.SimpleServiceImplBase() {

        @Override
        public void unaryRpc(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
            callMetricRecorderCapture.set(CallMetricRecorder.getCurrent());
            SimpleResponse response = SimpleResponse.newBuilder().setResponseMessage("Simple response").build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    };
    ServerInterceptor metricReportingServerInterceptor = new OrcaMetricReportingServerInterceptor();
    String serverName = InProcessServerBuilder.generateName();
    grpcCleanupRule.register(InProcessServerBuilder.forName(serverName).directExecutor().addStreamTracerFactory(callMetricRecorderSharingStreamTracerFactory).addService(ServerInterceptors.intercept(simpleServiceImpl, metricReportingServerInterceptor)).build().start());
    ManagedChannel channel = grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).build());
    ClientCalls.blockingUnaryCall(channel, SIMPLE_METHOD, CallOptions.DEFAULT, REQUEST);
    assertThat(callMetricRecorderCapture.get()).isSameInstanceAs(callMetricRecorder);
}
Also used : Context(io.grpc.Context) StreamObserver(io.grpc.stub.StreamObserver) ServerStreamTracer(io.grpc.ServerStreamTracer) Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) SimpleServiceGrpc(io.grpc.testing.protobuf.SimpleServiceGrpc) SimpleRequest(io.grpc.testing.protobuf.SimpleRequest) SimpleResponse(io.grpc.testing.protobuf.SimpleResponse) ServerInterceptor(io.grpc.ServerInterceptor) ManagedChannel(io.grpc.ManagedChannel) InternalCallMetricRecorder(io.grpc.services.InternalCallMetricRecorder) CallMetricRecorder(io.grpc.services.CallMetricRecorder) Test(org.junit.Test)

Aggregations

ServerInterceptor (io.grpc.ServerInterceptor)37 Metadata (io.grpc.Metadata)23 Test (org.junit.Test)15 ServerCall (io.grpc.ServerCall)10 ServerCallHandler (io.grpc.ServerCallHandler)9 SimpleForwardingServerCallListener (io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener)7 Server (io.grpc.Server)6 IOException (java.io.IOException)6 SimpleForwardingServerCall (io.grpc.ForwardingServerCall.SimpleForwardingServerCall)4 Status (io.grpc.Status)4 ManagedChannel (io.grpc.ManagedChannel)3 Listener (io.grpc.ServerCall.Listener)3 ServerTransportFilter (io.grpc.ServerTransportFilter)3 InetSocketAddress (java.net.InetSocketAddress)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 TraceContext (brave.propagation.TraceContext)2 GrpcStreamConfiguration (com.navercorp.pinpoint.collector.grpc.config.GrpcStreamConfiguration)2 DefaultServerRequestFactory (com.navercorp.pinpoint.collector.receiver.grpc.service.DefaultServerRequestFactory)2 StreamExecutorServerInterceptorFactory (com.navercorp.pinpoint.collector.receiver.grpc.service.StreamExecutorServerInterceptorFactory)2 MetadataServerTransportFilter (com.navercorp.pinpoint.grpc.server.MetadataServerTransportFilter)2