mirror of
https://github.com/google/nomulus.git
synced 2025-07-25 03:58:34 +02:00
Move metrics dependencies to artifacts under Maven groupId com.google.monitoring-client
------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=180580386
This commit is contained in:
parent
0aab48eb9f
commit
07622725bf
94 changed files with 153 additions and 6451 deletions
|
@ -28,7 +28,6 @@ java_library(
|
|||
"//java/google/registry/dns",
|
||||
"//java/google/registry/flows",
|
||||
"//java/google/registry/model",
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//java/google/registry/monitoring/whitebox",
|
||||
"//java/google/registry/pricing",
|
||||
"//java/google/registry/request",
|
||||
|
@ -46,6 +45,7 @@ java_library(
|
|||
"@com_google_dagger",
|
||||
"@com_google_guava",
|
||||
"@com_google_guava_testlib",
|
||||
"@com_google_monitoring_client_metrics",
|
||||
"@com_google_re2j",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
|
|
|
@ -20,8 +20,8 @@ import static org.mockito.Mockito.mock;
|
|||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
import google.registry.monitoring.metrics.EventMetric;
|
||||
import google.registry.monitoring.metrics.IncrementableMetric;
|
||||
import com.google.monitoring.metrics.EventMetric;
|
||||
import com.google.monitoring.metrics.IncrementableMetric;
|
||||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.InjectRule;
|
||||
import google.registry.testing.ShardableTestCase;
|
||||
|
|
|
@ -23,7 +23,6 @@ java_library(
|
|||
"//java/google/registry/dns/writer",
|
||||
"//java/google/registry/flows",
|
||||
"//java/google/registry/model",
|
||||
"//java/google/registry/monitoring/metrics/contrib",
|
||||
"//java/google/registry/util",
|
||||
"//java/google/registry/xml",
|
||||
"//javatests/google/registry/testing",
|
||||
|
@ -34,6 +33,7 @@ java_library(
|
|||
"@com_google_code_findbugs_jsr305",
|
||||
"@com_google_guava",
|
||||
"@com_google_guava_testlib",
|
||||
"@com_google_monitoring_client_contrib",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@joda_time",
|
||||
|
|
|
@ -16,6 +16,8 @@ package google.registry.model.registry.label;
|
|||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.model.ofy.ObjectifyService.ofy;
|
||||
import static google.registry.model.registry.label.DomainLabelMetrics.PremiumListCheckOutcome.BLOOM_FILTER_NEGATIVE;
|
||||
import static google.registry.model.registry.label.DomainLabelMetrics.PremiumListCheckOutcome.CACHED_NEGATIVE;
|
||||
|
@ -28,8 +30,6 @@ import static google.registry.model.registry.label.PremiumListUtils.deletePremiu
|
|||
import static google.registry.model.registry.label.PremiumListUtils.doesPremiumListExist;
|
||||
import static google.registry.model.registry.label.PremiumListUtils.getPremiumPrice;
|
||||
import static google.registry.model.registry.label.PremiumListUtils.savePremiumListAndEntries;
|
||||
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.testing.DatastoreHelper.createTld;
|
||||
import static google.registry.testing.DatastoreHelper.loadPremiumListEntries;
|
||||
import static google.registry.testing.DatastoreHelper.persistPremiumList;
|
||||
|
|
|
@ -16,6 +16,8 @@ package google.registry.model.registry.label;
|
|||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth.assertWithMessage;
|
||||
import static com.google.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.model.registry.label.DomainLabelMetrics.reservedListChecks;
|
||||
import static google.registry.model.registry.label.DomainLabelMetrics.reservedListHits;
|
||||
import static google.registry.model.registry.label.DomainLabelMetrics.reservedListProcessingTime;
|
||||
|
@ -28,8 +30,6 @@ import static google.registry.model.registry.label.ReservationType.RESERVED_FOR_
|
|||
import static google.registry.model.registry.label.ReservedList.getAllowedNameservers;
|
||||
import static google.registry.model.registry.label.ReservedList.getReservationTypes;
|
||||
import static google.registry.model.registry.label.ReservedList.matchesAnchorTenantReservation;
|
||||
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.testing.DatastoreHelper.createTld;
|
||||
import static google.registry.testing.DatastoreHelper.persistReservedList;
|
||||
import static google.registry.testing.DatastoreHelper.persistResource;
|
||||
|
|
|
@ -1,31 +0,0 @@
|
|||
package(
|
||||
default_testonly = 1,
|
||||
default_visibility = ["//java/google/registry:registry_project"],
|
||||
)
|
||||
|
||||
licenses(["notice"]) # Apache 2.0
|
||||
|
||||
load("//java/com/google/testing/builddefs:GenTestRules.bzl", "GenTestRules")
|
||||
|
||||
java_library(
|
||||
name = "metrics",
|
||||
srcs = glob(["*.java"]),
|
||||
deps = [
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//third_party/junit",
|
||||
"@com_google_guava",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@joda_time",
|
||||
"@junit",
|
||||
"@org_mockito_all",
|
||||
],
|
||||
)
|
||||
|
||||
GenTestRules(
|
||||
name = "GeneratedTestRules",
|
||||
test_files = glob(["*Test.java"]),
|
||||
deps = [
|
||||
":metrics",
|
||||
],
|
||||
)
|
|
@ -1,184 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link Counter}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class CounterTest {
|
||||
@Test
|
||||
public void testGetCardinality_reflectsCurrentCardinality() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
assertThat(counter.getCardinality()).isEqualTo(0);
|
||||
|
||||
counter.increment("foo");
|
||||
assertThat(counter.getCardinality()).isEqualTo(1);
|
||||
counter.increment("bar");
|
||||
assertThat(counter.getCardinality()).isEqualTo(2);
|
||||
counter.increment("foo");
|
||||
assertThat(counter.getCardinality()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncrementBy_wrongLabelValueCount_throwsException() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")));
|
||||
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> counter.increment("blah"));
|
||||
assertThat(thrown)
|
||||
.hasMessageThat()
|
||||
.contains(
|
||||
"The count of labelValues must be equal to the underlying Metric's count of labels.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncrement_incrementsValues() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
|
||||
assertThat(counter.getTimestampedValues()).isEmpty();
|
||||
|
||||
// use package-private incrementBy once to set the start timestamp predictably.
|
||||
counter.incrementBy(1, new Instant(1337), ImmutableList.of("test_value1"));
|
||||
assertThat(counter.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(counter, ImmutableList.of("test_value1"), new Instant(1337), 1L));
|
||||
|
||||
counter.increment("test_value1");
|
||||
assertThat(counter.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(counter, ImmutableList.of("test_value1"), new Instant(1337), 2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncrementBy_incrementsValues() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
|
||||
assertThat(counter.getTimestampedValues()).isEmpty();
|
||||
|
||||
counter.incrementBy(1, new Instant(1337), ImmutableList.of("test_value1"));
|
||||
assertThat(counter.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(counter, ImmutableList.of("test_value1"), new Instant(1337), 1L));
|
||||
|
||||
counter.set(-10L, new Instant(1337), ImmutableList.of("test_value2"));
|
||||
counter.incrementBy(5, new Instant(1337), ImmutableList.of("test_value2"));
|
||||
assertThat(counter.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(counter, ImmutableList.of("test_value1"), new Instant(1337), 1L),
|
||||
MetricPoint.create(counter, ImmutableList.of("test_value2"), new Instant(1337), -5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncrementBy_negativeOffset_throwsException() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> counter.incrementBy(-1L, "foo"));
|
||||
assertThat(thrown).hasMessageThat().contains("The offset provided must be non-negative");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResetAll_resetsAllValuesAndStartTimestamps() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
|
||||
counter.incrementBy(3, new Instant(1337), ImmutableList.of("foo"));
|
||||
counter.incrementBy(5, new Instant(1338), ImmutableList.of("moo"));
|
||||
|
||||
assertThat(counter.getTimestampedValues(new Instant(1400)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("foo"), new Instant(1337), new Instant(1400), 3L),
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("moo"), new Instant(1338), new Instant(1400), 5L));
|
||||
|
||||
counter.reset(new Instant(1339));
|
||||
|
||||
assertThat(counter.getTimestampedValues(new Instant(1400)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("foo"), new Instant(1339), new Instant(1400), 0L),
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("moo"), new Instant(1339), new Instant(1400), 0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReset_resetsValuesAndStartTimestamps() {
|
||||
Counter counter =
|
||||
new Counter(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
|
||||
counter.incrementBy(3, new Instant(1337), ImmutableList.of("foo"));
|
||||
counter.incrementBy(5, new Instant(1338), ImmutableList.of("moo"));
|
||||
|
||||
assertThat(counter.getTimestampedValues(new Instant(1400)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("foo"), new Instant(1337), new Instant(1400), 3L),
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("moo"), new Instant(1338), new Instant(1400), 5L));
|
||||
|
||||
counter.reset(new Instant(1339), ImmutableList.of("foo"));
|
||||
|
||||
assertThat(counter.getTimestampedValues(new Instant(1400)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("foo"), new Instant(1339), new Instant(1400), 0L),
|
||||
MetricPoint.create(
|
||||
counter, ImmutableList.of("moo"), new Instant(1338), new Instant(1400), 5L));
|
||||
}
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSortedSet;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Tests for {@link CustomFitter}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class CustomFitterTest {
|
||||
|
||||
@Test
|
||||
public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of()));
|
||||
assertThat(thrown).hasMessageThat().contains("boundaries must not be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of(2.0, 0.0)));
|
||||
assertThat(thrown).hasMessageThat().contains("boundaries must be sorted");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateCustomFitter_hasGivenBounds() {
|
||||
CustomFitter fitter = CustomFitter.create(ImmutableSortedSet.of(1.0, 2.0));
|
||||
assertThat(fitter.boundaries()).containsExactly(1.0, 2.0).inOrder();
|
||||
}
|
||||
}
|
|
@ -1,314 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableRangeMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Range;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link EventMetric}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class EventMetricTest {
|
||||
|
||||
private final DistributionFitter distributionFitter = CustomFitter.create(ImmutableSet.of(5.0));
|
||||
private EventMetric metric;
|
||||
@Before
|
||||
public void setUp() {
|
||||
metric =
|
||||
new EventMetric(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
distributionFitter,
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCardinality_reflectsCurrentCardinality() {
|
||||
assertThat(metric.getCardinality()).isEqualTo(0);
|
||||
|
||||
metric.record(1.0, "foo");
|
||||
|
||||
assertThat(metric.getCardinality()).isEqualTo(1);
|
||||
|
||||
metric.record(1.0, "bar");
|
||||
|
||||
assertThat(metric.getCardinality()).isEqualTo(2);
|
||||
|
||||
metric.record(1.0, "foo");
|
||||
|
||||
assertThat(metric.getCardinality()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncrementBy_wrongLabelValueCount_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> metric.record(1.0, "blah", "blah"));
|
||||
assertThat(thrown)
|
||||
.hasMessageThat()
|
||||
.contains(
|
||||
"The count of labelValues must be equal to the underlying Metric's count of labels.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecord_updatesDistribution() {
|
||||
assertThat(metric.getTimestampedValues()).isEmpty();
|
||||
|
||||
metric.recordMultiple(1.0, 1, new Instant(1337), ImmutableList.of("test_value1"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("test_value1"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
1.0,
|
||||
0.0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
|
||||
metric.record(10.0, "test_value1");
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("test_value1"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
5.5,
|
||||
40.5,
|
||||
2L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecord_multipleValues_updatesDistributions() {
|
||||
assertThat(metric.getTimestampedValues()).isEmpty();
|
||||
|
||||
metric.recordMultiple(1.0, 3, new Instant(1337), ImmutableList.of("test_value1"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("test_value1"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
1.0,
|
||||
0,
|
||||
3L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 3L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
|
||||
metric.recordMultiple(2.0, 5, new Instant(1337), ImmutableList.of("test_value1"));
|
||||
metric.recordMultiple(7.0, 10, new Instant(1337), ImmutableList.of("test_value2"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("test_value1"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
1.625,
|
||||
1.875,
|
||||
8L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 8L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)),
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("test_value2"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
7.0,
|
||||
0,
|
||||
10L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 10L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResetAll_resetsAllValuesAndStartTimestamps() {
|
||||
metric.recordMultiple(3.0, 1, new Instant(1336), ImmutableList.of("foo"));
|
||||
metric.recordMultiple(5.0, 1, new Instant(1337), ImmutableList.of("moo"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("foo"),
|
||||
new Instant(1336),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
3.0,
|
||||
0.0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)),
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("moo"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
5.0,
|
||||
0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
|
||||
metric.reset(new Instant(1339));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1340)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("foo"),
|
||||
new Instant(1339),
|
||||
new Instant(1340),
|
||||
ImmutableDistribution.create(
|
||||
0.0,
|
||||
0.0,
|
||||
0L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)),
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("moo"),
|
||||
new Instant(1339),
|
||||
new Instant(1340),
|
||||
ImmutableDistribution.create(
|
||||
0.0,
|
||||
0,
|
||||
0L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReset_resetsValueAndStartTimestamp() {
|
||||
metric.recordMultiple(3.0, 1, new Instant(1336), ImmutableList.of("foo"));
|
||||
metric.recordMultiple(5.0, 1, new Instant(1337), ImmutableList.of("moo"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("foo"),
|
||||
new Instant(1336),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
3.0,
|
||||
0.0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)),
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("moo"),
|
||||
new Instant(1337),
|
||||
new Instant(1338),
|
||||
ImmutableDistribution.create(
|
||||
5.0,
|
||||
0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
|
||||
metric.reset(new Instant(1339), ImmutableList.of("foo"));
|
||||
|
||||
assertThat(metric.getTimestampedValues(new Instant(1340)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("foo"),
|
||||
new Instant(1339),
|
||||
new Instant(1340),
|
||||
ImmutableDistribution.create(
|
||||
0.0,
|
||||
0.0,
|
||||
0L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build(),
|
||||
distributionFitter)),
|
||||
MetricPoint.create(
|
||||
metric,
|
||||
ImmutableList.of("moo"),
|
||||
new Instant(1337),
|
||||
new Instant(1340),
|
||||
ImmutableDistribution.create(
|
||||
5.0,
|
||||
0,
|
||||
1L,
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build(),
|
||||
distributionFitter)));
|
||||
}
|
||||
}
|
|
@ -1,69 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link ExponentialFitter}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class ExponentialFitterTest {
|
||||
@Test
|
||||
public void testCreateExponentialFitter_zeroNumIntervals_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(0, 3.0, 1.0));
|
||||
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateExponentialFitter_negativeNumIntervals_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(-1, 3.0, 1.0));
|
||||
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateExponentialFitter_invalidBase_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 0.5, 1.0));
|
||||
assertThat(thrown).hasMessageThat().contains("base must be greater than 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateExponentialFitter_zeroScale_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("scale must not be 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateExponentialFitter_NanScale_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, Double.NaN));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateExponentialFitter_hasCorrectBounds() {
|
||||
ExponentialFitter fitter = ExponentialFitter.create(3, 5.0, 2.0);
|
||||
|
||||
assertThat(fitter.boundaries()).containsExactly(2.0, 10.0, 50.0, 250.0).inOrder();
|
||||
}
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link FibonacciFitter}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class FibonacciFitterTest {
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeNegative_throwsException() {
|
||||
IllegalArgumentException e =
|
||||
expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(-1));
|
||||
assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeZero_throwsException() {
|
||||
IllegalArgumentException e =
|
||||
expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(0));
|
||||
assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeOne_createsTwoBoundaries() {
|
||||
assertThat(FibonacciFitter.create(1).boundaries()).containsExactly(0.0, 1.0).inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeTwo_createsThreeBoundaries() {
|
||||
assertThat(FibonacciFitter.create(2).boundaries()).containsExactly(0.0, 1.0, 2.0).inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeThree_createsFourBoundaries() {
|
||||
assertThat(FibonacciFitter.create(3).boundaries())
|
||||
.containsExactly(0.0, 1.0, 2.0, 3.0)
|
||||
.inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeFour_createsFourBoundaries() {
|
||||
assertThat(FibonacciFitter.create(4).boundaries())
|
||||
.containsExactly(0.0, 1.0, 2.0, 3.0)
|
||||
.inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_maxBucketSizeLarge_createsFibonacciSequenceBoundaries() {
|
||||
ImmutableList<Double> expectedBoundaries =
|
||||
ImmutableList.of(
|
||||
0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0, 55.0, 89.0, 144.0, 233.0, 377.0, 610.0,
|
||||
987.0);
|
||||
assertThat(FibonacciFitter.create(1000).boundaries())
|
||||
.containsExactlyElementsIn(expectedBoundaries)
|
||||
.inOrder();
|
||||
}
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link LabelDescriptor}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class LabelDescriptorTest {
|
||||
|
||||
@Test
|
||||
public void testCreate_invalidLabel_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> LabelDescriptor.create("@", "description"));
|
||||
assertThat(thrown).hasMessageThat().contains("Label name must match the regex");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_blankNameField_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> LabelDescriptor.create("", "description"));
|
||||
assertThat(thrown).hasMessageThat().contains("Name must not be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_blankDescriptionField_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LabelDescriptor.create("name", ""));
|
||||
assertThat(thrown).hasMessageThat().contains("Description must not be empty");
|
||||
}
|
||||
}
|
|
@ -1,89 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link LinearFitter}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class LinearFitterTest {
|
||||
@Test
|
||||
public void testCreateLinearFitter_zeroNumIntervals_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_negativeNumIntervals_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_zeroWidth_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_negativeWidth_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_NaNWidth_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, Double.NaN, 0.0));
|
||||
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_NaNOffset_throwsException() throws Exception {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 1.0, Double.NaN));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_hasCorrectBounds() {
|
||||
LinearFitter fitter = LinearFitter.create(1, 10, 0);
|
||||
|
||||
assertThat(fitter.boundaries()).containsExactly(0.0, 10.0).inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_withOffset_hasCorrectBounds() {
|
||||
LinearFitter fitter = LinearFitter.create(1, 10, 5);
|
||||
|
||||
assertThat(fitter.boundaries()).containsExactly(5.0, 15.0).inOrder();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateLinearFitter_withOffsetAndMultipleIntervals_hasCorrectBounds() {
|
||||
LinearFitter fitter = LinearFitter.create(3, 10, 5);
|
||||
|
||||
assertThat(fitter.boundaries()).containsExactly(5.0, 15.0, 25.0, 35.0).inOrder();
|
||||
}
|
||||
}
|
|
@ -1,130 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.util.concurrent.Service.State;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Matchers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
/** Unit tests for {@link MetricExporter}. */
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MetricExporterTest {
|
||||
|
||||
@Mock private MetricWriter writer;
|
||||
@Mock private MetricPoint<?> point;
|
||||
private MetricExporter exporter;
|
||||
private BlockingQueue<Optional<ImmutableList<MetricPoint<?>>>> writeQueue;
|
||||
private final Optional<ImmutableList<MetricPoint<?>>> poisonPill = Optional.empty();
|
||||
private final Optional<ImmutableList<MetricPoint<?>>> emptyBatch =
|
||||
Optional.of(ImmutableList.<MetricPoint<?>>of());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
writeQueue = new ArrayBlockingQueue<>(1);
|
||||
exporter = new MetricExporter(writeQueue, writer, Executors.defaultThreadFactory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRun_takesFromQueue_whileRunning() throws Exception {
|
||||
exporter.startAsync().awaitRunning();
|
||||
|
||||
insertAndAssert(emptyBatch);
|
||||
// Insert more batches to verify that the exporter hasn't gotten stuck
|
||||
insertAndAssert(emptyBatch);
|
||||
insertAndAssert(emptyBatch);
|
||||
|
||||
assertThat(exporter.state()).isEqualTo(State.RUNNING);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRun_terminates_afterPoisonPill() throws Exception {
|
||||
exporter.startAsync().awaitRunning();
|
||||
|
||||
insertAndAssert(poisonPill);
|
||||
try {
|
||||
exporter.awaitTerminated(500, TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException timeout) {
|
||||
fail("MetricExporter did not reach the TERMINATED state after receiving a poison pill");
|
||||
}
|
||||
|
||||
assertThat(exporter.state()).isEqualTo(State.TERMINATED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRun_staysRunning_afterIOException() throws Exception {
|
||||
Optional<ImmutableList<MetricPoint<?>>> threeBatch =
|
||||
Optional.of(ImmutableList.of(point, point, point));
|
||||
doThrow(new IOException()).when(writer).write(Matchers.<MetricPoint<?>>any());
|
||||
exporter.startAsync();
|
||||
|
||||
insertAndAssert(threeBatch);
|
||||
// Insert another batch in order to block until the exporter has processed the last one
|
||||
insertAndAssert(threeBatch);
|
||||
// Insert another to make sure the exporter hasn't gotten stuck
|
||||
insertAndAssert(threeBatch);
|
||||
|
||||
assertThat(exporter.state()).isNotEqualTo(State.FAILED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRun_writesMetrics() throws Exception {
|
||||
Optional<ImmutableList<MetricPoint<?>>> threeBatch =
|
||||
Optional.of(ImmutableList.of(point, point, point));
|
||||
exporter.startAsync();
|
||||
|
||||
insertAndAssert(threeBatch);
|
||||
// Insert another batch in order to block until the exporter has processed the last one
|
||||
insertAndAssert(threeBatch);
|
||||
|
||||
// Force the exporter to finish so that the verify counts below are deterministic
|
||||
insertAndAssert(poisonPill);
|
||||
try {
|
||||
exporter.awaitTerminated(500, TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException timeout) {
|
||||
fail("MetricExporter did not reach the TERMINATED state after receiving a poison pill");
|
||||
}
|
||||
|
||||
assertThat(exporter.state()).isNotEqualTo(State.FAILED);
|
||||
verify(writer, times(6)).write(point);
|
||||
verify(writer, times(2)).flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to insert into the {@link BlockingQueue} and assert that the item has been
|
||||
* enqueued.
|
||||
*/
|
||||
private void insertAndAssert(Optional<ImmutableList<MetricPoint<?>>> batch) throws Exception {
|
||||
boolean isTaken = writeQueue.offer(batch, 500, TimeUnit.MILLISECONDS);
|
||||
assertThat(isTaken).isTrue();
|
||||
}
|
||||
}
|
|
@ -1,167 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.MetricSchema.Kind;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MetricRegistryImpl}.
|
||||
*
|
||||
* <p>The MetricRegistryImpl is a singleton, so we have to be careful to empty it after every test
|
||||
* to maintain a blank slate.
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class MetricRegistryImplTest {
|
||||
private final LabelDescriptor label =
|
||||
LabelDescriptor.create("test_labelname", "test_labeldescription");
|
||||
|
||||
@After
|
||||
public void clearMetrics() {
|
||||
MetricRegistryImpl.getDefault().unregisterAllMetrics();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterAndUnregister_tracksRegistrations() {
|
||||
assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).isEmpty();
|
||||
|
||||
AbstractMetric<?> metric = mock(AbstractMetric.class);
|
||||
MetricRegistryImpl.getDefault().registerMetric("/test/metric", metric);
|
||||
|
||||
assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).containsExactly(metric);
|
||||
|
||||
MetricRegistryImpl.getDefault().unregisterMetric("/test/metric");
|
||||
|
||||
assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNewGauge_createsGauge() {
|
||||
Metric<?> testGauge =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newGauge(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
ImmutableSet.of(label),
|
||||
() -> ImmutableMap.of(ImmutableList.of("foo"), 1L),
|
||||
Long.class);
|
||||
|
||||
assertThat(testGauge.getValueClass()).isSameAs(Long.class);
|
||||
assertThat(testGauge.getMetricSchema())
|
||||
.isEqualTo(
|
||||
MetricSchema.create(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of(label)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNewCounter_createsCounter() {
|
||||
IncrementableMetric testCounter =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newIncrementableMetric(
|
||||
"/test_counter",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
ImmutableSet.of(label));
|
||||
|
||||
assertThat(testCounter.getValueClass()).isSameAs(Long.class);
|
||||
assertThat(testCounter.getMetricSchema())
|
||||
.isEqualTo(
|
||||
MetricSchema.create(
|
||||
"/test_counter",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
Kind.CUMULATIVE,
|
||||
ImmutableSet.of(label)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNewSettableMetric_createsSettableMetric() {
|
||||
SettableMetric<Boolean> testMetric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newSettableMetric(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
ImmutableSet.of(label),
|
||||
Boolean.class);
|
||||
|
||||
assertThat(testMetric.getValueClass()).isSameAs(Boolean.class);
|
||||
assertThat(testMetric.getMetricSchema())
|
||||
.isEqualTo(
|
||||
MetricSchema.create(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of(label)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNewEventMetric_createsEventMetric() {
|
||||
DistributionFitter fitter = CustomFitter.create(ImmutableSet.of(0.0));
|
||||
EventMetric testMetric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newEventMetric(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
ImmutableSet.of(label),
|
||||
fitter);
|
||||
|
||||
assertThat(testMetric.getValueClass()).isSameAs(Distribution.class);
|
||||
assertThat(testMetric.getMetricSchema())
|
||||
.isEqualTo(
|
||||
MetricSchema.create(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
Kind.CUMULATIVE,
|
||||
ImmutableSet.of(label)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegister_duplicateMetric_throwsException() {
|
||||
SettableMetric<Boolean> testMetric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newSettableMetric(
|
||||
"/test_metric",
|
||||
"test_description",
|
||||
"test_valuedisplayname",
|
||||
ImmutableSet.of(label),
|
||||
Boolean.class);
|
||||
MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric);
|
||||
|
||||
IllegalStateException thrown =
|
||||
expectThrows(
|
||||
IllegalStateException.class,
|
||||
() -> MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric));
|
||||
assertThat(thrown).hasMessageThat().contains("Duplicate metric of same name");
|
||||
}
|
||||
}
|
|
@ -1,69 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
/** Unit tests for {@link MetricReporter}. */
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MetricReporterTest {
|
||||
|
||||
@Mock MetricRegistry registry;
|
||||
@Mock Metric<?> metric;
|
||||
@Mock ThreadFactory threadFactory;
|
||||
@Mock MetricWriter writer;
|
||||
@Mock MetricSchema metricSchema;
|
||||
@Mock BlockingQueue<Optional<ImmutableList<MetricPoint<?>>>> writeQueue;
|
||||
|
||||
@Test
|
||||
public void testRunOneIteration_enqueuesBatch() throws Exception {
|
||||
Metric<?> metric = new Counter("/name", "description", "vdn", ImmutableSet.of());
|
||||
when(registry.getRegisteredMetrics()).thenReturn(ImmutableList.of(metric, metric));
|
||||
MetricReporter reporter = new MetricReporter(writer, 10L, threadFactory, registry, writeQueue);
|
||||
|
||||
reporter.runOneIteration();
|
||||
|
||||
verify(writeQueue).offer(Optional.of(ImmutableList.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testShutDown_enqueuesBatchAndPoisonPill() throws Exception {
|
||||
// Set up a registry with no metrics.
|
||||
when(registry.getRegisteredMetrics()).thenReturn(ImmutableList.of());
|
||||
MetricReporter reporter =
|
||||
spy(new MetricReporter(writer, 10L, threadFactory, registry, writeQueue));
|
||||
|
||||
reporter.shutDown();
|
||||
|
||||
verify(reporter).runOneIteration();
|
||||
InOrder interactions = Mockito.inOrder(writeQueue);
|
||||
interactions.verify(writeQueue).offer(Optional.of(ImmutableList.of()));
|
||||
interactions.verify(writeQueue).offer(Optional.empty());
|
||||
}
|
||||
}
|
|
@ -1,75 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.MetricSchema.Kind;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link MetricSchema}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class MetricSchemaTest {
|
||||
|
||||
@Test
|
||||
public void testCreate_blankNameField_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class,
|
||||
() ->
|
||||
MetricSchema.create(
|
||||
"",
|
||||
"description",
|
||||
"valueDisplayName",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of()));
|
||||
assertThat(thrown).hasMessageThat().contains("Name must not be blank");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_blankDescriptionField_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class,
|
||||
() ->
|
||||
MetricSchema.create(
|
||||
"/name", "", "valueDisplayName", Kind.GAUGE, ImmutableSet.of()));
|
||||
assertThat(thrown).hasMessageThat().contains("Description must not be blank");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_blankValueDisplayNameField_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> MetricSchema.create("/name", "description", "", Kind.GAUGE, ImmutableSet.of()));
|
||||
assertThat(thrown).hasMessageThat().contains("Value Display Name must not be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate_nakedNames_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class,
|
||||
() ->
|
||||
MetricSchema.create(
|
||||
"foo", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.of()));
|
||||
assertThat(thrown).hasMessageThat().contains("Name must be URL-like and start with a '/'");
|
||||
}
|
||||
}
|
|
@ -1,293 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableRangeMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Range;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Tests for {@link MutableDistribution} */
|
||||
@RunWith(JUnit4.class)
|
||||
public class MutableDistributionTest {
|
||||
|
||||
private MutableDistribution distribution;
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(3.0, 5.0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneValue() {
|
||||
distribution.add(5.0);
|
||||
|
||||
assertThat(distribution.count()).isEqualTo(1);
|
||||
assertThat(distribution.mean()).isWithin(0.0).of(5.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(0);
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(3.0), 0L)
|
||||
.put(Range.closedOpen(3.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_zero() {
|
||||
distribution.add(0.0);
|
||||
|
||||
assertThat(distribution.count()).isEqualTo(1);
|
||||
assertThat(distribution.mean()).isWithin(0.0).of(0.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(0);
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(3.0), 1L)
|
||||
.put(Range.closedOpen(3.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_multipleOfOneValue() {
|
||||
distribution.add(4.0, 2);
|
||||
|
||||
assertThat(distribution.count()).isEqualTo(2);
|
||||
assertThat(distribution.mean()).isWithin(0.0).of(4.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(0);
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(3.0), 0L)
|
||||
.put(Range.closedOpen(3.0, 5.0), 2L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_positiveThenNegativeValue() {
|
||||
distribution.add(2.0);
|
||||
distribution.add(-2.0);
|
||||
|
||||
assertThat(distribution.count()).isEqualTo(2);
|
||||
assertThat(distribution.mean()).isWithin(0.0).of(0.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(8.0);
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(3.0), 2L)
|
||||
.put(Range.closedOpen(3.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_wideRangeOfValues() {
|
||||
distribution.add(2.0);
|
||||
distribution.add(16.0);
|
||||
distribution.add(128.0, 5);
|
||||
distribution.add(1024.0, 0);
|
||||
|
||||
assertThat(distribution.count()).isEqualTo(7);
|
||||
assertThat(distribution.mean()).isWithin(0.0).of(94.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(20328.0);
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(3.0), 1L)
|
||||
.put(Range.closedOpen(3.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 6L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_negativeZero_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> distribution.add(Double.longBitsToDouble(0x80000000)));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_NaN_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> distribution.add(Double.NaN));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_positiveInfinity_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> distribution.add(Double.POSITIVE_INFINITY));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_negativeInfinity_throwsException() {
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(
|
||||
IllegalArgumentException.class, () -> distribution.add(Double.NEGATIVE_INFINITY));
|
||||
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_iteratedFloatingPointValues_hasLowAccumulatedError() {
|
||||
for (int i = 0; i < 500; i++) {
|
||||
distribution.add(1 / 3.0);
|
||||
distribution.add(1 / 7.0);
|
||||
}
|
||||
|
||||
// Test for nine significant figures of accuracy.
|
||||
assertThat(distribution.mean()).isWithin(0.000000001).of(5.0 / 21.0);
|
||||
assertThat(distribution.sumOfSquaredDeviation())
|
||||
.isWithin(0.000000001)
|
||||
.of(1000 * 4.0 / (21.0 * 21.0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_fitterWithNoFiniteIntervals_underflowValue_returnsUnderflowInterval()
|
||||
throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(5.0)));
|
||||
|
||||
distribution.add(3.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_noFiniteIntervals_overflowValue_returnsOverflowInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(5.0)));
|
||||
|
||||
distribution.add(10.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_noFiniteIntervals_edgeValue_returnsOverflowInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(2.0)));
|
||||
|
||||
distribution.add(2.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(2.0), 0L)
|
||||
.put(Range.atLeast(2.0), 1L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneFiniteInterval_underflowValue_returnsUnderflowInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
|
||||
|
||||
distribution.add(0.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(1.0), 1L)
|
||||
.put(Range.closedOpen(1.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneFiniteInterval_overflowValue_returnsOverflowInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
|
||||
|
||||
distribution.add(10.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(1.0), 0L)
|
||||
.put(Range.closedOpen(1.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneFiniteInterval_inBoundsValue_returnsInBoundsInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
|
||||
|
||||
distribution.add(3.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(1.0), 0L)
|
||||
.put(Range.closedOpen(1.0, 5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneFiniteInterval_firstEdgeValue_returnsFiniteInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
|
||||
|
||||
distribution.add(1.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(1.0), 0L)
|
||||
.put(Range.closedOpen(1.0, 5.0), 1L)
|
||||
.put(Range.atLeast(5.0), 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_oneFiniteInterval_secondEdgeValue_returnsOverflowInterval() throws Exception {
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0)));
|
||||
|
||||
distribution.add(5.0);
|
||||
|
||||
assertThat(distribution.intervalCounts())
|
||||
.isEqualTo(
|
||||
ImmutableRangeMap.<Double, Long>builder()
|
||||
.put(Range.lessThan(1.0), 0L)
|
||||
.put(Range.closedOpen(1.0, 5.0), 0L)
|
||||
.put(Range.atLeast(5.0), 1L)
|
||||
.build());
|
||||
}
|
||||
}
|
|
@ -1,98 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link StoredMetric}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class StoredMetricTest {
|
||||
|
||||
@Test
|
||||
public void testGetCardinality_reflectsCurrentCardinality() {
|
||||
StoredMetric<Boolean> smallMetric =
|
||||
new StoredMetric<>("/metric", "description", "vdn", ImmutableSet.of(), Boolean.class);
|
||||
assertThat(smallMetric.getCardinality()).isEqualTo(0);
|
||||
|
||||
smallMetric.set(true);
|
||||
|
||||
assertThat(smallMetric.getCardinality()).isEqualTo(1);
|
||||
|
||||
StoredMetric<Boolean> dimensionalMetric =
|
||||
new StoredMetric<>(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("foo", "bar")),
|
||||
Boolean.class);
|
||||
|
||||
dimensionalMetric.set(true, "test_value1");
|
||||
dimensionalMetric.set(true, "test_value2");
|
||||
|
||||
assertThat(dimensionalMetric.getCardinality()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet_wrongNumberOfLabels_throwsException() {
|
||||
StoredMetric<Boolean> dimensionalMetric =
|
||||
new StoredMetric<>(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")),
|
||||
Boolean.class);
|
||||
|
||||
IllegalArgumentException thrown =
|
||||
expectThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo"));
|
||||
assertThat(thrown)
|
||||
.hasMessageThat()
|
||||
.contains(
|
||||
"The count of labelValues must be equal to the underlying Metric's count of labels.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet_setsValue() {
|
||||
StoredMetric<Boolean> metric =
|
||||
new StoredMetric<>(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")),
|
||||
Boolean.class);
|
||||
|
||||
assertThat(metric.getTimestampedValues()).isEmpty();
|
||||
|
||||
metric.set(true, ImmutableList.of("test_value1"));
|
||||
assertThat(metric.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(metric, ImmutableList.of("test_value1"), new Instant(1337), true));
|
||||
|
||||
metric.set(false, ImmutableList.of("test_value1"));
|
||||
metric.set(true, ImmutableList.of("test_value2"));
|
||||
assertThat(metric.getTimestampedValues(new Instant(1338)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(metric, ImmutableList.of("test_value1"), new Instant(1338), false),
|
||||
MetricPoint.create(metric, ImmutableList.of("test_value2"), new Instant(1338), true));
|
||||
}
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link VirtualMetric}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class VirtualMetricTest {
|
||||
|
||||
private final VirtualMetric<String> metric =
|
||||
new VirtualMetric<>(
|
||||
"/metric",
|
||||
"description",
|
||||
"vdn",
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "bar")),
|
||||
Suppliers.ofInstance(
|
||||
ImmutableMap.of(
|
||||
ImmutableList.of("label_value1"), "value1",
|
||||
ImmutableList.of("label_value2"), "value2")),
|
||||
String.class);
|
||||
|
||||
@Test
|
||||
public void testGetCardinality_afterGetTimestampedValues_returnsLastCardinality() {
|
||||
metric.getTimestampedValues();
|
||||
assertThat(metric.getCardinality()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCardinality_beforeGetTimestampedValues_returnsZero() {
|
||||
assertThat(metric.getCardinality()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTimestampedValues_returnsValues() {
|
||||
assertThat(metric.getTimestampedValues(new Instant(1337)))
|
||||
.containsExactly(
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("label_value1"), new Instant(1337), "value1"),
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("label_value2"), new Instant(1337), "value2"));
|
||||
}
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
package(
|
||||
default_testonly = 1,
|
||||
default_visibility = ["//java/google/registry:registry_project"],
|
||||
)
|
||||
|
||||
licenses(["notice"]) # Apache 2.0
|
||||
|
||||
load("//java/com/google/testing/builddefs:GenTestRules.bzl", "GenTestRules")
|
||||
|
||||
java_library(
|
||||
name = "contrib",
|
||||
srcs = glob(["*.java"]),
|
||||
deps = [
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//java/google/registry/monitoring/metrics/contrib",
|
||||
"//third_party/junit",
|
||||
"@com_google_guava",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@junit",
|
||||
],
|
||||
)
|
||||
|
||||
GenTestRules(
|
||||
name = "GeneratedTestRules",
|
||||
test_files = glob(["*Test.java"]),
|
||||
deps = [
|
||||
":contrib",
|
||||
],
|
||||
)
|
|
@ -1,189 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics.contrib;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.EventMetric;
|
||||
import google.registry.monitoring.metrics.LabelDescriptor;
|
||||
import google.registry.monitoring.metrics.MetricRegistryImpl;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class DistributionMetricSubjectTest {
|
||||
|
||||
private static final ImmutableSet<LabelDescriptor> LABEL_DESCRIPTORS =
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("species", "Sheep Species"),
|
||||
LabelDescriptor.create("color", "Sheep Color"));
|
||||
|
||||
private static final EventMetric metric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newEventMetric(
|
||||
"/test/event/sheep",
|
||||
"Sheep Latency",
|
||||
"sheeplatency",
|
||||
LABEL_DESCRIPTORS,
|
||||
EventMetric.DEFAULT_FITTER);
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
metric.reset();
|
||||
metric.record(2.5, "Domestic", "Green");
|
||||
metric.record(10, "Bighorn", "Blue");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongNumberOfLabels_fails() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class, () -> assertThat(metric).hasAnyValueForLabels("Domestic"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/sheep> has a value for labels <Domestic>."
|
||||
+ " It has labeled values <[Bighorn:Blue =>"
|
||||
+ " {[4.0..16.0)=1}, Domestic:Green => {[1.0..4.0)=1}]>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveWrongNumberOfLabels_succeeds() {
|
||||
assertThat(metric).doesNotHaveAnyValueForLabels("Domestic");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasAnyValueForLabels_success() {
|
||||
assertThat(metric)
|
||||
.hasAnyValueForLabels("Domestic", "Green")
|
||||
.and()
|
||||
.hasAnyValueForLabels("Bighorn", "Blue")
|
||||
.and()
|
||||
.hasNoOtherValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveValueForLabels_success() {
|
||||
assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Blue");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveValueForLabels_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/sheep> has no value for labels <Domestic:Green>."
|
||||
+ " It has a value of <{[1.0..4.0)=1}>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnexpectedValue_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() ->
|
||||
assertThat(metric)
|
||||
.hasAnyValueForLabels("Domestic", "Green")
|
||||
.and()
|
||||
.hasNoOtherValues());
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/sheep> has <no other nondefault values>."
|
||||
+ " It has labeled values <[Bighorn:Blue =>"
|
||||
+ " {[4.0..16.0)=1}, Domestic:Green => {[1.0..4.0)=1}]>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExpectedDataSet_success() {
|
||||
metric.record(7.5, "Domestic", "Green");
|
||||
assertThat(metric).hasDataSetForLabels(ImmutableSet.of(2.5, 7.5), "Domestic", "Green");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExpectedDataSetsChained_success() {
|
||||
metric.record(7.5, "Domestic", "Green");
|
||||
assertThat(metric)
|
||||
.hasDataSetForLabels(ImmutableSet.of(2.5, 7.5), "Domestic", "Green")
|
||||
.and()
|
||||
.hasDataSetForLabels(ImmutableSet.of(10), "Bighorn", "Blue")
|
||||
.and()
|
||||
.hasNoOtherValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnexpectedDataSet_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() ->
|
||||
assertThat(metric)
|
||||
.hasDataSetForLabels(ImmutableSet.of(2.5, 7.5), "Domestic", "Green"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/sheep> has a value of"
|
||||
+ " {[1.0..4.0)=1,[4.0..16.0)=1} for labels <Domestic:Green>."
|
||||
+ " It has a value of <{[1.0..4.0)=1}>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonExistentLabels_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() ->
|
||||
assertThat(metric)
|
||||
.hasDataSetForLabels(ImmutableSet.of(2.5, 7.5), "Domestic", "Blue"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/sheep> has a value for labels <Domestic:Blue>."
|
||||
+ " It has labeled values <[Bighorn:Blue => {[4.0..16.0)=1},"
|
||||
+ " Domestic:Green => {[1.0..4.0)=1}]>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyMetric_failure() {
|
||||
EventMetric emptyMetric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newEventMetric(
|
||||
"/test/event/goat",
|
||||
"Sheep Latency",
|
||||
"sheeplatency",
|
||||
LABEL_DESCRIPTORS,
|
||||
EventMetric.DEFAULT_FITTER);
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() ->
|
||||
assertThat(emptyMetric)
|
||||
.hasDataSetForLabels(ImmutableSet.of(2.5, 7.5), "Domestic", "Blue"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/event/goat> has a distribution for labels <Domestic:Blue>."
|
||||
+ " It has <no values>");
|
||||
}
|
||||
}
|
|
@ -1,137 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics.contrib;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.expectThrows;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.IncrementableMetric;
|
||||
import google.registry.monitoring.metrics.LabelDescriptor;
|
||||
import google.registry.monitoring.metrics.MetricRegistryImpl;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class LongMetricSubjectTest {
|
||||
|
||||
private static final ImmutableSet<LabelDescriptor> LABEL_DESCRIPTORS =
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("species", "Sheep Species"),
|
||||
LabelDescriptor.create("color", "Sheep Color"));
|
||||
|
||||
private static final IncrementableMetric metric =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newIncrementableMetric(
|
||||
"/test/incrementable/sheep",
|
||||
"Count of Sheep",
|
||||
"sheepcount",
|
||||
LABEL_DESCRIPTORS);
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
metric.reset();
|
||||
metric.increment("Domestic", "Green");
|
||||
metric.incrementBy(2, "Bighorn", "Blue");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongNumberOfLabels_fails() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class, () -> assertThat(metric).hasValueForLabels(1, "Domestic"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/incrementable/sheep> has a value for labels <Domestic>."
|
||||
+ " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveWrongNumberOfLabels_succeeds() {
|
||||
assertThat(metric).doesNotHaveAnyValueForLabels("Domestic");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasValueForLabels_success() {
|
||||
assertThat(metric)
|
||||
.hasValueForLabels(1, "Domestic", "Green")
|
||||
.and()
|
||||
.hasValueForLabels(2, "Bighorn", "Blue")
|
||||
.and()
|
||||
.hasNoOtherValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHasAnyValueForLabels_success() {
|
||||
assertThat(metric)
|
||||
.hasAnyValueForLabels("Domestic", "Green")
|
||||
.and()
|
||||
.hasAnyValueForLabels("Bighorn", "Blue")
|
||||
.and()
|
||||
.hasNoOtherValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveValueForLabels_success() {
|
||||
assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Blue");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoesNotHaveValueForLabels_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/incrementable/sheep> has no value for labels <Domestic:Green>."
|
||||
+ " It has a value of <1>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongValue_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() -> assertThat(metric).hasValueForLabels(2, "Domestic", "Green"));
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/incrementable/sheep> has a value of 2"
|
||||
+ " for labels <Domestic:Green>. It has a value of <1>");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnexpectedValue_failure() {
|
||||
AssertionError e =
|
||||
expectThrows(
|
||||
AssertionError.class,
|
||||
() ->
|
||||
assertThat(metric)
|
||||
.hasValueForLabels(1, "Domestic", "Green")
|
||||
.and()
|
||||
.hasNoOtherValues());
|
||||
assertThat(e)
|
||||
.hasMessageThat()
|
||||
.isEqualTo(
|
||||
"Not true that </test/incrementable/sheep> has <no other nondefault values>."
|
||||
+ " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>");
|
||||
}
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
package(
|
||||
default_visibility = ["//java/google/registry:registry_project"],
|
||||
)
|
||||
|
||||
licenses(["notice"]) # Apache 2.0
|
||||
|
||||
java_binary(
|
||||
name = "SheepCounterExample",
|
||||
srcs = ["SheepCounterExample.java"],
|
||||
deps = [
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//java/google/registry/monitoring/metrics/stackdriver",
|
||||
"@com_google_api_client",
|
||||
"@com_google_apis_google_api_services_monitoring",
|
||||
"@com_google_guava",
|
||||
"@com_google_http_client",
|
||||
"@com_google_http_client_jackson2",
|
||||
],
|
||||
)
|
|
@ -1,259 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics.example;
|
||||
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.javanet.NetHttpTransport;
|
||||
import com.google.api.client.json.JsonFactory;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import com.google.api.services.monitoring.v3.Monitoring;
|
||||
import com.google.api.services.monitoring.v3.MonitoringScopes;
|
||||
import com.google.api.services.monitoring.v3.model.MonitoredResource;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.EventMetric;
|
||||
import google.registry.monitoring.metrics.IncrementableMetric;
|
||||
import google.registry.monitoring.metrics.LabelDescriptor;
|
||||
import google.registry.monitoring.metrics.LinearFitter;
|
||||
import google.registry.monitoring.metrics.Metric;
|
||||
import google.registry.monitoring.metrics.MetricRegistryImpl;
|
||||
import google.registry.monitoring.metrics.MetricReporter;
|
||||
import google.registry.monitoring.metrics.MetricWriter;
|
||||
import google.registry.monitoring.metrics.SettableMetric;
|
||||
import google.registry.monitoring.metrics.stackdriver.StackdriverWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogManager;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/** A sample application which uses the Metrics API to count sheep while sleeping. */
|
||||
public final class SheepCounterExample {
|
||||
|
||||
/*
|
||||
* The code below for using a custom {@link LogManager} is only necessary to enable logging at JVM
|
||||
* shutdown to show the shutdown logs of {@link MetricReporter} in this small standalone
|
||||
* application.
|
||||
*
|
||||
* <p>It is NOT necessary for normal use of the Metrics library.
|
||||
*/
|
||||
static {
|
||||
// must be called before any Logger method is used.
|
||||
System.setProperty("java.util.logging.manager", DelayedShutdownLogManager.class.getName());
|
||||
}
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SheepCounterExample.class.getName());
|
||||
|
||||
/**
|
||||
* The time interval, in seconds, between when the {@link MetricReporter} will read {@link Metric}
|
||||
* instances and enqueue them to the {@link MetricWriter}.
|
||||
*
|
||||
* @see MetricReporter
|
||||
*/
|
||||
private static final long METRICS_REPORTING_INTERVAL = 30L;
|
||||
|
||||
/**
|
||||
* The maximum queries per second to the Stackdriver API. Contact Cloud Support to raise this from
|
||||
* the default value if necessary.
|
||||
*/
|
||||
private static final int STACKDRIVER_MAX_QPS = 30;
|
||||
|
||||
/**
|
||||
* The maximum number of {@link com.google.api.services.monitoring.v3.model.TimeSeries} that can
|
||||
* be bundled into a single {@link
|
||||
* com.google.api.services.monitoring.v3.model.CreateTimeSeriesRequest}. This must be at most 200.
|
||||
* Setting this lower will cause the {@link StackdriverWriter} to {@link
|
||||
* StackdriverWriter#flush()} more frequently.
|
||||
*/
|
||||
private static final int STACKDRIVER_MAX_POINTS_PER_REQUEST = 200;
|
||||
|
||||
// Create some metrics to track your ZZZs.
|
||||
private static final ImmutableList<String> SHEEP_COLORS =
|
||||
ImmutableList.of("Green", "Yellow", "Red", "Blue");
|
||||
private static final ImmutableList<String> SHEEP_SPECIES =
|
||||
ImmutableList.of("Domestic", "Bighorn");
|
||||
private static final ImmutableSet<LabelDescriptor> SHEEP_ATTRIBUTES =
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("color", "Sheep Color"),
|
||||
LabelDescriptor.create("species", "Sheep Species"));
|
||||
|
||||
/**
|
||||
* Counters are good for tracking monotonically increasing values, like request counts or error
|
||||
* counts. Or, in this case, sheep.
|
||||
*/
|
||||
private static final IncrementableMetric sheepCounter =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newIncrementableMetric(
|
||||
"/sheep", "Counts sheep over time.", "Number of Sheep", SHEEP_ATTRIBUTES);
|
||||
|
||||
/**
|
||||
* Settable metrics are good for state indicators. For example, you could use one to track the
|
||||
* lifecycle of a {@link com.google.common.util.concurrent.Service}. In this case, we are just
|
||||
* using it to track the sleep state of this application.
|
||||
*/
|
||||
private static final SettableMetric<Boolean> isSleeping =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newSettableMetric(
|
||||
"/is_sleeping",
|
||||
"Tracks sleep state.",
|
||||
"Sleeping?",
|
||||
ImmutableSet.of(),
|
||||
Boolean.class);
|
||||
|
||||
/**
|
||||
* Gauge metrics never need to be accessed, so the assignment here is unnecessary. You only need
|
||||
* it if you plan on calling {@link Metric#getTimestampedValues()} to read the values of the
|
||||
* metric in the code yourself.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
private static final Metric<Double> sleepQuality =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newGauge(
|
||||
"/sleep_quality",
|
||||
"Quality of the sleep.",
|
||||
"Quality",
|
||||
ImmutableSet.of(),
|
||||
() -> ImmutableMap.of(ImmutableList.of(), new Random().nextDouble()),
|
||||
Double.class);
|
||||
|
||||
/**
|
||||
* Event metrics track aspects of an "event." Here, we track the fluffiness of the sheep we've
|
||||
* seen.
|
||||
*/
|
||||
private static final EventMetric sheepFluffiness =
|
||||
MetricRegistryImpl.getDefault()
|
||||
.newEventMetric(
|
||||
"/sheep_fluffiness",
|
||||
"Measures the fluffiness of seen sheep.",
|
||||
"Fill Power",
|
||||
SHEEP_ATTRIBUTES,
|
||||
LinearFitter.create(5, 20.0, 20.0));
|
||||
|
||||
private static Monitoring createAuthorizedMonitoringClient() throws IOException {
|
||||
// Grab the Application Default Credentials from the environment.
|
||||
// Generate these with 'gcloud beta auth application-default login'
|
||||
GoogleCredential credential =
|
||||
GoogleCredential.getApplicationDefault().createScoped(MonitoringScopes.all());
|
||||
|
||||
// Create and return the CloudMonitoring service object
|
||||
HttpTransport httpTransport = new NetHttpTransport();
|
||||
JsonFactory jsonFactory = new JacksonFactory();
|
||||
return new Monitoring.Builder(httpTransport, jsonFactory, credential)
|
||||
.setApplicationName("Monitoring Sample")
|
||||
.build();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 1) {
|
||||
System.err.println("Missing required project argument");
|
||||
System.err.printf(
|
||||
"Usage: java %s gcp-project-id [verbose]\n", SheepCounterExample.class.getName());
|
||||
return;
|
||||
}
|
||||
String project = args[0];
|
||||
|
||||
// Turn up the logging verbosity
|
||||
if (args.length > 1) {
|
||||
Logger log = LogManager.getLogManager().getLogger("");
|
||||
log.setLevel(Level.ALL);
|
||||
for (Handler h : log.getHandlers()) {
|
||||
h.setLevel(Level.ALL);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a sample resource. In this case, a GCE Instance.
|
||||
// See https://cloud.google.com/monitoring/api/resources for a list of resource types.
|
||||
MonitoredResource monitoredResource =
|
||||
new MonitoredResource()
|
||||
.setType("gce_instance")
|
||||
.setLabels(
|
||||
ImmutableMap.of(
|
||||
"instance_id", "test-instance",
|
||||
"zone", "us-central1-f"));
|
||||
|
||||
// Set up the Metrics infrastructure.
|
||||
MetricWriter stackdriverWriter =
|
||||
new StackdriverWriter(
|
||||
createAuthorizedMonitoringClient(),
|
||||
project,
|
||||
monitoredResource,
|
||||
STACKDRIVER_MAX_QPS,
|
||||
STACKDRIVER_MAX_POINTS_PER_REQUEST);
|
||||
final MetricReporter reporter =
|
||||
new MetricReporter(
|
||||
stackdriverWriter, METRICS_REPORTING_INTERVAL, Executors.defaultThreadFactory());
|
||||
reporter.startAsync().awaitRunning();
|
||||
|
||||
// Set up a handler to stop sleeping on SIGINT.
|
||||
Runtime.getRuntime()
|
||||
.addShutdownHook(
|
||||
new Thread(
|
||||
() -> {
|
||||
reporter.stopAsync().awaitTerminated();
|
||||
// Allow the LogManager to cleanup the loggers.
|
||||
DelayedShutdownLogManager.resetFinally();
|
||||
}));
|
||||
|
||||
System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");
|
||||
while (true) {
|
||||
// Count some Googley sheep.
|
||||
int colorIndex = new Random().nextInt(SHEEP_COLORS.size());
|
||||
int speciesIndex = new Random().nextInt(SHEEP_SPECIES.size());
|
||||
sheepCounter.incrementBy(1, SHEEP_COLORS.get(colorIndex), SHEEP_SPECIES.get(speciesIndex));
|
||||
sheepFluffiness.record(
|
||||
new Random().nextDouble() * 200,
|
||||
SHEEP_COLORS.get(colorIndex),
|
||||
SHEEP_SPECIES.get(speciesIndex));
|
||||
isSleeping.set(true);
|
||||
|
||||
logger.info("zzz...");
|
||||
Thread.sleep(5000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Special {@link LogManager} with a no-op {@link LogManager#reset()} so that logging can proceed
|
||||
* as usual until stopped in in another runtime shutdown hook.
|
||||
*
|
||||
* <p>The class is marked public because it is loaded by the JVM classloader at runtime.
|
||||
*/
|
||||
@SuppressWarnings("WeakerAccess")
|
||||
public static class DelayedShutdownLogManager extends LogManager {
|
||||
|
||||
private static DelayedShutdownLogManager instance;
|
||||
|
||||
public DelayedShutdownLogManager() {
|
||||
instance = this;
|
||||
}
|
||||
|
||||
/** A no-op implementation. */
|
||||
@Override
|
||||
public void reset() {
|
||||
/* don't reset yet. */
|
||||
}
|
||||
|
||||
static void resetFinally() {
|
||||
instance.delayedReset();
|
||||
}
|
||||
|
||||
private void delayedReset() {
|
||||
super.reset();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
package(
|
||||
default_testonly = 1,
|
||||
default_visibility = ["//java/google/registry:registry_project"],
|
||||
)
|
||||
|
||||
licenses(["notice"]) # Apache 2.0
|
||||
|
||||
load("//java/com/google/testing/builddefs:GenTestRules.bzl", "GenTestRules")
|
||||
|
||||
java_library(
|
||||
name = "stackdriver",
|
||||
srcs = glob(["*.java"]),
|
||||
deps = [
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//java/google/registry/monitoring/metrics/stackdriver",
|
||||
"//third_party/junit",
|
||||
"@com_google_api_client",
|
||||
"@com_google_apis_google_api_services_monitoring",
|
||||
"@com_google_guava",
|
||||
"@com_google_http_client",
|
||||
"@com_google_http_client_jackson2",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@joda_time",
|
||||
"@junit",
|
||||
"@org_mockito_all",
|
||||
],
|
||||
)
|
||||
|
||||
GenTestRules(
|
||||
name = "GeneratedTestRules",
|
||||
test_files = glob(["*Test.java"]),
|
||||
deps = [
|
||||
":stackdriver",
|
||||
],
|
||||
)
|
|
@ -1,171 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics.stackdriver;
|
||||
|
||||
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
|
||||
import com.google.api.client.http.GenericUrl;
|
||||
import com.google.api.client.http.HttpContent;
|
||||
import com.google.api.client.http.HttpRequest;
|
||||
import com.google.api.client.http.HttpRequestFactory;
|
||||
import com.google.api.client.http.HttpResponse;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.LowLevelHttpRequest;
|
||||
import com.google.api.client.http.LowLevelHttpResponse;
|
||||
import com.google.api.client.json.jackson2.JacksonFactory;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/** A helper to create instances of {@link GoogleJsonResponseException}. */
|
||||
public class GoogleJsonResponseExceptionHelper {
|
||||
/**
|
||||
* @param statusCode the status code that should be in the returned {@link
|
||||
* GoogleJsonResponseException}
|
||||
* @return a {@link GoogleJsonResponseException} with the status code {@code statusCode}
|
||||
* @throws IOException shouldn't occur
|
||||
*/
|
||||
public static GoogleJsonResponseException create(int statusCode) throws IOException {
|
||||
HttpResponse response = createHttpResponse(statusCode, null);
|
||||
return GoogleJsonResponseException.from(new JacksonFactory(), response);
|
||||
}
|
||||
|
||||
public static HttpResponse createHttpResponse(int statusCode, InputStream content)
|
||||
throws IOException {
|
||||
FakeHttpTransport transport = new FakeHttpTransport(statusCode, content);
|
||||
HttpRequestFactory factory = transport.createRequestFactory();
|
||||
HttpRequest request =
|
||||
factory.buildRequest(
|
||||
"foo", new GenericUrl("http://example.com/bar"), new EmptyHttpContent());
|
||||
request.setThrowExceptionOnExecuteError(false);
|
||||
return request.execute();
|
||||
}
|
||||
|
||||
private static class FakeHttpTransport extends HttpTransport {
|
||||
private final int statusCode;
|
||||
private final InputStream content;
|
||||
|
||||
FakeHttpTransport(int statusCode, InputStream content) {
|
||||
this.statusCode = statusCode;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
|
||||
return new FakeLowLevelHttpRequest(statusCode, content);
|
||||
}
|
||||
}
|
||||
|
||||
private static class FakeLowLevelHttpRequest extends LowLevelHttpRequest {
|
||||
private final int statusCode;
|
||||
private final InputStream content;
|
||||
|
||||
FakeLowLevelHttpRequest(int statusCode, InputStream content) {
|
||||
this.statusCode = statusCode;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addHeader(String name, String value) throws IOException {
|
||||
// Nothing!
|
||||
}
|
||||
|
||||
@Override
|
||||
public LowLevelHttpResponse execute() throws IOException {
|
||||
return new FakeLowLevelHttpResponse(statusCode, content);
|
||||
}
|
||||
}
|
||||
|
||||
private static class FakeLowLevelHttpResponse extends LowLevelHttpResponse {
|
||||
private final int statusCode;
|
||||
private final InputStream content;
|
||||
|
||||
FakeLowLevelHttpResponse(int statusCode, InputStream content) {
|
||||
this.statusCode = statusCode;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getContent() throws IOException {
|
||||
return content;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentEncoding() throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getContentLength() throws IOException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() throws IOException {
|
||||
return "text/json";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStatusLine() throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStatusCode() throws IOException {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReasonPhrase() throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHeaderCount() throws IOException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeaderName(int index) throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeaderValue(int index) throws IOException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class EmptyHttpContent implements HttpContent {
|
||||
@Override
|
||||
public long getLength() throws IOException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "text/json";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retrySupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(OutputStream out) throws IOException {
|
||||
// Nothing!
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,548 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.monitoring.metrics.stackdriver;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.assertThrows;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
|
||||
import com.google.api.client.http.HttpResponse;
|
||||
import com.google.api.client.http.HttpResponseException;
|
||||
import com.google.api.services.monitoring.v3.Monitoring;
|
||||
import com.google.api.services.monitoring.v3.model.BucketOptions;
|
||||
import com.google.api.services.monitoring.v3.model.CreateTimeSeriesRequest;
|
||||
import com.google.api.services.monitoring.v3.model.Explicit;
|
||||
import com.google.api.services.monitoring.v3.model.Exponential;
|
||||
import com.google.api.services.monitoring.v3.model.Linear;
|
||||
import com.google.api.services.monitoring.v3.model.MetricDescriptor;
|
||||
import com.google.api.services.monitoring.v3.model.MonitoredResource;
|
||||
import com.google.api.services.monitoring.v3.model.Point;
|
||||
import com.google.api.services.monitoring.v3.model.TimeSeries;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.monitoring.metrics.CustomFitter;
|
||||
import google.registry.monitoring.metrics.Distribution;
|
||||
import google.registry.monitoring.metrics.ExponentialFitter;
|
||||
import google.registry.monitoring.metrics.LabelDescriptor;
|
||||
import google.registry.monitoring.metrics.LinearFitter;
|
||||
import google.registry.monitoring.metrics.Metric;
|
||||
import google.registry.monitoring.metrics.MetricPoint;
|
||||
import google.registry.monitoring.metrics.MetricSchema;
|
||||
import google.registry.monitoring.metrics.MetricSchema.Kind;
|
||||
import google.registry.monitoring.metrics.MutableDistribution;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
/** Unit tests for {@link StackdriverWriter}. */
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class StackdriverWriterTest {
|
||||
|
||||
@Mock private Monitoring client;
|
||||
@Mock private Monitoring.Projects projects;
|
||||
@Mock private Monitoring.Projects.MetricDescriptors metricDescriptors;
|
||||
@Mock private Monitoring.Projects.MetricDescriptors.Get metricDescriptorGet;
|
||||
@Mock private Monitoring.Projects.TimeSeries timeSeries;
|
||||
@Mock private Monitoring.Projects.MetricDescriptors.Create metricDescriptorCreate;
|
||||
@Mock private Monitoring.Projects.TimeSeries.Create timeSeriesCreate;
|
||||
@Mock private Metric<Long> metric;
|
||||
@Mock private Metric<Boolean> boolMetric;
|
||||
@Mock private Metric<Distribution> distributionMetric;
|
||||
private static final String PROJECT = "PROJECT";
|
||||
private static final int MAX_QPS = 10;
|
||||
private static final int MAX_POINTS_PER_REQUEST = 10;
|
||||
private static final MonitoredResource MONITORED_RESOURCE = new MonitoredResource();
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
when(metric.getValueClass()).thenReturn(Long.class);
|
||||
when(metric.getCardinality()).thenReturn(1);
|
||||
when(metric.getMetricSchema())
|
||||
.thenReturn(
|
||||
MetricSchema.create(
|
||||
"/name",
|
||||
"desc",
|
||||
"vdn",
|
||||
Kind.CUMULATIVE,
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "desc1"))));
|
||||
// Store in an intermediate value, because Mockito hates when mocks are evaluated inside of
|
||||
// thenReturn() methods.
|
||||
MetricPoint<Long> longPoint =
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("value1"), new Instant(1337), new Instant(1338), 5L);
|
||||
when(metric.getTimestampedValues()).thenReturn(ImmutableList.of(longPoint));
|
||||
|
||||
when(boolMetric.getValueClass()).thenReturn(Boolean.class);
|
||||
when(boolMetric.getMetricSchema())
|
||||
.thenReturn(
|
||||
MetricSchema.create(
|
||||
"/name",
|
||||
"desc",
|
||||
"vdn",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "desc1"))));
|
||||
// Store in an intermediate value, because Mockito hates when mocks are evaluated inside of
|
||||
// thenReturn() methods.
|
||||
MetricPoint<Boolean> boolPoint =
|
||||
MetricPoint.create(boolMetric, ImmutableList.of("foo"), new Instant(1337), true);
|
||||
when(boolMetric.getTimestampedValues()).thenReturn(ImmutableList.of(boolPoint));
|
||||
|
||||
when(distributionMetric.getMetricSchema())
|
||||
.thenReturn(
|
||||
MetricSchema.create(
|
||||
"/name",
|
||||
"desc",
|
||||
"vdn",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "desc1"))));
|
||||
when(distributionMetric.getValueClass()).thenReturn(Distribution.class);
|
||||
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(metric);
|
||||
when(client.projects()).thenReturn(projects);
|
||||
when(projects.metricDescriptors()).thenReturn(metricDescriptors);
|
||||
when(projects.timeSeries()).thenReturn(timeSeries);
|
||||
when(metricDescriptors.create(anyString(), any(MetricDescriptor.class)))
|
||||
.thenReturn(metricDescriptorCreate);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(descriptor);
|
||||
when(metricDescriptors.get(anyString())).thenReturn(metricDescriptorGet);
|
||||
when(metricDescriptorGet.execute()).thenReturn(descriptor);
|
||||
when(timeSeries.create(anyString(), any(CreateTimeSeriesRequest.class)))
|
||||
.thenReturn(timeSeriesCreate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrite_maxPoints_flushes() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
spy(
|
||||
new StackdriverWriter(
|
||||
client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST));
|
||||
|
||||
|
||||
for (int i = 0; i < MAX_POINTS_PER_REQUEST; i++) {
|
||||
for (MetricPoint<?> point : metric.getTimestampedValues()) {
|
||||
writer.write(point);
|
||||
}
|
||||
}
|
||||
|
||||
verify(writer).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrite_lessThanMaxPoints_doesNotFlush() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
spy(
|
||||
new StackdriverWriter(
|
||||
client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST));
|
||||
for (int i = 0; i < MAX_POINTS_PER_REQUEST - 1; i++) {
|
||||
for (MetricPoint<?> point : metric.getTimestampedValues()) {
|
||||
writer.write(point);
|
||||
}
|
||||
}
|
||||
|
||||
verify(writer, never()).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrite_invalidMetricType_throwsException() throws Exception {
|
||||
when(metric.getValueClass()).thenAnswer((Answer<Class<?>>) invocation -> Object.class);
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
for (MetricPoint<?> point : metric.getTimestampedValues()) {
|
||||
assertThrows(IOException.class, () -> writer.write(point));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrite_ManyPoints_flushesTwice() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
spy(
|
||||
new StackdriverWriter(
|
||||
client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST));
|
||||
|
||||
for (int i = 0; i < MAX_POINTS_PER_REQUEST * 2; i++) {
|
||||
for (MetricPoint<?> point : metric.getTimestampedValues()) {
|
||||
writer.write(point);
|
||||
}
|
||||
}
|
||||
|
||||
verify(writer, times(2)).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterMetric_registersWithStackdriver() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
writer.registerMetric(metric);
|
||||
|
||||
verify(
|
||||
client
|
||||
.projects()
|
||||
.metricDescriptors()
|
||||
.create(PROJECT, StackdriverWriter.encodeMetricDescriptor(metric)))
|
||||
.execute();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerMetric_doesNotReregisterDupe() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
writer.registerMetric(metric);
|
||||
writer.registerMetric(metric);
|
||||
|
||||
verify(
|
||||
client
|
||||
.projects()
|
||||
.metricDescriptors()
|
||||
.create(PROJECT, StackdriverWriter.encodeMetricDescriptor(metric)))
|
||||
.execute();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerMetric_fetchesStackdriverDefinition() throws Exception {
|
||||
// Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to
|
||||
// register a metric that's already been registered, so we fake one here.
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
|
||||
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
|
||||
HttpResponseException.Builder httpResponseExceptionBuilder =
|
||||
new HttpResponseException.Builder(response);
|
||||
httpResponseExceptionBuilder.setStatusCode(400);
|
||||
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
|
||||
GoogleJsonResponseException exception =
|
||||
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
|
||||
when(metricDescriptorCreate.execute()).thenThrow(exception);
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
writer.registerMetric(metric);
|
||||
|
||||
verify(client.projects().metricDescriptors().get("metric")).execute();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerMetric_rethrowsException() throws Exception {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
|
||||
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
|
||||
HttpResponseException.Builder httpResponseExceptionBuilder =
|
||||
new HttpResponseException.Builder(response);
|
||||
httpResponseExceptionBuilder.setStatusCode(404);
|
||||
GoogleJsonResponseException exception =
|
||||
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
|
||||
when(metricDescriptorCreate.execute()).thenThrow(exception);
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
|
||||
assertThat(exception.getStatusCode()).isEqualTo(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
|
||||
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
|
||||
HttpResponseException.Builder httpResponseExceptionBuilder =
|
||||
new HttpResponseException.Builder(response);
|
||||
httpResponseExceptionBuilder.setStatusCode(400);
|
||||
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
|
||||
GoogleJsonResponseException exception =
|
||||
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
|
||||
when(metricDescriptorCreate.execute()).thenThrow(exception);
|
||||
when(metricDescriptorGet.execute())
|
||||
.thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
writer.registerMetric(metric);
|
||||
|
||||
TimeSeries timeSeries =
|
||||
writer.getEncodedTimeSeries(
|
||||
MetricPoint.create(metric, ImmutableList.of("foo"), new Instant(1337), 10L));
|
||||
|
||||
assertThat(timeSeries.getMetric().getLabels()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeMetricDescriptor_simpleMetric_encodes() {
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(metric);
|
||||
|
||||
assertThat(descriptor.getType()).isEqualTo("custom.googleapis.com/name");
|
||||
assertThat(descriptor.getValueType()).isEqualTo("INT64");
|
||||
assertThat(descriptor.getDescription()).isEqualTo("desc");
|
||||
assertThat(descriptor.getDisplayName()).isEqualTo("vdn");
|
||||
assertThat(descriptor.getLabels())
|
||||
.containsExactly(
|
||||
new com.google.api.services.monitoring.v3.model.LabelDescriptor()
|
||||
.setValueType("STRING")
|
||||
.setKey("label1")
|
||||
.setDescription("desc1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeLabelDescriptors_simpleLabels_encodes() {
|
||||
ImmutableSet<LabelDescriptor> descriptors =
|
||||
ImmutableSet.of(
|
||||
LabelDescriptor.create("label1", "description1"),
|
||||
LabelDescriptor.create("label2", "description2"));
|
||||
|
||||
ImmutableList<com.google.api.services.monitoring.v3.model.LabelDescriptor> encodedDescritors =
|
||||
StackdriverWriter.encodeLabelDescriptors(descriptors);
|
||||
|
||||
assertThat(encodedDescritors)
|
||||
.containsExactly(
|
||||
new com.google.api.services.monitoring.v3.model.LabelDescriptor()
|
||||
.setValueType("STRING")
|
||||
.setKey("label1")
|
||||
.setDescription("description1"),
|
||||
new com.google.api.services.monitoring.v3.model.LabelDescriptor()
|
||||
.setValueType("STRING")
|
||||
.setKey("label2")
|
||||
.setDescription("description2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_cumulativeMetricPoint_ZeroInterval_encodesGreaterEndTime()
|
||||
throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
MetricPoint<Long> nativePoint =
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("foo"), new Instant(1337), new Instant(1337), 10L);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("INT64");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("CUMULATIVE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getInt64Value()).isEqualTo(10L);
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.338Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_cumulativeMetricPoint_nonZeroInterval_encodesSameInterval()
|
||||
throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
MetricPoint<Long> nativePoint =
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("foo"), new Instant(1337), new Instant(1339), 10L);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("INT64");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("CUMULATIVE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getInt64Value()).isEqualTo(10L);
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.339Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_gaugeMetricPoint_zeroInterval_encodesSameInterval()
|
||||
throws Exception {
|
||||
when(metric.getMetricSchema())
|
||||
.thenReturn(
|
||||
MetricSchema.create(
|
||||
"/name",
|
||||
"desc",
|
||||
"vdn",
|
||||
Kind.GAUGE,
|
||||
ImmutableSet.of(LabelDescriptor.create("label1", "desc1"))));
|
||||
// Store in an intermediate value, because Mockito hates when mocks are evaluated inside of
|
||||
// thenReturn() methods.
|
||||
MetricPoint<Long> testPoint =
|
||||
MetricPoint.create(metric, ImmutableList.of("foo"), new Instant(1337), 10L);
|
||||
when(metric.getTimestampedValues()).thenReturn(ImmutableList.of(testPoint));
|
||||
// Store in an intermediate value, because Mockito hates when mocks are evaluated inside of
|
||||
// thenReturn() methods.
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(metric);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(descriptor);
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
MetricPoint<Long> nativePoint =
|
||||
MetricPoint.create(
|
||||
metric, ImmutableList.of("foo"), new Instant(1337), new Instant(1337), 10L);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("INT64");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("GAUGE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getInt64Value()).isEqualTo(10L);
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_booleanMetric_encodes() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
MetricDescriptor boolDescriptor = StackdriverWriter.encodeMetricDescriptor(boolMetric);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(boolDescriptor);
|
||||
MetricPoint<Boolean> nativePoint =
|
||||
MetricPoint.create(boolMetric, ImmutableList.of("foo"), new Instant(1337), true);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("BOOL");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("GAUGE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getBoolValue()).isEqualTo(true);
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_distributionMetricCustomFitter_encodes() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(distributionMetric);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(descriptor);
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(CustomFitter.create(ImmutableSet.of(5.0)));
|
||||
distribution.add(10.0, 5L);
|
||||
distribution.add(0.0, 5L);
|
||||
MetricPoint<Distribution> nativePoint =
|
||||
MetricPoint.create(
|
||||
distributionMetric, ImmutableList.of("foo"), new Instant(1337), distribution);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("DISTRIBUTION");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("GAUGE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getDistributionValue())
|
||||
.isEqualTo(
|
||||
new com.google.api.services.monitoring.v3.model.Distribution()
|
||||
.setMean(5.0)
|
||||
.setSumOfSquaredDeviation(250.0)
|
||||
.setCount(10L)
|
||||
.setBucketCounts(ImmutableList.of(5L, 5L))
|
||||
.setBucketOptions(
|
||||
new BucketOptions()
|
||||
.setExplicitBuckets(new Explicit().setBounds(ImmutableList.of(5.0)))));
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_distributionMetricLinearFitter_encodes() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(distributionMetric);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(descriptor);
|
||||
MutableDistribution distribution = new MutableDistribution(LinearFitter.create(2, 5.0, 3.0));
|
||||
distribution.add(0.0, 1L);
|
||||
distribution.add(3.0, 2L);
|
||||
distribution.add(10.0, 5L);
|
||||
distribution.add(20.0, 5L);
|
||||
MetricPoint<Distribution> nativePoint =
|
||||
MetricPoint.create(
|
||||
distributionMetric, ImmutableList.of("foo"), new Instant(1337), distribution);
|
||||
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("DISTRIBUTION");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("GAUGE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getDistributionValue())
|
||||
.isEqualTo(
|
||||
new com.google.api.services.monitoring.v3.model.Distribution()
|
||||
.setMean(12.0)
|
||||
.setSumOfSquaredDeviation(646.0)
|
||||
.setCount(13L)
|
||||
.setBucketCounts(ImmutableList.of(1L, 2L, 5L, 5L))
|
||||
.setBucketOptions(
|
||||
new BucketOptions()
|
||||
.setLinearBuckets(
|
||||
new Linear().setNumFiniteBuckets(2).setWidth(5.0).setOffset(3.0))));
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEncodedTimeSeries_distributionMetricExponentialFitter_encodes() throws Exception {
|
||||
StackdriverWriter writer =
|
||||
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
|
||||
|
||||
MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(distributionMetric);
|
||||
when(metricDescriptorCreate.execute()).thenReturn(descriptor);
|
||||
MutableDistribution distribution =
|
||||
new MutableDistribution(ExponentialFitter.create(2, 3.0, 0.5));
|
||||
distribution.add(0.0, 1L);
|
||||
distribution.add(3.0, 2L);
|
||||
distribution.add(10.0, 5L);
|
||||
distribution.add(20.0, 5L);
|
||||
MetricPoint<Distribution> nativePoint =
|
||||
MetricPoint.create(
|
||||
distributionMetric, ImmutableList.of("foo"), new Instant(1337), distribution);
|
||||
|
||||
TimeSeries timeSeries = writer.getEncodedTimeSeries(nativePoint);
|
||||
|
||||
assertThat(timeSeries.getValueType()).isEqualTo("DISTRIBUTION");
|
||||
assertThat(timeSeries.getMetricKind()).isEqualTo("GAUGE");
|
||||
List<Point> points = timeSeries.getPoints();
|
||||
assertThat(points).hasSize(1);
|
||||
Point point = points.get(0);
|
||||
assertThat(point.getValue().getDistributionValue())
|
||||
.isEqualTo(
|
||||
new com.google.api.services.monitoring.v3.model.Distribution()
|
||||
.setMean(12.0)
|
||||
.setSumOfSquaredDeviation(646.0)
|
||||
.setCount(13L)
|
||||
.setBucketCounts(ImmutableList.of(1L, 0L, 2L, 10L))
|
||||
.setBucketOptions(
|
||||
new BucketOptions()
|
||||
.setExponentialBuckets(
|
||||
new Exponential()
|
||||
.setNumFiniteBuckets(2)
|
||||
.setGrowthFactor(3.0)
|
||||
.setScale(0.5))));
|
||||
assertThat(point.getInterval().getEndTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
assertThat(point.getInterval().getStartTime()).isEqualTo("1970-01-01T00:00:01.337Z");
|
||||
}
|
||||
}
|
|
@ -15,14 +15,14 @@ java_library(
|
|||
"quota/testdata/*.yaml",
|
||||
]),
|
||||
deps = [
|
||||
"//java/google/registry/monitoring/metrics",
|
||||
"//java/google/registry/monitoring/metrics/contrib",
|
||||
"//java/google/registry/proxy",
|
||||
"//java/google/registry/util",
|
||||
"//javatests/google/registry/testing",
|
||||
"@com_beust_jcommander",
|
||||
"@com_google_dagger",
|
||||
"@com_google_guava",
|
||||
"@com_google_monitoring_client_contrib",
|
||||
"@com_google_monitoring_client_metrics",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@io_netty_buffer",
|
||||
|
|
|
@ -14,8 +14,8 @@
|
|||
|
||||
package google.registry.proxy.metric;
|
||||
|
||||
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static google.registry.proxy.TestUtils.makeHttpPostRequest;
|
||||
import static google.registry.proxy.TestUtils.makeHttpResponse;
|
||||
|
||||
|
|
|
@ -15,7 +15,7 @@
|
|||
package google.registry.proxy.metric;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.DefaultChannelId;
|
||||
|
|
|
@ -14,7 +14,6 @@ java_library(
|
|||
deps = [
|
||||
"//java/google/registry/config",
|
||||
"//java/google/registry/model",
|
||||
"//java/google/registry/monitoring/metrics/contrib",
|
||||
"//java/google/registry/rdap",
|
||||
"//java/google/registry/request",
|
||||
"//java/google/registry/request/auth",
|
||||
|
@ -26,6 +25,7 @@ java_library(
|
|||
"@com_google_code_findbugs_jsr305",
|
||||
"@com_google_dagger",
|
||||
"@com_google_guava",
|
||||
"@com_google_monitoring_client_contrib",
|
||||
"@com_google_truth",
|
||||
"@com_google_truth_extensions_truth_java8_extension",
|
||||
"@com_googlecode_json_simple",
|
||||
|
|
|
@ -14,8 +14,8 @@
|
|||
|
||||
package google.registry.rdap;
|
||||
|
||||
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
|
||||
import static com.google.monitoring.metrics.contrib.LongMetricSubject.assertThat;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import google.registry.rdap.RdapMetrics.EndpointType;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue