Search in sources :

Example 1 with Attributes

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

the class OobChannel method setSubchannel.

// Must be called only once, right after the OobChannel is created.
void setSubchannel(final InternalSubchannel subchannel) {
    log.log(Level.FINE, "[{0}] Created with [{1}]", new Object[] { this, subchannel });
    subchannelImpl = new SubchannelImpl() {

        @Override
        public void shutdown() {
            subchannel.shutdown();
        }

        @Override
        ClientTransport obtainActiveTransport() {
            return subchannel.obtainActiveTransport();
        }

        @Override
        public void requestConnection() {
            subchannel.obtainActiveTransport();
        }

        @Override
        public EquivalentAddressGroup getAddresses() {
            return subchannel.getAddressGroup();
        }

        @Override
        public Attributes getAttributes() {
            return Attributes.EMPTY;
        }
    };
    subchannelPicker = new SubchannelPicker() {

        final PickResult result = PickResult.withSubchannel(subchannelImpl);

        @Override
        public PickResult pickSubchannel(PickSubchannelArgs args) {
            return result;
        }
    };
    delayedTransport.reprocess(subchannelPicker);
}
Also used : SubchannelPicker(io.grpc.LoadBalancer.SubchannelPicker) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) Attributes(io.grpc.Attributes) PickResult(io.grpc.LoadBalancer.PickResult) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs)

Example 2 with Attributes

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

the class InProcessTransport method start.

@CheckReturnValue
@Override
public synchronized Runnable start(ManagedClientTransport.Listener listener) {
    this.clientTransportListener = listener;
    InProcessServer server = InProcessServer.findServer(name);
    if (server != null) {
        serverTransportListener = server.register(this);
    }
    if (serverTransportListener == null) {
        shutdownStatus = Status.UNAVAILABLE.withDescription("Could not find server: " + name);
        final Status localShutdownStatus = shutdownStatus;
        return new Runnable() {

            @Override
            public void run() {
                synchronized (InProcessTransport.this) {
                    notifyShutdown(localShutdownStatus);
                    notifyTerminated();
                }
            }
        };
    }
    return new Runnable() {

        @Override
        @SuppressWarnings("deprecation")
        public void run() {
            synchronized (InProcessTransport.this) {
                Attributes serverTransportAttrs = Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InProcessSocketAddress(name)).build();
                serverStreamAttributes = serverTransportListener.transportReady(serverTransportAttrs);
                clientTransportListener.transportReady();
            }
        }
    };
}
Also used : Status(io.grpc.Status) Attributes(io.grpc.Attributes) CheckReturnValue(javax.annotation.CheckReturnValue)

Example 3 with Attributes

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

the class ManagedChannelImplTest method informationPropagatedToNewStreamAndCallCredentials.

/**
   * Test that information such as the Call's context, MethodDescriptor, authority, executor are
   * propagated to newStream() and applyRequestMetadata().
   */
