io.envoyproxy.envoy.api.v2.core.Node Java Examples

The following examples show how to use io.envoyproxy.envoy.api.v2.core.Node. 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: SdsServerSslContextProvider.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
static SdsServerSslContextProvider getProvider(
    DownstreamTlsContext downstreamTlsContext,
    Node node,
    Executor watcherExecutor,
    Executor channelExecutor) {
  checkNotNull(downstreamTlsContext, "downstreamTlsContext");
  CommonTlsContext commonTlsContext = downstreamTlsContext.getCommonTlsContext();

  SdsSecretConfig certSdsConfig = null;
  if (commonTlsContext.getTlsCertificateSdsSecretConfigsCount() > 0) {
    certSdsConfig = commonTlsContext.getTlsCertificateSdsSecretConfigs(0);
  }

  SdsSecretConfig validationContextSdsConfig = null;
  if (commonTlsContext.hasValidationContextSdsSecretConfig()) {
    validationContextSdsConfig = commonTlsContext.getValidationContextSdsSecretConfig();
  }
  return new SdsServerSslContextProvider(
      node,
      certSdsConfig,
      validationContextSdsConfig,
      watcherExecutor,
      channelExecutor,
      downstreamTlsContext);
}
 
Example #2
Source File: K8sALSServiceMeshHTTPAnalysis.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public Role identify(StreamAccessLogsMessage.Identifier alsIdentifier, Role prev) {
    if (alsIdentifier != null) {
        Node node = alsIdentifier.getNode();
        if (node != null) {
            String id = node.getId();
            if (id.startsWith("router~")) {
                return Role.PROXY;
            } else if (id.startsWith("sidecar~")) {
                return Role.SIDECAR;
            }
        }
    }

    return prev;
}
 
Example #3
Source File: XdsClientImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
XdsClientImpl(
    String targetName,
    List<ServerInfo> servers,  // list of management servers
    XdsChannelFactory channelFactory,
    Node node,
    SynchronizationContext syncContext,
    ScheduledExecutorService timeService,
    BackoffPolicy.Provider backoffPolicyProvider,
    Supplier<Stopwatch> stopwatchSupplier) {
  this.targetName = checkNotNull(targetName, "targetName");
  this.channel =
      checkNotNull(channelFactory, "channelFactory")
          .createChannel(checkNotNull(servers, "servers"));
  this.node = checkNotNull(node, "node");
  this.syncContext = checkNotNull(syncContext, "syncContext");
  this.timeService = checkNotNull(timeService, "timeService");
  this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
  this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatch");
  adsStreamRetryStopwatch = stopwatchSupplier.get();
  logId = InternalLogId.allocate("xds-client", targetName);
  logger = XdsLogger.withLogId(logId);
  logger.log(XdsLogLevel.INFO, "Created");
}
 
Example #4
Source File: SdsClientUdsFileBasedMetadataTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  Assume.assumeTrue(Epoll.isAvailable());
  serverMock = mock(TestSdsServer.ServerMock.class);
  server = new TestSdsServer(serverMock);
  server.startServer(SDSCLIENT_TEST_SOCKET, /* useUds= */ true, /* useInterceptor= */ true);

  tempTokenFile = tempFolder.newFile(TOKEN_FILE_NAME);
  Files.write("test-token-content".getBytes(StandardCharsets.UTF_8), tempTokenFile);

  ConfigSource configSource =
      SdsClientFileBasedMetadataTest.buildConfigSourceWithCreds(
          "unix:" + SDSCLIENT_TEST_SOCKET,
          null,
          tempTokenFile.getAbsolutePath(),
          null,
          FileBasedPluginCredential.PLUGIN_NAME);
  sdsSecretConfig =
      SdsSecretConfig.newBuilder().setSdsConfig(configSource).setName("name1").build();
  node = Node.newBuilder().setId("sds-client-temp-test2").build();
  sdsClient =
      SdsClient.Factory.createSdsClient(
          sdsSecretConfig, node, MoreExecutors.directExecutor(), MoreExecutors.directExecutor());
  sdsClient.start();
}
 
