Java Code Examples for com.netflix.spectator.api.DefaultRegistry

The following examples show how to use com.netflix.spectator.api.DefaultRegistry. These examples are extracted from open source projects. 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 Project: titus-control-plane   Source File: TitusClientImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException {
    final MockJobManagerService mockJobManagerService = new MockJobManagerService();

    testServer = InProcessServerBuilder
            .forName("testServer")
            .directExecutor()
            .addService(mockJobManagerService)
            .build()
            .start();

    final ManagedChannel channel = InProcessChannelBuilder
            .forName("testServer")
            .directExecutor()
            .usePlaintext(true)
            .build();
    final JobManagementServiceStub jobManagementServiceStub = JobManagementServiceGrpc.newStub(channel);
    final JobManagementServiceFutureStub jobManagementServiceFutureStub = JobManagementServiceGrpc.newFutureStub(channel);
    titusClient = new TitusClientImpl(jobManagementServiceStub, jobManagementServiceFutureStub, new DefaultRegistry());
}
 
Example 2
Source Project: titus-control-plane   Source File: TitusFederationModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    bind(Archaius2ConfigurationLogger.class).asEagerSingleton();
    bind(Registry.class).toInstance(new DefaultRegistry());
    bind(SystemLogService.class).to(LoggingSystemLogService.class);
    bind(SystemAbortListener.class).to(LoggingSystemAbortListener.class);

    install(new GovernatorJerseySupportModule());

    install(new ContainerEventBusModule());
    install(new TitusEntitySanitizerModule());

    bind(HostCallerIdResolver.class).to(NoOpHostCallerIdResolver.class);
    bind(CellConnector.class).to(DefaultCellConnector.class);
    bind(CellWebClientConnector.class).to(DefaultCellWebClientConnector.class);
    bind(WebClientFactory.class).toInstance(SimpleWebClientFactory.getInstance());
    bind(CellInfoResolver.class).to(DefaultCellInfoResolver.class);

    install(new FederationEndpointModule());
    install(new ServiceModule());
}
 
Example 3
Source Project: titus-control-plane   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
private static AwsIamConnector createConnector() {
    AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
    AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
    AWSCredentialsProvider credentialsProvider = new DataPlaneAgentCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();

    Region currentRegion = Regions.getCurrentRegion();
    if (currentRegion == null) {
        currentRegion = Region.getRegion(Regions.US_EAST_1);
    }
    return new AwsIamConnector(
            CONFIGURATION,
            AmazonIdentityManagementAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            AWSSecurityTokenServiceAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            new DefaultRegistry()
    );
}
 
Example 4
@Test
public void testConnectionLossWillLeadToStartupFailure() {
    ZookeeperConfiguration config = mock(ZookeeperConfiguration.class);
    when(config.getZkConnectionString()).thenReturn("127.0.0.1:44444");

    ZookeeperClusterResolver clusterResolver = new DefaultZookeeperClusterResolver(config);
    try {
        CuratorServiceImpl cs = closeable.autoCloseable(new CuratorServiceImpl(config, clusterResolver, new DefaultRegistry()), CuratorServiceImpl::shutdown);
        cs.start();

        ZookeeperLeaderElector elector = new ZookeeperLeaderElector(leaderActivator, cs, zkPaths, masterDescription, titusRuntime);
        elector.join();
        fail("The elector should fail fast");
    } catch (IllegalStateException e) {
        assertEquals("The cause should be from ZK connection failure", CuratorConnectionLossException.class, e.getCause().getClass());
        assertTrue("The error message is unexpected: " + e.getMessage(), e.getCause().getMessage().contains("ConnectionLoss"));
    }
}
 
