Java Code Examples for io.grpc.Attributes#EMPTY

The following examples show how to use io.grpc.Attributes#EMPTY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void setSoLingerChannelOption() throws IOException {
  startServer();
  Map<ChannelOption<?>, Object> channelOptions = new HashMap<ChannelOption<?>, Object>();
  // set SO_LINGER option
  int soLinger = 123;
  channelOptions.put(ChannelOption.SO_LINGER, soLinger);
  NettyClientTransport transport = new NettyClientTransport(
      address, NioSocketChannel.class, channelOptions, group, newNegotiator(),
      DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE,
      KEEPALIVE_TIME_NANOS_DISABLED, 1L, false, authority, null /* user agent */,
      tooManyPingsRunnable, new TransportTracer(), Attributes.EMPTY, new SocketPicker());
  transports.add(transport);
  callMeMaybe(transport.start(clientTransportListener));

  // verify SO_LINGER has been set
  ChannelConfig config = transport.channel().config();
  assertTrue(config instanceof SocketChannelConfig);
  assertEquals(soLinger, ((SocketChannelConfig) config).getSoLinger());
}
 
Example 2
Source File: NettyServerStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected NettyServerStream createStream() {
  when(handler.getWriteQueue()).thenReturn(writeQueue);
  StatsTraceContext statsTraceCtx = StatsTraceContext.NOOP;
  TransportTracer transportTracer = new TransportTracer();
  NettyServerStream.TransportState state = new NettyServerStream.TransportState(
      handler, channel.eventLoop(), http2Stream, DEFAULT_MAX_MESSAGE_SIZE, statsTraceCtx,
      transportTracer, "method");
  NettyServerStream stream = new NettyServerStream(channel, state, Attributes.EMPTY,
      "test-authority", statsTraceCtx, transportTracer);
  stream.transportState().setListener(serverListener);
  state.onStreamAllocated();
  verify(serverListener, atLeastOnce()).onReady();
  verifyNoMoreInteractions(serverListener);
  return stream;
}
 
Example 3
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private SimpleServiceGrpc.SimpleServiceBlockingStub getBlockingStub(
    final UpstreamTlsContext upstreamTlsContext, String overrideAuthority)
    throws URISyntaxException {
  URI expectedUri = new URI("sdstest://localhost:" + port);
  fakeNameResolverFactory = new FakeNameResolverFactory.Builder(expectedUri).build();
  NameResolverRegistry.getDefaultRegistry().register(fakeNameResolverFactory);
  XdsChannelBuilder channelBuilder =
      XdsChannelBuilder.forTarget("sdstest://localhost:" + port);
  if (overrideAuthority != null) {
    channelBuilder = channelBuilder.overrideAuthority(overrideAuthority);
  }
  InetSocketAddress socketAddress =
      new InetSocketAddress(Inet4Address.getLoopbackAddress(), port);
  Attributes attrs =
      (upstreamTlsContext != null)
          ? Attributes.newBuilder()
              .set(XdsAttributes.ATTR_UPSTREAM_TLS_CONTEXT, upstreamTlsContext)
              .build()
          : Attributes.EMPTY;
  fakeNameResolverFactory.setServers(
      ImmutableList.of(new EquivalentAddressGroup(socketAddress, attrs)));
  return SimpleServiceGrpc.newBlockingStub(cleanupRule.register(channelBuilder.build()));
}
 
Example 4
Source File: GrpclbLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void abundantInitialResponse() {
  Metadata headers = new Metadata();
  PickSubchannelArgs args = mock(PickSubchannelArgs.class);
  when(args.getHeaders()).thenReturn(headers);

  List<EquivalentAddressGroup> grpclbResolutionList = createResolvedServerAddresses(true);
  Attributes grpclbResolutionAttrs = Attributes.EMPTY;
  deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);
  assertEquals(1, fakeOobChannels.size());
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  StreamObserver<LoadBalanceResponse> lbResponseObserver = lbResponseObserverCaptor.getValue();

  // Simulate LB initial response
  assertEquals(0, fakeClock.numPendingTasks(LOAD_REPORTING_TASK_FILTER));
  lbResponseObserver.onNext(buildInitialResponse(1983));

  // Load reporting task is scheduled
  assertEquals(1, fakeClock.numPendingTasks(LOAD_REPORTING_TASK_FILTER));
  FakeClock.ScheduledTask scheduledTask =
      Iterables.getOnlyElement(fakeClock.getPendingTasks(LOAD_REPORTING_TASK_FILTER));
  assertEquals(1983, scheduledTask.getDelay(TimeUnit.MILLISECONDS));

  logs.clear();
  // Simulate an abundant LB initial response, with a different report interval
  lbResponseObserver.onNext(buildInitialResponse(9097));

  // This incident is logged
  assertThat(logs).containsExactly(
      "DEBUG: Got an LB response: " + buildInitialResponse(9097),
      "WARNING: Ignoring unexpected response type: INITIAL_RESPONSE").inOrder();

  // It doesn't affect load-reporting at all
  assertThat(fakeClock.getPendingTasks(LOAD_REPORTING_TASK_FILTER))
      .containsExactly(scheduledTask);
  assertEquals(1983, scheduledTask.getDelay(TimeUnit.MILLISECONDS));
}
 