Example #5
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void clearSnapshotWithWatches() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT1);

  final Watch watch = cache.createWatch(ADS, DiscoveryRequest.newBuilder()
          .setNode(Node.getDefaultInstance())
          .setTypeUrl("")
          .build(),
      Collections.emptySet(),
      r -> { });

  // clearSnapshot should fail and the snapshot should be left untouched
  assertThat(cache.clearSnapshot(SingleNodeGroup.GROUP)).isFalse();
  assertThat(cache.getSnapshot(SingleNodeGroup.GROUP)).isEqualTo(SNAPSHOT1);
  assertThat(cache.statusInfo(SingleNodeGroup.GROUP)).isNotNull();

  watch.cancel();

  // now that the watch is gone we should be able to clear it
  assertThat(cache.clearSnapshot(SingleNodeGroup.GROUP)).isTrue();
  assertThat(cache.getSnapshot(SingleNodeGroup.GROUP)).isNull();
  assertThat(cache.statusInfo(SingleNodeGroup.GROUP)).isNull();
}
 
Example #6
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void watchIsLeftOpenIfNotRespondedImmediately() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());
  cache.setSnapshot(SingleNodeGroup.GROUP, Snapshot.create(
      ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), VERSION1));

  ResponseTracker responseTracker = new ResponseTracker();
  Watch watch = cache.createWatch(
      true,
      DiscoveryRequest.newBuilder()
          .setNode(Node.getDefaultInstance())
          .setTypeUrl(ROUTE_TYPE_URL)
          .addAllResourceNames(Collections.singleton(ROUTE_NAME))
          .build(),
      Collections.singleton(ROUTE_NAME),
      responseTracker);

  assertThatWatchIsOpenWithNoResponses(new WatchAndTracker(watch, responseTracker));
}
 
Example #7
Source File: SdsClientTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
static void verifyDiscoveryRequest(
    DiscoveryRequest request,
    String versionInfo,
    String responseNonce,
    Node node,
    String... resourceNames) {
  assertThat(request).isNotNull();
  assertThat(request.getNode()).isEqualTo(node);
  assertThat(request.getResourceNamesList()).isEqualTo(Arrays.asList(resourceNames));
  assertThat(request.getTypeUrl()).isEqualTo("type.googleapis.com/envoy.api.v2.auth.Secret");
  if (versionInfo != null) {
    assertThat(request.getVersionInfo()).isEqualTo(versionInfo);
  }
  if (responseNonce != null) {
    assertThat(request.getResponseNonce()).isEqualTo(responseNonce);
  }
}
 
Example #8
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendEdsWhenClusterChangedButEdsVersionDidnt() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT1);

  ResponseTracker responseTracker = new ResponseTracker();

  Watch watch = cache.createWatch(
      ADS,
      DiscoveryRequest.newBuilder()
          .setNode(Node.getDefaultInstance())
          .setVersionInfo(VERSION1)
          .setTypeUrl(Resources.ENDPOINT_TYPE_URL)
          .addAllResourceNames(SNAPSHOT1.resources(Resources.ENDPOINT_TYPE_URL).keySet())
          .build(),
      Sets.newHashSet(""),
      responseTracker,
      true);

  assertThat(watch.request().getTypeUrl()).isEqualTo(Resources.ENDPOINT_TYPE_URL);
  assertThat(watch.request().getResourceNamesList()).containsExactlyElementsOf(
      SNAPSHOT1.resources(Resources.ENDPOINT_TYPE_URL).keySet());

  assertThatWatchReceivesSnapshot(new WatchAndTracker(watch, responseTracker), SNAPSHOT1);
}
 
Example #9
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void successfullyWatchAllResourceTypesWithSetBeforeWatch() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT1);

  for (String typeUrl : Resources.TYPE_URLS) {
    ResponseTracker responseTracker = new ResponseTracker();

    Watch watch = cache.createWatch(
        ADS,
        DiscoveryRequest.newBuilder()
            .setNode(Node.getDefaultInstance())
            .setTypeUrl(typeUrl)
            .addAllResourceNames(SNAPSHOT1.resources(typeUrl).keySet())
            .build(),
        Collections.emptySet(),
        responseTracker);

    assertThat(watch.request().getTypeUrl()).isEqualTo(typeUrl);
    assertThat(watch.request().getResourceNamesList()).containsExactlyElementsOf(
        SNAPSHOT1.resources(typeUrl).keySet());

    assertThatWatchReceivesSnapshot(new WatchAndTracker(watch, responseTracker), SNAPSHOT1);
  }
}
 
