Search in sources :

Example 6 with Metadata

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

the class Http2ClientStreamTransportState method transportDataReceived.

/**
   * Called by subclasses whenever a data frame is received from the transport.
   *
   * @param frame the received data frame
   * @param endOfStream {@code true} if there will be no more data received for this stream
   */
protected void transportDataReceived(ReadableBuffer frame, boolean endOfStream) {
    if (transportError != null) {
        // We've already detected a transport error and now we're just accumulating more detail
        // for it.
        transportError = transportError.augmentDescription("DATA-----------------------------\n" + ReadableBuffers.readAsString(frame, errorCharset));
        frame.close();
        if (transportError.getDescription().length() > 1000 || endOfStream) {
            http2ProcessingFailed(transportError, transportErrorMetadata);
        }
    } else {
        inboundDataReceived(frame);
        if (endOfStream) {
            // This is a protocol violation as we expect to receive trailers.
            transportError = Status.INTERNAL.withDescription("Received unexpected EOS on DATA frame from server.");
            transportErrorMetadata = new Metadata();
            transportReportStatus(transportError, false, transportErrorMetadata);
        }
    }
}
Also used : Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata)

Example 7 with Metadata

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

the class ClientAuthInterceptorTest method testWithOAuth2Credential.

@Test
public void testWithOAuth2Credential() {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {

        @Override
        public AccessToken refreshAccessToken() throws IOException {
            return token;
        }
    };
    interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
    ClientCall<String, Integer> interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
    Metadata headers = new Metadata();
    interceptedCall.start(listener, headers);
    assertEquals(listener, call.responseListener);
    assertEquals(headers, call.headers);
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    Assert.assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Metadata(io.grpc.Metadata) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Date(java.util.Date) Test(org.junit.Test)

Example 8 with Metadata

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

the class GoogleAuthLibraryCallCredentialsTest method copyCredentialsToHeaders.

@Test
public void copyCredentialsToHeaders() throws Exception {
    ListMultimap<String, String> values = LinkedListMultimap.create();
    values.put("Authorization", "token1");
    values.put("Authorization", "token2");
    // bytes "token3" in base64
    values.put("Extra-Authorization-bin", "dG9rZW4z");
    // bytes "token4" in base64
    values.put("Extra-Authorization-bin", "dG9rZW40");
    when(credentials.getRequestMetadata(eq(expectedUri))).thenReturn(Multimaps.asMap(values));
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(method, attrs, executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(credentials).getRequestMetadata(eq(expectedUri));
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    assertArrayEquals(new String[] { "token1", "token2" }, Iterables.toArray(authorization, String.class));
    Iterable<byte[]> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION);
    assertEquals(2, Iterables.size(extraAuthorization));
    assertArrayEquals("token3".getBytes(US_ASCII), Iterables.get(extraAuthorization, 0));
    assertArrayEquals("token4".getBytes(US_ASCII), Iterables.get(extraAuthorization, 1));
}
Also used : Metadata(io.grpc.Metadata) Test(org.junit.Test)

Example 9 with Metadata

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

the class GoogleAuthLibraryCallCredentialsTest method oauth2Credential.

@Test
public void oauth2Credential() {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    final OAuth2Credentials credentials = new OAuth2Credentials() {

        @Override
        public AccessToken refreshAccessToken() throws IOException {
            return token;
        }
    };
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(method, attrs, executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Metadata(io.grpc.Metadata) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Date(java.util.Date) Test(org.junit.Test)

Example 10 with Metadata

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

the class ManagedChannelImplTest method subtestCallsAndShutdown.

private void subtestCallsAndShutdown(boolean shutdownNow, boolean shutdownNowAfterShutdown) {
    FakeNameResolverFactory nameResolverFactory = new FakeNameResolverFactory(true);
    createChannel(nameResolverFactory, NO_INTERCEPTOR);
    verify(executorPool).getObject();
    verify(timerServicePool).getObject();
    ClientStream mockStream = mock(ClientStream.class);
    ClientStream mockStream2 = mock(ClientStream.class);
    Metadata headers = new Metadata();
    Metadata headers2 = new Metadata();
    // Configure the picker so that first RPC goes to delayed transport, and second RPC goes to
    // real transport.
    Subchannel subchannel = helper.createSubchannel(addressGroup, Attributes.EMPTY);
    subchannel.requestConnection();
    verify(mockTransportFactory).newClientTransport(any(SocketAddress.class), any(String.class), any(String.class));
    MockClientTransportInfo transportInfo = transports.poll();
    ConnectionClientTransport mockTransport = transportInfo.transport;
    verify(mockTransport).start(any(ManagedClientTransport.Listener.class));
    ManagedClientTransport.Listener transportListener = transportInfo.listener;
    when(mockTransport.newStream(same(method), same(headers), same(CallOptions.DEFAULT), any(StatsTraceContext.class))).thenReturn(mockStream);
    when(mockTransport.newStream(same(method), same(headers2), same(CallOptions.DEFAULT), any(StatsTraceContext.class))).thenReturn(mockStream2);
    transportListener.transportReady();
    when(mockPicker.pickSubchannel(new PickSubchannelArgsImpl(method, headers, CallOptions.DEFAULT))).thenReturn(PickResult.withNoResult());
    when(mockPicker.pickSubchannel(new PickSubchannelArgsImpl(method, headers2, CallOptions.DEFAULT))).thenReturn(PickResult.withSubchannel(subchannel));
    helper.updatePicker(mockPicker);
    // First RPC, will be pending
    ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
    verifyNoMoreInteractions(mockTransportFactory);
    call.start(mockCallListener, headers);
    verify(mockTransport, never()).newStream(same(method), same(headers), same(CallOptions.DEFAULT), any(StatsTraceContext.class));
    statsCtxFactory.pollContextOrFail();
    // Second RPC, will be assigned to the real transport
    ClientCall<String, Integer> call2 = channel.newCall(method, CallOptions.DEFAULT);
    call2.start(mockCallListener2, headers2);
    verify(mockTransport).newStream(same(method), same(headers2), same(CallOptions.DEFAULT), statsTraceCtxCaptor.capture());
    assertEquals(statsCtxFactory.pollContextOrFail(), statsTraceCtxCaptor.getValue().getStatsContext());
    verify(mockTransport).newStream(same(method), same(headers2), same(CallOptions.DEFAULT), statsTraceCtxCaptor.capture());
    verify(mockStream2).start(any(ClientStreamListener.class));
    // Shutdown
    if (shutdownNow) {
        channel.shutdownNow();
    } else {
        channel.shutdown();
        if (shutdownNowAfterShutdown) {
            channel.shutdownNow();
            shutdownNow = true;
        }
    }
    assertTrue(channel.isShutdown());
    assertFalse(channel.isTerminated());
    assertEquals(1, nameResolverFactory.resolvers.size());
    verify(mockLoadBalancerFactory).newLoadBalancer(any(Helper.class));
    // Further calls should fail without going to the transport
    ClientCall<String, Integer> call3 = channel.newCall(method, CallOptions.DEFAULT);
    call3.start(mockCallListener3, headers2);
    timer.runDueTasks();
    executor.runDueTasks();
    verify(mockCallListener3).onClose(statusCaptor.capture(), any(Metadata.class));
    assertSame(Status.Code.UNAVAILABLE, statusCaptor.getValue().getCode());
    if (shutdownNow) {
        // LoadBalancer and NameResolver are shut down as soon as delayed transport is terminated.
        verify(mockLoadBalancer).shutdown();
        assertTrue(nameResolverFactory.resolvers.get(0).shutdown);
        // call should have been aborted by delayed transport
        executor.runDueTasks();
        verify(mockCallListener).onClose(same(ManagedChannelImpl.SHUTDOWN_NOW_STATUS), any(Metadata.class));
    } else {
        // LoadBalancer and NameResolver are still running.
        verify(mockLoadBalancer, never()).shutdown();
        assertFalse(nameResolverFactory.resolvers.get(0).shutdown);
        // call and call2 are still alive, and can still be assigned to a real transport
        SubchannelPicker picker2 = mock(SubchannelPicker.class);
        when(picker2.pickSubchannel(new PickSubchannelArgsImpl(method, headers, CallOptions.DEFAULT))).thenReturn(PickResult.withSubchannel(subchannel));
        helper.updatePicker(picker2);
        executor.runDueTasks();
        verify(mockTransport).newStream(same(method), same(headers), same(CallOptions.DEFAULT), any(StatsTraceContext.class));
        verify(mockStream).start(any(ClientStreamListener.class));
    }
    // After call is moved out of delayed transport, LoadBalancer, NameResolver and the transports
    // will be shutdown.
    verify(mockLoadBalancer).shutdown();
    assertTrue(nameResolverFactory.resolvers.get(0).shutdown);
    if (shutdownNow) {
        // Channel shutdownNow() all subchannels after shutting down LoadBalancer
        verify(mockTransport).shutdownNow(ManagedChannelImpl.SHUTDOWN_NOW_STATUS);
    } else {
        verify(mockTransport, never()).shutdownNow(any(Status.class));
    }
    // LoadBalancer should shutdown the subchannel
    subchannel.shutdown();
    verify(mockTransport).shutdown();
    // Killing the remaining real transport will terminate the channel
    transportListener.transportShutdown(Status.UNAVAILABLE);
    assertFalse(channel.isTerminated());
    verify(executorPool, never()).returnObject(anyObject());
    verify(timerServicePool, never()).returnObject(anyObject());
    transportListener.transportTerminated();
    assertTrue(channel.isTerminated());
    verify(executorPool).returnObject(executor.getScheduledExecutorService());
    verify(timerServicePool).returnObject(timer.getScheduledExecutorService());
    verifyNoMoreInteractions(oobExecutorPool);
    verify(mockTransportFactory).close();
    verifyNoMoreInteractions(mockTransportFactory);
    verify(mockTransport, atLeast(0)).getLogId();
    verifyNoMoreInteractions(mockTransport);
}
Also used : Status(io.grpc.Status) Metadata(io.grpc.Metadata) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) Matchers.anyString(org.mockito.Matchers.anyString) Helper(io.grpc.LoadBalancer.Helper) SubchannelPicker(io.grpc.LoadBalancer.SubchannelPicker) Subchannel(io.grpc.LoadBalancer.Subchannel) SocketAddress(java.net.SocketAddress)

Aggregations

Metadata (io.grpc.Metadata)283 Test (org.junit.Test)229 Status (io.grpc.Status)78 ByteArrayInputStream (java.io.ByteArrayInputStream)25 ClientStream (io.grpc.internal.ClientStream)20 InputStream (java.io.InputStream)19 Buffer (okio.Buffer)16 ClientCall (io.grpc.ClientCall)14 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 ServerStreamListener (io.grpc.internal.ServerStreamListener)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 ServerCall (io.grpc.ServerCall)12 StatsContext (com.google.instrumentation.stats.StatsContext)11 CallOptions (io.grpc.CallOptions)11 IOException (java.io.IOException)11 Context (io.grpc.Context)10 StatusRuntimeException (io.grpc.StatusRuntimeException)10 Matchers.anyString (org.mockito.Matchers.anyString)10 ServerStream (io.grpc.internal.ServerStream)9 ServiceDescriptor (io.grpc.ServiceDescriptor)8