Example 5
@Test
public void testBootstrapEngineInitialization() {
    InternalReconciliationEngine<SimpleReconcilerEvent> bootstrapEngine = mock(InternalReconciliationEngine.class);
    PublishSubject<SimpleReconcilerEvent> eventSubject = PublishSubject.create();
    when(bootstrapEngine.events()).thenReturn(eventSubject);
    when(bootstrapEngine.triggerActions()).thenReturn(true);
    when(bootstrapEngine.getReferenceView()).thenReturn(EntityHolder.newRoot("myRoot1", "myEntity1"));

    DefaultReconciliationFramework<SimpleReconcilerEvent> framework = new DefaultReconciliationFramework<>(
            Collections.singletonList(bootstrapEngine),
            engineFactory,
            IDLE_TIMEOUT_MS,
            ACTIVE_TIMEOUT_MS,
            indexComparators,
            new DefaultRegistry(),
            Optional.of(testScheduler)
    );
    framework.start();
    AssertableSubscriber<SimpleReconcilerEvent> eventSubscriber = framework.events().test();

    eventSubject.onNext(new SimpleReconcilerEvent(EventType.Changed, "test", Optional.empty()));
    eventSubscriber.assertValueCount(1);
}
 
Example 6
Source Project: kork   Source File: StackdriverWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddMeasurementsToTimeSeries() {
  DefaultRegistry testRegistry = new DefaultRegistry(clock);

  long millisA = TimeUnit.MILLISECONDS.convert(1472394975L, TimeUnit.SECONDS);
  long millisB = millisA + 987;
  String timeA = "2016-08-28T14:36:15.000000000Z";
  String timeB = "2016-08-28T14:36:15.987000000Z";
  Meter timerA = testRegistry.timer(idAXY);
  Meter timerB = testRegistry.timer(idBXY);
  Measurement measureAXY = new Measurement(idAXY, millisA, 1);
  Measurement measureBXY = new Measurement(idBXY, millisB, 20.1);

  descriptorRegistrySpy.addExtraTimeSeriesLabel(
      MetricDescriptorCache.INSTANCE_LABEL, INSTANCE_ID);

  Assert.assertEquals(
      makeTimeSeries(descriptorA, idAXY, 1, timeA),
      writer.measurementToTimeSeries(descriptorA.getType(), testRegistry, timerA, measureAXY));
  Assert.assertEquals(
      makeTimeSeries(descriptorB, idBXY, 20.1, timeB),
      writer.measurementToTimeSeries(descriptorB.getType(), testRegistry, timerB, measureBXY));
}
 
Example 7
Source Project: spectator   Source File: PolledMeterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void removeAndAddRepeatedlyCounter() {
  Registry r = new DefaultRegistry();
  Id id = r.createId("test");

  AtomicLong value = new AtomicLong();
  for (int i = 0; i < 10; ++i) {
    PolledMeter.using(r).withId(id).monitorMonotonicCounter(value);
    PolledMeter.update(r);
    value.incrementAndGet();
    PolledMeter.update(r);
    PolledMeter.remove(r, id);
  }

  Assertions.assertEquals(10, r.counter("test").count());
}
 
Example 8
Source Project: spectator   Source File: BucketDistributionSummaryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void basic() {
  Registry r = new DefaultRegistry();
  BucketDistributionSummary c = BucketDistributionSummary.get(
      r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS));

  c.record(TimeUnit.MILLISECONDS.toNanos(3750));
  Assertions.assertEquals(1, r.distributionSummaries().count());
  Assertions.assertEquals(1, sum(r, "test"));

  c.record(TimeUnit.MILLISECONDS.toNanos(4221));
  Assertions.assertEquals(2, r.distributionSummaries().count());
  Assertions.assertEquals(2, sum(r, "test"));

  c.record(TimeUnit.MILLISECONDS.toNanos(4221));
  Assertions.assertEquals(2, r.distributionSummaries().count());
  Assertions.assertEquals(3, sum(r, "test"));
}
 