Example 5
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public Attributes getAttributes() {
  if (stream != null) {
    return stream.getAttributes();
  }
  return Attributes.EMPTY;
}
 
Example 6
Source File: DelayedStream.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public Attributes getAttributes() {
  ClientStream savedRealStream;
  synchronized (this) {
    savedRealStream = realStream;
  }
  if (savedRealStream != null) {
    return savedRealStream.getAttributes();
  } else {
    return Attributes.EMPTY;
  }
}
 
Example 7
Source File: ClientCallImpl.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public Attributes getAttributes() {
  if (stream != null) {
    return stream.getAttributes();
  }
  return Attributes.EMPTY;
}
 
Example 8
Source File: GrpclbLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void grpclbThenNameResolutionFails() {
  InOrder inOrder = inOrder(helper, subchannelPool);
  // Go to GRPCLB first
  List<EquivalentAddressGroup> grpclbResolutionList = createResolvedServerAddresses(true);
  Attributes grpclbResolutionAttrs = Attributes.EMPTY;
  deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);

  verify(helper).createOobChannel(eq(grpclbResolutionList.get(0)), eq(lbAuthority(0)));
  assertEquals(1, fakeOobChannels.size());
  ManagedChannel oobChannel = fakeOobChannels.poll();
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  StreamObserver<LoadBalanceResponse> lbResponseObserver = lbResponseObserverCaptor.getValue();

  // Let name resolution fail before round-robin list is ready
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);

  inOrder.verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  RoundRobinPicker picker = (RoundRobinPicker) pickerCaptor.getValue();
  assertThat(picker.dropList).isEmpty();
  assertThat(picker.pickList).containsExactly(new ErrorEntry(error));
  assertFalse(oobChannel.isShutdown());

  // Simulate receiving LB response
  List<ServerEntry> backends = Arrays.asList(
      new ServerEntry("127.0.0.1", 2000, "TOKEN1"),
      new ServerEntry("127.0.0.1", 2010, "TOKEN2"));
  lbResponseObserver.onNext(buildInitialResponse());
  lbResponseObserver.onNext(buildLbResponse(backends));

  inOrder.verify(subchannelPool).takeOrCreateSubchannel(
      eq(new EquivalentAddressGroup(backends.get(0).addr, LB_BACKEND_ATTRS)),
      any(Attributes.class));
  inOrder.verify(subchannelPool).takeOrCreateSubchannel(
      eq(new EquivalentAddressGroup(backends.get(1).addr, LB_BACKEND_ATTRS)),
      any(Attributes.class));
}
 
Example 9
Source File: GrpclbLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolutionFailsThenRecover() {
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);
  verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  assertThat(logs).containsExactly(
      "DEBUG: Error: " + error,
      "INFO: TRANSIENT_FAILURE: picks="
          + "[Status{code=NOT_FOUND, description=www.google.com not found, cause=null}],"
          + " drops=[]")
      .inOrder();
  logs.clear();

  RoundRobinPicker picker = (RoundRobinPicker) pickerCaptor.getValue();
  assertThat(picker.dropList).isEmpty();
  assertThat(picker.pickList).containsExactly(new ErrorEntry(error));

  // Recover with a subsequent success
  List<EquivalentAddressGroup> resolvedServers = createResolvedServerAddresses(true);
  EquivalentAddressGroup eag = resolvedServers.get(0);

  Attributes resolutionAttrs = Attributes.EMPTY;
  deliverResolvedAddresses(resolvedServers, resolutionAttrs);

  verify(helper).createOobChannel(eq(eag), eq(lbAuthority(0)));
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
}
 