Example #10
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidNamesListShouldReturnWatcherWithResponseInXdsMode() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT1);

  ResponseTracker responseTracker = new ResponseTracker();

  Watch watch = cache.createWatch(
      false,
      DiscoveryRequest.newBuilder()
          .setNode(Node.getDefaultInstance())
          .setTypeUrl(Resources.ENDPOINT_TYPE_URL)
          .addResourceNames("none")
          .build(),
      Collections.emptySet(),
      responseTracker);

  assertThat(watch.isCancelled()).isFalse();
  assertThat(responseTracker.responses).isNotEmpty();
}
 
Example #11
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidNamesListShouldReturnWatcherWithNoResponseInAdsMode() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT1);

  ResponseTracker responseTracker = new ResponseTracker();

  Watch watch = cache.createWatch(
      true,
      DiscoveryRequest.newBuilder()
          .setNode(Node.getDefaultInstance())
          .setTypeUrl(Resources.ENDPOINT_TYPE_URL)
          .addResourceNames("none")
          .build(),
      Collections.emptySet(),
      responseTracker);

  assertThatWatchIsOpenWithNoResponses(new WatchAndTracker(watch, responseTracker));
}
 
Example #12
Source File: CacheStatusInfoTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentSetWatchAndRemove() {
  final boolean ads = ThreadLocalRandom.current().nextBoolean();
  final int watchCount = 50;

  CacheStatusInfo<Node> info = new CacheStatusInfo<>(Node.getDefaultInstance());

  Collection<Long> watchIds = LongStream.range(0, watchCount).boxed().collect(Collectors.toList());

  watchIds.parallelStream().forEach(watchId -> {
    Watch watch = new Watch(ads, DiscoveryRequest.getDefaultInstance(), r -> { });

    info.setWatch(watchId, watch);
  });

  assertThat(info.watchIds()).containsExactlyInAnyOrder(watchIds.toArray(new Long[0]));
  assertThat(info.numWatches()).isEqualTo(watchIds.size());

  watchIds.parallelStream().forEach(info::removeWatch);

  assertThat(info.watchIds()).isEmpty();
  assertThat(info.numWatches()).isZero();
}
 
Example #13
Source File: CacheStatusInfoTest.java    From java-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void watchesRemoveIfRemovesExpectedWatches() {
  final boolean ads = ThreadLocalRandom.current().nextBoolean();
  final long watchId1 = ThreadLocalRandom.current().nextLong(10000, 50000);
  final long watchId2 = ThreadLocalRandom.current().nextLong(50000, 100000);

  CacheStatusInfo<Node> info = new CacheStatusInfo<>(Node.getDefaultInstance());

  info.setWatch(watchId1, new Watch(ads, DiscoveryRequest.getDefaultInstance(), r -> { }));
  info.setWatch(watchId2, new Watch(ads, DiscoveryRequest.getDefaultInstance(), r -> { }));

  assertThat(info.numWatches()).isEqualTo(2);
  assertThat(info.watchIds()).containsExactlyInAnyOrder(watchId1, watchId2);

  info.watchesRemoveIf((watchId, watch) -> watchId.equals(watchId1));

  assertThat(info.numWatches()).isEqualTo(1);
  assertThat(info.watchIds()).containsExactlyInAnyOrder(watchId2);
}
 
Example #14
Source File: SdsClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private SdsClient(
    SdsSecretConfig sdsSecretConfig,
    Node node,
    Executor watcherExecutor,
    ManagedChannel channel,
    EventLoopGroup eventLoopGroup,
    CallCredentials callCredentials) {
  checkNotNull(sdsSecretConfig, "sdsSecretConfig");
  checkNotNull(node, "node");
  this.sdsSecretConfig = sdsSecretConfig;
  this.clientNode = node;
  this.watcherExecutor = watcherExecutor;
  this.eventLoopGroup = eventLoopGroup;
  checkNotNull(channel, "channel");
  this.channel = channel;
  this.callCredentials = callCredentials;
}
 