Example 9
Source Project: spectator   Source File: BucketTimerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void basic() {
  Registry r = new DefaultRegistry();
  BucketTimer t = BucketTimer.get(
      r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS));

  t.record(3750, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(1, r.timers().count());
  Assertions.assertEquals(1, sum(r, "test"));

  t.record(4221, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(2, r.timers().count());
  Assertions.assertEquals(2, sum(r, "test"));

  t.record(4221, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(2, r.timers().count());
  Assertions.assertEquals(3, sum(r, "test"));
}
 
Example 10
Source Project: spectator   Source File: BucketCounterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void basic() {
  Registry r = new DefaultRegistry();
  BucketCounter c = BucketCounter.get(
      r, r.createId("test"), BucketFunctions.latency(4, TimeUnit.SECONDS));

  c.record(TimeUnit.MILLISECONDS.toNanos(3750));
  Assertions.assertEquals(1, r.counters().count());
  Assertions.assertEquals(1, sum(r, "test"));

  c.record(TimeUnit.MILLISECONDS.toNanos(4221));
  Assertions.assertEquals(2, r.counters().count());
  Assertions.assertEquals(2, sum(r, "test"));

  c.record(TimeUnit.MILLISECONDS.toNanos(4221));
  Assertions.assertEquals(2, r.counters().count());
  Assertions.assertEquals(3, sum(r, "test"));
}
 
Example 11
Source Project: spectator   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void updateNextFixedDelay() {
  ManualClock clock = new ManualClock();
  Registry registry = new DefaultRegistry(clock);
  Counter skipped = registry.counter("skipped");

  Scheduler.Options options = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofSeconds(10));

  clock.setWallTime(5437L);
  Scheduler.DelayedTask task = new Scheduler.DelayedTask(clock, options, () -> {});
  Assertions.assertEquals(5437L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(12123L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(22123L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(27000L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(37000L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());
}
 
Example 12
Source Project: spectator   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shutdownStopsThreads() throws Exception {
  Scheduler s = new Scheduler(new DefaultRegistry(), "shutdown", 1);

  // Schedule something to force it to start the threads
  Scheduler.Options opts = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofMillis(10))
      .withStopOnFailure(false);
  ScheduledFuture<?> f = s.schedule(opts, () -> {});
  Assertions.assertEquals(1L, numberOfThreads("shutdown"));

  // Shutdown and wait a bit, this gives the thread a chance to restart
  s.shutdown();
  Thread.sleep(300);
  Assertions.assertEquals(0L, numberOfThreads("shutdown"));
}
 
Example 13
Source Project: spectator   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stopOnFailureFalseThrowable() throws Exception {
  Scheduler s = new Scheduler(new DefaultRegistry(), "test", 1);

  Scheduler.Options opts = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofMillis(10))
      .withStopOnFailure(false);

  final CountDownLatch latch = new CountDownLatch(5);
  ScheduledFuture<?> f = s.schedule(opts, () -> {
    latch.countDown();
    throw new IOError(new RuntimeException("stop"));
  });

  Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS));
  Assertions.assertFalse(f.isDone());
  s.shutdown();
}
 
Example 14
Source Project: spectator   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stopOnFailureFalse() throws Exception {
  Scheduler s = new Scheduler(new DefaultRegistry(), "test", 2);

  Scheduler.Options opts = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10))
      .withStopOnFailure(false);

  final CountDownLatch latch = new CountDownLatch(5);
  ScheduledFuture<?> f = s.schedule(opts, () -> {
    latch.countDown();
    throw new RuntimeException("stop");
  });

  Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS));
  Assertions.assertFalse(f.isDone());
  s.shutdown();
}
 
Example 15
Source Project: spectator   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stopOnFailureTrue() throws Exception {
  Scheduler s = new Scheduler(new DefaultRegistry(), "test", 2);

  Scheduler.Options opts = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10))
      .withStopOnFailure(true);

  final CountDownLatch latch = new CountDownLatch(1);
  ScheduledFuture<?> f = s.schedule(opts, () -> {
    latch.countDown();
    throw new RuntimeException("stop");
  });

  Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS));
  while (!f.isDone()); // This will be an endless loop if broken
  s.shutdown();
}
 
Example 16
Source Project: spectator   Source File: CassandraTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void readLatency() throws Exception {
  Registry r = new DefaultRegistry(new ManualClock());
  List<JmxConfig> configs = configs();

  JmxData data = timer("keyspace=test,name=ReadLatency,scope=foo,type=ColumnFamily", 0);
  List<Measurement> ms = measure(r, configs, data);
  Assertions.assertEquals(7, ms.size());
  Assertions.assertEquals(
      50.0e-4,
      Utils.first(ms, "statistic", "percentile_50").value(),
      1e-12);

  data = timer("keyspace=test,name=ReadLatency,scope=foo,type=ColumnFamily", 1);
  ms = measure(r, configs, data);
  Assertions.assertEquals(7, ms.size());
  Assertions.assertEquals(
      50.01e-4,
      Utils.first(ms, "statistic", "percentile_50").value(),
      1e-12);
}
 
Example 17
Source Project: spectator   Source File: MetricsControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeCombinedRegistry() {
  // Multiple occurrences of measurements in the same registry
  // (confirm these are handled within the registry itself).
  Measurement measureBXY2 = new Measurement(idBXY, 5, 5.5);
  Meter meterB2 = new TestMeter("ignoreB", measureBXY2);

  DefaultRegistry registry = new DefaultRegistry(clock);
  registry.register(meterB);
  registry.register(meterB2);

  List<TaggedDataPoints> expectedTaggedDataPoints = Arrays.asList(
     new TaggedDataPoints(
           Arrays.asList(new BasicTag("tagA", "X"),
                         new BasicTag("tagB", "Y")),
           Arrays.asList(new DataPoint(clock.wallTime(), 50.5 + 5.5))));

  HashMap<String, MetricValues> expect = new HashMap<>();
  expect.put("idB", new MetricValues("Counter", expectedTaggedDataPoints));

  PolledMeter.update(registry);
  Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
 
Example 18
@Test
public void testGuage() {
    DefaultRegistry registry = new DefaultRegistry();
    SpectatorMetricRegistry metricRegistry = new SpectatorMetricRegistry(registry, registry.createId("foo"));
    
    metricRegistry.gauge("bar", () -> 10);
    
    PolledMeter.update(registry);
    
    Assert.assertEquals(10.0, registry.gauge(registry.createId("foo.bar")).value(), 0);
}
 
Example 19
Source Project: spectator   Source File: MetricsControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoreNan() {
  Id id = idB.withTag("tagA", "Z");
  Measurement measure = new Measurement(id, 100, Double.NaN);
  Meter meter = new TestMeter("ignoreZ", measure);

  DefaultRegistry registry = new DefaultRegistry(clock);
  registry.register(meter);

  HashMap<String, MetricValues> expect = new HashMap<>();
  PolledMeter.update(registry);
  Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
 
Example 20
@Test
public void collect() throws IllegalAccessException, IOException {
  new Expectations(RegistrationManager.INSTANCE) {
    {
      RegistrationManager.INSTANCE.getAppId();
      result = "testAppId";
    }
  };
  ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:0");
  publisher.init(globalRegistry, null, null);

  Registry registry = new DefaultRegistry(new ManualClock());
  globalRegistry.add(registry);

  Counter counter = registry.counter("count.name", "tag1", "tag1v", "tag2", "tag2v");
  counter.increment();

  HTTPServer httpServer = (HTTPServer) FieldUtils.readField(publisher, "httpServer", true);
  com.sun.net.httpserver.HttpServer server = (HttpServer) FieldUtils.readField(httpServer, "server", true);

  URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/metrics");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  try (InputStream is = conn.getInputStream()) {
    Assert.assertEquals("# HELP ServiceComb_Metrics ServiceComb Metrics\n" +
            "# TYPE ServiceComb_Metrics untyped\n" +
            "count_name{appId=\"testAppId\",tag1=\"tag1v\",tag2=\"tag2v\",} 1.0\n",
        IOUtils.toString(is, StandardCharsets.UTF_8));
  }

  publisher.destroy();
}
 
Example 21
@Test
public void checkPublisherState() {
    int numTasks = 5;
    final TaskEventsGenerator taskEventsGenerator = new TaskEventsGenerator(
            mockTitusClient(numTasks),
            Collections.emptyMap());

    EsPublisher esPublisher = new EsPublisher(taskEventsGenerator, mockElasticSearchClient(),
            mockEsPublisherConfiguration(), new DefaultRegistry());
    esPublisher.activate();

    final CountDownLatch latch = new CountDownLatch(1);
    Flux.interval(Duration.ofSeconds(1), Schedulers.elastic())
            .take(1)
            .doOnNext(i -> {
                final int numTasksUpdated = esPublisher.getNumTasksPublished();
                final int numErrors = esPublisher.getNumErrorsInPublishing();
                assertThat(numErrors).isEqualTo(0);
                assertThat(numTasksUpdated).isGreaterThanOrEqualTo(numTasks);
                latch.countDown();
            }).subscribe();
    try {
        latch.await(2, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        fail("Timeout in checkPublisherState ", e);
    }
}
 
Example 22
Source Project: titus-control-plane   Source File: EmbeddedCloudModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    install(new ArchaiusModule());
    bind(Registry.class).toInstance(new DefaultRegistry());

    install(new SimulatedCloudEndpointModule());
    install(new EmbeddedJerseyModule());
    bind(SimulatedCloud.class).asEagerSingleton();
}
 
Example 23
@BeforeClass
public static void setUpClass() {
    // This is an arbitrary large timeout; the FailJobValidator fails instantaneously, so
    // timeout never occurs.
    when(configuration.getTimeoutMs()).thenReturn(10 * 1000);
    AggregatingValidator validator = new AggregatingValidator(configuration, new DefaultRegistry(), validators);
    titusStackResource = getTitusStackResource(validator);
}
 
Example 24
Source Project: spectator   Source File: GuiceServletFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
  registry = new DefaultRegistry();
  client = HttpClient.create(new IpcLogger(registry));
  Spectator.globalRegistry().removeAll();
  Spectator.globalRegistry().add(registry);
}
 
