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();
}
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();
}
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));
}
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));
}
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);
}
Aggregations