Example #15
Source File: SdsClientFileBasedMetadataTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  serverMock = mock(TestSdsServer.ServerMock.class);
  server = new TestSdsServer(serverMock);
  server.startServer("inproc", /* useUds= */ false, /* useInterceptor= */ true);

  tempTokenFile = tempFolder.newFile(TOKEN_FILE_NAME);
  Files.write("test-token-content".getBytes(StandardCharsets.UTF_8), tempTokenFile);

  ConfigSource configSource =
      buildConfigSourceWithCreds(
          "inproc",
          "inproc",
          tempTokenFile.getAbsolutePath(),
          null,
          FileBasedPluginCredential.PLUGIN_NAME);
  sdsSecretConfig =
      SdsSecretConfig.newBuilder().setSdsConfig(configSource).setName("name1").build();
  node = Node.newBuilder().setId("sds-client-temp-test1").build();
  sdsClient =
      SdsClient.Factory.createSdsClient(
          sdsSecretConfig, node, MoreExecutors.directExecutor(), MoreExecutors.directExecutor());
  sdsClient.start();
}
 
Example #16
Source File: LoadReportClientTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static LoadStatsRequest buildInitialRequest() {
  return
      LoadStatsRequest.newBuilder()
          .setNode(
              Node.newBuilder()
                  .setId("LRS test")
                  .setMetadata(
                      Struct.newBuilder()
                          .putFields(
                              "TRAFFICDIRECTOR_NETWORK_HOSTNAME",
                              Value.newBuilder().setStringValue("default").build())
                          .putFields(
                              LoadReportClient.TARGET_NAME_METADATA_KEY,
                              Value.newBuilder().setStringValue(TARGET_NAME).build())))
          .build();
}
 
Example #17
Source File: SdsClientSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private SdsClientSslContextProvider(
    Node node,
    SdsSecretConfig certSdsConfig,
    SdsSecretConfig validationContextSdsConfig,
    CertificateValidationContext staticCertValidationContext,
    Executor watcherExecutor,
    Executor channelExecutor,
    UpstreamTlsContext upstreamTlsContext) {
  super(node,
      certSdsConfig,
      validationContextSdsConfig,
      staticCertValidationContext,
      watcherExecutor,
      channelExecutor, upstreamTlsContext);
}
 
Example #18
Source File: SdsClientSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
static SdsClientSslContextProvider getProvider(
    UpstreamTlsContext upstreamTlsContext,
    Node node,
    Executor watcherExecutor,
    Executor channelExecutor) {
  checkNotNull(upstreamTlsContext, "upstreamTlsContext");
  CommonTlsContext commonTlsContext = upstreamTlsContext.getCommonTlsContext();
  SdsSecretConfig validationContextSdsConfig = null;
  CertificateValidationContext staticCertValidationContext = null;
  if (commonTlsContext.hasCombinedValidationContext()) {
    CombinedCertificateValidationContext combinedValidationContext =
        commonTlsContext.getCombinedValidationContext();
    if (combinedValidationContext.hasValidationContextSdsSecretConfig()) {
      validationContextSdsConfig =
          combinedValidationContext.getValidationContextSdsSecretConfig();
    }
    if (combinedValidationContext.hasDefaultValidationContext()) {
      staticCertValidationContext = combinedValidationContext.getDefaultValidationContext();
    }
  } else if (commonTlsContext.hasValidationContextSdsSecretConfig()) {
    validationContextSdsConfig = commonTlsContext.getValidationContextSdsSecretConfig();
  } else if (commonTlsContext.hasValidationContext()) {
    staticCertValidationContext = commonTlsContext.getValidationContext();
  }
  SdsSecretConfig certSdsConfig = null;
  if (commonTlsContext.getTlsCertificateSdsSecretConfigsCount() > 0) {
    certSdsConfig = commonTlsContext.getTlsCertificateSdsSecretConfigs(0);
  }
  return new SdsClientSslContextProvider(
      node,
      certSdsConfig,
      validationContextSdsConfig,
      staticCertValidationContext,
      watcherExecutor,
      channelExecutor,
      upstreamTlsContext);
}
 