Example 10
Source File: GoogleDefaultProtocolNegotiatorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void tlsHandler() {
  Attributes eagAttributes = Attributes.EMPTY;
  GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class);
  when(mockHandler.getEagAttributes()).thenReturn(eagAttributes);
  when(mockHandler.getAuthority()).thenReturn("authority");

  ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler);
  EmbeddedChannel chan = new EmbeddedChannel(h);
  chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault());

  assertThat(chan.pipeline().first().getClass().getSimpleName()).isEqualTo("SslHandler");
}
 
Example 11
Source File: GrpclbLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void grpclbFallback_breakLbStreamBeforeFallbackTimerExpires() {
  long loadReportIntervalMillis = 1983;
  InOrder inOrder = inOrder(helper, subchannelPool);

  // Create a resolution list with a mixture of balancer and backend addresses
  List<EquivalentAddressGroup> resolutionList =
      createResolvedServerAddresses(false, true, false);
  Attributes resolutionAttrs = Attributes.EMPTY;
  deliverResolvedAddresses(resolutionList, resolutionAttrs);

  inOrder.verify(helper).createOobChannel(eq(resolutionList.get(1)), eq(lbAuthority(0)));

  // Attempted to connect to balancer
  assertThat(fakeOobChannels).hasSize(1);
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  StreamObserver<LoadBalanceResponse> lbResponseObserver = lbResponseObserverCaptor.getValue();
  assertThat(lbRequestObservers).hasSize(1);
  StreamObserver<LoadBalanceRequest> lbRequestObserver = lbRequestObservers.poll();

  verify(lbRequestObserver).onNext(
      eq(LoadBalanceRequest.newBuilder().setInitialRequest(
              InitialLoadBalanceRequest.newBuilder().setName(SERVICE_AUTHORITY).build())
          .build()));
  lbResponseObserver.onNext(buildInitialResponse(loadReportIntervalMillis));
  // We don't care if these methods have been run.
  inOrder.verify(helper, atLeast(0)).getSynchronizationContext();
  inOrder.verify(helper, atLeast(0)).getScheduledExecutorService();

  inOrder.verifyNoMoreInteractions();

  assertEquals(1, fakeClock.numPendingTasks(FALLBACK_MODE_TASK_FILTER));

  /////////////////////////////////////////////
  // Break the LB stream before timer expires
  /////////////////////////////////////////////
  Status streamError = Status.UNAVAILABLE.withDescription("OOB stream broken");
  lbResponseObserver.onError(streamError.asException());

  // Fall back to the backends from resolver
  fallbackTestVerifyUseOfFallbackBackendLists(
      inOrder, Arrays.asList(resolutionList.get(0), resolutionList.get(2)));

  // A new stream is created
  verify(mockLbService, times(2)).balanceLoad(lbResponseObserverCaptor.capture());
  assertThat(lbRequestObservers).hasSize(1);
  lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(
      eq(LoadBalanceRequest.newBuilder().setInitialRequest(
              InitialLoadBalanceRequest.newBuilder().setName(SERVICE_AUTHORITY).build())
          .build()));
}
 
Example 12
Source File: NoopClientStream.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public Attributes getAttributes() {
  return Attributes.EMPTY;
}
 