Example 25
@Test
public void verifyStoreInit() throws Exception {
    Session session = cassandraCQLUnit.getSession();
    loadTestData();

    CassAppScalePolicyStore store = new CassAppScalePolicyStore(session, configuration, new DefaultRegistry());
    store.init().await();

    List<AutoScalingPolicy> allPolicies = store.retrievePolicies(false).toList().toBlocking().first();
    Assertions.assertThat(allPolicies.size()).isEqualTo(3);

    List<AutoScalingPolicy> jobOnePolicies = store.retrievePoliciesForJob("job-1").toList().toBlocking().first();
    Assertions.assertThat(jobOnePolicies.size()).isEqualTo(2);
    List<String> refIdList = jobOnePolicies.stream().map(as -> as.getRefId()).collect(Collectors.toList());
    Assertions.assertThat(refIdList).containsOnly(POLICY_1_ID, POLICY_3_ID);


    List<AutoScalingPolicy> jobTwoPolicies = store.retrievePoliciesForJob("job-2").toList().toBlocking().first();
    Assertions.assertThat(jobTwoPolicies.size()).isEqualTo(1);
    List<String> jobTwoRefIdList = jobTwoPolicies.stream().map(as -> as.getRefId()).collect(Collectors.toList());
    Assertions.assertThat(jobTwoRefIdList).isEqualTo(Arrays.asList(POLICY_2_ID));

    // verify metric lower/upper bounds
    List<StepAdjustment> stepAdjustments = jobTwoPolicies.stream()
            .flatMap(as -> as.getPolicyConfiguration().getStepScalingPolicyConfiguration().getSteps().stream())
            .collect(Collectors.toList());
    Assertions.assertThat(stepAdjustments.size()).isEqualTo(1);
    Assertions.assertThat(stepAdjustments.get(0).getMetricIntervalUpperBound()).isEqualTo(Optional.empty());
    Assertions.assertThat(stepAdjustments.get(0).getMetricIntervalLowerBound().get()).isEqualTo(Double.valueOf(0));
}
 