Example #19
Source File: SdsClientTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  serverMock = mock(TestSdsServer.ServerMock.class);
  server = new TestSdsServer(serverMock);
  server.startServer("inproc", /* useUds= */ false, /* useInterceptor= */ false);
  ConfigSource configSource = buildConfigSource("inproc", "inproc");
  sdsSecretConfig =
      SdsSecretConfig.newBuilder().setSdsConfig(configSource).setName("name1").build();
  node = Node.newBuilder().setId("sds-client-temp-test1").build();
  sdsClient =
      SdsClient.Factory.createSdsClient(
          sdsSecretConfig, node, MoreExecutors.directExecutor(), MoreExecutors.directExecutor());
  sdsClient.start();
}
 
Example #20
Source File: XdsClientImplTestForListener.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static Node getNodeToVerify() {
  Struct newMetadata = NODE.getMetadata().toBuilder()
      .putFields("TRAFFICDIRECTOR_PROXYLESS",
          Value.newBuilder().setStringValue("1").build())
      .build();
  Address listeningAddress =
      Address.newBuilder()
          .setSocketAddress(
              SocketAddress.newBuilder().setAddress("0.0.0.0").setPortValue(PORT).build())
          .build();
  return NODE.toBuilder()
      .setMetadata(newMetadata)
      .addListeningAddresses(listeningAddress)
      .build();
}
 
Example #21
Source File: XdsClientImplTestForListener.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static DiscoveryRequest buildDiscoveryRequest(
    Node node, String versionInfo, String typeUrl, String nonce) {
  return DiscoveryRequest.newBuilder()
      .setVersionInfo(versionInfo)
      .setNode(node)
      .setTypeUrl(typeUrl)
      .setResponseNonce(nonce)
      .build();
}
 
Example #22
Source File: BootstrapperTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static Node.Builder getNodeBuilder() {
  GrpcBuildVersion buildVersion = GrpcUtil.getGrpcBuildVersion();
  return
      Node.newBuilder()
          .setBuildVersion(buildVersion.toString())
          .setUserAgentName(buildVersion.getUserAgent())
          .setUserAgentVersion(buildVersion.getImplementationVersion())
          .addClientFeatures(Bootstrapper.CLIENT_FEATURE_DISABLE_OVERPROVISIONING);
}
 
Example #23
Source File: XdsNameResolver.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Listener2 listener) {
  BootstrapInfo bootstrapInfo;
  try {
    bootstrapInfo = bootstrapper.readBootstrap();
  } catch (Exception e) {
    listener.onError(Status.UNAVAILABLE.withDescription("Failed to bootstrap").withCause(e));
    return;
  }
  final List<ServerInfo> serverList = bootstrapInfo.getServers();
  final Node node = bootstrapInfo.getNode();
  if (serverList.isEmpty()) {
    listener.onError(
        Status.UNAVAILABLE.withDescription("No management server provided by bootstrap"));
    return;
  }

  XdsClientFactory xdsClientFactory = new XdsClientFactory() {
    @Override
    XdsClient createXdsClient() {
      return
          new XdsClientImpl(
              authority,
              serverList,
              channelFactory,
              node,
              syncContext,
              timeService,
              backoffPolicyProvider,
              stopwatchSupplier);
    }
  };
  xdsClientPool = new RefCountedXdsClientObjectPool(xdsClientFactory);
  xdsClient = xdsClientPool.getObject();
  xdsClient.watchConfigData(authority, new ConfigWatcherImpl(listener));
}
 
Example #24
Source File: SdsClientUdsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  Assume.assumeTrue(Epoll.isAvailable());
  serverMock = mock(TestSdsServer.ServerMock.class);
  server = new TestSdsServer(serverMock);
  server.startServer(SDSCLIENT_TEST_SOCKET, /* useUds= */ true, /* useInterceptor= */ false);
  ConfigSource configSource = buildConfigSource("unix:" + SDSCLIENT_TEST_SOCKET);
  sdsSecretConfig =
      SdsSecretConfig.newBuilder().setSdsConfig(configSource).setName("name1").build();
  node = Node.newBuilder().setId("sds-client-temp-test2").build();
  sdsClient =
      SdsClient.Factory.createSdsClient(
          sdsSecretConfig, node, MoreExecutors.directExecutor(), MoreExecutors.directExecutor());
  sdsClient.start();
}
 