Example 13
Source File: GrpclbLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void grpclbBalancerStreamRetry() throws Exception {
  LoadBalanceRequest expectedInitialRequest =
      LoadBalanceRequest.newBuilder()
          .setInitialRequest(
              InitialLoadBalanceRequest.newBuilder().setName(SERVICE_AUTHORITY).build())
          .build();
  InOrder inOrder =
      inOrder(mockLbService, backoffPolicyProvider, backoffPolicy1, backoffPolicy2);
  List<EquivalentAddressGroup> grpclbResolutionList = createResolvedServerAddresses(true);
  Attributes grpclbResolutionAttrs = Attributes.EMPTY;
  deliverResolvedAddresses(grpclbResolutionList, grpclbResolutionAttrs);

  assertEquals(1, fakeOobChannels.size());
  @SuppressWarnings("unused")
  ManagedChannel oobChannel = fakeOobChannels.poll();

  // First balancer RPC
  inOrder.verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  StreamObserver<LoadBalanceResponse> lbResponseObserver = lbResponseObserverCaptor.getValue();
  assertEquals(1, lbRequestObservers.size());
  StreamObserver<LoadBalanceRequest> lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(eq(expectedInitialRequest));
  assertEquals(0, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Balancer closes it immediately (erroneously)
  lbResponseObserver.onCompleted();
  // Will start backoff sequence 1 (10ns)
  inOrder.verify(backoffPolicyProvider).get();
  inOrder.verify(backoffPolicy1).nextBackoffNanos();
  assertEquals(1, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Fast-forward to a moment before the retry
  fakeClock.forwardNanos(9);
  verifyNoMoreInteractions(mockLbService);
  // Then time for retry
  fakeClock.forwardNanos(1);
  inOrder.verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  lbResponseObserver = lbResponseObserverCaptor.getValue();
  assertEquals(1, lbRequestObservers.size());
  lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(eq(expectedInitialRequest));
  assertEquals(0, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Balancer closes it with an error.
  lbResponseObserver.onError(Status.UNAVAILABLE.asException());
  // Will continue the backoff sequence 1 (100ns)
  verifyNoMoreInteractions(backoffPolicyProvider);
  inOrder.verify(backoffPolicy1).nextBackoffNanos();
  assertEquals(1, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Fast-forward to a moment before the retry
  fakeClock.forwardNanos(100 - 1);
  verifyNoMoreInteractions(mockLbService);
  // Then time for retry
  fakeClock.forwardNanos(1);
  inOrder.verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  lbResponseObserver = lbResponseObserverCaptor.getValue();
  assertEquals(1, lbRequestObservers.size());
  lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(eq(expectedInitialRequest));
  assertEquals(0, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Balancer sends initial response.
  lbResponseObserver.onNext(buildInitialResponse());

  // Then breaks the RPC
  lbResponseObserver.onError(Status.UNAVAILABLE.asException());

  // Will reset the retry sequence and retry immediately, because balancer has responded.
  inOrder.verify(backoffPolicyProvider).get();
  inOrder.verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  lbResponseObserver = lbResponseObserverCaptor.getValue();
  assertEquals(1, lbRequestObservers.size());
  lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(eq(expectedInitialRequest));

  // Fail the retry after spending 4ns
  fakeClock.forwardNanos(4);
  lbResponseObserver.onError(Status.UNAVAILABLE.asException());
  
  // Will be on the first retry (10ns) of backoff sequence 2.
  inOrder.verify(backoffPolicy2).nextBackoffNanos();
  assertEquals(1, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Fast-forward to a moment before the retry, the time spent in the last try is deducted.
  fakeClock.forwardNanos(10 - 4 - 1);
  verifyNoMoreInteractions(mockLbService);
  // Then time for retry
  fakeClock.forwardNanos(1);
  inOrder.verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  assertEquals(1, lbRequestObservers.size());
  lbRequestObserver = lbRequestObservers.poll();
  verify(lbRequestObserver).onNext(eq(expectedInitialRequest));
  assertEquals(0, fakeClock.numPendingTasks(LB_RPC_RETRY_TASK_FILTER));

  // Wrapping up
  verify(backoffPolicyProvider, times(2)).get();
  verify(backoffPolicy1, times(2)).nextBackoffNanos();
  verify(backoffPolicy2, times(1)).nextBackoffNanos();
}
 
Example 14
Source File: GrpcHttp2ConnectionHandler.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/** Get the attributes of the EquivalentAddressGroup used to create this transport. */
public Attributes getEagAttributes() {
  return Attributes.EMPTY;
}
 
Example 15
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public Attributes getTransportAttrs() {
  return Attributes.EMPTY;
}
 
Example 16
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Override
public Attributes getTransportAttrs() {
  return Attributes.EMPTY;
}
 
Example 17
Source File: GrpcHttp2ConnectionHandler.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
/** Get the attributes of the EquivalentAddressGroup used to create this transport. */
public Attributes getEagAttributes() {
  return Attributes.EMPTY;
}
 
Example 18
Source File: InProcessTransport.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Override
public Attributes getAttributes() {
  return Attributes.EMPTY;
}
 
Example 19
Source File: LrsLoadBalancerTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public Attributes getAttributes() {
  return Attributes.EMPTY;
}
 
Example 20
Source File: AbstractManagedChannelImplBuilder.java    From grpc-nebula-java with Apache License 2.0 2 votes vote down vote up
/**
 * Subclasses can override this method to provide additional parameters to {@link
 * NameResolver.Factory#newNameResolver}. The default implementation returns {@link
 * Attributes#EMPTY}.
 */
protected Attributes getNameResolverParams() {
  return Attributes.EMPTY;
}