@Test
public void informationPropagatedToNewStreamAndCallCredentials() {
    ResolvedServerInfoGroup serverInfoGroup = ResolvedServerInfoGroup.builder().add(server).build();
    createChannel(new FakeNameResolverFactory(true), NO_INTERCEPTOR);
    CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds);
    final Context.Key<String> testKey = Context.key("testing");
    Context ctx = Context.current().withValue(testKey, "testValue");
    final LinkedList<Context> credsApplyContexts = new LinkedList<Context>();
    final LinkedList<Context> newStreamContexts = new LinkedList<Context>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            credsApplyContexts.add(Context.current());
            return null;
        }
    }).when(creds).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // First call will be on delayed transport.  Only newCall() is run within the expected context,
    // so that we can verify that the context is explicitly attached before calling newStream() and
    // applyRequestMetadata(), which happens after we detach the context from the thread.
    Context origCtx = ctx.attach();
    assertEquals("testValue", testKey.get());
    ClientCall<String, Integer> call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    assertNull(testKey.get());
    call.start(mockCallListener, new Metadata());
    // Simulate name resolution results
    Subchannel subchannel = helper.createSubchannel(serverInfoGroup.toEquivalentAddressGroup(), Attributes.EMPTY);
    subchannel.requestConnection();
    verify(mockTransportFactory).newClientTransport(same(socketAddress), eq(authority), eq(userAgent));
    MockClientTransportInfo transportInfo = transports.poll();
    final ConnectionClientTransport transport = transportInfo.transport;
    when(transport.getAttributes()).thenReturn(Attributes.EMPTY);
    doAnswer(new Answer<ClientStream>() {

        @Override
        public ClientStream answer(InvocationOnMock in) throws Throwable {
            newStreamContexts.add(Context.current());
            return mock(ClientStream.class);
        }
    }).when(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    verify(creds, never()).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // applyRequestMetadata() is called after the transport becomes ready.
    transportInfo.listener.transportReady();
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    helper.updatePicker(mockPicker);
    executor.runDueTasks();
    ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(Attributes.class);
    ArgumentCaptor<MetadataApplier> applierCaptor = ArgumentCaptor.forClass(MetadataApplier.class);
    verify(creds).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    verify(transport, never()).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    // The context should not live beyond the scope of newStream() and applyRequestMetadata()
    assertNull(testKey.get());
    // Second call will not be on delayed transport
    origCtx = ctx.attach();
    call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    call.start(mockCallListener, new Metadata());
    verify(creds, times(2)).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    // This is from the first call
    verify(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // Still, newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport, times(2)).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    assertNull(testKey.get());
}
Also used : Attributes(io.grpc.Attributes) Metadata(io.grpc.Metadata) ResolvedServerInfoGroup(io.grpc.ResolvedServerInfoGroup) CallOptions(io.grpc.CallOptions) Matchers.anyString(org.mockito.Matchers.anyString) Executor(java.util.concurrent.Executor) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) Context(io.grpc.Context) MetadataApplier(io.grpc.CallCredentials.MetadataApplier) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) MethodDescriptor(io.grpc.MethodDescriptor) LinkedList(java.util.LinkedList) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Subchannel(io.grpc.LoadBalancer.Subchannel) Test(org.junit.Test)

Example 4 with Attributes

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

the class ManagedChannelImplGetNameResolverTest method validTargetNoResovler.

@Test
public void validTargetNoResovler() {
    Factory nameResolverFactory = new NameResolver.Factory() {

        @Override
        public NameResolver newNameResolver(URI targetUri, Attributes params) {
            return null;
        }

        @Override
        public String getDefaultScheme() {
            return "defaultscheme";
        }
    };
    try {
        ManagedChannelImpl.getNameResolver("foo.googleapis.com:8080", nameResolverFactory, NAME_RESOLVER_PARAMS);
        fail("Should fail");
    } catch (IllegalArgumentException e) {
    // expected
    }
}
Also used : Attributes(io.grpc.Attributes) Factory(io.grpc.NameResolver.Factory) URI(java.net.URI) Test(org.junit.Test)

Example 5 with Attributes

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

the class DelayedStreamTest method setStream_getAttributes.

@Test
public void setStream_getAttributes() {
    Attributes attributes = Attributes.newBuilder().set(Key.<String>of("fakeKey"), "fakeValue").build();
    when(realStream.getAttributes()).thenReturn(attributes);
    stream.start(listener);
    try {
        // expect to throw IllegalStateException, otherwise fail()
        stream.getAttributes();
        fail();
    } catch (IllegalStateException expected) {
    // ignore
    }
    stream.setStream(realStream);
    assertEquals(attributes, stream.getAttributes());
}
Also used : Attributes(io.grpc.Attributes) Test(org.junit.Test)

Aggregations

Attributes (io.grpc.Attributes)21 Test (org.junit.Test)17 ResolvedServerInfoGroup (io.grpc.ResolvedServerInfoGroup)9 Status (io.grpc.Status)9 EquivalentAddressGroup (io.grpc.EquivalentAddressGroup)7 ErrorPicker (io.grpc.grpclb.GrpclbLoadBalancer.ErrorPicker)5 MetadataApplier (io.grpc.CallCredentials.MetadataApplier)4 Subchannel (io.grpc.LoadBalancer.Subchannel)4 SubchannelPicker (io.grpc.LoadBalancer.SubchannelPicker)4 ManagedChannel (io.grpc.ManagedChannel)3 SocketAddress (java.net.SocketAddress)3 InOrder (org.mockito.InOrder)3 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)2 Metadata (io.grpc.Metadata)2 MockClientTransportInfo (io.grpc.internal.TestUtils.MockClientTransportInfo)2 Executor (java.util.concurrent.Executor)2 Matchers.anyString (org.mockito.Matchers.anyString)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 ByteString (com.google.protobuf.ByteString)1 CallOptions (io.grpc.CallOptions)1