Example #25
Source File: SdsSslContextProviderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  serverMock = mock(TestSdsServer.ServerMock.class);
  server = new TestSdsServer(serverMock);
  server.startServer(/* name= */ "inproc", /* useUds= */ false, /* useInterceptor= */ false);

  node = Node.newBuilder().setId("sds-client-temp-test1").build();
}
 
Example #26
Source File: XdsClientTestHelper.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
static DiscoveryRequest buildDiscoveryRequest(Node node, String versionInfo,
    List<String> resourceNames, String typeUrl, String nonce) {
  return
      DiscoveryRequest.newBuilder()
          .setVersionInfo(versionInfo)
          .setNode(node)
          .setTypeUrl(typeUrl)
          .addAllResourceNames(resourceNames)
          .setResponseNonce(nonce)
          .build();
}
 
Example #27
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public String hash(Node node) {
  if (node == null) {
    throw new IllegalArgumentException("node");
  }

  return GROUP;
}
 
Example #28
Source File: CacheStatusInfoTest.java    From java-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void nodeGroupReturnsExpectedGroup() {
  Node node = Node.newBuilder().setId(UUID.randomUUID().toString()).build();

  CacheStatusInfo<Node> info = new CacheStatusInfo<>(node);

  assertThat(info.nodeGroup()).isSameAs(node);
}
 
Example #29
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void successfullyWatchAllResourceTypesWithSetBeforeWatchWithSameRequestVersionNewResourceHintsNoChange() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  cache.setSnapshot(SingleNodeGroup.GROUP, SNAPSHOT2);

  // Set a watch for the current snapshot for the same version but with new resource hints not
  // present in the snapshot that the watch creator does not know about.
  //
  // Note that we're requesting the additional resources found in MULTIPLE_RESOURCE_SNAPSHOT2
  // while we only know about the resources found in SNAPSHOT2. Since SNAPSHOT2 is the current
  // snapshot, we have nothing to respond with for the new resources so we should not trigger
  // the watch.
  Map<String, WatchAndTracker> watches = Resources.TYPE_URLS.stream()
      .collect(Collectors.toMap(
          typeUrl -> typeUrl,
          typeUrl -> {
            ResponseTracker responseTracker = new ResponseTracker();

            Watch watch = cache.createWatch(
                ADS,
                DiscoveryRequest.newBuilder()
                    .setNode(Node.getDefaultInstance())
                    .setTypeUrl(typeUrl)
                    .setVersionInfo(SNAPSHOT2.version(typeUrl))
                    .addAllResourceNames(MULTIPLE_RESOURCES_SNAPSHOT2.resources(typeUrl).keySet())
                    .build(),
                SNAPSHOT2.resources(typeUrl).keySet(),
                responseTracker);

            return new WatchAndTracker(watch, responseTracker);
          }));

  // No watches should trigger since no new information will be returned
  for (WatchAndTracker watchAndTracker : watches.values()) {
    assertThatWatchIsOpenWithNoResponses(watchAndTracker);
  }
}
 
Example #30
Source File: SimpleCacheTest.java    From java-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void watchesAreReleasedAfterCancel() {
  SimpleCache<String> cache = new SimpleCache<>(new SingleNodeGroup());

  Map<String, WatchAndTracker> watches = Resources.TYPE_URLS.stream()
      .collect(Collectors.toMap(
          typeUrl -> typeUrl,
          typeUrl -> {
            ResponseTracker responseTracker = new ResponseTracker();

            Watch watch = cache.createWatch(
                ADS,
                DiscoveryRequest.newBuilder()
                    .setNode(Node.getDefaultInstance())
                    .setTypeUrl(typeUrl)
                    .addAllResourceNames(SNAPSHOT1.resources(typeUrl).keySet())
                    .build(),
                Collections.emptySet(),
                responseTracker);

            return new WatchAndTracker(watch, responseTracker);
          }));

  StatusInfo statusInfo = cache.statusInfo(SingleNodeGroup.GROUP);

  assertThat(statusInfo.numWatches()).isEqualTo(watches.size());

  watches.values().forEach(w -> w.watch.cancel());

  assertThat(statusInfo.numWatches()).isZero();

  watches.values().forEach(w -> assertThat(w.watch.isCancelled()).isTrue());
}