Example 26
@Test
public void checkStoreAndRetrieve() throws Exception {
    Session session = cassandraCQLUnit.getSession();
    CassAppScalePolicyStore store = new CassAppScalePolicyStore(session, configuration, new DefaultRegistry());

    String jobId = UUID.randomUUID().toString();
    Observable<String> respRefId = store.storePolicy(buildAutoScalingPolicy(jobId));
    String refId = respRefId.toBlocking().first();
    Assertions.assertThat(refId).isNotNull().isNotEmpty();

    Observable<AutoScalingPolicy> autoScalingPolicyObservable = store.retrievePolicyForRefId(refId);
    AutoScalingPolicy autoScalingPolicy = autoScalingPolicyObservable.toBlocking().first();
    Assertions.assertThat(autoScalingPolicy.getRefId()).isEqualTo(refId);
    Assertions.assertThat(autoScalingPolicy.getStatus()).isEqualTo(PolicyStatus.Pending);

    Observable<String> respRefIdTwo = store.storePolicy(buildAutoScalingPolicy(jobId));
    String refIdTwo = respRefIdTwo.toBlocking().first();
    Assertions.assertThat(refIdTwo).isNotNull().isNotEmpty();

    autoScalingPolicyObservable = store.retrievePoliciesForJob(jobId);
    List<AutoScalingPolicy> autoScalingPolicies = autoScalingPolicyObservable.toList().toBlocking().first();
    Assertions.assertThat(autoScalingPolicies.size()).isEqualTo(2);
    List<String> refIdList = autoScalingPolicies.stream().map(ap -> ap.getRefId()).collect(Collectors.toList());
    Assertions.assertThat(refIdList).isEqualTo(Arrays.asList(refId, refIdTwo));
    Assertions.assertThat(autoScalingPolicies.get(1).getStatus()).isEqualTo(PolicyStatus.Pending);


    autoScalingPolicyObservable = store.retrievePoliciesForJob("invalidJobId");
    List<AutoScalingPolicy> emptyPolicies = autoScalingPolicyObservable.toList().toBlocking().first();
    Assertions.assertThat(emptyPolicies.size()).isEqualTo(0);
}
 
Example 27
Source Project: spectator   Source File: IpcServletFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
  registry = new DefaultRegistry();
  client = HttpClient.create(new IpcLogger(registry));
  Spectator.globalRegistry().removeAll();
  Spectator.globalRegistry().add(registry);
}
 
Example 28
@Before
public void setUp() {
    when(configuration.isIamValidatorEnabled()).thenReturn(true);
    when(configuration.getAgentIamAssumeRole()).thenReturn(IAM_ASSUME_ROLE_NAME);
    when(configuration.getIamValidationTimeoutMs()).thenReturn(10000L);
    when(configuration.getErrorType()).thenReturn(ValidationError.Type.HARD.name());
    iamValidator = new JobIamValidator(configuration, iamConnector, new DefaultRegistry());
}
 
Example 29
Source Project: titus-control-plane   Source File: JobImageSanitizerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    when(configuration.isEnabled()).thenReturn(true);
    when(configuration.getJobImageValidationTimeoutMs()).thenReturn(1000L);
    when(configuration.getErrorType()).thenReturn(ValidationError.Type.HARD.name());
    when(registryClient.getImageDigest(anyString(), anyString())).thenReturn(Mono.just(digest));
    sanitizer = new JobImageSanitizer(configuration, registryClient, new DefaultRegistry());
}
 
Example 30
Source Project: titus-control-plane   Source File: TitusRuntimes.java    License: Apache License 2.0 5 votes vote down vote up
public static TitusRuntime internal(Duration localSchedulerLoopInterval) {
    return new DefaultTitusRuntime(
            new LoggingCodePointTracker(),
            LoggingCodeInvariants.getDefault(),
            LoggingSystemLogService.getInstance(),
            false,
            LoggingSystemAbortListener.getDefault(),
            localSchedulerLoopInterval,
            new DefaultRegistry(),
            Clocks.system(),
            false
    );
}