index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator/metrics5/MetricsTimer.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.metrics5;
import com.netflix.spectator.api.AbstractTimer;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** Timer implementation for the metrics5 registry. */
class MetricsTimer extends AbstractTimer {
private final Id id;
private final io.dropwizard.metrics5.Timer impl;
private final AtomicLong totalTime;
/** Create a new instance. */
MetricsTimer(Clock clock, Id id, io.dropwizard.metrics5.Timer impl) {
super(clock);
this.id = id;
this.impl = impl;
this.totalTime = new AtomicLong(0L);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount, TimeUnit unit) {
totalTime.addAndGet(unit.toNanos(amount));
impl.update(amount, unit);
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
return Collections.singleton(new Measurement(id, now, impl.getMeanRate()));
}
@Override public long count() {
return impl.getCount();
}
@Override public long totalTime() {
return totalTime.get();
}
}
| 5,900 |
0 | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator/metrics5/MetricsCounter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.metrics5;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.Collections;
/** Counter implementation for the metrics5 registry. */
class MetricsCounter implements Counter {
private final Clock clock;
private final Id id;
private final io.dropwizard.metrics5.Meter impl;
/** Create a new instance. */
MetricsCounter(Clock clock, Id id, io.dropwizard.metrics5.Meter impl) {
this.clock = clock;
this.id = id;
this.impl = impl;
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public Iterable<Measurement> measure() {
long now = clock.wallTime();
long v = impl.getCount();
return Collections.singleton(new Measurement(id, now, v));
}
@Override public void add(double amount) {
impl.mark((long) amount);
}
@Override public double actualCount() {
return impl.getCount();
}
}
| 5,901 |
0 | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics5/src/main/java/com/netflix/spectator/metrics5/DoubleMaxGauge.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.metrics5;
/** metrics5 max gauge type. */
class DoubleMaxGauge extends DoubleGauge {
/** Update the value. */
@Override void set(double v) {
value.max(v);
}
}
| 5,902 |
0 | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers/MetricsControllerTest.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.controllers.model.DataPoint;
import com.netflix.spectator.controllers.model.MetricValues;
import com.netflix.spectator.controllers.model.TaggedDataPoints;
import com.netflix.spectator.controllers.model.TestMeter;
import java.util.function.Predicate;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class MetricsControllerTest {
private Clock clock = new ManualClock(12345L, 0L);
MetricsController controller = new MetricsController();
Id idA = Id.create("idA");
Id idB = Id.create("idB");
Id idAXY = idA.withTag("tagA", "X").withTag("tagB", "Y");
Id idAYX = idA.withTag("tagA", "Y").withTag("tagB", "X");
Id idAXZ = idA.withTag("tagA", "X").withTag("tagZ", "Z");
Id idBXY = idB.withTag("tagA", "X").withTag("tagB", "Y");
Measurement measureAXY = new Measurement(idAXY, 11, 11.11);
Measurement measureAYX = new Measurement(idAYX, 12, 12.12);
Measurement measureAXZ = new Measurement(idAXZ, 13, 13.13);
Measurement measureBXY = new Measurement(idBXY, 50, 50.50);
static final Predicate<Measurement> allowAll
= MetricsController.ALL_MEASUREMENTS_FILTER;
Meter meterA = new TestMeter("ignoreA", Arrays.asList(measureAXY, measureAYX, measureAXZ));
Meter meterB = new TestMeter("ignoreB", measureBXY);
@Test
public void testMeterToKind() {
DefaultRegistry r = new DefaultRegistry(clock);
Assertions.assertEquals(
"Counter", MetricsController.meterToKind(r, r.counter(idAXY)));
Assertions.assertEquals(
"Timer", MetricsController.meterToKind(r, r.timer(idBXY)));
Assertions.assertEquals(
"TestMeter", MetricsController.meterToKind(r, meterA));
}
@Test
public void testEncodeSimpleRegistry() {
DefaultRegistry registry = new DefaultRegistry(clock);
Counter counterA = registry.counter(idAXY);
Counter counterB = registry.counter(idBXY);
counterA.increment(4);
counterB.increment(10);
List<TaggedDataPoints> expectedTaggedDataPointsA
= Arrays.asList(
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "X"),
new BasicTag("tagB", "Y")),
Arrays.asList(new DataPoint(clock.wallTime(), 4))));
List<TaggedDataPoints> expectedTaggedDataPointsB
= Arrays.asList(
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "X"),
new BasicTag("tagB", "Y")),
Arrays.asList(new DataPoint(clock.wallTime(), 10))));
HashMap<String, MetricValues> expect = new HashMap<>();
expect.put("idA", new MetricValues("Counter", expectedTaggedDataPointsA));
expect.put("idB", new MetricValues("Counter", expectedTaggedDataPointsB));
Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
@Test
public void testEncodeCombinedRegistry() {
// Multiple occurrences of measurements in the same registry
// (confirm these are handled within the registry itself).
Measurement measureBXY2 = new Measurement(idBXY, 5, 5.5);
Meter meterB2 = new TestMeter("ignoreB", measureBXY2);
DefaultRegistry registry = new DefaultRegistry(clock);
registry.register(meterB);
registry.register(meterB2);
List<TaggedDataPoints> expectedTaggedDataPoints = Arrays.asList(
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "X"),
new BasicTag("tagB", "Y")),
Arrays.asList(new DataPoint(clock.wallTime(), 50.5 + 5.5))));
HashMap<String, MetricValues> expect = new HashMap<>();
expect.put("idB", new MetricValues("Counter", expectedTaggedDataPoints));
PolledMeter.update(registry);
Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
@Test
public void testIgnoreNan() {
Id id = idB.withTag("tagA", "Z");
Measurement measure = new Measurement(id, 100, Double.NaN);
Meter meter = new TestMeter("ignoreZ", measure);
DefaultRegistry registry = new DefaultRegistry(clock);
registry.register(meter);
HashMap<String, MetricValues> expect = new HashMap<>();
PolledMeter.update(registry);
Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
@Test
public void testEncodeCompositeRegistry() {
// Multiple occurrences of measurements in the same registry
// (confirm these are handled within the registry itself).
// Here measurements are duplicated but meters have different sets.
Measurement measureAXY2 = new Measurement(idAXY, 20, 20.20);
Meter meterA2 = new TestMeter("ignoreA", measureAXY2);
DefaultRegistry registry = new DefaultRegistry(clock);
registry.register(meterA);
registry.register(meterA2);
List<TaggedDataPoints> expectedDataPoints = Arrays.asList(
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "X"), new BasicTag("tagZ", "Z")),
Arrays.asList(new DataPoint(clock.wallTime(), 13.13))),
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "X"), new BasicTag("tagB", "Y")),
Arrays.asList(new DataPoint(clock.wallTime(), 11.11 + 20.20))),
new TaggedDataPoints(
Arrays.asList(new BasicTag("tagA", "Y"), new BasicTag("tagB", "X")),
Arrays.asList(new DataPoint(clock.wallTime(), 12.12)))
);
HashMap<String, MetricValues> expect = new HashMap<>();
expect.put("idA", new MetricValues("Counter", expectedDataPoints));
PolledMeter.update(registry);
Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
}
| 5,903 |
0 | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers/model/TestMeter.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.model;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Meter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestMeter implements Meter {
private Id myId;
private List<Measurement> myMeasurements;
public TestMeter(Id id) {
myId = id;
myMeasurements = new ArrayList<>();
}
public TestMeter(String name, Measurement measurement) {
this(name, Collections.singletonList(measurement));
}
public TestMeter(String name, List<Measurement> measures) {
myId = Id.create(name);
myMeasurements = measures;
}
public Id id() { return myId; }
public Iterable<Measurement> measure() {
return myMeasurements;
}
public boolean hasExpired() {
return false;
}
}
| 5,904 |
0 | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers/filter/PrototypeMeasurementFilterTest.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.filter;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Tag;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PrototypeMeasurementFilterTest {
PrototypeMeasurementFilterSpecification.ValueFilterSpecification valueSpecAxBy;
PrototypeMeasurementFilterSpecification.ValueFilterSpecification valueSpecAyBx;
PrototypeMeasurementFilterSpecification.ValueFilterSpecification valueSpecAzBy;
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpecA;
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpecB;
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpecC;
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpecD;
@BeforeEach
public void setup() {
List<PrototypeMeasurementFilterSpecification.TagFilterSpecification> tagsAxBy = Arrays.asList(
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagA", "X"),
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagB", "Y"));
List<PrototypeMeasurementFilterSpecification.TagFilterSpecification> tagsAyBx = Arrays.asList(
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagA", "Y"),
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagB", "X"));
List<PrototypeMeasurementFilterSpecification.TagFilterSpecification> tagsAzBy = Arrays.asList(
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagA", "Z"),
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagB", "Y"));
valueSpecAxBy = new PrototypeMeasurementFilterSpecification.ValueFilterSpecification();
valueSpecAxBy.getTags().addAll(tagsAxBy);
valueSpecAyBx = new PrototypeMeasurementFilterSpecification.ValueFilterSpecification();
valueSpecAyBx.getTags().addAll(tagsAyBx);
valueSpecAzBy = new PrototypeMeasurementFilterSpecification.ValueFilterSpecification();
valueSpecAzBy.getTags().addAll(tagsAzBy);
meterSpecA = new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Collections.singletonList(valueSpecAxBy));
meterSpecB = new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Collections.singletonList(valueSpecAyBx));
meterSpecC = new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Collections.singletonList(valueSpecAzBy));
meterSpecD = new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Arrays.asList(valueSpecAxBy, valueSpecAyBx));
}
@Test
public void testPatternFromSpec() {
List<PrototypeMeasurementFilter.TagFilterPattern> tagPatterns = Arrays.asList(
new PrototypeMeasurementFilter.TagFilterPattern(Pattern.compile("tagA"), Pattern.compile("X")),
new PrototypeMeasurementFilter.TagFilterPattern(Pattern.compile("tagB"), Pattern.compile("Y")));
PrototypeMeasurementFilter.MeterFilterPattern meterPattern
= new PrototypeMeasurementFilter.MeterFilterPattern("meterA", meterSpecA);
Assertions.assertEquals(meterPattern.getValues().size(), 1);
Assertions.assertEquals(meterPattern.getValues().get(0).getTags(), tagPatterns);
}
@Test
public void testMetricToPatterns() {
PrototypeMeasurementFilterSpecification spec = new PrototypeMeasurementFilterSpecification();
spec.getInclude().put("meterA", meterSpecA);
spec.getInclude().put(".+B", meterSpecB);
spec.getInclude().put(".+C.*", meterSpecC);
PrototypeMeasurementFilter filter = new PrototypeMeasurementFilter(spec);
PrototypeMeasurementFilter.MeterFilterPattern meterPatternA
= new PrototypeMeasurementFilter.MeterFilterPattern("meterA", meterSpecA);
PrototypeMeasurementFilter.MeterFilterPattern meterPatternC
= new PrototypeMeasurementFilter.MeterFilterPattern(".+C.*", meterSpecC);
final List<PrototypeMeasurementFilter.ValueFilterPattern> emptyList = new ArrayList<>();
Assertions.assertEquals(
filter.metricToPatterns("meterA"),
new PrototypeMeasurementFilter.IncludeExcludePatterns(
meterPatternA.getValues(), emptyList));
Assertions.assertEquals(
filter.metricToPatterns("meterBextra"),
new PrototypeMeasurementFilter.IncludeExcludePatterns(
emptyList, emptyList));
Assertions.assertEquals(
filter.metricToPatterns("meterCthing"),
new PrototypeMeasurementFilter.IncludeExcludePatterns(
meterPatternC.getValues(), emptyList));
}
@Test
public void testMetricToPatternsWithMultipleMeters() {
PrototypeMeasurementFilterSpecification spec = new PrototypeMeasurementFilterSpecification();
spec.getInclude().put("meterA", meterSpecA);
spec.getInclude().put("meter.+", meterSpecB);
PrototypeMeasurementFilter filter = new PrototypeMeasurementFilter(spec);
PrototypeMeasurementFilter.MeterFilterPattern meterPatternA
= new PrototypeMeasurementFilter.MeterFilterPattern("ignored", meterSpecA);
PrototypeMeasurementFilter.MeterFilterPattern meterPatternB
= new PrototypeMeasurementFilter.MeterFilterPattern("ignored", meterSpecB);
final List<PrototypeMeasurementFilter.ValueFilterPattern> emptyList = new ArrayList<>();
Assertions.assertEquals(
filter.metricToPatterns("meterB"),
new PrototypeMeasurementFilter.IncludeExcludePatterns(
meterPatternB.getValues(), emptyList));
List<PrototypeMeasurementFilter.ValueFilterPattern> expect = new ArrayList<>();
expect.addAll(meterPatternA.getValues());
expect.addAll(meterPatternB.getValues());
PrototypeMeasurementFilter.IncludeExcludePatterns patterns
= filter.metricToPatterns("meterA");
Assertions.assertEquals(new HashSet<>(expect), new HashSet<>(patterns.getInclude()));
}
@Test
public void keepAnyTag() {
PrototypeMeasurementFilter.TagFilterPattern pattern
= new PrototypeMeasurementFilter.TagFilterPattern(
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("", ""));
Tag tagA = new BasicTag("some_name_value", "some_value_string");
Assertions.assertTrue(pattern.test(tagA));
}
@Test
public void keepTagOk() {
PrototypeMeasurementFilter.TagFilterPattern pattern
= new PrototypeMeasurementFilter.TagFilterPattern(
Pattern.compile(".+_name_.+"), Pattern.compile(".+_value_.+"));
Tag tagA = new BasicTag("some_name_value", "some_value_string");
Assertions.assertTrue(pattern.test(tagA));
}
@Test
public void keepTagNotOk() {
PrototypeMeasurementFilter.TagFilterPattern pattern
= new PrototypeMeasurementFilter.TagFilterPattern(
Pattern.compile(".+_name_.+"), Pattern.compile(".+_value_.+"));
Tag tagOnlyNameOk = new BasicTag("some_name_value", "some_string");
Tag tagOnlyValueOk = new BasicTag("some_value", "some_value_string");
Tag tagNeitherOk = new BasicTag("some_value", "some_string");
Assertions.assertFalse(pattern.test(tagOnlyNameOk));
Assertions.assertFalse(pattern.test(tagOnlyValueOk));
Assertions.assertFalse(pattern.test(tagNeitherOk));
}
@Test
public void valueTagsOk() {
PrototypeMeasurementFilter.ValueFilterPattern pattern
= new PrototypeMeasurementFilter.ValueFilterPattern(valueSpecAxBy);
List<Tag> tagsAxBy = Arrays.asList(new BasicTag("tagA", "X"),
new BasicTag("tagB", "Y"));
List<Tag> tagsByAx = Arrays.asList(tagsAxBy.get(1), tagsAxBy.get(0));
Assertions.assertTrue(pattern.test(tagsAxBy));
Assertions.assertTrue(pattern.test(tagsByAx));
}
@Test
public void extraValueTagsOk() {
PrototypeMeasurementFilter.ValueFilterPattern pattern
= new PrototypeMeasurementFilter.ValueFilterPattern(valueSpecAxBy);
List<Tag> tagsAxBy = Arrays.asList(new BasicTag("tagX", "X"),
new BasicTag("tagA", "X"),
new BasicTag("tagC", "C"),
new BasicTag("tagB", "Y"));
List<Tag> tagsByAx
= Arrays.asList(tagsAxBy.get(3), tagsAxBy.get(2),
tagsAxBy.get(1), tagsAxBy.get(0));
Assertions.assertTrue(pattern.test(tagsAxBy));
Assertions.assertTrue(pattern.test(tagsByAx));
}
@Test
public void valueTagsMissing() {
PrototypeMeasurementFilter.ValueFilterPattern pattern
= new PrototypeMeasurementFilter.ValueFilterPattern(valueSpecAxBy);
List<Tag> tagsAx = Collections.singletonList(new BasicTag("tagA", "X"));
List<Tag> tagsAxZy = Arrays.asList(new BasicTag("tagA", "X"),
new BasicTag("tagZ","Y"));
List<Tag> tagsAyBy = Arrays.asList(new BasicTag("tagA", "Y"),
new BasicTag("tagB", "Y"));
Assertions.assertFalse(pattern.test(tagsAx));
Assertions.assertFalse(pattern.test(tagsAxZy));
Assertions.assertFalse(pattern.test(tagsAyBy));
}
@Test
public void meterOk() {
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpec
= new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Arrays.asList(valueSpecAyBx, valueSpecAzBy));
PrototypeMeasurementFilterSpecification spec = new PrototypeMeasurementFilterSpecification();
spec.getInclude().put("counter.+", meterSpec);
PrototypeMeasurementFilter filter = new PrototypeMeasurementFilter(spec);
Id idAYX = Id.create("counterA").withTag("tagA", "Y").withTag("tagB", "X");
Id idBZY = Id.create("counterB").withTag("tagA", "Z").withTag("tagB", "Y");
Assertions.assertTrue(filter.test(new Measurement(idAYX, 1, 1)));
Assertions.assertTrue(filter.test(new Measurement(idBZY, 2, 2)));
}
@Test
public void metersExcluded() {
PrototypeMeasurementFilterSpecification spec = new PrototypeMeasurementFilterSpecification();
spec.getInclude().put(
"counter.+",
new PrototypeMeasurementFilterSpecification.MeterFilterSpecification());
spec.getExclude().put(
"counterC",
new PrototypeMeasurementFilterSpecification.MeterFilterSpecification());
PrototypeMeasurementFilter filter = new PrototypeMeasurementFilter(spec);
Id idAYX = Id.create("counterA").withTag("tagA", "Y").withTag("tagB", "X");
Id idCYX = Id.create("counterC").withTag("tagA", "Y").withTag("tagB", "X");
Assertions.assertTrue(filter.test(new Measurement(idAYX, 1, 1)));
Assertions.assertFalse(filter.test(new Measurement(idCYX, 2, 2)));
}
@Test
public void meterNotOkBecauseNotIncluded() {
PrototypeMeasurementFilterSpecification.MeterFilterSpecification meterSpec
= new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Arrays.asList(valueSpecAyBx, valueSpecAzBy));
PrototypeMeasurementFilterSpecification spec = new PrototypeMeasurementFilterSpecification();
spec.getInclude().put("counter.+", meterSpec);
PrototypeMeasurementFilter filter = new PrototypeMeasurementFilter(spec);
Id idAXX = Id.create("counterA").withTag("tagA", "X").withTag("tagB", "X");
Id idBZX = Id.create("counterB").withTag("tagA", "Z").withTag("tagB", "X");
Assertions.assertFalse(filter.test(new Measurement(idAXX, 1, 1)));
Assertions.assertFalse(filter.test(new Measurement(idBZX, 2, 2)));
}
@Test
public void loadFromJson() throws IOException {
String path = getClass().getResource("/test_measurement_filter.json").getFile();
PrototypeMeasurementFilterSpecification spec
= PrototypeMeasurementFilterSpecification.loadFromPath(path);
PrototypeMeasurementFilterSpecification specA
= new PrototypeMeasurementFilterSpecification();
specA.getInclude().put("meterA", meterSpecA);
specA.getInclude().put("meterD", meterSpecD);
specA.getInclude().put(
"empty",
new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
new ArrayList<>()));
List<PrototypeMeasurementFilterSpecification.TagFilterSpecification> tagsX = Arrays.asList(
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagA", "X"),
new PrototypeMeasurementFilterSpecification.TagFilterSpecification("tagX", ".*"));
PrototypeMeasurementFilterSpecification.ValueFilterSpecification valueSpecX
= new PrototypeMeasurementFilterSpecification.ValueFilterSpecification();
valueSpecX.getTags().addAll(tagsX);
specA.getExclude().put(
".+",
new PrototypeMeasurementFilterSpecification.MeterFilterSpecification(
Collections.singletonList(valueSpecX)));
Assertions.assertEquals(spec, specA);
}
}
| 5,905 |
0 | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/test/java/com/netflix/spectator/controllers/filter/TagFilterTest.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.filter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.function.Predicate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TagFilterTest {
Id idA = Id.create("idA");
Id idB = Id.create("idB");
Id idAXY = idA.withTag("tagA", "X").withTag("tagB", "Y");
Id idAXZ = idA.withTag("tagA", "X").withTag("tagZ", "Z");
Id idBXY = idB.withTag("tagA", "X").withTag("tagB", "Y");
Measurement measureAXY = new Measurement(idAXY, 11, 11.11);
Measurement measureAXZ = new Measurement(idAXZ, 13, 13.13);
Measurement measureBXY = new Measurement(idBXY, 50, 50.50);
@Test
public void testFilteredName() {
Predicate<Measurement> filter = new TagMeasurementFilter("idA", null, null);
Assertions.assertTrue(filter.test(measureAXY));
Assertions.assertFalse(filter.test(measureBXY));
}
@Test
public void collectFilteredTagName() {
Predicate<Measurement> filter = new TagMeasurementFilter(null, "tagZ", null);
Assertions.assertTrue(filter.test(measureAXZ));
Assertions.assertFalse(filter.test(measureAXY));
}
@Test
public void collectFilteredTagValue() {
Predicate<Measurement> filter = new TagMeasurementFilter(null, null, "Z");
Assertions.assertTrue(filter.test(measureAXZ));
Assertions.assertFalse(filter.test(measureAXY));
}
}
| 5,906 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/MetricsController.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.controllers.filter.PrototypeMeasurementFilter;
import com.netflix.spectator.controllers.filter.TagMeasurementFilter;
import com.netflix.spectator.controllers.model.ApplicationRegistry;
import com.netflix.spectator.controllers.model.MetricValues;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.function.Predicate;
import java.util.Map;
import java.util.HashMap;
/**
* Provides an HTTP endpoint for polling spectator metrics.
*/
@RequestMapping("/spectator/metrics")
@RestController
@ConditionalOnExpression("${spectator.web-endpoint.enabled:false}")
public class MetricsController {
@Autowired
private Registry registry;
/**
* A measurement filter that accepts all measurements.
*/
public static final Predicate<Measurement> ALL_MEASUREMENTS_FILTER = m -> true;
@Value("${spectator.application-name:}")
private String applicationName;
@Value("${spectator.application-version:}")
private String applicationVersion;
@Value("${spectator.web-endpoint.prototype-filter.path:}")
private String prototypeFilterPath;
private final Map<Id, String> knownMeterKinds = new HashMap<>();
private Predicate<Measurement> defaultMeasurementFilter = null;
/**
* The default measurement filter is configured through properties.
*/
public Predicate<Measurement> getDefaultMeasurementFilter() throws IOException {
if (defaultMeasurementFilter != null) {
return defaultMeasurementFilter;
}
if (!prototypeFilterPath.isEmpty()) {
defaultMeasurementFilter = PrototypeMeasurementFilter.loadFromPath(
prototypeFilterPath);
} else {
defaultMeasurementFilter = ALL_MEASUREMENTS_FILTER;
}
return defaultMeasurementFilter;
}
/**
* Endpoint for querying current metric values.
*
* The result is a JSON document describing the metrics and their values.
* The result can be filtered using query parameters or configuring the
* controller instance itself.
*/
@RequestMapping(method = RequestMethod.GET)
public ApplicationRegistry getMetrics(@RequestParam Map<String, String> filters)
throws IOException {
boolean all = filters.get("all") != null;
String filterMeterNameRegex = filters.getOrDefault("meterNameRegex", "");
String filterTagNameRegex = filters.getOrDefault("tagNameRegex", "");
String filterTagValueRegex = filters.getOrDefault("tagValueRegex", "");
TagMeasurementFilter queryFilter = new TagMeasurementFilter(
filterMeterNameRegex, filterTagNameRegex, filterTagValueRegex);
Predicate<Measurement> filter;
if (all) {
filter = queryFilter;
} else {
filter = queryFilter.and(getDefaultMeasurementFilter());
}
ApplicationRegistry response = new ApplicationRegistry();
response.setApplicationName(applicationName);
response.setApplicationVersion(applicationVersion);
response.setMetrics(encodeRegistry(registry, filter));
return response;
}
/**
* Internal API for encoding a registry that can be encoded as JSON.
* This is a helper function for the REST endpoint and to test against.
*/
Map<String, MetricValues> encodeRegistry(
Registry sourceRegistry, Predicate<Measurement> filter) {
Map<String, MetricValues> metricMap = new HashMap<>();
/*
* Flatten the meter measurements into a map of measurements keyed by
* the name and mapped to the different tag variants.
*/
for (Meter meter : sourceRegistry) {
String kind = knownMeterKinds.computeIfAbsent(
meter.id(), k -> meterToKind(sourceRegistry, meter));
for (Measurement measurement : meter.measure()) {
if (!filter.test(measurement)) {
continue;
}
if (Double.isNaN(measurement.value())) {
continue;
}
String meterName = measurement.id().name();
MetricValues have = metricMap.get(meterName);
if (have == null) {
metricMap.put(meterName, new MetricValues(kind, measurement));
} else {
have.addMeasurement(measurement);
}
}
}
return metricMap;
}
/**
* Determine the type of a meter for reporting purposes.
*
* @param registry
* Used to provide supplemental information (e.g. to search for the meter).
*
* @param meter
* The meters whose kind we want to know.
*
* @return
* A string such as "Counter". If the type cannot be identified as one of
* the standard Spectator api interface variants, then the simple class name
* is returned.
*/
public static String meterToKind(Registry registry, Meter meter) {
String kind;
if (meter instanceof Timer) {
kind = "Timer";
} else if (meter instanceof Counter) {
kind = "Counter";
} else if (meter instanceof Gauge) {
kind = "Gauge";
} else if (meter instanceof DistributionSummary) {
kind = "DistributionSummary";
} else {
kind = meter.getClass().getSimpleName();
}
return kind;
}
}
| 5,907 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/model/DataPoint.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.model;
import com.netflix.spectator.api.Measurement;
import java.util.Objects;
/**
* A serializable Measurement.
* Measurement is a value at a given time.
*
* The id is implicit by the parent node containing this DataPoint.
*
* This is only public for testing purposes so implements equals but not hash.
*/
@SuppressWarnings("PMD.DataClass")
public class DataPoint {
/**
* Factory method to create a DataPoint from a Measurement.
*/
public static DataPoint make(Measurement m) {
return new DataPoint(m.timestamp(), m.value());
}
/**
* The measurement timestamp.
*/
public long getT() {
return timestamp;
}
/**
* The measurement value.
*/
public double getV() {
return value;
}
/**
* Constructor.
*/
public DataPoint(long timestamp, double value) {
this.timestamp = timestamp;
this.value = value;
}
@Override
public String toString() {
return String.format("t=%d, v=%f", timestamp, value);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DataPoint)) return false;
DataPoint other = (DataPoint) obj;
return timestamp == other.timestamp && (Math.abs(value - other.value) < 0.001);
}
@Override
public int hashCode() {
return Objects.hash(timestamp, value);
}
private final long timestamp;
private final double value;
}
| 5,908 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/model/ApplicationRegistry.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.model;
import java.lang.management.ManagementFactory;
import java.util.Map;
import java.util.Objects;
/**
* An ApplicationRegistry is the encoding of the metrics from a particular application.
*
* This is only public for testing purposes so implements equals but not hash.
*/
@SuppressWarnings("PMD.DataClass")
public class ApplicationRegistry {
private static final long START_TIME = ManagementFactory.getRuntimeMXBean().getStartTime();
private String applicationName;
private String applicationVersion;
private Map<String, MetricValues> metrics;
/**
* The application name exporting the metrics.
*/
public String getApplicationName() {
return applicationName;
}
/**
* The application name exporting the metrics.
*/
public void setApplicationName(String name) {
applicationName = name;
}
/**
* The version of the application name exporting the metrics.
*/
public String getApplicationVersion() {
return applicationVersion;
}
/**
* The version of the application name exporting the metrics.
*/
public void setApplicationVersion(String version) {
applicationVersion = version;
}
/**
* The JVM start time (millis).
*/
public long getStartTime() {
return START_TIME;
}
/**
* The current metrics.
*/
public Map<String, MetricValues> getMetrics() {
return metrics;
}
/**
* Sets the metric map.
*
* This is just an assignment, not a copy.
*/
public void setMetrics(Map<String, MetricValues> map) {
metrics = map;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ApplicationRegistry)) return false;
ApplicationRegistry other = (ApplicationRegistry) obj;
return applicationName.equals(other.applicationName) && metrics.equals(other.metrics);
}
@Override
public int hashCode() {
return Objects.hash(applicationName, metrics);
}
}
| 5,909 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/model/MetricValues.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.model;
import com.netflix.spectator.api.Measurement;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* A metric and all its tagged values
*
* This is only public for testing purposes so implements equals but not hash.
*/
public class MetricValues {
/**
* Returns a string denoting the type of Meter.
* These are strings we've added; Spectator doesnt have this.
*/
public String getKind() {
return kind;
}
/**
* Returns the current data point values for this metric.
*/
public Iterable<TaggedDataPoints> getValues() {
return dataPoints;
}
/**
* Adds another measurement datapoint.
*/
public void addMeasurement(Measurement measurement) {
dataPoints.add(new TaggedDataPoints(measurement));
}
/**
* Constructor from a single measurement datapoint.
*/
public MetricValues(String kind, Measurement measurement) {
this.kind = kind;
dataPoints = new ArrayList<>();
dataPoints.add(new TaggedDataPoints(measurement));
}
/**
* Constructor from a list of datapoints (for testing).
*/
public MetricValues(String kind, List<TaggedDataPoints> dataPoints) {
this.kind = kind;
this.dataPoints = new ArrayList<>(dataPoints);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MetricValues)) return false;
MetricValues other = (MetricValues) obj;
// Ignore the kind because spectator internally transforms it
// into internal types that we cannot test against.
return dataPoints.equals(other.dataPoints);
}
@Override
public int hashCode() {
return Objects.hash(kind, dataPoints);
}
@Override
public String toString() {
return String.format("%s: %s", kind, dataPoints);
}
private final String kind;
private final List<TaggedDataPoints> dataPoints;
}
| 5,910 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/model/TaggedDataPoints.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.model;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Tag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* A collection of DataPoint instances for a common set of Tags.
*
* This is only public for testing purposes so implements equals but not hash.
*/
public class TaggedDataPoints {
private static class JacksonableTag implements Tag {
private final String key;
private final String value;
JacksonableTag(Tag tag) {
key = tag.key();
value = tag.value();
}
@Override public String key() {
return key;
}
@Override public String value() {
return value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override public int hashCode() {
return Objects.hash(key, value);
}
@Override public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Tag)) return false;
Tag tag = (Tag) obj;
return key.equals(tag.key()) && value.equals(tag.value());
}
@Override public String toString() {
return key + "=" + value;
}
static List<Tag> convertTags(Iterable<Tag> iterable) {
ArrayList<Tag> result = new ArrayList<>();
for (Tag tag : iterable) {
result.add(new JacksonableTag(tag));
}
return result;
}
}
/**
* The tag bindings for the values.
*/
public Iterable<Tag> getTags() {
return tags;
}
/**
* The current values.
*/
public Iterable<DataPoint> getValues() {
return dataPoints;
}
/**
* Constructor from a single measurement data point.
*/
public TaggedDataPoints(Measurement measurement) {
tags = JacksonableTag.convertTags(measurement.id().tags());
dataPoints = Collections.singletonList(DataPoint.make(measurement));
}
/**
* Constructor from a list of data points (for testing).
*/
public TaggedDataPoints(Iterable<Tag> tags, List<DataPoint> dataPoints) {
this.tags = JacksonableTag.convertTags(tags);
this.dataPoints = dataPoints;
}
@Override
public String toString() {
return String.format("{TAGS={%s} DATA={%s}", tags, dataPoints);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TaggedDataPoints)) return false;
TaggedDataPoints other = (TaggedDataPoints) obj;
return tags.equals(other.tags) && dataPoints.equals(other.dataPoints);
}
@Override
public int hashCode() {
return Objects.hash(tags, dataPoints);
}
private final List<Tag> tags;
private final List<DataPoint> dataPoints;
}
| 5,911 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/filter/TagMeasurementFilter.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.filter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Tag;
import java.util.function.Predicate;
import java.util.regex.Pattern;
/**
* A simple MeasurementFilter based on meter/tag names and values.
*/
public class TagMeasurementFilter implements Predicate<Measurement> {
private final Pattern meterNamePattern;
private final Pattern tagNamePattern;
private final Pattern tagValuePattern;
private static Pattern regexToPatternOrNull(String regex) {
if (regex != null && !regex.isEmpty() && !regex.equals(".*")) {
return Pattern.compile(regex);
}
return null;
}
private static boolean stringMatches(String text, Pattern pattern) {
return pattern == null || pattern.matcher(text).matches();
}
/**
* Constructor.
*/
public TagMeasurementFilter(String meterNameRegex, String tagNameRegex, String tagValueRegex) {
meterNamePattern = regexToPatternOrNull(meterNameRegex);
tagNamePattern = regexToPatternOrNull(tagNameRegex);
tagValuePattern = regexToPatternOrNull(tagValueRegex);
}
/**
* Implements MeasurementFilter interface.
*/
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
@Override public boolean test(Measurement measurement) {
Id id = measurement.id();
if (!stringMatches(id.name(), meterNamePattern)) {
return false;
}
if (tagNamePattern != null || tagValuePattern != null) {
for (Tag tag : id.tags()) {
boolean nameOk = stringMatches(tag.key(), tagNamePattern);
boolean valueOk = stringMatches(tag.value(), tagValuePattern);
if (nameOk && valueOk) {
return true;
}
}
return false;
}
return true;
}
}
| 5,912 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/filter/PrototypeMeasurementFilterSpecification.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Represents the specification for a PrototypeMeasurementFilter.
*/
public class PrototypeMeasurementFilterSpecification {
/**
* Specifies how to filter an individual tag (name and value).
*/
public static class TagFilterSpecification {
private final String key; // regex
private final String value; // regex
public String getKey() {
return key;
}
public String getValue() {
return value;
}
/**
* Default constructor.
*/
public TagFilterSpecification() {
key = null;
value = null;
}
/**
* Construct a filter with particular regular expressions.
*/
public TagFilterSpecification(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TagFilterSpecification)) {
return false;
}
TagFilterSpecification other = (TagFilterSpecification) obj;
return key.equals(other.key) && value.equals(other.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return String.format("%s=%s", key, value);
}
}
/**
* Specifies how to filter values.
*
* Values are identified by a collection of tags, so the filter
* is based on having a particular collection of name/value bindings.
*
* Actual values are not currently considered, but could be added later.
*/
public static class ValueFilterSpecification {
/**
* A filter that allows everything.
*/
static final ValueFilterSpecification ALL = new ValueFilterSpecification();
static {
ALL.tags.add(new TagFilterSpecification(".*", ".*"));
}
/**
* Default constructor.
*/
ValueFilterSpecification() {
// empty.
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ValueFilterSpecification)) {
return false;
}
ValueFilterSpecification other = (ValueFilterSpecification) obj;
return tags.equals(other.tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
@Override
public String toString() {
return tags.toString();
}
/**
* The tag specifications.
*/
public List<TagFilterSpecification> getTags() {
return tags;
}
/**
* The minimal list of tag bindings that are covered by this specification.
*/
private final List<TagFilterSpecification> tags
= new ArrayList<>();
}
/**
* A specification for filtering on a Spectator Meter.
*
* A meter is a name pattern and collection of tag bindings.
*/
public static class MeterFilterSpecification {
/**
* Default constructor.
*/
public MeterFilterSpecification() {
// empty.
}
/**
* Constructor injecting a value specification.
*/
public MeterFilterSpecification(List<ValueFilterSpecification> values) {
this.values.addAll(values);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MeterFilterSpecification)) {
return false;
}
MeterFilterSpecification other = (MeterFilterSpecification) obj;
return values.equals(other.values);
}
@Override
public int hashCode() {
return values.hashCode();
}
@Override
public String toString() {
return values.toString();
}
/**
* The metric vlaue specifications.
*/
public List<ValueFilterSpecification> getValues() {
return values;
}
/**
* The meter can be filtered on one or more collection of tag bindings.
* In essence, this permits certain aspects of a meter to be considered
* but not others.
*/
private final List<ValueFilterSpecification> values
= new ArrayList<>();
}
/**
* Loads a specification from a file.
*/
public static PrototypeMeasurementFilterSpecification loadFromPath(String path)
throws IOException {
byte[] jsonData = Files.readAllBytes(Paths.get(path));
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(
jsonData, PrototypeMeasurementFilterSpecification.class);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PrototypeMeasurementFilterSpecification)) {
return false;
}
PrototypeMeasurementFilterSpecification other
= (PrototypeMeasurementFilterSpecification) obj;
return include.equals(other.include) && exclude.equals(other.exclude);
}
@Override
public int hashCode() {
return Objects.hash(include, exclude);
}
@Override
public String toString() {
return String.format("INCLUDE=%s%nEXCLUDE=%s",
include.toString(), exclude.toString());
}
/**
* The list of specifications for when meters should be included.
*/
public Map<String, MeterFilterSpecification> getInclude() {
return include;
}
/**
* The list of specifications for when meters should be excluded.
*/
public Map<String, MeterFilterSpecification> getExclude() {
return exclude;
}
/**
* Maps meter name patterns to the meter specification for that pattern.
* The specified filter only passes meter/measurements that can be
* traced back to a specification in this list.
*/
private final Map<String, MeterFilterSpecification> include
= new HashMap<>();
/**
* Maps meter name patterns to the meter specification for that pattern.
* The specified filter does not pass meter/measurements that can be
* traced back to a specification in this list.
*/
private final Map<String, MeterFilterSpecification> exclude
= new HashMap<>();
}
| 5,913 |
0 | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers | Create_ds/spectator/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/filter/PrototypeMeasurementFilter.java | /*
* Copyright 2016 Google, Inc.
*
* 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 com.netflix.spectator.controllers.filter;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Tag;
import java.io.IOException;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
/**
* A general filter specified using a prototype "JSON" document.
*
* The json document generally follows the structure of the response,
* however in addition to containing a "metrics" section of what is desired,
* it also contains an "excludes" section saying what is not desired.
*
* Each of the section contains regular expression rather than literals
* where the regular expressions are matched against the actual names (or values).
* Thus the excludes section can be used to restrict more general matching
* expressions.
*
* Each measurement is evaluated against all the entries in the filter until one
* is found that would cause it to be accepted and not excluded.
*/
public class PrototypeMeasurementFilter implements Predicate<Measurement> {
/**
* Filters based on Spectator Id tag names and/or values.
*/
public static class TagFilterPattern {
/**
* Construct from regex patterns.
*/
public TagFilterPattern(Pattern key, Pattern value) {
this.key = key;
this.value = value;
}
/**
* Construct from the prototype specification.
*/
public TagFilterPattern(PrototypeMeasurementFilterSpecification.TagFilterSpecification spec) {
if (spec == null) return;
String keySpec = spec.getKey();
String valueSpec = spec.getValue();
if (keySpec != null && !keySpec.isEmpty() && !keySpec.equals(".*")) {
key = Pattern.compile(keySpec);
}
if (valueSpec != null && !valueSpec.isEmpty() && !valueSpec.equals(".*")) {
value = Pattern.compile(valueSpec);
}
}
@Override
public int hashCode() {
return Objects.hash(key.pattern(), value.pattern());
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TagFilterPattern)) return false;
TagFilterPattern other = (TagFilterPattern) obj;
return key.pattern().equals(other.key.pattern()) && value.pattern().equals(other.value.pattern());
}
/**
* Implements the MeasurementFilter interface.
*/
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
public boolean test(Tag tag) {
if ((key != null) && !key.matcher(tag.key()).matches()) return false;
return ((value == null) || value.matcher(tag.value()).matches());
}
@Override
public String toString() {
return String.format("%s=%s", key.pattern(), value.pattern());
}
/**
* Pattern for matching the Spectator tag key.
*/
private Pattern key;
/**
* Pattern for matching the Spectator tag value.
*/
private Pattern value;
}
/**
* Filters on measurement values.
*
* A value includes a set of tags.
* This filter does not currently include the actual measurement value, only sets of tags.
*/
public static class ValueFilterPattern {
/**
* Constructs a filter from a specification.
*/
public ValueFilterPattern(PrototypeMeasurementFilterSpecification.ValueFilterSpecification spec) {
if (spec == null) return;
for (PrototypeMeasurementFilterSpecification.TagFilterSpecification tag : spec.getTags()) {
this.tags.add(new TagFilterPattern(tag));
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ValueFilterPattern)) return false;
ValueFilterPattern other = (ValueFilterPattern) obj;
return tags.equals(other.tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
/**
* Determins if a particular TagFilter is satisfied among the value's tag set.
*/
static boolean patternInList(TagFilterPattern tagPattern,
Iterable<Tag> sourceTags) {
for (Tag candidateTag : sourceTags) {
if (tagPattern.test(candidateTag)) {
return true;
}
}
return false;
}
/**
* Implements the MeasurementFilter interface.
*/
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
public boolean test(Iterable<Tag> sourceTags) {
for (TagFilterPattern tagPattern : this.tags) {
if (!patternInList(tagPattern, sourceTags)) {
return false;
}
}
return true;
}
/**
* The list of tag filters that must be satisfied for the value to be satisfied.
*/
public List<TagFilterPattern> getTags() {
return tags;
}
private final List<TagFilterPattern> tags = new ArrayList<>();
}
/**
* Filters a meter.
*/
public static class MeterFilterPattern {
/**
* Constructs from a specification.
*
* The nameRegex specifies the name of the Spectator meter itself.
*/
public MeterFilterPattern(
String nameRegex,
PrototypeMeasurementFilterSpecification.MeterFilterSpecification spec) {
namePattern = Pattern.compile(nameRegex);
if (spec == null) return;
if (spec.getValues().isEmpty()) {
values.add(new ValueFilterPattern(PrototypeMeasurementFilterSpecification.ValueFilterSpecification.ALL));
}
for (PrototypeMeasurementFilterSpecification.ValueFilterSpecification value : spec.getValues()) {
values.add(new ValueFilterPattern(value));
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MeterFilterPattern)) return false;
MeterFilterPattern other = (MeterFilterPattern) obj;
return namePattern.equals(other.namePattern) && values.equals(other.values);
}
@Override
public int hashCode() {
return Objects.hash(namePattern, values);
}
/**
* Filters the name of the meter.
*/
private final Pattern namePattern;
/**
* A list of value filters acts as a disjunction.
* Any of the values can be satisifed to satisfy the Meter.
*/
public List<ValueFilterPattern> getValues() {
return values;
}
private final List<ValueFilterPattern> values = new ArrayList<>();
}
/**
* A collection of Include patterns and Exclude patterns for filtering.
*/
public static class IncludeExcludePatterns {
/**
* The value patterns that must be satisifed to include.
*/
public List<ValueFilterPattern> getInclude() {
return include;
}
private final List<ValueFilterPattern> include = new ArrayList<>();
/**
* The value patterns that cannot be satisifed to include.
* This is meant to refine the include list from being too generous.
*/
public List<ValueFilterPattern> getExclude() {
return exclude;
}
private final List<ValueFilterPattern> exclude = new ArrayList<>();
/**
* Default constructor.
*/
public IncludeExcludePatterns() {
// empty.
}
/**
* Constructor.
*/
public IncludeExcludePatterns(List<ValueFilterPattern> include,
List<ValueFilterPattern> exclude) {
this.include.addAll(include);
this.exclude.addAll(exclude);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IncludeExcludePatterns)) {
return false;
}
IncludeExcludePatterns other = (IncludeExcludePatterns) obj;
return include.equals(other.include) && exclude.equals(other.exclude);
}
@Override
public int hashCode() {
return Objects.hash(include, exclude);
}
/**
* Implements the MeasurementFilter interface.
*/
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
public boolean test(Measurement measurement) {
boolean ok = include.isEmpty();
for (ValueFilterPattern pattern : include) {
if (pattern.test(measurement.id().tags())) {
ok = true;
break;
}
}
if (ok) {
for (ValueFilterPattern pattern : exclude) {
if (pattern.test(measurement.id().tags())) {
return false;
}
}
}
return ok;
}
}
/**
* Constructor.
*/
public PrototypeMeasurementFilter(PrototypeMeasurementFilterSpecification specification) {
for (Map.Entry<String, PrototypeMeasurementFilterSpecification.MeterFilterSpecification> entry
: specification.getInclude().entrySet()) {
includePatterns.add(new MeterFilterPattern(entry.getKey(), entry.getValue()));
}
for (Map.Entry<String, PrototypeMeasurementFilterSpecification.MeterFilterSpecification> entry
: specification.getExclude().entrySet()) {
excludePatterns.add(new MeterFilterPattern(entry.getKey(), entry.getValue()));
}
}
/**
* Implements the MeasurementFilter interface.
*/
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
@Override public boolean test(Measurement measurement) {
IncludeExcludePatterns patterns = metricToPatterns(measurement.id().name());
return patterns != null && patterns.test(measurement);
}
/**
* Find the IncludeExcludePatterns for filtering a given metric.
*
* The result is the union of all the individual pattern entries
* where their specified metric name patterns matches the actual metric name.
*/
public IncludeExcludePatterns metricToPatterns(String metric) {
IncludeExcludePatterns foundPatterns = metricNameToPatterns.get(metric);
if (foundPatterns != null) {
return foundPatterns;
}
// Since the keys in the prototype can be regular expressions,
// need to look at all of them and can potentially match multiple,
// each having a different set of rules.
foundPatterns = new IncludeExcludePatterns();
for (MeterFilterPattern meterPattern : includePatterns) {
if (meterPattern.namePattern.matcher(metric).matches()) {
foundPatterns.include.addAll(meterPattern.values);
}
}
for (MeterFilterPattern meterPattern : excludePatterns) {
if (meterPattern.namePattern.matcher(metric).matches()) {
foundPatterns.exclude.addAll(meterPattern.values);
}
}
metricNameToPatterns.put(metric, foundPatterns);
return foundPatterns;
}
/**
* Factory method building a filter from a specification file.
*/
public static PrototypeMeasurementFilter loadFromPath(String path) throws IOException {
PrototypeMeasurementFilterSpecification spec =
PrototypeMeasurementFilterSpecification.loadFromPath(path);
return new PrototypeMeasurementFilter(spec);
}
/**
* All the meter filter patterns that can be satisfied.
*/
private final List<MeterFilterPattern> includePatterns = new ArrayList<>();
/**
* All the meter filter patterns that cannot be satisfied.
*/
private final List<MeterFilterPattern> excludePatterns = new ArrayList<>();
/**
* A cache of previously computed includeExcludePatterns.
* Since the patterns are static and meters heavily reused,
* we'll cache previous results for the next time we apply the filter.
*/
private final Map<String, IncludeExcludePatterns> metricNameToPatterns
= new HashMap<>();
}
| 5,914 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/UdpWriterTest.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class UdpWriterTest {
@Test
public void udp() throws IOException {
try (UdpServer server = new UdpServer()) {
try (SidecarWriter w = SidecarWriter.create(server.address())) {
w.write("foo");
Assertions.assertEquals("foo", server.read());
w.write("bar");
Assertions.assertEquals("bar", server.read());
}
}
}
// Disabled because it can have issues on CI
@Test
@Disabled
public void concurrentWrites() throws Exception {
List<String> lines = Collections.synchronizedList(new ArrayList<>());
try (UdpServer server = new UdpServer()) {
try (SidecarWriter w = SidecarWriter.create(server.address())) {
Thread reader = new Thread(() -> {
while (true) {
try {
String line = server.read();
if (!"done".equals(line)) {
lines.add(line);
} else {
break;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
});
reader.start();
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; ++i) {
final int n = i;
Runnable task = () -> {
int base = n * 10_000;
for (int j = 0; j < 10_000; ++j) {
w.write("" + (base + j));
}
};
threads[i] = new Thread(task);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
w.write("done");
reader.join();
}
}
int N = 40_000;
Assertions.assertEquals(N, lines.size());
Assertions.assertEquals(N * (N - 1) / 2, lines.stream().mapToInt(Integer::parseInt).sum());
}
}
| 5,915 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/UdpServer.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
class UdpServer implements Closeable {
private final DatagramChannel channel;
UdpServer() throws IOException {
channel = DatagramChannel.open();
channel.bind(new InetSocketAddress("localhost", 0));
}
String address() throws IOException {
InetSocketAddress addr = (InetSocketAddress) channel.getLocalAddress();
return "udp://" + addr.getHostName() + ":" + addr.getPort();
}
String read() throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.receive(buffer);
int length = buffer.position();
return new String(buffer.array(), 0, length, StandardCharsets.UTF_8);
}
@Override public void close() throws IOException {
channel.close();
}
}
| 5,916 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/SidecarRegistryTest.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Timer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SidecarRegistryTest {
private final ManualClock clock = new ManualClock();
private final TestConfig config = new TestConfig();
private final SidecarRegistry registry = new SidecarRegistry(clock, config, config.writer());
@BeforeEach
public void beforeEach() throws Exception {
clock.setWallTime(0L);
clock.setMonotonicTime(0L);
registry.close();
}
private void assertSingleMessage(String expected) {
List<String> messages = config.writer().messages();
Assertions.assertEquals(1, messages.size());
Assertions.assertEquals(messages.get(0), expected);
}
private void assertNoMessage() {
List<String> messages = config.writer().messages();
Assertions.assertEquals(0, messages.size());
}
@Test
public void idJustName() {
registry.counter("test").increment();
assertSingleMessage("c:test:1");
}
@Test
public void idJustNameInvalidChars() {
registry.counter("test name").increment();
assertSingleMessage("c:test_name:1");
}
@Test
public void idWithTags() {
registry.counter("test", "app", "foo", "node", "i$1234").increment();
assertSingleMessage("c:test,app=foo,node=i_1234:1");
}
@Test
public void counter() {
Counter c = registry.counter("test");
c.increment();
assertSingleMessage("c:test:1");
Assertions.assertTrue(Double.isNaN(c.actualCount()));
}
@Test
public void counterIncrementAmount() {
registry.counter("test").increment(42);
assertSingleMessage("c:test:42");
}
@Test
public void counterIncrementNegative() {
registry.counter("test").increment(-42);
assertNoMessage();
}
@Test
public void counterIncrementZero() {
registry.counter("test").increment(0);
assertNoMessage();
}
@Test
public void counterAdd() {
registry.counter("test").add(42.0);
assertSingleMessage("c:test:42.0");
}
@Test
public void counterAddNegative() {
registry.counter("test").add(-42.0);
assertNoMessage();
}
@Test
public void counterAddZero() {
registry.counter("test").add(0.0);
assertNoMessage();
}
@Test
public void distributionSummary() {
DistributionSummary d = registry.distributionSummary("test");
d.record(42);
assertSingleMessage("d:test:42");
Assertions.assertEquals(0L, d.count());
Assertions.assertEquals(0L, d.totalAmount());
}
@Test
public void distributionSummaryNegative() {
DistributionSummary d = registry.distributionSummary("test");
d.record(-42);
assertNoMessage();
}
@Test
public void distributionSummaryZero() {
DistributionSummary d = registry.distributionSummary("test");
d.record(0);
assertSingleMessage("d:test:0");
}
@Test
public void gauge() {
Gauge g = registry.gauge("test");
g.set(42);
assertSingleMessage("g:test:42.0");
Assertions.assertTrue(Double.isNaN(g.value()));
}
@Test
public void maxGauge() {
Gauge g = registry.maxGauge("test");
g.set(42);
assertSingleMessage("m:test:42.0");
Assertions.assertTrue(Double.isNaN(g.value()));
}
@Test
public void timer() {
Timer t = registry.timer("test");
t.record(42, TimeUnit.MILLISECONDS);
assertSingleMessage("t:test:0.042");
Assertions.assertEquals(0L, t.count());
Assertions.assertEquals(0L, t.totalTime());
}
@Test
public void timerNegative() {
Timer t = registry.timer("test");
t.record(-42, TimeUnit.MILLISECONDS);
assertNoMessage();
}
@Test
public void timerZero() {
Timer t = registry.timer("test");
t.record(0, TimeUnit.MILLISECONDS);
assertSingleMessage("t:test:0.0");
}
@Test
public void timerRecordCallable() throws Exception {
Timer t = registry.timer("test");
long v = t.record(() -> {
clock.setMonotonicTime(100_000_000);
return registry.clock().monotonicTime();
});
Assertions.assertEquals(100_000_000L, v);
assertSingleMessage("t:test:0.1");
}
@Test
public void timerRecordRunnable() {
Timer t = registry.timer("test");
t.record(() -> {
clock.setMonotonicTime(100_000_000);
});
assertSingleMessage("t:test:0.1");
}
@Test
public void get() {
registry.counter("test").increment();
Assertions.assertNull(registry.get(Id.create("test")));
}
@Test
public void iterator() {
registry.counter("test").increment();
Assertions.assertFalse(registry.iterator().hasNext());
}
private static class TestConfig implements SidecarConfig {
private final MemoryWriter writer = new MemoryWriter();
@Override public String get(String k) {
return null;
}
@Override public String outputLocation() {
return "none";
}
MemoryWriter writer() {
return writer;
}
}
}
| 5,917 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/SidecarConfigTest.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.function.Function;
public class SidecarConfigTest {
@Test
public void outputLocationDefault() {
SidecarConfig config = s -> null;
Assertions.assertEquals("udp://127.0.0.1:1234", config.outputLocation());
}
@Test
public void outputLocationSet() {
SidecarConfig config = s -> "sidecar.output-location".equals(s) ? "none" : null;
Assertions.assertEquals("none", config.outputLocation());
}
@Test
public void commonTagsEmpty() {
SidecarConfig config = s -> null;
Assertions.assertEquals(Collections.emptyMap(), config.commonTags());
}
@Test
public void commonTagsProcess() {
Function<String, String> getenv = s -> "NETFLIX_PROCESS_NAME".equals(s) ? "test" : null;
Assertions.assertEquals(
Collections.singletonMap("nf.process", "test"),
CommonTags.commonTags(getenv));
}
@Test
public void commonTagsContainer() {
Function<String, String> getenv = s -> "TITUS_CONTAINER_NAME".equals(s) ? "test" : null;
Assertions.assertEquals(
Collections.singletonMap("nf.container", "test"),
CommonTags.commonTags(getenv));
}
}
| 5,918 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/MemoryWriter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class MemoryWriter extends SidecarWriter {
private final List<String> messages;
MemoryWriter() {
super("memory");
messages = new ArrayList<>();
}
List<String> messages() {
return messages;
}
@Override
void writeImpl(String line) throws IOException {
messages.add(line);
}
@Override
public void close() throws IOException {
messages.clear();
}
}
| 5,919 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/test/java/com/netflix/spectator/sidecar/PrintStreamWriterTest.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class PrintStreamWriterTest {
private SidecarWriter newWriter(Path path) throws IOException {
String location = "file://" + path.toString();
return SidecarWriter.create(location);
}
@Test
public void file() throws IOException {
Path tmp = Files.createTempFile("spectator", "test");
try (SidecarWriter w = newWriter(tmp)) {
w.write("foo");
w.write("bar");
}
List<String> lines = Files.readAllLines(tmp, StandardCharsets.UTF_8);
Assertions.assertEquals(2, lines.size());
Assertions.assertEquals("foo", lines.get(0));
Assertions.assertEquals("bar", lines.get(1));
Files.deleteIfExists(tmp);
}
@Test
public void concurrentWrites() throws Exception {
Path tmp = Files.createTempFile("spectator", "test");
try (SidecarWriter w = newWriter(tmp)) {
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; ++i) {
final int n = i;
Runnable task = () -> {
int base = n * 10_000;
for (int j = 0; j < 10_000; ++j) {
w.write("" + (base + j));
}
};
threads[i] = new Thread(task);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
}
List<String> lines = Files.readAllLines(tmp, StandardCharsets.UTF_8);
int N = 40_000;
Assertions.assertEquals(N, lines.size());
Assertions.assertEquals(N * (N - 1) / 2, lines.stream().mapToInt(Integer::parseInt).sum());
Files.deleteIfExists(tmp);
}
}
| 5,920 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarMaxGauge.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
/**
* Max gauge that writes updates in format compatible with SpectatorD.
*/
class SidecarMaxGauge extends SidecarMeter implements Gauge {
private final SidecarWriter writer;
/** Create a new instance. */
SidecarMaxGauge(Id id, SidecarWriter writer) {
super(id, 'm');
this.writer = writer;
}
@Override public void set(double v) {
writer.write(idString, v);
}
@Override public double value() {
return Double.NaN;
}
}
| 5,921 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/CommonTags.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Helper for accessing common tags that are specific to a process and thus cannot be
* managed by a shared spectatord instance.
*/
final class CommonTags {
private CommonTags() {
}
/**
* Extract common infrastructure tags from the Netflix environment variables.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @return
* Common tags based on the environment.
*/
static Map<String, String> commonTags(Function<String, String> getenv) {
Map<String, String> tags = new HashMap<>();
putIfNotEmptyOrNull(getenv, tags, "nf.container", "TITUS_CONTAINER_NAME");
putIfNotEmptyOrNull(getenv, tags, "nf.process", "NETFLIX_PROCESS_NAME");
return tags;
}
private static void putIfNotEmptyOrNull(
Function<String, String> getenv, Map<String, String> tags, String key, String... envVars) {
for (String envVar : envVars) {
String value = getenv.apply(envVar);
if (value != null) {
value = value.trim();
if (!value.isEmpty()) {
tags.put(key, value.trim());
break;
}
}
}
}
}
| 5,922 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarCounter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
/**
* Counter that writes updates in format compatible with SpectatorD.
*/
class SidecarCounter extends SidecarMeter implements Counter {
private final SidecarWriter writer;
/** Create a new instance. */
SidecarCounter(Id id, SidecarWriter writer) {
super(id, 'c');
this.writer = writer;
}
@Override public void increment() {
writer.write(idString, 1L);
}
@Override public void increment(long delta) {
if (delta > 0L) {
writer.write(idString, delta);
}
}
@Override public void add(double amount) {
if (amount > 0.0) {
writer.write(idString, amount);
}
}
@Override public double actualCount() {
return Double.NaN;
}
}
| 5,923 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarWriter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
/** Base type for writer that accepts SpectatorD line protocol. */
abstract class SidecarWriter implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(SidecarWriter.class);
/**
* Create a new writer based on a location string.
*/
static SidecarWriter create(String location) {
try {
if ("none".equals(location)) {
return new NoopWriter();
} else if ("stderr".equals(location)) {
return new PrintStreamWriter(location, System.err);
} else if ("stdout".equals(location)) {
return new PrintStreamWriter(location, System.out);
} else if (location.startsWith("file://")) {
OutputStream out = Files.newOutputStream(Paths.get(URI.create(location)));
PrintStream stream = new PrintStream(out, false, "UTF-8");
return new PrintStreamWriter(location, stream);
} else if (location.startsWith("udp://")) {
URI uri = URI.create(location);
String host = uri.getHost();
int port = uri.getPort();
SocketAddress address = new InetSocketAddress(host, port);
return new UdpWriter(location, address);
} else {
throw new IllegalArgumentException("unsupported location: " + location);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final String location;
private volatile boolean suppressWarnings;
SidecarWriter(String location) {
this.location = location;
this.suppressWarnings = false;
}
abstract void writeImpl(String line) throws IOException;
void write(String line) {
try {
LOGGER.trace("writing to {}: {}", location, line);
writeImpl(line);
} catch (IOException e) {
// Some writers such as the UDP writer can be quite noisy if the sidecar is not present.
// To avoid spamming the user with warnings, they will be suppressed after a warning is
// logged. Note, in some cases UDP writes will fail without throwing an exception.
if (!suppressWarnings) {
LOGGER.warn("write to {} failed: {}", location, line, e);
suppressWarnings = true;
}
}
}
void write(String prefix, long value) {
write(prefix + value);
}
void write(String prefix, double value) {
write(prefix + value);
}
}
| 5,924 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarTimer.java | /*
* Copyright 2014-2023 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Timer;
import java.util.concurrent.TimeUnit;
/**
* Timer that writes updates in format compatible with SpectatorD.
*/
class SidecarTimer extends SidecarMeter implements Timer {
private final Clock clock;
private final SidecarWriter writer;
/** Create a new instance. */
SidecarTimer(Id id, Clock clock, SidecarWriter writer) {
super(id, 't');
this.clock = clock;
this.writer = writer;
}
@Override public Clock clock() {
return clock;
}
@Override public void record(long amount, TimeUnit unit) {
final double seconds = unit.toNanos(amount) / 1e9;
if (seconds >= 0.0) {
writer.write(idString, seconds);
}
}
@Override public long count() {
return 0L;
}
@Override public long totalTime() {
return 0L;
}
}
| 5,925 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/NoopWriter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.io.IOException;
/** Writer that does nothing. Used to disable output. */
final class NoopWriter extends SidecarWriter {
/** Create a new instance. */
NoopWriter() {
super("none");
}
@Override void writeImpl(String line) throws IOException {
}
@Override public void close() throws IOException {
}
}
| 5,926 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarRegistry.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.TagList;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.patterns.PolledMeter;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Registry for reporting data to <a href="https://github.com/Netflix-Skunkworks/spectatord">
* SpectatorD</a>.
*/
public final class SidecarRegistry implements Registry, Closeable {
private final Clock clock;
private final TagList commonTags;
private final SidecarWriter writer;
private final ConcurrentHashMap<Id, Object> state;
/** Create a new instance. */
public SidecarRegistry(Clock clock, SidecarConfig config) {
this(clock, config, SidecarWriter.create(config.outputLocation()));
}
/** Create a new instance. */
SidecarRegistry(Clock clock, SidecarConfig config, SidecarWriter writer) {
this.clock = clock;
this.commonTags = TagList.create(config.commonTags());
this.writer = writer;
this.state = new ConcurrentHashMap<>();
}
/**
* Stop the scheduler reporting data.
*/
@Override public void close() throws IOException {
writer.close();
state.clear();
}
@Override
public Clock clock() {
return clock;
}
@Override
public Id createId(String name) {
return Id.create(name);
}
@Override
public Id createId(String name, Iterable<Tag> tags) {
return Id.create(name).withTags(tags);
}
@Deprecated
@Override
public void register(Meter meter) {
PolledMeter.monitorMeter(this, meter);
}
@Override
public ConcurrentMap<Id, Object> state() {
return state;
}
private Id mergeCommonTags(Id id) {
return commonTags.size() == 0 ? id : id.withTags(commonTags);
}
@Override
public Counter counter(Id id) {
return new SidecarCounter(mergeCommonTags(id), writer);
}
@Override
public DistributionSummary distributionSummary(Id id) {
return new SidecarDistributionSummary(mergeCommonTags(id), writer);
}
@Override
public Timer timer(Id id) {
return new SidecarTimer(mergeCommonTags(id), clock, writer);
}
@Override
public Gauge gauge(Id id) {
return new SidecarGauge(mergeCommonTags(id), writer);
}
@Override
public Gauge maxGauge(Id id) {
return new SidecarMaxGauge(mergeCommonTags(id), writer);
}
@Override
public Meter get(Id id) {
return null;
}
@Override
public Iterator<Meter> iterator() {
return Collections.emptyIterator();
}
}
| 5,927 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarMeter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.impl.AsciiSet;
import java.util.Collections;
/** Base class for core meter types used by {@link SidecarRegistry}. */
abstract class SidecarMeter implements Meter {
private static final AsciiSet ALLOWED_CHARS = AsciiSet.fromPattern("-._A-Za-z0-9~^");
/** Base identifier for all measurements supplied by this meter. */
protected final Id id;
/** Prefix string for line to output to SpectatorD. */
protected final String idString;
/** Create a new instance. */
SidecarMeter(Id id, char type) {
this.id = id;
this.idString = createIdString(id, type);
}
private String replaceInvalidChars(String s) {
return ALLOWED_CHARS.replaceNonMembers(s, '_');
}
private String createIdString(Id id, char type) {
StringBuilder builder = new StringBuilder();
builder.append(type).append(':').append(replaceInvalidChars(id.name()));
int n = id.size();
for (int i = 1; i < n; ++i) {
String k = replaceInvalidChars(id.getKey(i));
String v = replaceInvalidChars(id.getValue(i));
builder.append(',').append(k).append('=').append(v);
}
return builder.append(':').toString();
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
}
| 5,928 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/PrintStreamWriter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.io.IOException;
import java.io.PrintStream;
/** Writer that outputs data to a PrintStream instance. */
final class PrintStreamWriter extends SidecarWriter {
private final PrintStream stream;
/** Create a new instance. */
PrintStreamWriter(String location, PrintStream stream) {
super(location);
this.stream = stream;
}
@Override public void writeImpl(String line) throws IOException {
stream.println(line);
}
@Override public void close() throws IOException {
stream.close();
}
}
| 5,929 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/UdpWriter.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
/** Writer that outputs data to UDP socket. */
final class UdpWriter extends SidecarWriter {
private final DatagramChannel channel;
/** Create a new instance. */
UdpWriter(String location, SocketAddress address) throws IOException {
super(location);
this.channel = DatagramChannel.open();
this.channel.connect(address);
}
@Override public void writeImpl(String line) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(line.getBytes(StandardCharsets.UTF_8));
channel.write(buffer);
}
@Override public void close() throws IOException {
channel.close();
}
}
| 5,930 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarConfig.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.RegistryConfig;
import java.util.Map;
/**
* Configuration for sidecar registry.
*/
public interface SidecarConfig extends RegistryConfig {
/**
* Returns the location for where to emit the data. The default is
* {@code udp://127.0.0.1:1234}. Supported values include:
*
* <ul>
* <li><code>none</code>: to disable output.</li>
* <li><code>stdout</code>: write to standard out for the process.</li>
* <li><code>stderr</code>: write to standard error for the process.</li>
* <li><code>file://$path_to_file</code>: write to a file.</li>
* <li><code>udp://$host:$port</code>: write to a UDP socket.</li>
* </ul>
*/
default String outputLocation() {
String v = get("sidecar.output-location");
return (v == null) ? "udp://127.0.0.1:1234" : v;
}
/**
* Returns the common tags to apply to all metrics.
*/
default Map<String, String> commonTags() {
return CommonTags.commonTags(System::getenv);
}
}
| 5,931 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarGauge.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
/**
* Gauge that writes updates in format compatible with SpectatorD.
*/
class SidecarGauge extends SidecarMeter implements Gauge {
private final SidecarWriter writer;
/** Create a new instance. */
SidecarGauge(Id id, SidecarWriter writer) {
super(id, 'g');
this.writer = writer;
}
@Override public void set(double v) {
writer.write(idString, v);
}
@Override public double value() {
return Double.NaN;
}
}
| 5,932 |
0 | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-sidecar/src/main/java/com/netflix/spectator/sidecar/SidecarDistributionSummary.java | /*
* Copyright 2014-2022 Netflix, Inc.
*
* 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 com.netflix.spectator.sidecar;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
/**
* Distribution summary that writes updates in format compatible with SpectatorD.
*/
class SidecarDistributionSummary extends SidecarMeter implements DistributionSummary {
private final SidecarWriter writer;
/** Create a new instance. */
SidecarDistributionSummary(Id id, SidecarWriter writer) {
super(id, 'd');
this.writer = writer;
}
@Override public void record(long amount) {
if (amount >= 0) {
writer.write(idString, amount);
}
}
@Override public long count() {
return 0L;
}
@Override public long totalAmount() {
return 0L;
}
}
| 5,933 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/ServoCounterTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.Monitor;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.ManualClock;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ServoCounterTest {
private final ManualClock clock = new ManualClock();
private Counter newCounter(String name) {
final ServoRegistry r = Servo.newRegistry(clock);
return r.newCounter(r.createId(name));
}
@BeforeEach
public void before() {
clock.setWallTime(0L);
clock.setMonotonicTime(0L);
}
@Test
public void testInit() {
Counter c = newCounter("foo");
Assertions.assertEquals(c.count(), 0L);
c.increment();
Assertions.assertEquals(c.count(), 1L);
}
@Test
public void expiration() {
final long initTime = TimeUnit.MINUTES.toMillis(30);
final long fifteenMinutes = TimeUnit.MINUTES.toMillis(15);
// Not expired on init, wait for activity to mark as active
clock.setWallTime(initTime);
Counter c = newCounter("foo");
Assertions.assertFalse(c.hasExpired());
c.increment(42);
Assertions.assertFalse(c.hasExpired());
// Expires with inactivity, total count in memory is maintained
clock.setWallTime(initTime + fifteenMinutes);
Assertions.assertFalse(c.hasExpired());
// Expires with inactivity, total count in memory is maintained
clock.setWallTime(initTime + fifteenMinutes + 1);
Assertions.assertEquals(c.count(), 42);
Assertions.assertTrue(c.hasExpired());
// Activity brings it back
c.increment();
Assertions.assertEquals(c.count(), 43);
Assertions.assertFalse(c.hasExpired());
}
@Test
public void hasStatistic() {
List<Monitor<?>> ms = new ArrayList<>();
Counter c = newCounter("foo");
((ServoCounter) c).addMonitors(ms);
Assertions.assertEquals(1, ms.size());
Assertions.assertEquals("count", ms.get(0).getConfig().getTags().getValue("statistic"));
}
}
| 5,934 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/ServoRegistryTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.MonitorRegistry;
import com.netflix.spectator.api.CompositeRegistry;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.function.Function;
public class ServoRegistryTest {
@Test
public void multiRegistration() {
// Servo uses statics internally and the indended use of ServoRegistry
// is there would be one in use at a given time. We don't want to make
// it a singleton because that would break some existing unit tests that
// expect isolated counts from the spectator api. This test just verifies
// that multiple registrations can coexist in servo and will not clobber
// each other.
MonitorRegistry mr = Servo.getInstance();
ServoRegistry r1 = Servo.newRegistry();
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r1));
ServoRegistry r2 = Servo.newRegistry();
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r1));
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r2));
ServoRegistry r3 = Servo.newRegistry();
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r1));
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r2));
Assertions.assertTrue(mr.getRegisteredMonitors().contains(r3));
}
@Test
public void iteratorDoesNotContainNullMeters() {
Registry dflt = Servo.newRegistry();
boolean found = false;
Counter counter = dflt.counter("servo.testCounter");
for (Meter m : dflt) {
found = m.id().equals(counter.id());
}
Assertions.assertTrue(found, "id could not be found in iterator");
}
// Reproduces: https://github.com/Netflix/spectator/issues/530
public void globalIterator(Function<Registry, Meter> createMeter) {
Registry dflt = Servo.newRegistry();
CompositeRegistry global = Spectator.globalRegistry();
global.removeAll();
global.add(dflt);
boolean found = false;
Id expected = createMeter.apply(dflt).id();
for (Meter m : global) {
found |= m.id().equals(expected);
}
Assertions.assertTrue(found, "id for sub-registry could not be found in global iterator");
}
@Test
public void globalIteratorCounter() {
globalIterator(r -> r.counter("servo.testCounter"));
}
@Test
public void globalIteratorGauge() {
globalIterator(r -> r.gauge("servo.testGauge"));
}
@Test
public void globalIteratorTimer() {
globalIterator(r -> r.timer("servo.testTimer"));
}
@Test
public void globalIteratorDistSummary() {
globalIterator(r -> r.distributionSummary("servo.testDistSummary"));
}
@Test
public void keepNonExpired() {
ManualClock clock = new ManualClock();
ServoRegistry registry = Servo.newRegistry(clock);
registry.counter("test").increment();
Assertions.assertEquals(1, registry.getMonitors().size());
Assertions.assertEquals(1, registry.counters().count());
}
@Test
public void removesExpired() {
ManualClock clock = new ManualClock();
ServoRegistry registry = Servo.newRegistry(clock);
registry.counter("test").increment();
clock.setWallTime(60000 * 30);
Assertions.assertEquals(0, registry.getMonitors().size());
Assertions.assertEquals(0, registry.counters().count());
}
@Test
public void resurrectExpiredAndIncrement() {
ManualClock clock = new ManualClock();
ServoRegistry registry = Servo.newRegistry(clock);
Counter c = registry.counter("test");
clock.setWallTime(60000 * 30);
registry.getMonitors();
Assertions.assertTrue(c.hasExpired());
c.increment();
Assertions.assertEquals(1, c.count());
Assertions.assertEquals(1, registry.counter("test").count());
clock.setWallTime(60000 * 60);
registry.getMonitors();
Assertions.assertTrue(c.hasExpired());
c.increment();
Assertions.assertEquals(1, c.count());
Assertions.assertEquals(1, registry.counter("test").count());
}
}
| 5,935 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/Servo.java | /*
* Copyright 2014-2020 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.MonitorRegistry;
import com.netflix.spectator.api.Clock;
final class Servo {
static {
System.setProperty(
"com.netflix.servo.DefaultMonitorRegistry.registryClass",
"com.netflix.servo.jmx.JmxMonitorRegistry");
}
static MonitorRegistry getInstance() {
return DefaultMonitorRegistry.getInstance();
}
static ServoRegistry newRegistry() {
return new ServoRegistry();
}
static ServoRegistry newRegistry(Clock clock) {
return new ServoRegistry(clock);
}
}
| 5,936 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/ServoGaugeTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.Monitor;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Measurement;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ServoGaugeTest {
private final ManualClock clock = new ManualClock();
private Gauge newGauge(String name) {
final ServoRegistry r = Servo.newRegistry(clock);
return r.newGauge(r.createId(name));
}
@BeforeEach
public void before() {
clock.setWallTime(0L);
clock.setMonotonicTime(0L);
}
@Test
public void testInit() {
Gauge g = newGauge("foo");
Assertions.assertEquals(g.value(), Double.NaN, 1e-12);
g.set(1.0);
Assertions.assertEquals(g.value(), 1.0, 1e-12);
}
@Test
public void testGet() {
final ServoRegistry r = Servo.newRegistry(clock);
Gauge g = r.gauge(r.createId("foo"));
g.set(1.0);
Assertions.assertEquals(1, r.getMonitors().size());
Assertions.assertEquals(1.0, (Double) r.getMonitors().get(0).getValue(0), 1e-12);
}
@Test
public void expiration() {
final long initTime = TimeUnit.MINUTES.toMillis(30);
final long fifteenMinutes = TimeUnit.MINUTES.toMillis(15);
// Not expired on init, wait for activity to mark as active
clock.setWallTime(initTime);
Gauge g = newGauge("foo");
Assertions.assertFalse(g.hasExpired());
g.set(42.0);
Assertions.assertFalse(g.hasExpired());
Assertions.assertEquals(g.value(), 42.0, 1e-12);
// Expires with inactivity
clock.setWallTime(initTime + fifteenMinutes);
Assertions.assertFalse(g.hasExpired());
// Expires with inactivity
clock.setWallTime(initTime + fifteenMinutes + 1);
Assertions.assertEquals(g.value(), Double.NaN, 1e-12);
Assertions.assertTrue(g.hasExpired());
// Activity brings it back
g.set(1.0);
Assertions.assertEquals(g.value(), 1.0, 1e-12);
Assertions.assertFalse(g.hasExpired());
}
@Test
public void hasGaugeType() {
final ServoRegistry r = Servo.newRegistry(clock);
Gauge g = r.gauge(r.createId("foo"));
g.set(1.0);
Map<String, String> tags = r.getMonitors().get(0).getConfig().getTags().asMap();
Assertions.assertEquals("GAUGE", tags.get("type"));
}
@Test
public void measure() {
final ServoRegistry r = Servo.newRegistry(clock);
Gauge g = r.gauge(r.createId("foo"));
g.set(1.0);
Iterator<Measurement> ms = g.measure().iterator();
Assertions.assertTrue(ms.hasNext());
Measurement m = ms.next();
Assertions.assertFalse(ms.hasNext());
Assertions.assertEquals("foo", m.id().name());
Assertions.assertEquals(1.0, 1.0, 1e-12);
}
@Test
@SuppressWarnings("unchecked")
public void hasStatistic() {
List<Monitor<?>> ms = new ArrayList<>();
Gauge g = newGauge("foo");
((ServoGauge) g).addMonitors(ms);
Assertions.assertEquals(1, ms.size());
Assertions.assertEquals("gauge", ms.get(0).getConfig().getTags().getValue("statistic"));
}
}
| 5,937 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/ServoTimerTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.Utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class ServoTimerTest {
private final ManualClock clock = new ManualClock();
private Timer newTimer(String name) {
final Registry r = Servo.newRegistry(clock);
return r.timer(r.createId(name));
}
@BeforeEach
public void before() {
clock.setWallTime(0L);
clock.setMonotonicTime(0L);
}
@Test
public void testInit() {
Timer t = newTimer("foo");
Assertions.assertEquals(t.count(), 0L);
Assertions.assertEquals(t.totalTime(), 0L);
}
@Test
public void testRecord() {
Timer t = newTimer("foo");
t.record(42, TimeUnit.MILLISECONDS);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 42000000L);
}
@Test
public void testRecordNegative() {
Timer t = newTimer("foo");
t.record(-42, TimeUnit.MILLISECONDS);
Assertions.assertEquals(t.count(), 0L);
Assertions.assertEquals(t.totalTime(), 0L);
}
@Test
public void testRecordZero() {
Timer t = newTimer("foo");
t.record(0, TimeUnit.MILLISECONDS);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 0L);
}
@Test
public void testRecordCallable() throws Exception {
Timer t = newTimer("foo");
clock.setMonotonicTime(100L);
int v = t.record(() -> {
clock.setMonotonicTime(500L);
return 42;
});
Assertions.assertEquals(v, 42);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 400L);
}
@Test
public void testRecordCallableException() throws Exception {
Timer t = newTimer("foo");
clock.setMonotonicTime(100L);
boolean seen = false;
try {
t.record((Callable<Integer>) () -> {
clock.setMonotonicTime(500L);
throw new RuntimeException("foo");
});
} catch (Exception e) {
seen = true;
}
Assertions.assertTrue(seen);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 400L);
}
@Test
public void testRecordRunnable() throws Exception {
Timer t = newTimer("foo");
clock.setMonotonicTime(100L);
t.record(() -> clock.setMonotonicTime(500L));
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 400L);
}
@Test
public void testRecordRunnableException() throws Exception {
Timer t = newTimer("foo");
clock.setMonotonicTime(100L);
boolean seen = false;
try {
t.record((Runnable) () -> {
clock.setMonotonicTime(500L);
throw new RuntimeException("foo");
});
} catch (Exception e) {
seen = true;
}
Assertions.assertTrue(seen);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalTime(), 400L);
}
@Test
public void testMeasure() {
Timer t = newTimer("foo");
t.record(42, TimeUnit.MILLISECONDS);
clock.setWallTime(61000L);
for (Measurement m : t.measure()) {
Assertions.assertEquals(m.timestamp(), 61000L);
final double count = Utils.first(t.measure(), Statistic.count).value();
final double totalTime = Utils.first(t.measure(), Statistic.totalTime).value();
Assertions.assertEquals(count, 1.0 / 60.0, 0.1e-12);
Assertions.assertEquals(totalTime, 42e-3 / 60.0, 0.1e-12);
}
}
@Test
public void totalOfSquaresOverflow() {
final long seconds = 10;
final long nanos = TimeUnit.SECONDS.toNanos(seconds);
final BigInteger s = new BigInteger("" + nanos);
final BigInteger s2 = s.multiply(s);
Timer t = newTimer("foo");
t.record(seconds, TimeUnit.SECONDS);
clock.setWallTime(61000L);
final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();
final double factor = 1e9 * 1e9;
final BigInteger perSec = s2.divide(BigInteger.valueOf(60));
Assertions.assertEquals(perSec.doubleValue() / factor, v, 1e-12);
}
@Test
public void totalOfSquaresManySmallValues() {
Timer t = newTimer("foo");
BigInteger sumOfSq = new BigInteger("0");
for (int i = 0; i < 100000; ++i) {
final long nanos = i;
final BigInteger s = new BigInteger("" + nanos);
final BigInteger s2 = s.multiply(s);
sumOfSq = sumOfSq.add(s2);
t.record(i, TimeUnit.NANOSECONDS);
}
clock.setWallTime(61000L);
final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();
final double factor = 1e9 * 1e9;
sumOfSq = sumOfSq.divide(BigInteger.valueOf(60));
Assertions.assertEquals(sumOfSq.doubleValue() / factor, v, 1e-12);
}
@Test
public void totalOfSquaresManyBigValues() {
Timer t = newTimer("foo");
BigInteger sumOfSq = new BigInteger("0");
for (int i = 0; i < 100000; ++i) {
final long nanos = TimeUnit.SECONDS.toNanos(i);
final BigInteger s = new BigInteger("" + nanos);
final BigInteger s2 = s.multiply(s);
sumOfSq = sumOfSq.add(s2);
t.record(i, TimeUnit.SECONDS);
}
clock.setWallTime(61000L);
final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();
// Expected :3.3332833335E14
// Actual :3.3332833334999825E14
final double factor = 1e9 * 1e9;
sumOfSq = sumOfSq.divide(BigInteger.valueOf(60));
Assertions.assertEquals(sumOfSq.doubleValue() / factor, v, 2.0);
}
@Test
public void expiration() {
final long initTime = TimeUnit.MINUTES.toMillis(30);
final long fifteenMinutes = TimeUnit.MINUTES.toMillis(15);
// Not expired on init, wait for activity to mark as active
clock.setWallTime(initTime);
Timer t = newTimer("foo");
Assertions.assertFalse(t.hasExpired());
t.record(1, TimeUnit.SECONDS);
Assertions.assertFalse(t.hasExpired());
// Expires with inactivity
clock.setWallTime(initTime + fifteenMinutes + 1);
Assertions.assertTrue(t.hasExpired());
// Activity brings it back
t.record(42, TimeUnit.SECONDS);
Assertions.assertFalse(t.hasExpired());
}
}
| 5,938 |
0 | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/test/java/com/netflix/spectator/servo/DoubleCounterTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 com.netflix.spectator.servo;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.util.ManualClock;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class DoubleCounterTest {
private static final double DELTA = 1e-06;
private final ManualClock clock = new ManualClock(ServoPollers.POLLING_INTERVALS[1]);
private DoubleCounter newInstance(String name) {
return new DoubleCounter(MonitorConfig.builder(name).build(), clock);
}
private long time(long t) {
return t * 1000 + ServoPollers.POLLING_INTERVALS[1];
}
@Test
public void testSimpleTransition() {
clock.set(time(1));
DoubleCounter c = newInstance("c");
Assertions.assertEquals(0.0, c.getValue(1).doubleValue(), DELTA);
clock.set(time(3));
c.increment(1);
Assertions.assertEquals(0.0, c.getValue(1).doubleValue(), DELTA);
clock.set(time(9));
c.increment(1);
Assertions.assertEquals(0.0, c.getValue(1).doubleValue(), DELTA);
clock.set(time(12));
c.increment(1);
Assertions.assertEquals(2.0 / 10.0, c.getValue(1).doubleValue(), DELTA);
}
@Test
public void testInitialPollIsZero() {
clock.set(time(1));
DoubleCounter c = newInstance("foo");
Assertions.assertEquals(0.0, c.getValue(1).doubleValue(), DELTA);
}
@Test
public void testHasRightType() throws Exception {
Assertions.assertEquals(newInstance("foo").getConfig().getTags().getValue(DataSourceType.KEY),
"NORMALIZED");
}
@Test
public void testBoundaryTransition() {
clock.set(time(1));
DoubleCounter c = newInstance("foo");
// Should all go to one bucket
c.increment(1);
clock.set(time(4));
c.increment(1);
clock.set(time(9));
c.increment(1);
// Should cause transition
clock.set(time(10));
c.increment(1);
clock.set(time(19));
c.increment(1);
// Check counts
Assertions.assertEquals(0.3, c.getValue(1).doubleValue(), DELTA);
}
@Test
public void testResetPreviousValue() {
clock.set(time(1));
DoubleCounter c = newInstance("foo");
for (int i = 1; i <= 100000; ++i) {
c.increment(1);
clock.set(time(i * 10 + 1));
Assertions.assertEquals(0.1, c.getValue(1).doubleValue(), DELTA);
}
}
@Test
public void testMissedInterval() {
clock.set(time(1));
DoubleCounter c = newInstance("foo");
c.getValue(1);
// Multiple updates without polling
c.increment(1);
clock.set(time(4));
c.increment(1);
clock.set(time(14));
c.increment(1);
clock.set(time(24));
c.increment(1);
clock.set(time(34));
c.increment(1);
// Check counts
Assertions.assertTrue(Double.isNaN(c.getValue(1).doubleValue()));
}
@Test
public void testNonMonotonicClock() {
clock.set(time(1));
DoubleCounter c = newInstance("foo");
c.getValue(1);
c.increment(1);
c.increment(1);
clock.set(time(10));
c.increment(1);
clock.set(time(9)); // Should get ignored
c.increment(1);
c.increment(1);
clock.set(time(10));
c.increment(1);
c.increment(1);
// Check rate for previous interval
Assertions.assertEquals(0.2, c.getValue(1).doubleValue(), DELTA);
}
@Test
public void testGetValueTwice() {
ManualClock manualClock = new ManualClock(0L);
DoubleCounter c = new DoubleCounter(MonitorConfig.builder("test").build(), manualClock);
c.increment(1);
for (int i = 1; i < 10; ++i) {
manualClock.set(i * 60000L);
c.increment(1);
c.getValue(0);
Assertions.assertEquals(1 / 60.0, c.getValue(0).doubleValue(), DELTA);
}
}
}
| 5,939 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoRegistry.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.monitor.*;
import com.netflix.spectator.api.*;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.impl.SwapMeter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Registry that maps spectator types to servo.
*
* @deprecated Servo is deprecated and we do not encourage new use of this implementation.
* Consider use of another implementation. This class is scheduled for removal in a future
* release.
*/
@Deprecated
public class ServoRegistry extends AbstractRegistry implements CompositeMonitor<Integer> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServoRegistry.class);
/**
* The amount of time in milliseconds after which activity based meters will get marked as
* expired. Right now they will not go away completely so the total count for the life of the
* process can be maintained in the api.
*
* The configuration setting is in minutes.
*/
static final long EXPIRATION_TIME_MILLIS = getExpirationTimeMillis();
private static long getExpirationTimeMillis() {
final String key = "spectator.servo.expirationTimeInMinutes";
long minutes = 15;
String v = System.getProperty(key, "" + minutes);
try {
minutes = Long.parseLong(v);
} catch (NumberFormatException e) {
LOGGER.error("invalid value for property '" + key + "', expecting integer: '" + v + "'."
+ " The default value of " + minutes + " minutes will be used.", e);
}
return TimeUnit.MINUTES.toMillis(minutes);
}
// Create an id for the composite monitor that will be used with Servo. This
// id will not get reported since the composite will get flattened. The UUID
// is to avoid having multiple instances of ServoRegistry clobber each other.
private MonitorConfig defaultConfig() {
return (new MonitorConfig.Builder("spectator.registry"))
.withTag("id", UUID.randomUUID().toString()).build();
}
private final MonitorConfig config;
/** Create a new instance. */
public ServoRegistry() {
this(Clock.SYSTEM);
}
/** Create a new instance. */
public ServoRegistry(Clock clock) {
this(clock, null);
}
/** Create a new instance. */
ServoRegistry(Clock clock, MonitorConfig config) {
super(clock);
this.config = (config == null) ? defaultConfig() : config;
DefaultMonitorRegistry.getInstance().register(this);
}
/** Converts a spectator id into a MonitorConfig that can be used by servo. */
MonitorConfig toMonitorConfig(Id id, Tag stat) {
MonitorConfig.Builder builder = new MonitorConfig.Builder(id.name());
if (stat != null) {
builder.withTag(stat.key(), stat.value());
}
for (Tag t : id.tags()) {
builder.withTag(t.key(), t.value());
}
return builder.build();
}
@Override protected Counter newCounter(Id id) {
MonitorConfig cfg = toMonitorConfig(id, Statistic.count);
DoubleCounter counter = new DoubleCounter(cfg, new ServoClock(clock()));
return new ServoCounter(id, clock(), counter);
}
@Override protected DistributionSummary newDistributionSummary(Id id) {
return new ServoDistributionSummary(this, id);
}
@Override protected Timer newTimer(Id id) {
return new ServoTimer(this, id);
}
@Override protected Gauge newGauge(Id id) {
return new ServoGauge(id, clock(), toMonitorConfig(id, Statistic.gauge));
}
@Override protected Gauge newMaxGauge(Id id) {
return new ServoMaxGauge(id, clock(), toMonitorConfig(id, Statistic.max));
}
@Override public Integer getValue() {
return 0;
}
@Override public Integer getValue(int pollerIndex) {
return 0;
}
@Override public MonitorConfig getConfig() {
return config;
}
@Override public List<Monitor<?>> getMonitors() {
List<Monitor<?>> monitors = new ArrayList<>();
for (Meter meter : this) {
ServoMeter sm = getServoMeter(meter);
if (!meter.hasExpired() && sm != null) {
sm.addMonitors(monitors);
}
}
removeExpiredMeters();
return monitors;
}
@SuppressWarnings("unchecked")
private ServoMeter getServoMeter(Meter meter) {
if (meter instanceof SwapMeter<?>) {
return getServoMeter(((SwapMeter<?>) meter).get());
} else if (meter instanceof ServoMeter) {
return (ServoMeter) meter;
} else {
return null;
}
}
}
| 5,940 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoClock.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.spectator.api.Clock;
/**
* Servo clock based on spectator clock.
*/
class ServoClock implements com.netflix.servo.util.Clock {
private final Clock impl;
/** Create a new instance. */
ServoClock(Clock c) {
this.impl = c;
}
@Override public long now() {
return impl.wallTime();
}
}
| 5,941 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/StepLong.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.util.Clock;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
/**
* Utility class for managing a set of AtomicLong instances mapped to a particular step interval.
* The current implementation keeps an array of with two items where one is the current value
* being updated and the other is the value from the previous interval and is only available for
* polling.
*/
class StepLong {
private static final int PREVIOUS = 0;
private static final int CURRENT = 1;
private final long init;
private final Clock clock;
private final AtomicLong[] data;
private final AtomicLong[] lastPollTime;
private final AtomicLong[] lastInitPos;
/** Create a new instance. */
StepLong(long init, Clock clock) {
this.init = init;
this.clock = clock;
lastInitPos = new AtomicLong[ServoPollers.NUM_POLLERS];
lastPollTime = new AtomicLong[ServoPollers.NUM_POLLERS];
for (int i = 0; i < ServoPollers.NUM_POLLERS; ++i) {
lastInitPos[i] = new AtomicLong(0L);
lastPollTime[i] = new AtomicLong(0L);
}
data = new AtomicLong[2 * ServoPollers.NUM_POLLERS];
for (int i = 0; i < data.length; ++i) {
data[i] = new AtomicLong(init);
}
}
/** Add to the current bucket. */
void addAndGet(long amount) {
for (int i = 0; i < ServoPollers.NUM_POLLERS; ++i) {
getCurrent(i).addAndGet(amount);
}
}
private void rollCount(int pollerIndex, long now) {
final long step = ServoPollers.POLLING_INTERVALS[pollerIndex];
final long stepTime = now / step;
final long lastInit = lastInitPos[pollerIndex].get();
if (lastInit < stepTime && lastInitPos[pollerIndex].compareAndSet(lastInit, stepTime)) {
final int prev = 2 * pollerIndex + PREVIOUS;
final int curr = 2 * pollerIndex + CURRENT;
data[prev].set(data[curr].getAndSet(init));
}
}
/** Get the AtomicLong for the current bucket. */
AtomicLong getCurrent(int pollerIndex) {
rollCount(pollerIndex, clock.now());
return data[2 * pollerIndex + CURRENT];
}
/** Get the value for the last completed interval. */
Long poll(int pollerIndex) {
final long now = clock.now();
final long step = ServoPollers.POLLING_INTERVALS[pollerIndex];
rollCount(pollerIndex, now);
final int prevPos = 2 * pollerIndex + PREVIOUS;
final long value = data[prevPos].get();
final long last = lastPollTime[pollerIndex].getAndSet(now);
final long missed = (now - last) / step - 1;
if (last / step == now / step) {
return value;
} else if (last > 0L && missed > 0L) {
return null;
} else {
return value;
}
}
@Override public String toString() {
return "StepLong{init=" + init
+ ", data=" + Arrays.toString(data)
+ ", lastPollTime=" + Arrays.toString(lastPollTime)
+ ", lastInitPos=" + Arrays.toString(lastInitPos) + '}';
}
}
| 5,942 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoTimer.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.MaxGauge;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.NumericMonitor;
import com.netflix.servo.monitor.StepCounter;
import com.netflix.spectator.api.AbstractTimer;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Tag;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** Timer implementation for the servo registry. */
class ServoTimer extends AbstractTimer implements ServoMeter {
private static final double CNV_SECONDS = 1.0 / TimeUnit.SECONDS.toNanos(1L);
private static final double CNV_SQUARES = CNV_SECONDS * CNV_SECONDS;
private final Id id;
// Local count so that we have more flexibility on servo counter impl without changing the
// value returned by the {@link #count()} method.
private final AtomicLong count;
private final AtomicLong totalTime;
private final StepCounter servoCount;
private final StepCounter servoTotal;
private final DoubleCounter servoTotalOfSquares;
private final MaxGauge servoMax;
private final AtomicLong lastUpdated;
/** Create a new instance. */
ServoTimer(ServoRegistry r, Id id) {
super(r.clock());
this.id = id;
count = new AtomicLong(0L);
totalTime = new AtomicLong(0L);
ServoClock sc = new ServoClock(clock);
servoCount = new StepCounter(r.toMonitorConfig(id.withTag(Statistic.count), null), sc);
servoTotal = new StepCounter(r.toMonitorConfig(id.withTag(Statistic.totalTime), null), sc);
servoTotalOfSquares = new DoubleCounter(
r.toMonitorConfig(id.withTag(Statistic.totalOfSquares), null), sc);
// Constructor that takes a clock param is not public
servoMax = new MaxGauge(r.toMonitorConfig(id.withTag(Statistic.max), null));
lastUpdated = new AtomicLong(clock.wallTime());
}
@Override public void addMonitors(List<Monitor<?>> monitors) {
monitors.add(servoCount);
monitors.add(new FactorMonitor<>(servoTotal, CNV_SECONDS));
monitors.add(new FactorMonitor<>(servoTotalOfSquares, CNV_SQUARES));
monitors.add(new FactorMonitor<>(servoMax, CNV_SECONDS));
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
long now = clock.wallTime();
return now - lastUpdated.get() > ServoRegistry.EXPIRATION_TIME_MILLIS;
}
@Override public void record(long amount, TimeUnit unit) {
if (amount >= 0) {
final long nanos = unit.toNanos(amount);
final double nanosSquared = (double) nanos * (double) nanos;
totalTime.addAndGet(nanos);
count.incrementAndGet();
servoTotal.increment(nanos);
servoTotalOfSquares.increment(nanosSquared);
servoCount.increment();
servoMax.update(nanos);
lastUpdated.set(clock.wallTime());
}
}
private Measurement newMeasurement(Tag t, long timestamp, Number n) {
return new Measurement(id.withTag(t), timestamp, n.doubleValue());
}
private double getValue(NumericMonitor<?> m, double factor) {
return m.getValue(0).doubleValue() * factor;
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
final List<Measurement> ms = new ArrayList<>(2);
ms.add(newMeasurement(Statistic.count, now, servoCount.getValue(0)));
ms.add(newMeasurement(Statistic.totalTime, now, getValue(servoTotal, CNV_SECONDS)));
ms.add(newMeasurement(Statistic.totalOfSquares, now, getValue(servoTotalOfSquares, CNV_SQUARES)));
ms.add(newMeasurement(Statistic.max, now, getValue(servoMax, CNV_SECONDS)));
return ms;
}
@Override public long count() {
return count.get();
}
@Override public long totalTime() {
return totalTime.get();
}
}
| 5,943 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoMaxGauge.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.AbstractMonitor;
import com.netflix.servo.monitor.MaxGauge;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.NumericMonitor;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* Reports a constant value passed into the constructor.
*/
final class ServoMaxGauge<T extends Number> extends AbstractMonitor<Double>
implements Gauge, ServoMeter, NumericMonitor<Double> {
private final Id id;
private final Clock clock;
private final MaxGauge impl;
private final AtomicLong lastUpdated;
/**
* Create a new monitor that returns {@code value}.
*/
ServoMaxGauge(Id id, Clock clock, MonitorConfig config) {
super(config.withAdditionalTag(DataSourceType.GAUGE));
this.id = id;
this.clock = clock;
this.impl = new MaxGauge(config);
this.lastUpdated = new AtomicLong(clock.wallTime());
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
long now = clock.wallTime();
return now - lastUpdated.get() > ServoRegistry.EXPIRATION_TIME_MILLIS;
}
@Override public Iterable<Measurement> measure() {
long now = clock.wallTime();
double v = impl.getValue(0).doubleValue();
return Collections.singleton(new Measurement(id(), now, v));
}
@Override public void set(double v) {
impl.update((long) v);
lastUpdated.set(clock.wallTime());
}
@Override public double value() {
return hasExpired() ? Double.NaN : impl.getValue(0).doubleValue();
}
@Override public Double getValue(int pollerIndex) {
return value();
}
@Override public void addMonitors(List<Monitor<?>> monitors) {
monitors.add(this);
}
}
| 5,944 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoDistributionSummary.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.MaxGauge;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.StepCounter;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Statistic;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/** Distribution summary implementation for the servo registry. */
class ServoDistributionSummary implements DistributionSummary, ServoMeter {
private final Clock clock;
private final Id id;
// Local count so that we have more flexibility on servo counter impl without changing the
// value returned by the {@link #count()} method.
private final AtomicLong count;
private final AtomicLong totalAmount;
private final StepCounter servoCount;
private final StepCounter servoTotal;
private final StepCounter servoTotalOfSquares;
private final MaxGauge servoMax;
private final AtomicLong lastUpdated;
/** Create a new instance. */
ServoDistributionSummary(ServoRegistry r, Id id) {
this.clock = r.clock();
this.id = id;
count = new AtomicLong(0L);
totalAmount = new AtomicLong(0L);
servoCount = new StepCounter(r.toMonitorConfig(id.withTag(Statistic.count), null));
servoTotal = new StepCounter(r.toMonitorConfig(id.withTag(Statistic.totalAmount), null));
servoTotalOfSquares = new StepCounter(
r.toMonitorConfig(id.withTag(Statistic.totalOfSquares), null));
servoMax = new MaxGauge(r.toMonitorConfig(id.withTag(Statistic.max), null));
lastUpdated = new AtomicLong(clock.wallTime());
}
@Override public void addMonitors(List<Monitor<?>> monitors) {
monitors.add(servoCount);
monitors.add(servoTotal);
monitors.add(servoTotalOfSquares);
monitors.add(servoMax);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
long now = clock.wallTime();
return now - lastUpdated.get() > ServoRegistry.EXPIRATION_TIME_MILLIS;
}
@Override public void record(long amount) {
if (amount >= 0) {
totalAmount.addAndGet(amount);
count.incrementAndGet();
servoTotal.increment(amount);
servoTotalOfSquares.increment(amount * amount);
servoCount.increment();
servoMax.update(amount);
lastUpdated.set(clock.wallTime());
}
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
final List<Measurement> ms = new ArrayList<>(2);
ms.add(new Measurement(id.withTag(Statistic.count), now, count.get()));
ms.add(new Measurement(id.withTag(Statistic.totalAmount), now, totalAmount.get()));
return ms;
}
@Override public long count() {
return count.get();
}
@Override public long totalAmount() {
return totalAmount.get();
}
}
| 5,945 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoMeter.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.Monitor;
import java.util.List;
/** Meter that can return a servo monitor. */
interface ServoMeter {
/** Returns the monitor corresponding to this meter. */
void addMonitors(List<Monitor<?>> monitors);
}
| 5,946 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/DoubleCounter.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.AbstractMonitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.NumericMonitor;
import com.netflix.servo.util.Clock;
import com.netflix.servo.util.ClockWithOffset;
import java.util.concurrent.atomic.AtomicLong;
/**
* A simple counter implementation backed by a StepLong. The value returned is a rate for the
* previous interval as defined by the step.
*/
class DoubleCounter extends AbstractMonitor<Number> implements NumericMonitor<Number> {
private final StepLong count;
/**
* Creates a new instance of the counter.
*/
DoubleCounter(MonitorConfig config) {
this(config, ClockWithOffset.INSTANCE);
}
/**
* Creates a new instance of the counter.
*/
DoubleCounter(MonitorConfig config, Clock clock) {
// This class will reset the value so it is not a monotonically increasing value as
// expected for type=COUNTER. This class looks like a counter to the user and a gauge to
// the publishing pipeline receiving the value.
super(config.withAdditionalTag(DataSourceType.NORMALIZED));
count = new StepLong(0L, clock);
}
private void add(AtomicLong num, double amount) {
long v;
double d;
long next;
do {
v = num.get();
d = Double.longBitsToDouble(v);
next = Double.doubleToLongBits(d + amount);
} while (!num.compareAndSet(v, next));
}
/**
* Increment the value by the specified amount.
*/
void increment(double amount) {
if (amount >= 0.0) {
for (int i = 0; i < ServoPollers.NUM_POLLERS; ++i) {
add(count.getCurrent(i), amount);
}
}
}
@Override public Number getValue(int pollerIndex) {
final Long dp = count.poll(pollerIndex);
final double stepSeconds = ServoPollers.POLLING_INTERVALS[pollerIndex] / 1000.0;
return (dp == null) ? Double.NaN : Double.longBitsToDouble(dp) / stepSeconds;
}
@Override public String toString() {
return "DoubleCounter(config=" + config + ",count=" + getValue() + ")";
}
}
| 5,947 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoTag.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.spectator.api.Tag;
/** Tag implementation for the servo registry. */
class ServoTag implements Tag {
private final com.netflix.servo.tag.Tag tag;
/** Create a new instance. */
ServoTag(com.netflix.servo.tag.Tag tag) {
this.tag = tag;
}
@Override public String key() {
return tag.getKey();
}
@Override public String value() {
return tag.getValue();
}
}
| 5,948 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/FactorMonitor.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.AbstractMonitor;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.NumericMonitor;
/**
* Multiplies the value from the wrapped monitor by a given factor. Primarily used to perform
* time unit conversions for timer monitors that internally store in nanoseconds but report in
* the base time unit of seconds.
*/
final class FactorMonitor<T extends Number> extends AbstractMonitor<Double>
implements NumericMonitor<Double> {
private final Monitor<T> wrapped;
private final double factor;
/**
* Create a new monitor that returns {@code wrapped.getValue() * factor}.
*
* @param wrapped
* A simple monitor that will have its value converted.
* @param factor
* Conversion factor to apply to the wrapped monitors value.
*/
FactorMonitor(Monitor<T> wrapped, double factor) {
super(wrapped.getConfig());
this.wrapped = wrapped;
this.factor = factor;
}
@Override public Double getValue(int pollerIndex) {
final double v = wrapped.getValue(pollerIndex).doubleValue();
return v * factor;
}
}
| 5,949 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoPollers.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Poller configuration. This class provides the mechanism
* to know how many pollers will be used, and at their estimated polling intervals.
*/
final class ServoPollers {
private ServoPollers() {
}
/**
* A comma separated list of longs indicating the frequency of the pollers. For example: <br/>
* {@code 60000, 10000 }<br/>
* indicates that the main poller runs every 60s and a secondary
* poller will run every 10 seconds.
* This is used to deal with monitors that need to get reset after they're polled.
* For example a MinGauge or a MaxGauge.
*/
static final String POLLERS = System.getProperty("servo.pollers", "60000,10000");
/** Default periods, used if the servo.poller property isn't set. */
static final long[] DEFAULT_PERIODS = {60000L, 10000L};
/**
* Polling intervals in milliseconds.
*/
static final long[] POLLING_INTERVALS = parse(POLLERS);
private static final ImmutableList<Long> POLLING_INTERVALS_AS_LIST;
/**
* Get list of polling intervals in milliseconds.
*/
static List<Long> getPollingIntervals() {
return POLLING_INTERVALS_AS_LIST;
}
/**
* Number of pollers that will run.
*/
static final int NUM_POLLERS = POLLING_INTERVALS.length;
/**
* For debugging. Simple toString for non-empty arrays
*/
private static String join(long[] a) {
assert (a.length > 0);
StringBuilder builder = new StringBuilder();
builder.append(a[0]);
for (int i = 1; i < a.length; ++i) {
builder.append(',');
builder.append(a[i]);
}
return builder.toString();
}
/**
* Parse the content of the system property that describes the polling intervals,
* and in case of errors
* use the default of one poller running every minute.
*/
static long[] parse(String pollers) {
String[] periods = pollers.split(",\\s*");
long[] result = new long[periods.length];
boolean errors = false;
Logger logger = LoggerFactory.getLogger(ServoPollers.class);
for (int i = 0; i < periods.length; ++i) {
String period = periods[i];
try {
result[i] = Long.parseLong(period);
if (result[i] <= 0) {
logger.error("Invalid polling interval: {} must be positive.", period);
errors = true;
}
} catch (NumberFormatException e) {
logger.error("Cannot parse '{}' as a long: {}", period, e.getMessage());
errors = true;
}
}
if (errors || periods.length == 0) {
logger.info("Using a default configuration for poller intervals: {}",
join(DEFAULT_PERIODS));
return DEFAULT_PERIODS;
} else {
return result;
}
}
static {
ImmutableList.Builder<Long> builder = ImmutableList.builder();
for (long pollingInterval : POLLING_INTERVALS) {
builder.add(pollingInterval);
}
POLLING_INTERVALS_AS_LIST = builder.build();
}
}
| 5,950 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoGauge.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.AbstractMonitor;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.NumericMonitor;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* Reports a constant value passed into the constructor.
*/
final class ServoGauge<T extends Number> extends AbstractMonitor<Double>
implements Gauge, ServoMeter, NumericMonitor<Double> {
private final Id id;
private final Clock clock;
private final AtomicDouble value;
private final AtomicLong lastUpdated;
/**
* Create a new monitor that returns {@code value}.
*/
ServoGauge(Id id, Clock clock, MonitorConfig config) {
super(config.withAdditionalTag(DataSourceType.GAUGE));
this.id = id;
this.clock = clock;
this.value = new AtomicDouble(Double.NaN);
this.lastUpdated = new AtomicLong(clock.wallTime());
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
long now = clock.wallTime();
return now - lastUpdated.get() > ServoRegistry.EXPIRATION_TIME_MILLIS;
}
@Override public Iterable<Measurement> measure() {
long now = clock.wallTime();
return Collections.singleton(new Measurement(id(), now, value.get()));
}
@Override public void set(double v) {
value.set(v);
lastUpdated.set(clock.wallTime());
}
@Override public double value() {
return hasExpired() ? Double.NaN : value.get();
}
@Override public Double getValue(int pollerIndex) {
return value();
}
@Override public void addMonitors(List<Monitor<?>> monitors) {
monitors.add(this);
}
}
| 5,951 |
0 | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-servo/src/main/java/com/netflix/spectator/servo/ServoCounter.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.servo;
import com.netflix.servo.monitor.Monitor;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/** Counter implementation for the servo registry. */
class ServoCounter implements Counter, ServoMeter {
private final Id id;
private final Clock clock;
private final DoubleCounter impl;
private final AtomicDouble count;
private final AtomicLong lastUpdated;
/** Create a new instance. */
ServoCounter(Id id, Clock clock, DoubleCounter impl) {
this.id = id;
this.clock = clock;
this.impl = impl;
this.count = new AtomicDouble(0.0);
this.lastUpdated = new AtomicLong(clock.wallTime());
}
@Override public void addMonitors(List<Monitor<?>> monitors) {
monitors.add(impl);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
long now = clock.wallTime();
return now - lastUpdated.get() > ServoRegistry.EXPIRATION_TIME_MILLIS;
}
@Override public Iterable<Measurement> measure() {
long now = clock.wallTime();
double v = impl.getValue(0).doubleValue();
return Collections.singleton(new Measurement(id(), now, v));
}
@Override public void add(double amount) {
if (Double.isFinite(amount) && amount > 0.0) {
impl.increment(amount);
count.addAndGet(amount);
lastUpdated.set(clock.wallTime());
}
}
@Override public double actualCount() {
return count.get();
}
}
| 5,952 |
0 | Create_ds/spectator/spectator-ext-aws/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-aws/src/test/java/com/netflix/spectator/aws/SpectatorRequestMetricCollectorTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.aws;
import com.amazonaws.DefaultRequest;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.handlers.HandlerContextKey;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.services.cloudwatch.model.ListMetricsRequest;
import com.amazonaws.util.AWSRequestMetrics;
import com.amazonaws.util.AWSRequestMetricsFullSupport;
import com.amazonaws.util.TimingInfo;
import com.netflix.spectator.api.*;
import java.util.*;
import com.netflix.spectator.api.Timer;
import org.apache.http.client.methods.HttpPost;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.stream.Collectors;
import static com.netflix.spectator.aws.SpectatorRequestMetricCollector.DEFAULT_HANDLER_CONTEXT_KEY;
import static org.junit.jupiter.api.Assertions.*;
public class SpectatorRequestMetricCollectorTest {
Registry registry;
SpectatorRequestMetricCollector collector;
@BeforeEach
public void setUp() {
registry = new DefaultRegistry();
collector = new SpectatorRequestMetricCollector(registry);
}
private void execRequest(String endpoint, int status) {
execRequest(endpoint, status, null, null);
}
private void execRequest(String endpoint, int status,
HandlerContextKey<String> handlerContextKey,
String handlerContextValue) {
AWSRequestMetrics metrics = new AWSRequestMetricsFullSupport();
metrics.addProperty(AWSRequestMetrics.Field.ServiceName, "AmazonCloudWatch");
metrics.addProperty(AWSRequestMetrics.Field.ServiceEndpoint, endpoint);
metrics.addProperty(AWSRequestMetrics.Field.StatusCode, "" + status);
if (status == 503) {
metrics.addProperty(AWSRequestMetrics.Field.AWSErrorCode, "Throttled");
}
String counterName = "BytesProcessed";
String timerName = "ClientExecuteTime";
String gaugeName = "HttpClientPoolAvailableCount";
metrics.setCounter(counterName, 12345);
metrics.getTimingInfo().addSubMeasurement(timerName, TimingInfo.unmodifiableTimingInfo(100000L, 200000L));
metrics.setCounter(gaugeName, -5678);
Request<?> req = new DefaultRequest(new ListMetricsRequest(), "AmazonCloudWatch");
req.setAWSRequestMetrics(metrics);
req.setEndpoint(URI.create(endpoint));
if ((handlerContextKey != null) && (handlerContextValue != null)) {
req.addHandlerContext(handlerContextKey, handlerContextValue);
}
HttpResponse hr = new HttpResponse(req, new HttpPost(endpoint));
hr.setStatusCode(status);
Response<?> resp = new Response<>(null, new HttpResponse(req, new HttpPost(endpoint)));
collector.collectMetrics(req, resp);
}
/** Returns a set of all values for a given tag key. */
private Set<String> valueSet(String k) {
return registry.stream()
.map(m -> Utils.getTagValue(m.id(), k))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
private Set<String> set(String... vs) {
return new HashSet<>(Arrays.asList(vs));
}
@Test
public void extractServiceEndpoint() {
execRequest("http://monitoring", 200);
assertEquals(set("monitoring"), valueSet("serviceEndpoint"));
execRequest("http://s3", 200);
assertEquals(set("monitoring", "s3"), valueSet("serviceEndpoint"));
}
@Test
public void extractServiceName() {
execRequest("http://monitoring", 200);
assertEquals(set("AmazonCloudWatch"), valueSet("serviceName"));
}
@Test
public void extractRequestType() {
execRequest("http://monitoring", 200);
assertEquals(set("ListMetricsRequest"), valueSet("requestType"));
}
@Test
public void extractStatusCode() {
execRequest("http://monitoring", 200);
execRequest("http://monitoring", 429);
execRequest("http://monitoring", 503);
assertEquals(set("200", "429", "503"), valueSet("statusCode"));
}
@Test
public void extractErrorCode() {
execRequest("http://monitoring", 200);
assertEquals(set(), valueSet("AWSErrorCode"));
execRequest("http://monitoring", 503);
assertEquals(set("Throttled"), valueSet("AWSErrorCode"));
}
@Test
public void testMetricCollection() {
execRequest("http://foo", 200);
//then
List<Meter> allMetrics = new ArrayList<>();
registry.iterator().forEachRemaining(allMetrics::add);
// We didn't provide a handler context value, so don't expect any gauges.
// That leaves 2 metrics.
assertEquals(2, allMetrics.size());
Optional<Timer> expectedTimer = registry.timers().findFirst();
assertTrue(expectedTimer.isPresent());
Timer timer = expectedTimer.get();
assertEquals(1, timer.count());
assertEquals(100000, timer.totalTime());
Optional<Counter> expectedCounter = registry.counters().findFirst();
assertTrue(expectedCounter.isPresent());
assertEquals(12345L, expectedCounter.get().count());
// Again, don't expect any gauges.
Optional<Gauge> expectedGauge = registry.gauges().findFirst();
assertFalse(expectedGauge.isPresent());
}
@Test
public void testListFiltering() {
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(null, Object::toString));
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(Collections.emptyList(), Object::toString));
assertEquals(Optional.of("1"), SpectatorRequestMetricCollector.firstValue(Collections.singletonList(1L), Object::toString));
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(Collections.singletonList(null), Object::toString));
}
@Test
public void testCustomTags() {
Map<String, String> customTags = new HashMap<>();
customTags.put("tagname", "tagvalue");
collector = new SpectatorRequestMetricCollector(registry, customTags);
execRequest("http://monitoring", 503);
assertEquals(set("tagvalue"), valueSet("tagname"));
}
@Test
public void testCustomTags_overrideDefault() {
Map<String, String> customTags = new HashMap<>();
customTags.put("error", "true");
// enable warning propagation
RegistryConfig config = k -> "propagateWarnings".equals(k) ? "true" : null;
assertThrows(IllegalArgumentException.class, () ->
new SpectatorRequestMetricCollector(new DefaultRegistry(Clock.SYSTEM, config), customTags));
}
@Test
public void testHandlerContextKey() {
String contextKeyName = "myContextKey";
HandlerContextKey<String> handlerContextKey = new HandlerContextKey<>(contextKeyName);
collector = new SpectatorRequestMetricCollector(registry, handlerContextKey);
String handlerContextValue = "some-value";
execRequest("http://monitoring", 503, handlerContextKey, handlerContextValue);
assertEquals(set(handlerContextValue), valueSet(contextKeyName));
}
@Test
public void testDefaultHandlerContextKey() {
collector = new SpectatorRequestMetricCollector(registry);
String handlerContextValue = "some-value";
execRequest("http://monitoring", 503, DEFAULT_HANDLER_CONTEXT_KEY, handlerContextValue);
assertEquals(set(handlerContextValue), valueSet(DEFAULT_HANDLER_CONTEXT_KEY.getName()));
// With a value in the handler context key, make sure there is a gauge
// metric.
Optional<Gauge> expectedGauge = registry.gauges().findFirst();
assertTrue(expectedGauge.isPresent());
assertEquals(-5678d, expectedGauge.get().value());
}
}
| 5,953 |
0 | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator/aws/SpectatorMetricCollector.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.aws;
import com.amazonaws.metrics.MetricCollector;
import com.amazonaws.metrics.RequestMetricCollector;
import com.amazonaws.metrics.ServiceMetricCollector;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.impl.Preconditions;
/**
* A MetricCollector that captures SDK metrics.
*/
public class SpectatorMetricCollector extends MetricCollector {
private final RequestMetricCollector requestMetricCollector;
private final ServiceMetricCollector serviceMetricCollector;
/**
* Constructs a new instance.
*/
public SpectatorMetricCollector(Registry registry) {
super();
Preconditions.checkNotNull(registry, "registry");
this.requestMetricCollector = new SpectatorRequestMetricCollector(registry);
this.serviceMetricCollector = new SpectatorServiceMetricCollector(registry);
}
@Override public boolean start() {
return true;
}
@Override public boolean stop() {
return true;
}
@Override public boolean isEnabled() {
return Boolean.parseBoolean(System.getProperty("spectator.ext.aws.enabled", "true"));
}
@Override public RequestMetricCollector getRequestMetricCollector() {
return requestMetricCollector;
}
@Override public ServiceMetricCollector getServiceMetricCollector() {
return serviceMetricCollector;
}
}
| 5,954 |
0 | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator/aws/SpectatorRequestMetricCollector.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.aws;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.handlers.HandlerContextKey;
import com.amazonaws.metrics.RequestMetricCollector;
import com.amazonaws.util.AWSRequestMetrics;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.util.TimingInfo;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.impl.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.Introspector;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* A {@link RequestMetricCollector} that captures request level metrics for AWS clients.
*/
public class SpectatorRequestMetricCollector extends RequestMetricCollector {
/**
* The default handler context key. If none is specified, and a value exists
* at this key in a request, that key/value pair is an additional tag on each
* metrics for that request.
*/
public static final HandlerContextKey<String> DEFAULT_HANDLER_CONTEXT_KEY = new HandlerContextKey("ClientIdKey");
private static final Logger LOGGER = LoggerFactory.getLogger(SpectatorRequestMetricCollector.class);
private static final Set<String> ALL_DEFAULT_TAGS = new HashSet<>();
private static final String TAG_ERROR = "error";
private static final String TAG_REQUEST_TYPE = "requestType";
private static final String TAG_THROTTLE_EXCEPTION = "throttleException";
private static final String UNKNOWN = "UNKNOWN";
private static final Field[] TIMERS = {
Field.ClientExecuteTime,
Field.CredentialsRequestTime,
Field.HttpClientReceiveResponseTime,
Field.HttpClientSendRequestTime,
Field.HttpRequestTime,
Field.RequestMarshallTime,
Field.RequestSigningTime,
Field.ResponseProcessingTime,
Field.RetryPauseTime
};
private static final Field[] COUNTERS = {
Field.BytesProcessed,
Field.HttpClientRetryCount,
Field.RequestCount
};
private static final Field[] GAUGES = {
Field.HttpClientPoolAvailableCount,
Field.HttpClientPoolLeasedCount,
Field.HttpClientPoolPendingCount,
};
private static final TagField[] TAGS = {
new TagField(Field.ServiceEndpoint, SpectatorRequestMetricCollector::getHost),
new TagField(Field.ServiceName),
new TagField(Field.StatusCode)
};
private static final TagField[] ERRORS = {
new TagField(Field.AWSErrorCode),
new TagField(Field.Exception, e -> e.getClass().getSimpleName())
};
static {
Stream.concat(Arrays.stream(TAGS), Arrays.stream(ERRORS))
.map(TagField::getName).forEach(ALL_DEFAULT_TAGS::add);
ALL_DEFAULT_TAGS.addAll(Arrays.asList(TAG_THROTTLE_EXCEPTION, TAG_REQUEST_TYPE, TAG_ERROR));
}
private final Registry registry;
private final Map<String, String> customTags;
private final HandlerContextKey<String> handlerContextKey;
/**
* Constructs a new instance using no custom tags and the default handler context key.
*/
public SpectatorRequestMetricCollector(Registry registry) {
this(registry, Collections.emptyMap(), DEFAULT_HANDLER_CONTEXT_KEY);
}
/**
* Constructs a new instance using the specified handler context key and no
* custom tags.
*/
public SpectatorRequestMetricCollector(Registry registry, HandlerContextKey<String> handlerContextKey) {
this(registry, Collections.emptyMap(), handlerContextKey);
}
/**
* Constructs a new instance. Custom tags provided by the user will be applied to every metric.
* Overriding built-in tags is not allowed. Uses the default handler context key.
*/
public SpectatorRequestMetricCollector(Registry registry, Map<String, String> customTags) {
this(registry, customTags, DEFAULT_HANDLER_CONTEXT_KEY);
}
/**
* Constructs a new instance using the optional handler context key. If
* present, and a request context has a value for this key, the key/value pair
* is an additional tag on every metric for that request. Custom tags
* provided by the user will be applied to every metric. Overriding built-in
* tags is not allowed.
*/
public SpectatorRequestMetricCollector(Registry registry, Map<String, String> customTags,
HandlerContextKey<String> handlerContextKey) {
super();
this.registry = Preconditions.checkNotNull(registry, "registry");
Preconditions.checkNotNull(customTags, "customTags");
this.customTags = new HashMap<>();
customTags.forEach((key, value) -> {
if (ALL_DEFAULT_TAGS.contains(key)) {
registry.propagate(new IllegalArgumentException("Invalid custom tag " + key
+ " - cannot override built-in tag"));
} else {
this.customTags.put(key, value);
}
});
Preconditions.checkNotNull(handlerContextKey, "handlerContextKey");
this.handlerContextKey = handlerContextKey;
if (ALL_DEFAULT_TAGS.contains(this.handlerContextKey.getName())) {
registry.propagate(new IllegalArgumentException("Invalid handler context key "
+ this.handlerContextKey.getName()
+ " - cannot override built-in tag"));
}
}
@Override
public void collectMetrics(Request<?> request, Response<?> response) {
final AWSRequestMetrics metrics = request.getAWSRequestMetrics();
if (metrics.isEnabled()) {
final Map<String, String> allTags = getAllTags(request);
final TimingInfo timing = metrics.getTimingInfo();
for (Field counter : COUNTERS) {
Optional.ofNullable(timing.getCounter(counter.name()))
.filter(v -> v.longValue() > 0)
.ifPresent(v -> registry.counter(metricId(counter, allTags)).increment(v.longValue()));
}
for (Field timer : TIMERS) {
Optional.ofNullable(timing.getLastSubMeasurement(timer.name()))
.filter(TimingInfo::isEndTimeKnown)
.ifPresent(t -> registry.timer(metricId(timer, allTags))
.record(t.getEndTimeNano() - t.getStartTimeNano(), TimeUnit.NANOSECONDS));
}
// Only include gauge metrics if there is a value in the context handler
// key. Without that, it's likely that gauge metrics from multiple
// connection pools don't make sense. This assumes that all gauge metrics
// are about connection pools.
if (request.getHandlerContext(handlerContextKey) != null) {
for (Field gauge : GAUGES) {
Optional.ofNullable(timing.getCounter(gauge.name()))
.ifPresent(v -> registry.gauge(metricId(gauge, allTags)).set(v.doubleValue()));
}
}
notEmpty(metrics.getProperty(Field.ThrottleException)).ifPresent(throttleExceptions -> {
final Id throttling = metricId("throttling", allTags);
throttleExceptions.forEach(ex ->
registry.counter(throttling.withTag(TAG_THROTTLE_EXCEPTION,
ex.getClass().getSimpleName())).increment());
});
}
}
private Id metricId(Field metric, Map<String, String> tags) {
return metricId(metric.name(), tags);
}
private Id metricId(String metric, Map<String, String> tags) {
return registry.createId(idName(metric), tags);
}
private Map<String, String> getAllTags(Request<?> request) {
final AWSRequestMetrics metrics = request.getAWSRequestMetrics();
final Map<String, String> allTags = new HashMap<>();
for (TagField tag : TAGS) {
allTags.put(tag.getName(), tag.getValue(metrics).orElse(UNKNOWN));
}
allTags.put(TAG_REQUEST_TYPE, request.getOriginalRequest().getClass().getSimpleName());
String contextTagValue = request.getHandlerContext(handlerContextKey);
if (contextTagValue != null) {
allTags.put(handlerContextKey.getName(), contextTagValue);
}
final boolean error = isError(metrics);
if (error) {
for (TagField tag : ERRORS) {
allTags.put(tag.getName(), tag.getValue(metrics).orElse(UNKNOWN));
}
}
allTags.put(TAG_ERROR, Boolean.toString(error));
allTags.putAll(customTags);
return Collections.unmodifiableMap(allTags);
}
/**
* Produces the name of a metric from the name of the SDK measurement.
*
* @param name
* Name of the SDK measurement, usually from the enum
* {@link com.amazonaws.util.AWSRequestMetrics.Field}.
* @return
* Name to use in the metric id.
*/
//VisibleForTesting
static String idName(String name) {
return "aws.request." + Introspector.decapitalize(name);
}
private static Optional<List<Object>> notEmpty(List<Object> properties) {
return Optional.ofNullable(properties).filter(v -> !v.isEmpty());
}
/**
* Extracts and transforms the first item from a list.
*
* @param properties
* The list of properties to filter, may be null or empty
* @param transform
* The transform to apply to the extracted list item. The
* transform is only applied if the list contains a non-null
* item at index 0.
* @param <R>
* The transform return type
* @return
* The transformed value, or Optional.empty() if there is no
* non-null item at index 0 of the list.
*/
//VisibleForTesting
static <R> Optional<R> firstValue(List<Object> properties, Function<Object, R> transform) {
return notEmpty(properties).map(v -> v.get(0)).map(transform::apply);
}
private static boolean isError(AWSRequestMetrics metrics) {
for (TagField err : ERRORS) {
if (err.getValue(metrics).isPresent()) {
return true;
}
}
return false;
}
private static String getHost(Object u) {
try {
return URI.create(u.toString()).getHost();
} catch (Exception e) {
LOGGER.debug("failed to parse endpoint uri: " + u, e);
return UNKNOWN;
}
}
private static class TagField {
private final Field field;
private final String name;
private final Function<Object, String> tagExtractor;
TagField(Field field) {
this(field, Object::toString);
}
TagField(Field field, Function<Object, String> tagExtractor) {
this.field = field;
this.tagExtractor = tagExtractor;
this.name = Introspector.decapitalize(field.name());
}
String getName() {
return name;
}
Optional<String> getValue(AWSRequestMetrics metrics) {
return firstValue(metrics.getProperty(field), tagExtractor);
}
}
}
| 5,955 |
0 | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-aws/src/main/java/com/netflix/spectator/aws/SpectatorServiceMetricCollector.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.aws;
import com.amazonaws.metrics.ByteThroughputProvider;
import com.amazonaws.metrics.ServiceLatencyProvider;
import com.amazonaws.metrics.ServiceMetricCollector;
import com.amazonaws.util.AWSServiceMetrics;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import java.util.concurrent.TimeUnit;
/**
* A {@link ServiceMetricCollector} that captures the time it takes to get a connection
* from the pool.
*/
class SpectatorServiceMetricCollector extends ServiceMetricCollector {
private final Timer clientGetConnectionTime;
/** Create a new instance. */
SpectatorServiceMetricCollector(Registry registry) {
super();
this.clientGetConnectionTime = registry.timer("aws.request.httpClientGetConnectionTime");
}
@Override
public void collectByteThroughput(ByteThroughputProvider provider) {
}
@Override
public void collectLatency(ServiceLatencyProvider provider) {
if (provider.getServiceMetricType() == AWSServiceMetrics.HttpClientGetConnectionTime) {
long nanos = (long) (provider.getDurationMilli() * 1e6);
clientGetConnectionTime.record(nanos, TimeUnit.NANOSECONDS);
}
}
}
| 5,956 |
0 | Create_ds/spectator/spectator-ext-gc/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/test/java/com/netflix/spectator/gc/GcEventTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
public class GcEventTest {
@Test
public void toStringSizes() {
// Try to ensure that at least one GC event has occurred
System.gc();
// Loop through and get a GcInfo
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
GcInfo gcInfo = ((com.sun.management.GarbageCollectorMXBean) mbean).getLastGcInfo();
if (gcInfo != null) {
GarbageCollectionNotificationInfo info = new GarbageCollectionNotificationInfo(
mbean.getName(),
"Action",
"Allocation Failure",
gcInfo);
GcEvent event = new GcEvent(info, 0L);
final String eventStr = event.toString();
Assertions.assertTrue(eventStr.contains("cause=[Allocation Failure]"));
// TODO: need to find a better way to create a fake GcInfo object for tests
final long max = HelperFunctions.getTotalMaxUsage(gcInfo.getMemoryUsageAfterGc());
if (max > (1L << 30)) {
Assertions.assertTrue(eventStr.contains("GiB"));
} else if (max > (1L << 20)) {
Assertions.assertTrue(eventStr.contains("MiB"));
} else {
Assertions.assertTrue(eventStr.contains("KiB"));
}
}
}
}
}
| 5,957 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/HelperFunctions.java | /*
* Copyright 2014-2021 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
import com.sun.management.GcInfo;
import java.lang.management.MemoryUsage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/** Utility functions for GC. */
final class HelperFunctions {
private static final Map<String, GcType> KNOWN_COLLECTOR_NAMES = knownCollectors();
private HelperFunctions() {
}
private static Map<String, GcType> knownCollectors() {
Map<String, GcType> m = new HashMap<>();
m.put("ConcurrentMarkSweep", GcType.OLD);
m.put("Copy", GcType.YOUNG);
m.put("G1 Old Generation", GcType.OLD);
m.put("G1 Young Generation", GcType.YOUNG);
m.put("MarkSweepCompact", GcType.OLD);
m.put("PS MarkSweep", GcType.OLD);
m.put("PS Scavenge", GcType.YOUNG);
m.put("ParNew", GcType.YOUNG);
m.put("ZGC", GcType.OLD);
m.put("ZGC Cycles", GcType.OLD);
m.put("ZGC Pauses", GcType.OLD);
m.put("ZGC Minor Cycles", GcType.YOUNG);
m.put("ZGC Minor Pauses", GcType.YOUNG);
m.put("ZGC Major Cycles", GcType.OLD);
m.put("ZGC Major Pauses", GcType.OLD);
m.put("Shenandoah Cycles", GcType.OLD);
m.put("Shenandoah Pauses", GcType.OLD);
return Collections.unmodifiableMap(m);
}
/** Determine the type, old or young, based on the name of the collector. */
static GcType getGcType(String name) {
GcType t = KNOWN_COLLECTOR_NAMES.get(name);
return (t == null) ? GcType.UNKNOWN : t;
}
/** Return true if it is an old GC type. */
static boolean isOldGcType(String name) {
return getGcType(name) == GcType.OLD;
}
/** Returns true if memory pool name matches an old generation pool. */
static boolean isOldGenPool(String name) {
return name.contains("Old Gen")
|| name.endsWith("Tenured Gen")
|| "Shenandoah".equals(name)
|| "ZHeap".equals(name);
}
/** Returns true if memory pool name matches an young generation pool. */
static boolean isYoungGenPool(String name) {
return name.contains("Young Gen")
|| name.endsWith("Eden Space")
|| "Shenandoah".equals(name)
|| "ZHeap".equals(name);
}
static boolean isSurvivorPool(String name) {
return name.endsWith("Survivor Space");
}
/** Compute the total usage across all pools. */
static long getTotalUsage(Map<String, MemoryUsage> usages) {
long sum = 0L;
for (Map.Entry<String, MemoryUsage> e : usages.entrySet()) {
sum += e.getValue().getUsed();
}
return sum;
}
/** Compute the max usage across all pools. */
static long getTotalMaxUsage(Map<String, MemoryUsage> usages) {
long sum = 0L;
for (Map.Entry<String, MemoryUsage> e : usages.entrySet()) {
long max = e.getValue().getMax();
if (max > 0) {
sum += e.getValue().getMax();
}
}
return sum;
}
/** Compute the amount of data promoted during a GC event. */
static long getPromotionSize(GcInfo info) {
long totalBefore = getTotalUsage(info.getMemoryUsageBeforeGc());
long totalAfter = getTotalUsage(info.getMemoryUsageAfterGc());
return totalAfter - totalBefore;
}
}
| 5,958 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcEvent.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import java.util.Comparator;
import java.util.Date;
/**
* Metadata about a garbage collection event.
*/
@SuppressWarnings("PMD.DataClass")
public class GcEvent {
private static final long ONE_KIBIBYTE = 1 << 10;
private static final long ONE_MEBIBYTE = 1 << 20;
private static final long ONE_GIBIBYTE = 1 << 30;
private final String name;
private final GarbageCollectionNotificationInfo info;
private final GcType type;
private final long startTime;
/**
* Create a new instance.
*
* @param info
* The info object from the notification emitter on the
* {@link java.lang.management.GarbageCollectorMXBean}.
* @param startTime
* Start time in milliseconds since the epoch. Note the info object has a start time relative
* to the time the jvm process was started.
*/
public GcEvent(GarbageCollectionNotificationInfo info, long startTime) {
this.name = info.getGcName();
this.info = info;
this.type = HelperFunctions.getGcType(name);
this.startTime = startTime;
}
/** Type of GC event that occurred. */
public GcType getType() {
return type;
}
/** Name of the collector for the event. */
public String getName() {
return name;
}
/** Start time in milliseconds since the epoch. */
public long getStartTime() {
return startTime;
}
/**
* Info object from the {@link java.lang.management.GarbageCollectorMXBean} notification
* emitter.
*/
public GarbageCollectionNotificationInfo getInfo() {
return info;
}
@Override
public String toString() {
final GcInfo gcInfo = info.getGcInfo();
final long totalBefore = HelperFunctions.getTotalUsage(gcInfo.getMemoryUsageBeforeGc());
final long totalAfter = HelperFunctions.getTotalUsage(gcInfo.getMemoryUsageAfterGc());
final long max = HelperFunctions.getTotalMaxUsage(gcInfo.getMemoryUsageAfterGc());
String unit = "KiB";
double cnv = ONE_KIBIBYTE;
if (max > ONE_GIBIBYTE) {
unit = "GiB";
cnv = ONE_GIBIBYTE;
} else if (max > ONE_MEBIBYTE) {
unit = "MiB";
cnv = ONE_MEBIBYTE;
}
String change = String.format(
"%.1f%s => %.1f%s / %.1f%s",
totalBefore / cnv, unit,
totalAfter / cnv, unit,
max / cnv, unit);
String percentChange = String.format(
"%.1f%% => %.1f%%", 100.0 * totalBefore / max, 100.0 * totalAfter / max);
final Date d = new Date(startTime);
return type.toString() + ": "
+ name + ", id=" + gcInfo.getId() + ", at=" + d.toString()
+ ", duration=" + gcInfo.getDuration() + "ms" + ", cause=[" + info.getGcCause() + "]"
+ ", " + change + " (" + percentChange + ")";
}
/** Order events from oldest to newest. */
public static final Comparator<GcEvent> TIME_ORDER = Comparator.comparing(GcEvent::getStartTime);
/** Order events from newest to oldest. */
public static final Comparator<GcEvent> REVERSE_TIME_ORDER = TIME_ORDER.reversed();
}
| 5,959 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/CircularBuffer.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Fixed size buffer that overwrites previous entries after filling up all slots.
*/
class CircularBuffer<T> {
private final AtomicInteger nextIndex;
private final AtomicReferenceArray<T> data;
/** Create a new instance. */
CircularBuffer(int length) {
nextIndex = new AtomicInteger(0);
data = new AtomicReferenceArray<>(length);
}
/** Add a new item to the buffer. If the buffer is full a previous entry will get overwritten. */
void add(T item) {
int i = nextIndex.getAndIncrement() % data.length();
data.set(i, item);
}
/** Get the item in the buffer at position {@code i} or return null if it isn't set. */
T get(int i) {
return data.get(i);
}
/** Return the capacity of the buffer. */
int size() {
return data.length();
}
/** Return a list with a copy of the data in the buffer. */
List<T> toList() {
List<T> items = new ArrayList<>(data.length());
for (int i = 0; i < data.length(); ++i) {
T item = data.get(i);
if (item != null) {
items.add(item);
}
}
return items;
}
}
| 5,960 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcEventListener.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
/** Listener for GC events. */
public interface GcEventListener {
/** Invoked after a GC event occurs. */
void onComplete(GcEvent event);
}
| 5,961 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java | /*
* Copyright 2014-2021 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.impl.Preconditions;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.ListenerNotFoundException;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Logger to collect GC notifcation events.
*/
public final class GcLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(GcLogger.class);
// One major GC per hour would require 168 for a week
// One minor GC per minute would require 180 for three hours
private static final int BUFFER_SIZE = 256;
// Max size of old generation memory pool
private static final AtomicLong MAX_DATA_SIZE =
Spectator.globalRegistry().gauge("jvm.gc.maxDataSize", new AtomicLong(0L));
// Size of old generation memory pool after a full GC
private static final AtomicLong LIVE_DATA_SIZE =
Spectator.globalRegistry().gauge("jvm.gc.liveDataSize", new AtomicLong(0L));
// Incremented for any positive increases in the size of the old generation memory pool
// before GC to after GC
private static final Counter PROMOTION_RATE =
Spectator.globalRegistry().counter("jvm.gc.promotionRate");
// Incremented for the increase in the size of the young generation memory pool after one GC
// to before the next
private static final Counter ALLOCATION_RATE =
Spectator.globalRegistry().counter("jvm.gc.allocationRate");
// Incremented for any positive increases in the size of the survivor memory pool
// before GC to after GC
private static final Counter SURVIVOR_RATE =
Spectator.globalRegistry().counter("jvm.gc.survivorRate");
// Pause time due to GC event
private static final Id PAUSE_TIME = Spectator.globalRegistry().createId("jvm.gc.pause");
// Time spent in concurrent phases of GC
private static final Id CONCURRENT_PHASE_TIME =
Spectator.globalRegistry().createId("jvm.gc.concurrentPhaseTime");
private final Lock lock = new ReentrantLock();
private final long jvmStartTime;
private final Map<String, CircularBuffer<GcEvent>> gcLogs;
private long youngGenSizeAfter = 0L;
private String youngGenPoolName = null;
private String survivorPoolName = null;
private String oldGenPoolName = null;
private GcNotificationListener notifListener = null;
private GcEventListener eventListener = null;
/** Create a new instance. */
public GcLogger() {
jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
Map<String, CircularBuffer<GcEvent>> gcLogs = new HashMap<>();
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
CircularBuffer<GcEvent> buffer = new CircularBuffer<>(BUFFER_SIZE);
gcLogs.put(mbean.getName(), buffer);
}
this.gcLogs = Collections.unmodifiableMap(gcLogs);
for (MemoryPoolMXBean mbean : ManagementFactory.getMemoryPoolMXBeans()) {
String poolName = mbean.getName();
// For non-generational collectors the young and old gen pool names will be the
// same
if (HelperFunctions.isYoungGenPool(poolName)) {
youngGenPoolName = poolName;
}
if (HelperFunctions.isSurvivorPool(poolName)) {
survivorPoolName = poolName;
}
if (HelperFunctions.isOldGenPool(poolName)) {
oldGenPoolName = poolName;
}
}
}
/**
* Start collecting data about GC events.
*
* @param listener
* If not null, the listener will be called with the event objects after metrics and the
* log buffer is updated.
*/
public void start(GcEventListener listener) {
lock.lock();
try {
// TODO: this class has a bad mix of static fields used from an instance of the class. For now
// this has been changed not to throw to make the dependency injection use-cases work. A
// more general refactor of the GcLogger class is needed.
if (notifListener != null) {
LOGGER.warn("logger already started");
return;
}
eventListener = listener;
notifListener = new GcNotificationListener();
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (mbean instanceof NotificationEmitter) {
final NotificationEmitter emitter = (NotificationEmitter) mbean;
emitter.addNotificationListener(notifListener, null, null);
}
}
} finally {
lock.unlock();
}
}
/** Stop collecting GC events. */
public void stop() {
lock.lock();
try {
Preconditions.checkState(notifListener != null, "logger has not been started");
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (mbean instanceof NotificationEmitter) {
final NotificationEmitter emitter = (NotificationEmitter) mbean;
try {
emitter.removeNotificationListener(notifListener);
} catch (ListenerNotFoundException e) {
LOGGER.warn("could not remove gc listener", e);
}
}
}
notifListener = null;
} finally {
lock.unlock();
}
}
/** Return the current set of GC events in the in-memory log. */
public List<GcEvent> getLogs() {
final List<GcEvent> logs = new ArrayList<>();
for (CircularBuffer<GcEvent> buffer : gcLogs.values()) {
logs.addAll(buffer.toList());
}
logs.sort(GcEvent.REVERSE_TIME_ORDER);
return logs;
}
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
private void updateMetrics(String name, GcInfo info) {
final Map<String, MemoryUsage> before = info.getMemoryUsageBeforeGc();
final Map<String, MemoryUsage> after = info.getMemoryUsageAfterGc();
if (oldGenPoolName != null) {
final long oldBefore = before.get(oldGenPoolName).getUsed();
final long oldAfter = after.get(oldGenPoolName).getUsed();
final long delta = oldAfter - oldBefore;
if (delta > 0L) {
PROMOTION_RATE.increment(delta);
}
// Shenandoah doesn't report accurate pool sizes for pauses, all numbers are 0. Ignore
// those updates.
//
// Some GCs such as G1 can reduce the old gen size as part of a minor GC. To track the
// live data size we record the value if we see a reduction in the old gen heap size or
// after a major GC.
if (oldAfter > 0L && (oldAfter < oldBefore || HelperFunctions.isOldGcType(name))) {
LIVE_DATA_SIZE.set(oldAfter);
final long oldMaxAfter = after.get(oldGenPoolName).getMax();
MAX_DATA_SIZE.set(oldMaxAfter);
}
}
if (survivorPoolName != null) {
final long survivorBefore = before.get(survivorPoolName).getUsed();
final long survivorAfter = after.get(survivorPoolName).getUsed();
final long delta = survivorAfter - survivorBefore;
if (delta > 0L) {
SURVIVOR_RATE.increment(delta);
}
}
if (youngGenPoolName != null) {
final long youngBefore = before.get(youngGenPoolName).getUsed();
final long youngAfter = after.get(youngGenPoolName).getUsed();
// Shenandoah doesn't report accurate pool sizes for pauses, all numbers are 0. Ignore
// those updates.
if (youngBefore > 0L) {
final long delta = youngBefore - youngGenSizeAfter;
youngGenSizeAfter = youngAfter;
if (delta > 0L) {
ALLOCATION_RATE.increment(delta);
}
}
}
}
private void processGcEvent(GarbageCollectionNotificationInfo info) {
GcEvent event = new GcEvent(info, jvmStartTime + info.getGcInfo().getStartTime());
gcLogs.get(info.getGcName()).add(event);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(event.toString());
}
// Update pause timer for the action and cause...
Id eventId = (isConcurrentPhase(info) ? CONCURRENT_PHASE_TIME : PAUSE_TIME)
.withTag("action", info.getGcAction())
.withTag("cause", info.getGcCause());
Timer timer = Spectator.globalRegistry().timer(eventId);
timer.record(info.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
// Update promotion and allocation counters
updateMetrics(info.getGcName(), info.getGcInfo());
// Notify an event listener if registered
if (eventListener != null) {
try {
eventListener.onComplete(event);
} catch (Exception e) {
LOGGER.warn("exception thrown by event listener", e);
}
}
}
private boolean isConcurrentPhase(GarbageCollectionNotificationInfo info) {
// So far the only indicator known is that the cause will be reported as "No GC"
// when using CMS.
//
// For ZGC, behavior was changed in JDK17:
// https://bugs.openjdk.java.net/browse/JDK-8265136
//
// For ZGC in older versions, there is no way to accurately get the amount of time
// in STW pauses.
//
// For G1, a new bean was added in JDK20 to indicate time spent in concurrent
// phases:
// https://bugs.openjdk.org/browse/JDK-8297247
return "No GC".equals(info.getGcCause()) // CMS
|| "G1 Concurrent GC".equals(info.getGcName()) // G1 in JDK20+
|| info.getGcName().endsWith(" Cycles"); // Shenandoah, ZGC
}
private class GcNotificationListener implements NotificationListener {
@Override public void handleNotification(Notification notification, Object ref) {
final String type = notification.getType();
if (GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(type)) {
CompositeData cd = (CompositeData) notification.getUserData();
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(cd);
processGcEvent(info);
}
}
}
}
| 5,962 |
0 | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcType.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.gc;
/**
* Simple classification of gc type to avoid reliance on names than can vary.
*/
public enum GcType {
/** Major collection. */
OLD,
/** Minor collection. */
YOUNG,
/** Could not determine the collection type. */
UNKNOWN
}
| 5,963 |
0 | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator/spark/SparkNameFunctionTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Utils;
import com.typesafe.config.ConfigFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SparkNameFunctionTest {
private final Registry registry = new DefaultRegistry();
private final SparkNameFunction f = SparkNameFunction.fromConfig(ConfigFactory.load(), registry);
private void assertEquals(Id expected, Id actual) {
Assertions.assertEquals(Utils.normalize(expected), Utils.normalize(actual));
}
//EXECUTOR
@Test
public void executorMetric_executor() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.97278898-4bd4-49c2-9889-aa5f969a7816-S1/2.executor.filesystem.file.largeRead_ops";
final Id expected = registry.createId("spark.executor.filesystem.file.largeRead_ops")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("agentId","97278898-4bd4-49c2-9889-aa5f969a7816-S1")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric_jvm() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.97278898-4bd4-49c2-9889-aa5f969a7816-S1/2.jvm.heap.committed";
final Id expected = registry.createId("spark.jvm.heap.committed")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("agentId","97278898-4bd4-49c2-9889-aa5f969a7816-S1")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric_CodeGenerator() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.97278898-4bd4-49c2-9889-aa5f969a7816-S1/2.CodeGenerator.compilationTime";
final Id expected = registry.createId("spark.CodeGenerator.compilationTime")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("agentId","97278898-4bd4-49c2-9889-aa5f969a7816-S1")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric20_executor() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.2.executor.filesystem.file.largeRead_ops";
final Id expected = registry.createId("spark.executor.filesystem.file.largeRead_ops")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric20_jvm() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.2.jvm.heap.committed";
final Id expected = registry.createId("spark.jvm.heap.committed")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric20_CodeGenerator() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.2.CodeGenerator.compilationTime";
final Id expected = registry.createId("spark.CodeGenerator.compilationTime")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
@Test
public void executorMetric21_HiveExternalCatalog() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.2.HiveExternalCatalog.fileCacheHits";
final Id expected = registry.createId("spark.HiveExternalCatalog.fileCacheHits")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("executorId", "2")
.withTag("role", "executor");
assertEquals(expected, f.apply(name));
}
// DRIVER
@Test
public void driverMetric_BlockManager() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.BlockManager.disk.diskSpaceUsed_MB";
final Id expected = registry.createId("spark.BlockManager.disk.diskSpaceUsed") // Trailing _MB removed
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
@Test
public void driverMetric_CodeGenerator() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.CodeGenerator.compilationTime";
final Id expected = registry.createId("spark.CodeGenerator.compilationTime")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
@Test
public void driverMetric_DAGScheduler() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.DAGScheduler.messageProcessingTime";
final Id expected = registry.createId("spark.DAGScheduler.messageProcessingTime")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
@Test
public void driverMetric_jvm() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.jvm.heap.committed";
final Id expected = registry.createId("spark.jvm.heap.committed")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
@Test
public void driverMetric21_HiveExternalCatalog() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.HiveExternalCatalog.fileCacheHits";
final Id expected = registry.createId("spark.HiveExternalCatalog.fileCacheHits")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
// Streaming
@Test
public void driverStreamingSimple() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0013.driver.HdfsWordCount.StreamingMetrics.streaming.lastCompletedBatch_processingDelay";
final Id expected = registry.createId("spark.streaming.lastCompletedBatch_processingDelay")
.withTag("appId", "97278898-4bd4-49c2-9889-aa5f969a7816-0013")
.withTag("role", "driver");
assertEquals(expected, f.apply(name));
}
@Test
public void JustPatternMatching() {
final String pattern_string = "^([^.]+)\\.(driver)\\.((CodeGenerator|DAGScheduler|BlockManager|jvm)\\..*)$";
final String metric = "97278898-4bd4-49c2-9889-aa5f969a7816-0023.driver.jvm.pools.PS-Old-Gen.used";
final Pattern pattern = Pattern.compile(pattern_string);
final Matcher m = pattern.matcher(metric);
Assertions.assertTrue(m.matches());
Assertions.assertEquals("97278898-4bd4-49c2-9889-aa5f969a7816-0023", m.group(1));
Assertions.assertEquals("driver", m.group(2));
Assertions.assertEquals("jvm.pools.PS-Old-Gen.used", m.group(3));
Assertions.assertEquals("jvm", m.group(4));
}
}
| 5,964 |
0 | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator/spark/SparkValueFunctionTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.typesafe.config.ConfigFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SparkValueFunctionTest {
private final SparkValueFunction f = SparkValueFunction.fromConfig(ConfigFactory.load());
@Test
public void executorName() {
final String name = "app-20150309231421-0000.0.executor.filesystem.file.largeRead_ops";
Assertions.assertEquals(42.0, f.convert(name, 42.0), 1e-12);
}
@Test
public void driverName() {
final String name = "app-20150309231421-0000.driver.BlockManager.disk.diskSpaceUsed_MB";
Assertions.assertEquals(42.0 * 1e6, f.convert(name, 42.0), 1e-12);
}
@Test
public void driverStreamingTime() {
final String name = "97278898-4bd4-49c2-9889-aa5f969a7816-0129.driver.HdfsWordCount.StreamingMetrics.streaming.lastCompletedBatch_processingEndTime";
Assertions.assertEquals(42.0 / 1000.0, f.convert(name, 42.0), 1e-12);
}
@Test
public void driverStreamingDelay() {
final String name = "app-20150527224111-0014.<driver>.SubscriptionEnded.StreamingMetrics.streaming.lastReceivedBatch_submissionDelay";
Assertions.assertEquals(42.0 / 1000.0, f.convert(name, 42.0), 1e-12);
}
@Test
public void driverStreamingDelayAbnormal() {
final String name = "app-20150527224111-0014.<driver>.SubscriptionEnded.StreamingMetrics.streaming.lastReceivedBatch_submissionDelay";
Assertions.assertEquals(Double.NaN, f.convert(name, -1.0), 1e-12);
}
}
| 5,965 |
0 | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator/spark/SpectatorReporterTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Registry;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
public class SpectatorReporterTest {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final Registry registry = new DefaultRegistry();
private final SpectatorReporter reporter = SpectatorReporter.forRegistry(metricsRegistry)
.withSpectatorRegistry(registry)
.withGaugeCounters(Pattern.compile("^gaugeCounter.*$"))
.build();
private final Counter metricsCounter = metricsRegistry.counter("metricsCounter");
private final Counter gaugeCounter = metricsRegistry.counter("gaugeCounter");
@Test
public void incrementGaugeCounter() {
long before = registry.counter("gaugeCounter").count();
gaugeCounter.inc();
reporter.report();
long after = registry.counter("gaugeCounter").count();
Assertions.assertEquals(before + 1, after);
metricsCounter.dec();
reporter.report();
before = after;
after = getValue("gaugeCounter");
Assertions.assertEquals(before, after);
}
private long getValue(String name) {
Meter meter = registry.get(registry.createId(name));
if (meter != null) {
for (Measurement m : meter.measure()) {
return (long) m.value();
}
}
return Long.MAX_VALUE;
}
@Test
public void incrementMetricsCounter() {
reporter.report();
long before = getValue("metricsCounter");
metricsCounter.inc();
reporter.report();
long after = getValue("metricsCounter");
Assertions.assertEquals(before + 1, after);
metricsCounter.dec();
reporter.report();
before = after;
after = getValue("metricsCounter");
Assertions.assertEquals(before - 1, after);
}
}
| 5,966 |
0 | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/test/java/com/netflix/spectator/spark/SpectatorConfigTest.java | package com.netflix.spectator.spark;
import com.typesafe.config.ConfigFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SpectatorConfigTest {
private final SpectatorConfig config = new SpectatorConfig(
ConfigFactory.load().getConfig("spectator.spark.sidecar")
);
@Test
public void enabled() {
Assertions.assertFalse(config.outputLocation().isEmpty());
}
}
| 5,967 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SparkValueFunction.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.typesafe.config.Config;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Function for performing simple conversions to normalize the values.
*/
public final class SparkValueFunction implements ValueFunction {
/**
* Create a value function based on a config. It will use the key
* {@code spectator.spark.value-conversions}.
*/
public static SparkValueFunction fromConfig(Config config) {
return fromConfig(config, "spectator.spark.value-conversions");
}
/**
* Create a value function based on a config.
*/
public static SparkValueFunction fromConfig(Config config, String key) {
return fromPatternList(config.getConfigList(key));
}
private static SparkValueFunction fromPatternList(List<? extends Config> patterns) {
final List<NameMatcher> matchers = new ArrayList<>();
for (Config config : patterns) {
final Pattern pattern = Pattern.compile(config.getString("pattern"));
matchers.add(new NameMatcher(pattern, config.getDouble("factor")));
}
return new SparkValueFunction(matchers);
}
private static class NameMatcher {
private final Pattern pattern;
private final double factor;
NameMatcher(Pattern pattern, double factor) {
this.pattern = pattern;
this.factor = factor;
}
boolean matches(String name) {
return pattern.matcher(name).matches();
}
double apply(double v) {
// streaming/src/main/scala/org/apache/spark/streaming/StreamingSource.scala
// -1 is used for abnormal conditions
return (Math.abs(v + 1.0) <= 1e-12) ? Double.NaN : v * factor;
}
}
private final List<NameMatcher> matchers;
private SparkValueFunction(List<NameMatcher> matchers) {
this.matchers = matchers;
}
@Override public double convert(String name, double v) {
for (NameMatcher matcher : matchers) {
if (matcher.matches(name)) {
return matcher.apply(v);
}
}
return v;
}
}
| 5,968 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SpectatorReporter.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Timer;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
/**
* Reporter for mapping data in a metrics3 registry to spectator.
*/
public final class SpectatorReporter extends ScheduledReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(SpectatorReporter.class);
/**
* Return a builder for creating a spectator reported based on {@code registry}.
*/
public static Builder forRegistry(MetricRegistry registry) {
return new Builder(registry);
}
/**
* Builder for configuring the spectator reporter.
*/
public static final class Builder {
private final MetricRegistry registry;
private Registry spectatorRegistry;
private NameFunction nameFunction = new NameFunction() {
@Override public Id apply(String name) {
return spectatorRegistry.createId(name);
}
};
private ValueFunction valueFunction = (name, v) -> v;
/**
* By default none should match. Note the '$' sign is regex end of line so it cannot be
* followed by characters and thus the pattern will not match anything.
*/
private Pattern gaugeCounters = Pattern.compile("$NONE");
/** Create a new instance. */
Builder(MetricRegistry registry) {
this.registry = registry;
}
/** Set the spectator registry to use. */
public Builder withSpectatorRegistry(Registry r) {
spectatorRegistry = r;
return this;
}
/** Set the name mapping function to use. */
public Builder withNameFunction(NameFunction f) {
nameFunction = f;
return this;
}
/** Set the value mapping function to use. */
public Builder withValueFunction(ValueFunction f) {
valueFunction = f;
return this;
}
/** Set the regex for matching names of gauges that should be treated as counters. */
public Builder withGaugeCounters(Pattern pattern) {
gaugeCounters = pattern;
return this;
}
/** Create a new instance of the reporter. */
public SpectatorReporter build() {
if (spectatorRegistry == null) {
spectatorRegistry = Spectator.globalRegistry();
}
return new SpectatorReporter(
registry, spectatorRegistry, nameFunction, valueFunction, gaugeCounters);
}
}
private final Registry spectatorRegistry;
private final NameFunction nameFunction;
private final ValueFunction valueFunction;
private final Pattern gaugeCounters;
private final ConcurrentHashMap<String, AtomicLong> previousValues = new ConcurrentHashMap<>();
/** Create a new instance. */
SpectatorReporter(
MetricRegistry metricRegistry,
Registry spectatorRegistry,
NameFunction nameFunction,
ValueFunction valueFunction,
Pattern gaugeCounters) {
super(metricRegistry,
"spectator", // name
MetricFilter.ALL, // filter
TimeUnit.SECONDS, // rateUnit
TimeUnit.SECONDS); // durationUnit
this.spectatorRegistry = spectatorRegistry;
this.nameFunction = nameFunction;
this.valueFunction = valueFunction;
this.gaugeCounters = gaugeCounters;
}
@SuppressWarnings("PMD.NPathComplexity")
@Override public void report(
SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers) {
LOGGER.debug("gauges {}, counters {}, histograms {}, meters {}, timers {}",
gauges.size(), counters.size(), histograms.size(), meters.size(), timers.size());
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
final Object obj = entry.getValue().getValue();
if (obj instanceof Number) {
if (gaugeCounters.matcher(entry.getKey()).matches()) {
final long v = ((Number) obj).longValue();
updateCounter(entry.getKey(), v);
} else {
final double v = ((Number) obj).doubleValue();
setGaugeValue(entry.getKey(), v);
}
}
}
for (Map.Entry<String, Counter> entry : counters.entrySet()) {
if (gaugeCounters.matcher(entry.getKey()).matches()) {
updateCounter(entry.getKey(), entry.getValue().getCount());
} else {
setGaugeValue(entry.getKey(), entry.getValue().getCount());
}
}
for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
final Id id = nameFunction.apply(entry.getKey());
if (id != null) {
final DistributionSummary sHisto = spectatorRegistry.distributionSummary(id);
final Histogram mHisto = entry.getValue();
final long[] vs = mHisto.getSnapshot().getValues();
for (long v : vs) {
sHisto.record(v);
}
}
}
for (Map.Entry<String, Meter> entry : meters.entrySet()) {
updateCounter(entry.getKey(), entry.getValue().getCount());
}
for (Map.Entry<String, Timer> entry : timers.entrySet()) {
final Id id = nameFunction.apply(entry.getKey());
if (id != null) {
final com.netflix.spectator.api.Timer sTimer = spectatorRegistry.timer(id);
final Timer mTimer = entry.getValue();
final long[] vs = mTimer.getSnapshot().getValues();
for (long v : vs) {
sTimer.record(v, TimeUnit.NANOSECONDS);
}
}
}
}
private void setGaugeValue(String name, double v) {
Id id = nameFunction.apply(name);
if (id != null) {
final double cv = valueFunction.convert(name, v);
LOGGER.debug("setting gauge {} to {}", name, cv);
spectatorRegistry.gauge(id).set(cv);
}
}
private long getAndSetPrevious(String name, long newValue) {
AtomicLong prev = previousValues.get(name);
if (prev == null) {
AtomicLong tmp = new AtomicLong(0L);
prev = previousValues.putIfAbsent(name, tmp);
prev = (prev == null) ? tmp : prev;
}
return prev.getAndSet(newValue);
}
private void updateCounter(String k, long curr) {
final long prev = getAndSetPrevious(k, curr);
final Id id = nameFunction.apply(k);
if (id != null) {
spectatorRegistry.counter(id).increment(curr - prev);
}
}
}
| 5,969 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SpectatorConfig.java | /*
* Copyright 2014-2020 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.netflix.spectator.sidecar.SidecarConfig;
import com.typesafe.config.Config;
import java.util.HashMap;
import java.util.Map;
class SpectatorConfig implements SidecarConfig {
private final Config config;
SpectatorConfig(Config config) {
this.config = config;
}
@Override
public String get(String k) {
return config.hasPath(k) ? config.getString(k) : null;
}
@Override
public String outputLocation() {
return config.getString("output-location");
}
@Override
public Map<String, String> commonTags() {
Map<String, String> tags = new HashMap<>(SidecarConfig.super.commonTags());
for (Config cfg : config.getConfigList("tags")) {
// These are often populated by environment variables that can sometimes be empty
// rather than not set when missing. Empty strings are not allowed by Atlas.
String value = cfg.getString("value");
if (!value.isEmpty()) {
tags.put(cfg.getString("key"), cfg.getString("value"));
}
}
return tags;
}
}
| 5,970 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/ValueFunction.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
/**
* Maps a value based on the name. This is typically used to perform simple unit conversions so
* that data can be made to follow common conventions with other sources (e.g. always use base
* units and do conversions as part of presentation).
*/
public interface ValueFunction {
/** Convert the value for a given metric name. */
double convert(String name, double v);
}
| 5,971 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/DataType.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.netflix.spectator.api.Tag;
/**
* Data types for messages sent to the sidecar metrics endpoint.
*/
public enum DataType implements Tag {
/** Value reported as is, the most recent value received by the sidecar will get used. */
GAUGE,
/** Value is a delta to use when incrementing the counter. */
COUNTER,
/** Value is an amount in milliseconds that will be recorded on the timer. */
TIMER;
@Override public String key() {
return "type";
}
@Override public String value() {
return name();
}
}
| 5,972 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/NameFunction.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.netflix.spectator.api.Id;
/**
* Maps a name used for the metrics registry into an id for spectator.
*/
public interface NameFunction {
/**
* Return the id corresponding to the name, or null if the name cannot be mapped and the value
* should be dropped.
*/
Id apply(String name);
}
| 5,973 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SparkSink.java | /*
* Copyright 2014-2020 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.codahale.metrics.MetricRegistry;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.gc.GcLogger;
import com.netflix.spectator.jvm.Jmx;
import com.netflix.spectator.sidecar.SidecarRegistry;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.spark.metrics.sink.Sink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Sink for exporting spark metrics.
*/
public class SparkSink implements Sink {
private static final Logger LOGGER = LoggerFactory.getLogger(SparkSink.class);
private final SpectatorReporter reporter;
private final SidecarRegistry sidecarRegistry;
private final long pollPeriod;
private final TimeUnit pollUnit;
private GcLogger gcLogger;
/**
* Create a new instance. Spark looks for a constructor with all three parameters, so the
* {@code SecurityManager} needs to be in the signature even though it isn't used.
*/
@SuppressWarnings("PMD.UnusedFormalParameter")
public SparkSink(
Properties properties,
MetricRegistry registry,
org.apache.spark.SecurityManager manager) throws MalformedURLException {
final Config config = loadConfig();
sidecarRegistry = new SidecarRegistry(
Clock.SYSTEM, new SpectatorConfig(config.getConfig("spectator.spark.sidecar")));
reporter = SpectatorReporter.forRegistry(registry)
.withSpectatorRegistry(sidecarRegistry)
.withNameFunction(SparkNameFunction.fromConfig(config, sidecarRegistry))
.withValueFunction(SparkValueFunction.fromConfig(config))
.withGaugeCounters(Pattern.compile(config.getString("spectator.spark.gauge-counters")))
.build();
pollPeriod = getPeriod(properties);
pollUnit = getUnit(properties);
// If there is a need to collect application metrics from jobs running on Spark, then
// this should be enabled. The apps can report to the global registry and it will get
// picked up by the Spark integration.
if (shouldAddToGlobal(properties)) {
Spectator.globalRegistry().add(sidecarRegistry);
}
}
private Config loadConfig() {
return ConfigFactory.load(pickClassLoader());
}
@SuppressWarnings("PMD.UseProperClassLoader")
private ClassLoader pickClassLoader() {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
return getClass().getClassLoader();
} else {
return cl;
}
}
private void startJvmCollection() {
try {
Jmx.registerStandardMXBeans(sidecarRegistry);
gcLogger = new GcLogger();
gcLogger.start(null);
} catch (Exception e) {
LOGGER.error("failed to start collection of jvm stats", e);
throw e;
}
}
private long getPeriod(Properties properties) {
final String v = properties.getProperty("period");
return (v == null) ? 10L : Long.parseLong(v);
}
private TimeUnit getUnit(Properties properties) {
final String v = properties.getProperty("unit");
return (v == null) ? TimeUnit.SECONDS : TimeUnit.valueOf(v.toUpperCase(Locale.US));
}
private boolean shouldAddToGlobal(Properties properties) {
final String v = properties.getProperty("addToGlobalRegistry");
return (v == null) || Boolean.parseBoolean(v);
}
@Override public void start() {
LOGGER.info("starting poller");
reporter.start(pollPeriod, pollUnit);
startJvmCollection();
}
@Override public void stop() {
LOGGER.info("stopping poller");
reporter.stop();
gcLogger.stop();
}
@Override public void report() {
LOGGER.info("reporting values");
reporter.report();
}
}
| 5,974 |
0 | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SparkNameFunction.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.spark;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValue;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Maps hierarchical spark names into tagged ids.
*/
public final class SparkNameFunction implements NameFunction {
private static final String PREFIX = "spark.";
private static final Id DROP_METRIC = null;
/**
* Create a name function based on a config. It will use the key
* {@code spectator.spark.name-patterns}.
*/
public static SparkNameFunction fromConfig(Config config, Registry registry) {
return fromConfig(config, "spectator.spark.name-patterns", registry);
}
/**
* Create a name function based on a config.
*/
public static SparkNameFunction fromConfig(Config config, String key, Registry registry) {
return fromPatternList(config.getConfigList(key), registry);
}
private static SparkNameFunction fromPatternList(List<? extends Config> patterns, Registry registry) {
final List<NameMatcher> matchers = new ArrayList<>();
for (Config config : patterns) {
final Pattern pattern = Pattern.compile(config.getString("pattern"));
final Map<String, Integer> tagsMap = new LinkedHashMap<>();
final Config tagsCfg = config.getConfig("tags");
for (Map.Entry<String, ConfigValue> entry : tagsCfg.entrySet()) {
tagsMap.put(entry.getKey(), (Integer) entry.getValue().unwrapped());
}
matchers.add(new NameMatcher(pattern, registry, config.getInt("name"), tagsMap));
}
return new SparkNameFunction(matchers);
}
private static class NameMatcher {
private final Pattern pattern;
private final Registry registry;
private final int name;
private final Map<String, Integer> tags;
NameMatcher(Pattern pattern, Registry registry, int name, Map<String, Integer> tags) {
this.pattern = pattern;
this.registry = registry;
this.name = name;
this.tags = tags;
}
Id apply(String metric) {
final Matcher m = pattern.matcher(metric);
if (m.matches()) {
Id id = registry.createId(PREFIX + m.group(name));
for (Map.Entry<String, Integer> entry : tags.entrySet()) {
id = id.withTag(entry.getKey(), m.group(entry.getValue()));
}
// separate executor jvm metrics from driver executor metrics
if (!tags.containsKey("role")) {
id = id.withTag("role", "executor");
}
return id;
} else {
return DROP_METRIC;
}
}
}
private final List<NameMatcher> matchers;
private SparkNameFunction(List<NameMatcher> matchers) {
this.matchers = matchers;
}
@Override public Id apply(String name) {
for (NameMatcher matcher : matchers) {
Id id = matcher.apply(name);
if (id != DROP_METRIC) {
return id;
}
}
return DROP_METRIC;
}
}
| 5,975 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/HttpResponseTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpResponseTest {
@Test
public void toStringEmpty() {
HttpResponse res = new HttpResponse(200, Collections.emptyMap());
String expected = "HTTP/1.1 200\n\n... 0 bytes ...\n";
Assertions.assertEquals(expected, res.toString());
}
@Test
public void toStringContent() {
byte[] entity = "content".getBytes(StandardCharsets.UTF_8);
HttpResponse res = new HttpResponse(200, Collections.emptyMap(), entity);
String expected = "HTTP/1.1 200\n\n... 7 bytes ...\n";
Assertions.assertEquals(expected, res.toString());
}
@Test
public void toStringHeaders() {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Date", Collections.singletonList("Mon, 27 Jul 2012 17:21:03 GMT"));
headers.put("Content-Type", Collections.singletonList("application/json"));
byte[] entity = "{}".getBytes(StandardCharsets.UTF_8);
HttpResponse res = new HttpResponse(200, headers, entity);
String expected = "HTTP/1.1 200\nContent-Type: application/json\nDate: Mon, 27 Jul 2012 17:21:03 GMT\n\n... 2 bytes ...\n";
Assertions.assertEquals(expected, res.toString());
}
@Test
public void header() {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
HttpResponse res = new HttpResponse(200, headers);
Assertions.assertEquals("application/json", res.header("content-type"));
Assertions.assertEquals("application/json", res.header("Content-Type"));
}
@Test
public void dateHeaderNull() {
Map<String, List<String>> headers = new HashMap<>();
HttpResponse res = new HttpResponse(200, headers);
Assertions.assertNull(res.dateHeader("Date"));
}
@Test
public void dateHeaderGMT() {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Date", Collections.singletonList("Fri, 27 Jul 2012 17:21:03 GMT"));
HttpResponse res = new HttpResponse(200, headers);
Instant expected = Instant.ofEpochMilli(1343409663000L);
Assertions.assertEquals(expected, res.dateHeader("Date"));
}
@Test
public void decompressNoChange() throws IOException {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8));
HttpResponse res = new HttpResponse(200, headers, entity);
Assertions.assertSame(res, res.decompress());
}
@Test
public void decompress() throws IOException {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
headers.put("Content-Encoding", Collections.singletonList("gzip"));
byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8));
HttpResponse res = new HttpResponse(200, headers, entity);
Assertions.assertEquals("foo bar baz foo bar baz", res.decompress().entityAsString());
Assertions.assertNull(res.decompress().header("content-encoding"));
}
@Test
public void decompressEmpty() throws IOException {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
headers.put("Content-Encoding", Collections.singletonList("gzip"));
HttpResponse res = new HttpResponse(200, headers);
Assertions.assertEquals("", res.decompress().entityAsString());
Assertions.assertEquals(0, res.decompress().entity().length);
}
}
| 5,976 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/DoubleDistributionSummaryTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class DoubleDistributionSummaryTest {
private final ManualClock clock = new ManualClock();
private Registry registry = new DefaultRegistry();
private DoubleDistributionSummary newInstance() {
clock.setWallTime(0L);
return new DoubleDistributionSummary(clock, registry.createId("foo"), 60000);
}
private String get(Id id, String key) {
for (Tag t : id.tags()) {
if (key.equals(t.key())) {
return t.value();
}
}
return null;
}
@Test
public void testInit() {
DoubleDistributionSummary t = newInstance();
Assertions.assertEquals(t.count(), 0L);
Assertions.assertEquals(t.totalAmount(), 0.0, 1e-12);
}
@Test
public void testRecord() {
DoubleDistributionSummary t = newInstance();
t.record(42.0);
Assertions.assertEquals(t.count(), 1L);
Assertions.assertEquals(t.totalAmount(), 42.0, 1e-12);
}
@Test
public void testExpire() {
clock.setWallTime(0L);
DoubleDistributionSummary t = newInstance();
Assertions.assertFalse(t.hasExpired());
t.record(42.0);
clock.setWallTime(15L * 60000L);
Assertions.assertFalse(t.hasExpired());
clock.setWallTime(15L * 60000L + 1);
Assertions.assertTrue(t.hasExpired());
t.record(42.0);
Assertions.assertFalse(t.hasExpired());
}
@Test
public void testMeasureNotEnoughTime() {
DoubleDistributionSummary t = newInstance();
t.record(42.0);
clock.setWallTime(500L);
int c = 0;
for (Measurement m : t.measure()) {
++c;
}
Assertions.assertEquals(0L, c);
}
@Test
public void testMeasure() {
DoubleDistributionSummary t = newInstance();
t.record(42.0);
clock.setWallTime(65000L);
for (Measurement m : t.measure()) {
Assertions.assertEquals(m.timestamp(), 65000L);
switch (get(m.id(), "statistic")) {
case "count":
Assertions.assertEquals(m.value(), 1.0 / 65.0, 1e-12);
break;
case "totalAmount":
Assertions.assertEquals(m.value(), 42.0 / 65.0, 1e-12);
break;
case "totalOfSquares":
Assertions.assertEquals(m.value(), 42.0 * 42.0 / 65.0, 1e-12);
break;
case "max":
Assertions.assertEquals(m.value(), 42.0, 1e-12);
break;
default:
Assertions.fail("unexpected id: " + m.id());
break;
}
}
}
private double stddev(double[] values) {
double t = 0.0;
double t2 = 0.0;
double n = 0.0;
for (double v : values) {
t += v;
t2 += v * v;
n += 1.0;
}
return Math.sqrt((n * t2 - t * t) / (n * n));
}
@Test
public void testMeasureZeroToOne() {
double[] values = { 0.1, 0.2, 0.7, 0.8, 0.1, 0.4, 0.6, 0.9, 0.1, 1.0, 0.0, 0.5, 0.4 };
DoubleDistributionSummary s = newInstance();
for (double v : values) {
s.record(v);
}
clock.setWallTime(65000L);
double t = 0.0;
double t2 = 0.0;
double n = 0.0;
double max = 0.0;
for (Measurement m : s.measure()) {
switch (get(m.id(), "statistic")) {
case "count": n = m.value(); break;
case "totalAmount": t = m.value(); break;
case "totalOfSquares": t2 = m.value(); break;
case "max": max = m.value(); break;
default:
Assertions.fail("unexpected id: " + m.id());
break;
}
}
Assertions.assertEquals(1.0, max, 1e-12);
Assertions.assertEquals(stddev(values), Math.sqrt((n * t2 - t * t) / (n * n)), 1e-12);
}
@Disabled
public void testRegister() {
DoubleDistributionSummary t = newInstance();
registry.register(t);
t.record(42.0);
clock.setWallTime(65000L);
for (Measurement m : registry.get(t.id()).measure()) {
Assertions.assertEquals(m.timestamp(), 65000L);
switch (get(m.id(), "statistic")) {
case "count":
Assertions.assertEquals(m.value(), 1.0 / 65.0, 1e-12);
break;
case "totalAmount":
Assertions.assertEquals(m.value(), 42.0 / 65.0, 1e-12);
break;
case "totalOfSquares":
Assertions.assertEquals(m.value(), 42.0 * 42.0 / 65.0, 1e-12);
break;
case "max":
Assertions.assertEquals(m.value(), 42.0, 1e-12);
break;
default:
Assertions.fail("unexpected id: " + m.id());
break;
}
}
}
@Disabled
public void staticGet() {
Id id = registry.createId("foo");
DoubleDistributionSummary t = DoubleDistributionSummary.get(registry, id);
Assertions.assertSame(t, DoubleDistributionSummary.get(registry, id));
Assertions.assertNotNull(registry.get(id));
}
}
| 5,977 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/BucketFunctionsTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
public class BucketFunctionsTest {
@Test
public void age60s() {
BucketFunction f = BucketFunctions.age(60, TimeUnit.SECONDS);
Assertions.assertEquals("future", f.apply(TimeUnit.SECONDS.toNanos(-1)));
Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(1)));
Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(6)));
Assertions.assertEquals("07s", f.apply(TimeUnit.SECONDS.toNanos(7)));
Assertions.assertEquals("15s", f.apply(TimeUnit.SECONDS.toNanos(10)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(20)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(30)));
Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(42)));
Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(60)));
Assertions.assertEquals("old", f.apply(TimeUnit.SECONDS.toNanos(61)));
}
@Test
public void age60sBiasOld() {
BucketFunction f = BucketFunctions.ageBiasOld(60, TimeUnit.SECONDS);
Assertions.assertEquals("future", f.apply(TimeUnit.SECONDS.toNanos(-1)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(1)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(6)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(7)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(10)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(20)));
Assertions.assertEquals("30s", f.apply(TimeUnit.SECONDS.toNanos(30)));
Assertions.assertEquals("45s", f.apply(TimeUnit.SECONDS.toNanos(42)));
Assertions.assertEquals("52s", f.apply(TimeUnit.SECONDS.toNanos(48)));
Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(59)));
Assertions.assertEquals("60s", f.apply(TimeUnit.SECONDS.toNanos(60)));
Assertions.assertEquals("old", f.apply(TimeUnit.SECONDS.toNanos(61)));
}
@Test
public void latency100ms() {
BucketFunction f = BucketFunctions.latency(100, TimeUnit.MILLISECONDS);
Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1)));
Assertions.assertEquals("012ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1)));
Assertions.assertEquals("025ms", f.apply(TimeUnit.MILLISECONDS.toNanos(13)));
Assertions.assertEquals("025ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25)));
Assertions.assertEquals("100ms", f.apply(TimeUnit.MILLISECONDS.toNanos(99)));
Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(101)));
}
@Test
public void latency100msBiasSlow() {
BucketFunction f = BucketFunctions.latencyBiasSlow(100, TimeUnit.MILLISECONDS);
Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1)));
Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1)));
Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(13)));
Assertions.assertEquals("050ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25)));
Assertions.assertEquals("075ms", f.apply(TimeUnit.MILLISECONDS.toNanos(74)));
Assertions.assertEquals("075ms", f.apply(TimeUnit.MILLISECONDS.toNanos(75)));
Assertions.assertEquals("100ms", f.apply(TimeUnit.MILLISECONDS.toNanos(99)));
Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(101)));
}
@Test
public void latency3s() {
BucketFunction f = BucketFunctions.latency(3, TimeUnit.SECONDS);
Assertions.assertEquals("negative_latency", f.apply(TimeUnit.MILLISECONDS.toNanos(-1)));
Assertions.assertEquals("0375ms", f.apply(TimeUnit.MILLISECONDS.toNanos(25)));
Assertions.assertEquals("0750ms", f.apply(TimeUnit.MILLISECONDS.toNanos(740)));
Assertions.assertEquals("1500ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1000)));
Assertions.assertEquals("3000ms", f.apply(TimeUnit.MILLISECONDS.toNanos(1567)));
Assertions.assertEquals("slow", f.apply(TimeUnit.MILLISECONDS.toNanos(3001)));
}
}
| 5,978 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/HttpUtilsTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
public class HttpUtilsTest {
private String extract(String u) {
return HttpUtils.clientNameForURI(URI.create(u));
}
@Test
public void relativeUri() {
Assertions.assertEquals("default", extract("/foo"));
}
@Test
public void dashFirst() {
Assertions.assertEquals("ec2", extract("http://ec2-127-0-0-1.compute-1.amazonaws.com/foo"));
}
@Test
public void dotFirst() {
Assertions.assertEquals("foo", extract("http://foo.test.netflix.com/foo"));
}
@Test
public void gzip() throws IOException {
byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8);
String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data)), StandardCharsets.UTF_8);
Assertions.assertEquals("foo bar baz", result);
}
@Test
public void gzipWithLevel() throws IOException {
byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8);
String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data, Deflater.BEST_SPEED)), StandardCharsets.UTF_8);
Assertions.assertEquals("foo bar baz", result);
}
}
| 5,979 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/HttpLogEntryTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.net.URI;
public class HttpLogEntryTest {
@Test
public void npeIfMethodIsNotSet() {
Assertions.assertThrows(NullPointerException.class, () -> {
HttpLogEntry entry = new HttpLogEntry()
.withClientName("test")
.withRequestUri(URI.create("http://test.com/foo"));
try {
HttpLogEntry.logClientRequest(entry);
} catch (NullPointerException e) {
Assertions.assertEquals("parameter 'method' cannot be null", e.getMessage());
throw e;
}
});
}
}
| 5,980 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/DefaultHttpClientTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.concurrent.Executors;
public class DefaultHttpClientTest {
private static HttpServer server;
private static int port;
private static void ignore(InputStream input) throws IOException {
try (InputStream in = input) {
byte[] buf = new byte[1024];
while (in.read(buf) > 0);
}
}
private static int getInt(Headers headers, String k, int dflt) {
String v = headers.getFirst(k);
return (v == null) ? dflt : Integer.parseInt(v);
}
@BeforeAll
public static void startServer() throws Exception {
server = HttpServer.create(new InetSocketAddress(0), 100);
server.setExecutor(Executors.newFixedThreadPool(10, r -> new Thread(r, "HttpServer")));
port = server.getAddress().getPort();
server.createContext("/", exchange -> {
Headers headers = exchange.getRequestHeaders();
int status = getInt(headers, "X-Status", 200);
int length = getInt(headers, "X-Length", -1);
ignore(exchange.getRequestBody());
exchange.sendResponseHeaders(status, length);
exchange.close();
});
server.createContext("/echo", exchange -> {
Headers headers = exchange.getRequestHeaders();
int status = getInt(headers, "X-Status", 200);
boolean compressResponse = headers
.getOrDefault("Content-Encoding", Collections.emptyList())
.contains("gzip");
if (compressResponse) {
exchange.getResponseHeaders().add("Content-Encoding", "gzip");
}
exchange.sendResponseHeaders(status, 0L);
try (InputStream in = exchange.getRequestBody();
OutputStream out = exchange.getResponseBody()) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
exchange.close();
});
server.start();
}
@AfterAll
public static void stopServer() {
server.stop(0);
}
private URI uri(String path) {
return URI.create("http://127.0.0.1:" + port + path);
}
@Test
public void ok() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.get(uri("/ok"))
.addHeader("X-Status", "200")
.addHeader("X-Length", "-1")
.send();
Assertions.assertEquals(200, res.status());
}
@Test
public void emptyChunked() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.get(uri("/ok"))
.addHeader("X-Status", "200")
.addHeader("X-Length", "0")
.send();
Assertions.assertEquals(200, res.status());
}
@Test
public void unavailableEmpty() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.get(uri("/ok"))
.addHeader("X-Status", "503")
.addHeader("X-Length", "-1")
.send();
Assertions.assertEquals(503, res.status());
}
@Test
public void unavailableEmptyChunked() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.get(uri("/ok"))
.addHeader("X-Status", "503")
.addHeader("X-Length", "0")
.send();
Assertions.assertEquals(503, res.status());
}
@Test
public void okWithBody() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.post(uri("/echo"))
.addHeader("X-Status", "200")
.withContent("text/plain", "foo")
.send();
Assertions.assertEquals(200, res.status());
Assertions.assertEquals("foo", res.entityAsString());
}
@Test
public void okWithCompressedBody() throws IOException {
HttpResponse res = HttpClient.DEFAULT
.post(uri("/echo"))
.acceptGzip()
.addHeader("X-Status", "200")
.withContent("text/plain", "foo")
.compress()
.send()
.decompress();
Assertions.assertEquals(200, res.status());
Assertions.assertEquals("foo", res.entityAsString());
}
}
| 5,981 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/test/java/com/netflix/spectator/sandbox/HttpRequestBuilderTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
public class HttpRequestBuilderTest {
private static final HttpResponse OK = new HttpResponse(200, Collections.emptyMap());
private static final HttpResponse REDIRECT = new HttpResponse(302, Collections.emptyMap());
private static final HttpResponse BAD_REQUEST = new HttpResponse(400, Collections.emptyMap());
private static final HttpResponse THROTTLED = new HttpResponse(429, Collections.emptyMap());
private static final HttpResponse SERVER_ERROR = new HttpResponse(500, Collections.emptyMap());
private static final HttpResponse UNAVAILABLE = new HttpResponse(503, Collections.emptyMap());
@Test
public void ok() throws IOException {
HttpResponse res = new TestRequestBuilder(() -> OK).send();
Assertions.assertEquals(200, res.status());
}
@Test
public void retry0() throws Exception {
Assertions.assertThrows(IOException.class,
() -> new TestRequestBuilder(() -> { throw new IOException("failed"); }).send());
}
@Test
public void retry2() {
AtomicInteger attempts = new AtomicInteger();
boolean failed = false;
try {
HttpResponseSupplier supplier = () -> {
attempts.incrementAndGet();
throw new IOException("failed");
};
new TestRequestBuilder(supplier).withRetries(2).send();
} catch (IOException e) {
failed = true;
}
Assertions.assertEquals(3, attempts.get());
Assertions.assertTrue(failed);
}
private void retryStatus(HttpResponse expectedRes, int expectedAttempts) throws IOException {
AtomicInteger attempts = new AtomicInteger();
HttpResponseSupplier supplier = () -> {
attempts.incrementAndGet();
return expectedRes;
};
HttpResponse res = new TestRequestBuilder(supplier)
.withInitialRetryDelay(0L)
.withRetries(2)
.send();
Assertions.assertEquals(expectedAttempts, attempts.get());
Assertions.assertEquals(expectedRes.status(), res.status());
}
@Test
public void retry2xx() throws IOException {
retryStatus(OK, 1);
}
@Test
public void retry3xx() throws IOException {
retryStatus(REDIRECT, 1);
}
@Test
public void retry4xx() throws IOException {
retryStatus(BAD_REQUEST, 1);
}
@Test
public void retry5xx() throws IOException {
retryStatus(SERVER_ERROR, 3);
}
@Test
public void retry429() throws IOException {
retryStatus(THROTTLED, 3);
}
@Test
public void retry503() throws IOException {
retryStatus(UNAVAILABLE, 3);
}
@Test
public void hostnameVerificationWithHTTP() throws IOException {
Assertions.assertThrows(IllegalStateException.class,
() -> new TestRequestBuilder(() -> OK).allowAllHosts());
}
@Test
public void hostnameVerificationWithHTTPS() throws IOException {
HttpResponse res = new TestRequestBuilder(() -> OK, URI.create("https://foo.com/path"))
.allowAllHosts()
.send();
Assertions.assertEquals(200, res.status());
}
private static class TestRequestBuilder extends HttpRequestBuilder {
private HttpResponseSupplier supplier;
TestRequestBuilder(HttpResponseSupplier supplier) {
this(supplier, URI.create("/path"));
}
TestRequestBuilder(HttpResponseSupplier supplier, URI uri) {
super("test", uri);
this.supplier = supplier;
}
@Override protected HttpResponse sendImpl() throws IOException {
return supplier.get();
}
}
private interface HttpResponseSupplier {
HttpResponse get() throws IOException;
}
}
| 5,982 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketTimer.java | /*
* Copyright 2014-2023 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.api.Timer;
import java.util.concurrent.TimeUnit;
/**
* Timers that get updated based on the bucket for recorded values.
*
* @deprecated Moved to {@code com.netflix.spectator.api.histogram} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public final class BucketTimer implements Timer {
/**
* Creates a timer object that manages a set of timers based on the bucket
* function supplied. Calling record will be mapped to the record on the appropriate timer.
*
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Timer that manages sub-timers based on the bucket function.
*/
public static BucketTimer get(Id id, BucketFunction f) {
return get(Spectator.globalRegistry(), id, f);
}
/**
* Creates a timer object that manages a set of timers based on the bucket
* function supplied. Calling record will be mapped to the record on the appropriate timer.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Timer that manages sub-timers based on the bucket function.
*/
public static BucketTimer get(Registry registry, Id id, BucketFunction f) {
return new BucketTimer(
com.netflix.spectator.api.histogram.BucketTimer.get(registry, id, f));
}
private final com.netflix.spectator.api.histogram.BucketTimer t;
/** Create a new instance. */
BucketTimer(com.netflix.spectator.api.histogram.BucketTimer t) {
this.t = t;
}
@Override public Id id() {
return t.id();
}
@Override public Iterable<Measurement> measure() {
return t.measure();
}
@Override public boolean hasExpired() {
return t.hasExpired();
}
@Override public Clock clock() {
return t.clock();
}
@Override public void record(long amount, TimeUnit unit) {
t.record(amount, unit);
}
@Override public long count() {
return t.count();
}
@Override public long totalTime() {
return t.totalTime();
}
}
| 5,983 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketCounter.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
/**
* Counters that get incremented based on the bucket for recorded values.
*
* @deprecated Moved to {@code com.netflix.spectator.api.histogram} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public final class BucketCounter implements DistributionSummary {
/**
* Creates a distribution summary object that manages a set of counters based on the bucket
* function supplied. Calling record will increment the appropriate counter.
*
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketCounter get(Id id, BucketFunction f) {
return get(Spectator.globalRegistry(), id, f);
}
/**
* Creates a distribution summary object that manages a set of counters based on the bucket
* function supplied. Calling record will increment the appropriate counter.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketCounter get(Registry registry, Id id, BucketFunction f) {
return new BucketCounter(
com.netflix.spectator.api.histogram.BucketCounter.get(registry, id, f));
}
private final com.netflix.spectator.api.histogram.BucketCounter c;
/** Create a new instance. */
BucketCounter(com.netflix.spectator.api.histogram.BucketCounter c) {
this.c = c;
}
@Override public Id id() {
return c.id();
}
@Override public Iterable<Measurement> measure() {
return c.measure();
}
@Override public boolean hasExpired() {
return c.hasExpired();
}
@Override public void record(long amount) {
c.record(amount);
}
@Override public long count() {
return c.count();
}
@Override public long totalAmount() {
return c.totalAmount();
}
}
| 5,984 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketFunctions.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import java.util.concurrent.TimeUnit;
import java.util.function.LongFunction;
/**
* Helpers for creating bucketing functions.
*
* @deprecated Moved to {@code com.netflix.spectator.api.histogram} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public final class BucketFunctions {
private BucketFunctions() {
}
private static BucketFunction wrap(LongFunction<String> f) {
return f::apply;
}
/**
* Returns a function that maps age values to a set of buckets. Example use-case would be
* tracking the age of data flowing through a processing pipeline. Values that are less than
* 0 will be marked as "future". These typically occur due to minor variations in the clocks
* across nodes. In addition to a bucket at the max, it will create buckets at max / 2, max / 4,
* and max / 8.
*
* @param max
* Maximum expected age of data flowing through. Values greater than this max will be mapped
* to an "old" bucket.
* @param unit
* Unit for the max value.
* @return
* Function mapping age values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static BucketFunction age(long max, TimeUnit unit) {
return wrap(com.netflix.spectator.api.histogram.BucketFunctions.age(max, unit));
}
/**
* Returns a function that maps latencies to a set of buckets. Example use-case would be
* tracking the amount of time to process a request on a server. Values that are less than
* 0 will be marked as "negative_latency". These typically occur due to minor variations in the
* clocks, e.g., using {@link System#currentTimeMillis()} to measure the latency and having a
* time adjustment between the start and end. In addition to a bucket at the max, it will create
* buckets at max / 2, max / 4, and max / 8.
*
* @param max
* Maximum expected age of data flowing through. Values greater than this max will be mapped
* to an "old" bucket.
* @param unit
* Unit for the max value.
* @return
* Function mapping age values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static BucketFunction latency(long max, TimeUnit unit) {
return wrap(com.netflix.spectator.api.histogram.BucketFunctions.latency(max, unit));
}
/**
* Returns a function that maps age values to a set of buckets. Example use-case would be
* tracking the age of data flowing through a processing pipeline. Values that are less than
* 0 will be marked as "future". These typically occur due to minor variations in the clocks
* across nodes. In addition to a bucket at the max, it will create buckets at max - max / 8,
* max - max / 4, and max - max / 2.
*
* @param max
* Maximum expected age of data flowing through. Values greater than this max will be mapped
* to an "old" bucket.
* @param unit
* Unit for the max value.
* @return
* Function mapping age values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static BucketFunction ageBiasOld(long max, TimeUnit unit) {
return wrap(com.netflix.spectator.api.histogram.BucketFunctions.ageBiasOld(max, unit));
}
/**
* Returns a function that maps latencies to a set of buckets. Example use-case would be
* tracking the amount of time to process a request on a server. Values that are less than
* 0 will be marked as "negative_latency". These typically occur due to minor variations in the
* clocks, e.g., using {@link System#currentTimeMillis()} to measure the latency and having a
* time adjustment between the start and end. In addition to a bucket at the max, it will create
* buckets at max - max / 8, max - max / 4, and max - max / 2.
*
* @param max
* Maximum expected age of data flowing through. Values greater than this max will be mapped
* to an "old" bucket.
* @param unit
* Unit for the max value.
* @return
* Function mapping age values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static BucketFunction latencyBiasSlow(long max, TimeUnit unit) {
return wrap(com.netflix.spectator.api.histogram.BucketFunctions.latencyBiasSlow(max, unit));
}
}
| 5,985 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketDistributionSummary.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
/**
* Distribution summaries that get updated based on the bucket for recorded values.
*
* @deprecated Moved to {@code com.netflix.spectator.api.histogram} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public final class BucketDistributionSummary implements DistributionSummary {
/**
* Creates a distribution summary object that manages a set of distribution summaries based on
* the bucket function supplied. Calling record will be mapped to the record on the appropriate
* distribution summary.
*
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketDistributionSummary get(Id id, BucketFunction f) {
return get(Spectator.globalRegistry(), id, f);
}
/**
* Creates a distribution summary object that manages a set of distribution summaries based on
* the bucket function supplied. Calling record will be mapped to the record on the appropriate
* distribution summary.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketDistributionSummary get(Registry registry, Id id, BucketFunction f) {
return new BucketDistributionSummary(
com.netflix.spectator.api.histogram.BucketDistributionSummary.get(registry, id, f));
}
private final com.netflix.spectator.api.histogram.BucketDistributionSummary s;
/** Create a new instance. */
BucketDistributionSummary(com.netflix.spectator.api.histogram.BucketDistributionSummary s) {
this.s = s;
}
@Override public Id id() {
return s.id();
}
@Override public Iterable<Measurement> measure() {
return s.measure();
}
@Override public boolean hasExpired() {
return s.hasExpired();
}
@Override public void record(long amount) {
s.record(amount);
}
@Override public long count() {
return s.count();
}
@Override public long totalAmount() {
return s.totalAmount();
}
}
| 5,986 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/DoubleDistributionSummary.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.api.Statistic;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* Experiment for supporting a distribution summary type that accepts floating point values instead
* of just long values.
*/
public class DoubleDistributionSummary implements Meter {
private static final ConcurrentHashMap<Id, DoubleDistributionSummary> INSTANCES =
new ConcurrentHashMap<>();
// https://github.com/Netflix/spectator/issues/43
private static final long RESET_FREQ = 60000L;
// How long to keep reporting if there is no activity. Set to 15 minutes to match default
// behavior in servo.
private static final long INACTIVE_TTL = 15 * RESET_FREQ;
/**
* Get or create a double distribution summary with the specified id.
*
* @param id
* Identifier for the metric being registered.
* @return
* Distribution summary corresponding to the id.
*/
public static DoubleDistributionSummary get(Id id) {
return get(Spectator.globalRegistry(), id);
}
/**
* Get or create a double distribution summary with the specified id.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @return
* Distribution summary corresponding to the id.
*/
static DoubleDistributionSummary get(Registry registry, Id id) {
DoubleDistributionSummary instance = INSTANCES.get(id);
if (instance == null) {
final Clock c = registry.clock();
DoubleDistributionSummary tmp = new DoubleDistributionSummary(c, id, RESET_FREQ);
instance = INSTANCES.putIfAbsent(id, tmp);
if (instance == null) {
instance = tmp;
registry.register(tmp);
}
}
return instance;
}
private static final long ZERO = Double.doubleToLongBits(0.0);
private final Clock clock;
private final Id id;
private final long resetFreq;
private final AtomicLong lastResetTime;
private final AtomicLong lastUpdateTime;
private final AtomicLong count;
private final AtomicLong totalAmount;
private final AtomicLong totalOfSquares;
private final AtomicLong max;
private final Id countId;
private final Id totalAmountId;
private final Id totalOfSquaresId;
private final Id maxId;
/**
* Create a new instance.
*/
DoubleDistributionSummary(Clock clock, Id id, long resetFreq) {
this.clock = clock;
this.id = id;
this.resetFreq = resetFreq;
lastResetTime = new AtomicLong(clock.wallTime());
lastUpdateTime = new AtomicLong(clock.wallTime());
count = new AtomicLong(0L);
totalAmount = new AtomicLong(ZERO);
totalOfSquares = new AtomicLong(ZERO);
max = new AtomicLong(ZERO);
countId = id.withTag(Statistic.count);
totalAmountId = id.withTag(Statistic.totalAmount);
totalOfSquaresId = id.withTag(Statistic.totalOfSquares);
maxId = id.withTag(Statistic.max);
}
private void add(AtomicLong num, double amount) {
long v;
double d;
long next;
do {
v = num.get();
d = Double.longBitsToDouble(v);
next = Double.doubleToLongBits(d + amount);
} while (!num.compareAndSet(v, next));
}
private void max(AtomicLong num, double amount) {
long n = Double.doubleToLongBits(amount);
long v;
double d;
do {
v = num.get();
d = Double.longBitsToDouble(v);
} while (amount > d && !num.compareAndSet(v, n));
}
private double toRateLong(AtomicLong num, long deltaMillis, boolean reset) {
final long v = reset ? num.getAndSet(0L) : num.get();
final double delta = deltaMillis / 1000.0;
return v / delta;
}
private double toRateDouble(AtomicLong num, long deltaMillis, boolean reset) {
final long v = reset ? num.getAndSet(ZERO) : num.get();
final double delta = deltaMillis / 1000.0;
return Double.longBitsToDouble(v) / delta;
}
private double toDouble(AtomicLong num, boolean reset) {
final long v = reset ? num.getAndSet(ZERO) : num.get();
return Double.longBitsToDouble(v);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return clock.wallTime() - lastUpdateTime.get() > INACTIVE_TTL;
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
final long prev = lastResetTime.get();
final long delta = now - prev;
final boolean reset = delta > resetFreq;
if (reset) {
lastResetTime.set(now);
}
final List<Measurement> ms = new ArrayList<>(3);
if (delta > 1000L) {
ms.add(new Measurement(countId, now, toRateLong(count, delta, reset)));
ms.add(new Measurement(totalAmountId, now, toRateDouble(totalAmount, delta, reset)));
ms.add(new Measurement(totalOfSquaresId, now, toRateDouble(totalOfSquares, delta, reset)));
ms.add(new Measurement(maxId, now, toDouble(max, reset)));
}
return ms;
}
/**
* Updates the statistics kept by the summary with the specified amount.
*
* @param amount
* Amount for an event being measured. For example, if the size in bytes of responses
* from a server. If the amount is less than 0 the value will be dropped.
*/
public void record(double amount) {
if (amount >= 0.0) {
add(totalAmount, amount);
add(totalOfSquares, amount * amount);
max(max, amount);
count.incrementAndGet();
lastUpdateTime.set(clock.wallTime());
}
}
/** The number of times that record has been called since this timer was created. */
public long count() {
return count.get();
}
/** The total amount of all recorded events since this summary was created. */
public double totalAmount() {
return Double.longBitsToDouble(totalAmount.get());
}
}
| 5,987 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/HttpLogEntry.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.impl.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Helper for logging http request related information.
*
* @deprecated Moved to {@code com.netflix.spectator.ipc.http} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public class HttpLogEntry {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpLogEntry.class);
private static final Marker CLIENT = MarkerFactory.getMarker("http-client");
private static final Marker SERVER = MarkerFactory.getMarker("http-server");
private static final Registry REGISTRY = Spectator.globalRegistry();
private static final Id COMPLETE = REGISTRY.createId("http.req.complete");
private static final Id ATTEMPT = REGISTRY.createId("http.req.attempt");
private static final Id REQ_HEADER_SIZE = REGISTRY.createId("http.req.headerSize");
private static final Id REQ_ENTITY_SIZE = REGISTRY.createId("http.req.entitySize");
private static final Id RES_HEADER_SIZE = REGISTRY.createId("http.res.headerSize");
private static final Id RES_ENTITY_SIZE = REGISTRY.createId("http.res.entitySize");
private static final BucketFunction BUCKETS =
BucketFunctions.latency(maxLatency(), TimeUnit.MILLISECONDS);
/**
* Including the endpoint is useful, but we need to be careful about the number of
* matches. A fixed prefix list is fairly easy to use and makes the number and set of matches
* explicit.
*/
private static final List<String> ENDPOINT_PREFIXES = parseEndpoints(endpointPrefixes());
private static long maxLatency() {
return Long.parseLong(System.getProperty("spectator.http.maxLatency", "8000"));
}
private static String endpointPrefixes() {
return System.getProperty("spectator.http.endpointPrefixes", "/healthcheck");
}
private static List<String> parseEndpoints(String s) {
String[] prefixes = (s == null) ? new String[] {} : s.split("[,\\s]+");
List<String> buf = new ArrayList<>();
for (String prefix : prefixes) {
String tmp = prefix.trim();
if (tmp.length() > 0) {
buf.add(prefix);
}
}
Collections.sort(buf);
return buf;
}
private static String longestPrefixMatch(String path, String dflt) {
if (path == null || path.length() == 0) {
return dflt;
}
int length = 0;
String longest = null;
for (String prefix : ENDPOINT_PREFIXES) {
if (path.startsWith(prefix) && prefix.length() > length) {
longest = prefix;
length = prefix.length();
}
}
return (longest == null) ? dflt : longest;
}
/** Log a client request. */
public static void logClientRequest(HttpLogEntry entry) {
log(LOGGER, CLIENT, entry);
}
/**
* Log a client request.
* @deprecated Use {@link #logClientRequest(HttpLogEntry)} instead.
*/
@Deprecated
public static void logClientRequest(Logger logger, HttpLogEntry entry) {
log(logger, CLIENT, entry);
}
/** Log a request received by a server. */
public static void logServerRequest(HttpLogEntry entry) {
log(LOGGER, SERVER, entry);
}
/**
* Log a request received by a server.
* @deprecated Use {@link #logServerRequest(HttpLogEntry)} instead.
*/
@Deprecated
public static void logServerRequest(Logger logger, HttpLogEntry entry) {
log(logger, SERVER, entry);
}
private static void log(Logger logger, Marker marker, HttpLogEntry entry) {
Preconditions.checkNotNull(entry.method, "method");
Id dimensions = REGISTRY.createId("tags")
.withTag("mode", marker.getName())
.withTag("status", entry.getStatusTag())
.withTag("statusCode", entry.getStatusCodeTag())
.withTag("method", entry.method);
if (entry.clientName != null) {
dimensions = dimensions.withTag("client", entry.clientName);
}
if (marker == SERVER && entry.path != null) {
dimensions = dimensions.withTag("endpoint", longestPrefixMatch(entry.path, "other"));
}
// Update stats for the final attempt after retries are exhausted
if (!entry.canRetry || entry.attempt >= entry.maxAttempts) {
BucketTimer.get(REGISTRY, COMPLETE.withTags(dimensions.tags()), BUCKETS)
.record(entry.getOverallLatency(), TimeUnit.MILLISECONDS);
}
// Update stats for every actual http request
BucketTimer.get(REGISTRY, ATTEMPT.withTags(dimensions.tags()), BUCKETS)
.record(entry.getLatency(), TimeUnit.MILLISECONDS);
REGISTRY.distributionSummary(REQ_HEADER_SIZE.withTags(dimensions.tags()))
.record(entry.getRequestHeadersLength());
REGISTRY.distributionSummary(REQ_ENTITY_SIZE.withTags(dimensions.tags()))
.record(entry.requestContentLength);
REGISTRY.distributionSummary(RES_HEADER_SIZE.withTags(dimensions.tags()))
.record(entry.getResponseHeadersLength());
REGISTRY.distributionSummary(RES_ENTITY_SIZE.withTags(dimensions.tags()))
.record(entry.responseContentLength);
// Write data out to logger if enabled. For many monitoring use-cases there tend to be
// frequent requests that can be quite noisy so the log level is set to debug. This class is
// mostly intended to generate something like an access log so it presumes users who want the
// information will configure an appender based on the markers to send the data to a
// dedicated file. Others shouldn't have to deal with the spam in the logs, so debug for the
// level seems reasonable.
if (logger.isDebugEnabled(marker)) {
logger.debug(marker, entry.toString());
}
}
/** Generate a new request id. */
private static String newId() {
return UUID.randomUUID().toString();
}
// Cannot be static constant, date format is not thread-safe
private final SimpleDateFormat isoDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private String clientName = null;
private String requestId = newId();
private String originalUri = null;
private String requestUri = null;
private String path = null;
private String method = null;
private List<Header> requestHeaders = new ArrayList<>();
private long requestContentLength = -1;
private String remoteAddr = null;
private int remotePort = -1;
private String attemptId = requestId;
private int attempt = 1;
private int maxAttempts = -1;
private boolean canRetry = false;
private int redirect = 0;
private Throwable exception = null;
private int statusCode = -1;
private String statusReason = null;
private List<Header> responseHeaders = new ArrayList<>();
private long responseContentLength = -1;
private List<Event> events = new ArrayList<>();
private long latency = -1;
private long originalStart = -1;
private void reset(int redir) {
if (originalStart < 0 && !events.isEmpty()) {
originalStart = events.get(0).timestamp();
}
requestHeaders.clear();
requestContentLength = -1;
remoteAddr = null;
remotePort = -1;
redirect = redir;
exception = null;
statusCode = -1;
responseHeaders.clear();
responseContentLength = -1;
events.clear();
latency = -1;
}
/** Set the name of the client, often used for clients to identify a particular config. */
public HttpLogEntry withClientName(String name) {
this.clientName = name;
return this;
}
/**
* Set the original uri. In the case of approaches with client-side load balancing this will
* be some alias indicating the group of hosts. The request uri would indicate a specific host
* used for an actual network request.
*/
public HttpLogEntry withOriginalUri(String uri) {
this.originalUri = uri;
return this;
}
/**
* Set the original uri. In the case of approaches with client-side load balancing this will
* be some alias indicating the group of hosts. The request uri would indicate a specific host
* used for an actual network request.
*/
public HttpLogEntry withOriginalUri(URI uri) {
return withOriginalUri(uri.toString());
}
/** Set the URI for the actual http request. */
public HttpLogEntry withRequestUri(String uri, String path) {
this.requestUri = uri;
this.path = path;
return this;
}
/** Set the URI for the actual http request. */
public HttpLogEntry withRequestUri(URI uri) {
return withRequestUri(uri.toString(), uri.getPath());
}
/** Set the method for the request. */
public HttpLogEntry withMethod(String httpMethod) {
this.method = httpMethod;
return this;
}
/** Add a header that was on the request. */
public HttpLogEntry withRequestHeader(String name, String value) {
requestHeaders.add(new Header(name, value));
return this;
}
/** Set the content-length for the request. */
public HttpLogEntry withRequestContentLength(long size) {
this.requestContentLength = size;
return this;
}
/**
* Set the remote address. For a client making a request this should be the server, for a
* server receiving a request it should be the client.
*/
public HttpLogEntry withRemoteAddr(String addr) {
this.remoteAddr = addr;
return this;
}
/**
* Set the remote port. For a client making a request this should be the server, for a
* server receiving a request it should be the client.
*/
public HttpLogEntry withRemotePort(int port) {
this.remotePort = port;
return this;
}
/** Set the attempt if retries are used, should only be used after the initial request. */
public HttpLogEntry withAttempt(int n) {
this.attempt = n;
this.attemptId = newId();
reset(0);
return this;
}
/** Set the attempt if redirect occurs, should only be used after the initial request. */
public HttpLogEntry withRedirect(URI loc) {
reset(redirect + 1);
return withRequestUri(loc);
}
/** Set the max number of attempts that will be tried. */
public HttpLogEntry withMaxAttempts(int attempts) {
this.maxAttempts = attempts;
return this;
}
/** Set to true if the error is one that can be retried. */
public HttpLogEntry withCanRetry(boolean retry) {
this.canRetry = retry;
return this;
}
/** Set the exception if there is a failure such as a connect timeout. */
public HttpLogEntry withException(Throwable t) {
exception = t;
return this;
}
/** Set the status code from the response. */
public HttpLogEntry withStatusCode(int code) {
this.statusCode = code;
return this;
}
/** Set the status reason from the response. */
public HttpLogEntry withStatusReason(String reason) {
this.statusReason = reason;
return this;
}
/** Add a header that was on the response. */
public HttpLogEntry withResponseHeader(String name, String value) {
responseHeaders.add(new Header(name, value));
return this;
}
/** Set the content-length from the response. */
public HttpLogEntry withResponseContentLength(long size) {
this.responseContentLength = size;
return this;
}
/** Set the latency for the request. */
public HttpLogEntry withRequestLatency(long t) {
this.latency = t;
return this;
}
/** Mark the time an event occurred. Should include at least the start and end of a request. */
public HttpLogEntry mark(String name) {
events.add(new Event(name, System.currentTimeMillis()));
return this;
}
/** Mark the time an event occurred. Should include at least the start and end of a request. */
public HttpLogEntry mark(String name, long timestamp) {
events.add(new Event(name, timestamp));
return this;
}
/** Return the request id. */
public String getRequestId() {
return requestId;
}
/** Return the attempt id. */
public String getAttemptId() {
return attemptId;
}
/**
* Return the latency for the request. If not explicitly set it will be calculated from the
* events.
*/
public long getLatency() {
if (latency >= 0L) {
return latency;
} else if (events.size() >= 2) {
return events.get(events.size() - 1).timestamp() - events.get(0).timestamp();
} else {
return -1;
}
}
/** Return the overall latency for a group of requests including all retries. */
public long getOverallLatency() {
if (maxAttempts <= 1 || originalStart < 0) {
return getLatency();
} else if (events.isEmpty()) {
return -1;
} else {
return events.get(events.size() - 1).timestamp() - originalStart;
}
}
/** Return the starting time for the request. */
public String getStartTime() {
return events.isEmpty()
? "unknown"
: isoDate.format(new Date(events.get(0).timestamp()));
}
private int getHeadersLength(List<Header> headers) {
int size = 0;
for (Header h : headers) {
size += h.numBytes();
}
return size;
}
/** Return the size in bytes of all request headers. */
public int getRequestHeadersLength() {
return getHeadersLength(requestHeaders);
}
/** Return the size in bytes of all response headers. */
public int getResponseHeadersLength() {
return getHeadersLength(responseHeaders);
}
/** Return a time line based on marked events. */
public String getTimeline() {
StringBuilder builder = new StringBuilder();
for (Event event : events) {
builder.append(event.name()).append(":").append(event.timestamp()).append(";");
}
return builder.toString();
}
private String getExceptionClass() {
return (exception == null)
? "null"
: exception.getClass().getName();
}
private String getExceptionMessage() {
return (exception == null)
? "null"
: exception.getMessage();
}
private String getHeaders(List<Header> headers) {
StringBuilder builder = new StringBuilder();
for (Header h : headers) {
builder.append(h.name()).append(':').append(h.value()).append(';');
}
return builder.toString();
}
/** Return a summary of all request headers. */
public String getRequestHeaders() {
return getHeaders(requestHeaders);
}
/** Return a summary of all response headers. */
public String getResponseHeaders() {
return getHeaders(responseHeaders);
}
private String getStatusTag() {
return (exception != null)
? exception.getClass().getSimpleName()
: (statusCode >= 100 ? (statusCode / 100) + "xx" : "unknown");
}
private String getStatusCodeTag() {
return (exception != null)
? exception.getClass().getSimpleName()
: (statusCode >= 100 ? "" + statusCode : "unknown");
}
@Override public String toString() {
return new StringBuilder()
.append(clientName).append('\t')
.append(getStartTime()).append('\t')
.append(getLatency()).append('\t')
.append(getOverallLatency()).append('\t')
.append(getTimeline()).append('\t')
.append(method).append('\t')
.append(originalUri).append('\t')
.append(requestUri).append('\t')
.append(remoteAddr).append('\t')
.append(remotePort).append('\t')
.append(statusCode).append('\t')
.append(statusReason).append('\t')
.append(getExceptionClass()).append('\t')
.append(getExceptionMessage()).append('\t')
.append(getRequestHeadersLength()).append('\t')
.append(requestContentLength).append('\t')
.append(getResponseHeadersLength()).append('\t')
.append(responseContentLength).append('\t')
.append(getRequestHeaders()).append('\t')
.append(getResponseHeaders()).append('\t')
.append(redirect).append('\t')
.append(attempt).append('\t')
.append(maxAttempts)
.toString();
}
private static class Header {
private final String name;
private final String value;
Header(String name, String value) {
this.name = name;
this.value = value;
}
String name() {
return name;
}
String value() {
return value;
}
int numBytes() {
return name.length() + ": ".length() + value.length() + "\n".length();
}
}
private static class Event {
private final String name;
private final long timestamp;
Event(String name, long timestamp) {
this.name = name;
this.timestamp = timestamp;
}
String name() {
return name;
}
long timestamp() {
return timestamp;
}
}
}
| 5,988 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/HttpClient.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import java.net.URI;
/**
* Simple blocking http client using {@link HttpLogEntry} and
* {@link java.net.HttpURLConnection}. This can be used as an example of the logging
* or for light use-cases where it is more desirable not to have dependencies on
* a more robust HTTP library. Usage:
*
* <pre>
* HttpClient client = HttpClient.DEFAULT;
* HttpResponse response = client.get(URI.create("http://example.com")).send();
* </pre>
*
* For testing an alternative client implementation can be used to customize the
* send. For example to create a client that will always fail:
*
* <pre>
* HttpClient client = (n, u) -> new HttpRequestBuilder(n, u) {
* {@literal @}Override protected HttpResponse sendImpl() throws IOException {
* throw new ConnectException("could not connect to " + u.getHost());
* }
* };
* </pre>
*
* @deprecated Moved to {@code com.netflix.spectator.ipc.http} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public interface HttpClient {
/** Client implementation based on {@link java.net.HttpURLConnection}. */
HttpClient DEFAULT = HttpRequestBuilder::new;
/**
* Create a new request builder.
*
* @param clientName
* Name used to identify this client.
* @param uri
* URI to use for the request.
* @return
* Builder for creating and executing a request.
*/
HttpRequestBuilder newRequest(String clientName, URI uri);
/**
* Create a new GET request builder. The client name will be selected based
* on a prefix of the host name.
*
* @param uri
* URI to use for the request.
* @return
* Builder for creating and executing a request.
*/
default HttpRequestBuilder get(URI uri) {
return newRequest(HttpUtils.clientNameForURI(uri), uri).withMethod("GET");
}
/**
* Create a new POST request builder. The client name will be selected based
* on a prefix of the host name.
*
* @param uri
* URI to use for the request.
* @return
* Builder for creating and executing a request.
*/
default HttpRequestBuilder post(URI uri) {
return newRequest(HttpUtils.clientNameForURI(uri), uri).withMethod("POST");
}
/**
* Create a new PUT request builder. The client name will be selected based
* on a prefix of the host name.
*
* @param uri
* URI to use for the request.
* @return
* Builder for creating and executing a request.
*/
default HttpRequestBuilder put(URI uri) {
return newRequest(HttpUtils.clientNameForURI(uri), uri).withMethod("PUT");
}
/**
* Create a new DELETE request builder. The client name will be selected based
* on a prefix of the host name.
*
* @param uri
* URI to use for the request.
* @return
* Builder for creating and executing a request.
*/
default HttpRequestBuilder delete(URI uri) {
return newRequest(HttpUtils.clientNameForURI(uri), uri).withMethod("DELETE");
}
}
| 5,989 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketFunction.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import java.util.function.LongFunction;
/**
* Function to map an amount passed to a distribution summary or timer to a bucket.
*
* @deprecated Moved to {@code com.netflix.spectator.api.histogram} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public interface BucketFunction extends LongFunction<String> {
/**
* Returns a bucket for the specified amount.
*
* @param amount
* Amount for an event being measured.
* @return
* Bucket name to use for the amount.
*/
@Override String apply(long amount);
}
| 5,990 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/HttpRequestBuilder.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import com.netflix.spectator.impl.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.Deflater;
/**
* Helper for executing simple HTTP client requests using {@link HttpURLConnection}
* and logging via {@link HttpLogEntry}. This is mostly used for simple use-cases
* where it is undesirable to have additional dependencies on a more robust HTTP
* library.
*
* @deprecated Moved to {@code com.netflix.spectator.ipc.http} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public class HttpRequestBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestBuilder.class);
private final URI uri;
private final HttpLogEntry entry;
private String method = "GET";
private Map<String, String> reqHeaders = new LinkedHashMap<>();
private byte[] entity = HttpUtils.EMPTY;
private int connectTimeout = 1000;
private int readTimeout = 30000;
private long initialRetryDelay = 1000L;
private int numAttempts = 1;
private HostnameVerifier hostVerifier = null;
private SSLSocketFactory sslFactory = null;
/** Create a new instance for the specified URI. */
public HttpRequestBuilder(String clientName, URI uri) {
this.uri = uri;
this.entry = new HttpLogEntry()
.withRequestUri(uri)
.withClientName(clientName)
.withMethod(method);
}
/** Set the request method (GET, PUT, POST, DELETE). */
public HttpRequestBuilder withMethod(String m) {
this.method = m;
entry.withMethod(method);
return this;
}
/**
* Add a header to the request. Note the content type will be set automatically
* when providing the content payload and should not be set here.
*/
public HttpRequestBuilder addHeader(String name, String value) {
reqHeaders.put(name, value);
entry.withRequestHeader(name, value);
return this;
}
/** Add user-agent header. */
public HttpRequestBuilder userAgent(String agent) {
return addHeader("User-Agent", agent);
}
/** Add header to accept {@code application/json} data. */
public HttpRequestBuilder acceptJson() {
return addHeader("Accept", "application/json");
}
/** Add accept header. */
public HttpRequestBuilder accept(String type) {
return addHeader("Accept", type);
}
/** Add header to accept-encoding of gzip. */
public HttpRequestBuilder acceptGzip() {
return acceptEncoding("gzip");
}
/** Add accept-encoding header. */
public HttpRequestBuilder acceptEncoding(String enc) {
return addHeader("Accept-Encoding", enc);
}
/** Set the connection timeout for the request in milliseconds. */
public HttpRequestBuilder withConnectTimeout(int timeout) {
this.connectTimeout = timeout;
return this;
}
/** Set the read timeout for the request milliseconds. */
public HttpRequestBuilder withReadTimeout(int timeout) {
this.readTimeout = timeout;
return this;
}
/** Set the request body as JSON. */
public HttpRequestBuilder withJsonContent(String content) {
return withContent("application/json", content);
}
/** Set the request body. */
public HttpRequestBuilder withContent(String type, String content) {
return withContent(type, content.getBytes(StandardCharsets.UTF_8));
}
/** Set the request body. */
public HttpRequestBuilder withContent(String type, byte[] content) {
addHeader("Content-Type", type);
entity = content;
return this;
}
/**
* Compress the request body using the default compression level.
* The content must have already been set on the builder.
*/
public HttpRequestBuilder compress() throws IOException {
return compress(Deflater.DEFAULT_COMPRESSION);
}
/**
* Compress the request body using the specified compression level.
* The content must have already been set on the builder.
*/
public HttpRequestBuilder compress(int level) throws IOException {
addHeader("Content-Encoding", "gzip");
entity = HttpUtils.gzip(entity, level);
return this;
}
/** How many times to retry if the intial attempt fails? */
public HttpRequestBuilder withRetries(int n) {
Preconditions.checkArg(n >= 0, "number of retries must be >= 0");
this.numAttempts = n + 1;
entry.withMaxAttempts(numAttempts);
return this;
}
/**
* How long to delay before retrying if the request is throttled. This will get doubled
* for each attempt that is throttled. Unit is milliseconds.
*/
public HttpRequestBuilder withInitialRetryDelay(long delay) {
Preconditions.checkArg(delay >= 0L, "initial retry delay must be >= 0");
this.initialRetryDelay = delay;
return this;
}
private void requireHttps(String msg) {
Preconditions.checkState("https".equals(uri.getScheme()), msg);
}
/** Sets the policy used to verify hostnames when using HTTPS. */
public HttpRequestBuilder withHostnameVerifier(HostnameVerifier verifier) {
requireHttps("hostname verification cannot be used with http, switch to https");
this.hostVerifier = verifier;
return this;
}
/**
* Specify that all hosts are allowed. Using this option effectively disables hostname
* verification. Use with caution.
*/
public HttpRequestBuilder allowAllHosts() {
return withHostnameVerifier((host, session) -> true);
}
/** Sets the socket factory to use with HTTPS. */
public HttpRequestBuilder withSSLSocketFactory(SSLSocketFactory factory) {
requireHttps("ssl cannot be used with http, use https");
this.sslFactory = factory;
return this;
}
/** Send the request and log/update metrics for the results. */
@SuppressWarnings("PMD.ExceptionAsFlowControl")
public HttpResponse send() throws IOException {
HttpResponse response = null;
for (int attempt = 1; attempt <= numAttempts; ++attempt) {
entry.withAttempt(attempt);
try {
response = sendImpl();
int s = response.status();
if (s == 429 || s == 503) {
// Request is getting throttled, exponentially back off
// - 429 client sending too many requests
// - 503 server unavailable
try {
long delay = initialRetryDelay << (attempt - 1);
LOGGER.debug("request throttled, delaying for {}ms: {} {}", delay, method, uri);
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("request failed " + method + " " + uri, e);
}
} else if (s < 500) {
// 4xx errors other than 429 are not considered retriable, so for anything
// less than 500 just return the response to the user
return response;
}
} catch (IOException e) {
// All exceptions are considered retriable. Some like UnknownHostException are
// debatable, but we have seen them in some cases if there is a high latency for
// DNS lookups. So for now assume all exceptions are transient issues.
if (attempt == numAttempts) {
throw e;
} else {
LOGGER.warn("attempt {} of {} failed: {} {}", attempt, numAttempts, method, uri);
}
}
}
if (response == null) {
// Should not get here
throw new IOException("request failed " + method + " " + uri);
}
return response;
}
private void configureHTTPS(HttpURLConnection http) {
if (http instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) http;
if (hostVerifier != null) {
https.setHostnameVerifier(hostVerifier);
}
if (sslFactory != null) {
https.setSSLSocketFactory(sslFactory);
}
}
}
/** Send the request and log/update metrics for the results. */
protected HttpResponse sendImpl() throws IOException {
HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
con.setRequestMethod(method);
for (Map.Entry<String, String> h : reqHeaders.entrySet()) {
con.setRequestProperty(h.getKey(), h.getValue());
}
configureHTTPS(con);
boolean canRetry = true;
try {
con.setDoInput(true);
// HttpURLConnection will change method to POST if there is a body associated
// with a GET request. Only try to write entity if it is not empty.
entry.withRequestContentLength(entity.length).mark("start");
if (entity.length > 0) {
con.setDoOutput(true);
try (OutputStream out = con.getOutputStream()) {
out.write(entity);
}
}
int status = con.getResponseCode();
canRetry = (status >= 500 || status == 429);
entry.mark("complete").withStatusCode(status);
// A null key is used to return the status line, remove it before sending to
// the log entry or creating the response object
Map<String, List<String>> headers = new LinkedHashMap<>(con.getHeaderFields());
headers.remove(null);
for (Map.Entry<String, List<String>> h : headers.entrySet()) {
for (String v : h.getValue()) {
entry.withResponseHeader(h.getKey(), v);
}
}
try (InputStream in = (status >= 400) ? con.getErrorStream() : con.getInputStream()) {
byte[] data = readAll(in);
entry.withResponseContentLength(data.length);
return new HttpResponse(status, headers, data);
}
} catch (IOException e) {
entry.mark("complete").withException(e);
throw e;
} finally {
entry.withCanRetry(canRetry);
HttpLogEntry.logClientRequest(entry);
}
}
@SuppressWarnings("PMD.AssignmentInOperand")
private byte[] readAll(InputStream in) throws IOException {
if (in == null) {
// For error status codes with a content-length of 0 we see this case
return new byte[0];
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
return baos.toByteArray();
}
}
}
| 5,991 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/HttpUtils.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Helper functions for the http client.
*/
final class HttpUtils {
private HttpUtils() {
}
/** Empty byte array constant. */
static final byte[] EMPTY = new byte[0];
private static final String DEFAULT = "default";
private static final Pattern PREFIX = Pattern.compile("^([^.-]+).*$");
/**
* Extract a client name based on the host. This will currently select up
* to the first dash or dot in the name. The goal is to have a reasonable
* name, but avoid a large explosion in number of names in dynamic environments
* such as EC2. Examples:
*
* <pre>
* name host
* ----------------------------------------------------
* foo foo.test.netflix.com
* ec2 ec2-127-0-0-1.compute-1.amazonaws.com
* </pre>
*/
static String clientNameForHost(String host) {
Matcher m = PREFIX.matcher(host);
return m.matches() ? m.group(1) : DEFAULT;
}
/**
* Extract a client name based on the uri host. See {@link #clientNameForHost(String)}
* for more details.
*/
static String clientNameForURI(URI uri) {
String host = uri.getHost();
return (host == null) ? DEFAULT : clientNameForHost(host);
}
/** Wrap GZIPOutputStream allowing the user to override the compression level. */
static class GzipLevelOutputStream extends GZIPOutputStream {
/** Creates a new output stream with a default compression level. */
GzipLevelOutputStream(OutputStream outputStream) throws IOException {
super(outputStream);
}
/** Set the compression level for the underlying deflater. */
void setLevel(int level) {
def.setLevel(level);
}
}
/**
* Compress a byte array using GZIP's default compression level.
*/
static byte[] gzip(byte[] data) throws IOException {
return gzip(data, Deflater.DEFAULT_COMPRESSION);
}
/**
* Compress a byte array using GZIP with the given compression level.
*/
static byte[] gzip(byte[] data, int level) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
try (GzipLevelOutputStream out = new GzipLevelOutputStream(baos)) {
out.setLevel(level);
out.write(data);
}
return baos.toByteArray();
}
/** Decompress a GZIP compressed byte array. */
@SuppressWarnings("PMD.AssignmentInOperand")
static byte[] gunzip(byte[] data) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length * 10);
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
}
return baos.toByteArray();
}
}
| 5,992 |
0 | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/HttpResponse.java | /*
* Copyright 2014-2020 Netflix, Inc.
*
* 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 com.netflix.spectator.sandbox;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Response for an HTTP request made via {@link HttpRequestBuilder}.
*
* @deprecated Moved to {@code com.netflix.spectator.ipc.http} package. This is now just a
* thin wrapper to preserve compatibility. This class is scheduled for removal in a future release.
*/
@Deprecated
public class HttpResponse {
private final int status;
private final Map<String, List<String>> headers;
private final byte[] data;
/** Create a new response instance with an empty entity. */
public HttpResponse(int status, Map<String, List<String>> headers) {
this(status, headers, HttpUtils.EMPTY);
}
/** Create a new response instance. */
public HttpResponse(int status, Map<String, List<String>> headers, byte[] data) {
this.status = status;
Map<String, List<String>> hs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
hs.putAll(headers);
this.headers = Collections.unmodifiableMap(hs);
this.data = data;
}
/** Return the status code of the response. */
public int status() {
return status;
}
/**
* Return the headers for the response as an unmodifiable map with case-insensitive keys.
*/
public Map<String, List<String>> headers() {
return headers;
}
/** Return the value for the first occurrence of a given header or null if not found. */
public String header(String k) {
List<String> vs = headers.get(k);
return (vs == null || vs.isEmpty()) ? null : vs.get(0);
}
/**
* Return the value for a date header. The return value will be null if the header does
* not exist or if it cannot be parsed correctly as a date.
*/
public Instant dateHeader(String k) {
String d = header(k);
return (d == null) ? null : parseDate(d);
}
private Instant parseDate(String d) {
try {
return LocalDateTime.parse(d, DateTimeFormatter.RFC_1123_DATE_TIME)
.atZone(ZoneOffset.UTC)
.toInstant();
} catch (Exception e) {
return null;
}
}
/** Return the entity for the response. */
public byte[] entity() {
return data;
}
/** Return the entity as a UTF-8 string. */
public String entityAsString() {
return new String(data, StandardCharsets.UTF_8);
}
/** Return a copy of the response with the entity decompressed. */
public HttpResponse decompress() throws IOException {
String enc = header("Content-Encoding");
return (enc != null && enc.contains("gzip")) ? unzip() : this;
}
private HttpResponse unzip() throws IOException {
Map<String, List<String>> newHeaders = headers.entrySet().stream()
.filter(e -> !"Content-Encoding".equalsIgnoreCase(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (data.length == 0) {
return new HttpResponse(status, newHeaders);
} else {
return new HttpResponse(status, newHeaders, HttpUtils.gunzip(data));
}
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(50);
builder.append("HTTP/1.1 ").append(status).append('\n');
for (Map.Entry<String, List<String>> h : headers.entrySet()) {
for (String v : h.getValue()) {
builder.append(h.getKey()).append(": ").append(v).append('\n');
}
}
builder.append("\n... ")
.append(data.length)
.append(" bytes ...\n");
return builder.toString();
}
}
| 5,993 |
0 | Create_ds/spectator/spectator-agent/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-agent/src/test/java/com/netflix/spectator/agent/AgentTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.agent;
import com.typesafe.config.Config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AgentTest {
@Test
public void loadConfigA() {
Config config = Agent.loadConfig(Agent.parseResourceList("a"));
Assertions.assertEquals("a", config.getString("option"));
Assertions.assertTrue(config.getBoolean("a"));
}
@Test
public void loadConfigAB() {
Config config = Agent.loadConfig(Agent.parseResourceList("a,b"));
Assertions.assertEquals("b", config.getString("option"));
Assertions.assertTrue(config.getBoolean("a"));
Assertions.assertTrue(config.getBoolean("b"));
}
@Test
public void loadConfigABC() {
Config config = Agent.loadConfig(Agent.parseResourceList("a\tb, \nc"));
Assertions.assertEquals("c", config.getString("option"));
Assertions.assertTrue(config.getBoolean("a"));
Assertions.assertTrue(config.getBoolean("b"));
Assertions.assertTrue(config.getBoolean("c"));
}
@Test
public void loadConfigListsAppend() {
Config config = Agent.loadConfig(Agent.parseResourceList("a,b,c"));
List<String> items = config.getStringList("list");
Collections.sort(items);
List<String> expected = new ArrayList<>();
expected.add("a");
expected.add("b");
expected.add("c");
Assertions.assertEquals(expected, items);
}
}
| 5,994 |
0 | Create_ds/spectator/spectator-agent/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-agent/src/main/java/com/netflix/spectator/agent/Agent.java | /*
* Copyright 2014-2021 Netflix, Inc.
*
* 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 com.netflix.spectator.agent;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.atlas.AtlasConfig;
import com.netflix.spectator.atlas.AtlasRegistry;
import com.netflix.spectator.gc.GcLogger;
import com.netflix.spectator.jvm.Jmx;
import com.netflix.spectator.jvm.JmxPoller;
import com.netflix.spectator.nflx.tagging.NetflixTagging;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.instrument.Instrumentation;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
/**
* Agent that can be added to JVM to get basic stats about GC, memory, and optionally
* JMX.
*/
public final class Agent {
private static final Logger LOGGER = LoggerFactory.getLogger(Agent.class);
private Agent() {
}
/** Parse the set of user resources. */
static List<Object> parseResourceList(String userResources) {
List<Object> resources = new ArrayList<>();
if (userResources != null && !"".equals(userResources)) {
for (String userResource : userResources.split("[,\\s]+")) {
if (userResource.startsWith("file:")) {
File file = new File(userResource.substring("file:".length()));
resources.add(file);
} else {
resources.add(userResource);
}
}
}
return resources;
}
/** Check for changes to the configs on the file system. */
static List<File> findUpdatedConfigs(List<Object> resources, long timestamp) {
return resources.stream()
.filter(r -> r instanceof File && ((File) r).lastModified() > timestamp)
.map(r -> (File) r)
.collect(Collectors.toList());
}
/** Helper to load config files specified by the user. */
static Config loadConfig(List<Object> resources) {
Config config = ConfigFactory.load("agent");
for (Object r : resources) {
if (r instanceof File) {
File file = (File) r;
LOGGER.info("loading configuration from file: {}", file);
Config user = ConfigFactory.parseFile(file);
config = user.withFallback(config);
} else {
String userResource = (String) r;
LOGGER.info("loading configuration from resource: {}", userResource);
Config user = ConfigFactory.parseResourcesAnySyntax(userResource);
config = user.withFallback(config);
}
}
return config.resolve().getConfig("netflix.spectator.agent");
}
/**
* To make debugging easier since we usually create a fat jar, system properties can
* be created so that all jar versions can easily be accessed via JMX or using tools
* like {@code jinfo}.
*/
private static void createDependencyProperties(Config config) {
if (config.hasPath("dependencies")) {
List<String> deps = config.getStringList("dependencies");
for (int i = 0; i < deps.size(); ++i) {
String prop = String.format("netflix.spectator.agent.dependency.%03d", i);
System.setProperty(prop, deps.get(i));
}
}
}
/** Entry point for the agent. */
public static void premain(String arg, Instrumentation instrumentation) throws Exception {
// Setup logging
final List<Object> resources = parseResourceList(arg);
Config config = loadConfig(resources);
LOGGER.debug("loaded configuration: {}", config.root().render());
createDependencyProperties(config);
// Setup Registry
AtlasRegistry registry = new AtlasRegistry(Clock.SYSTEM, new AgentAtlasConfig(config));
// Add to global registry for http stats and GC logger
Spectator.globalRegistry().add(registry);
// Enable GC logger
GcLogger gcLogger = new GcLogger();
if (config.getBoolean("collection.gc")) {
gcLogger.start(null);
}
// Enable JVM data collection
if (config.getBoolean("collection.jvm")) {
Jmx.registerStandardMXBeans(registry);
}
// Enable JMX query collection
if (config.getBoolean("collection.jmx")) {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "spectator-agent-jmx");
t.setDaemon(true);
return t;
});
// Poll the JMX data at least once per step interval unless it is less than a second
// to avoid to much overhead
Duration step = Duration.parse(config.getString("atlas.step"));
long delay = Math.max(1000L, step.toMillis() / 2L);
// Keep track of last time the configs have been loaded
final AtomicLong lastUpdated = new AtomicLong(System.currentTimeMillis());
final JmxPoller poller = new JmxPoller(registry);
poller.updateConfigs(config.getConfigList("jmx.mappings"));
exec.scheduleWithFixedDelay(() -> {
try {
List<File> updatedConfigs = findUpdatedConfigs(resources, lastUpdated.get());
if (!updatedConfigs.isEmpty()) {
LOGGER.info("detected updated config files: {}", updatedConfigs);
lastUpdated.set(System.currentTimeMillis());
Config cfg = loadConfig(resources);
poller.updateConfigs(cfg.getConfigList("jmx.mappings"));
}
} catch (Exception e) {
LOGGER.warn("failed to update jmx config mappings, using previous config", e);
}
poller.poll();
}, delay, delay, TimeUnit.MILLISECONDS);
}
// Start collection for the registry
registry.start();
// Shutdown registry
Runtime.getRuntime().addShutdownHook(new Thread(registry::stop, "spectator-agent-shutdown"));
}
private static class AgentAtlasConfig implements AtlasConfig {
private final Config config;
AgentAtlasConfig(Config config) {
this.config = config;
}
@Override public String get(String k) {
return config.hasPath(k) ? config.getString(k) : null;
}
@Override public Map<String, String> commonTags() {
Map<String, String> tags = NetflixTagging.commonTagsForAtlas();
for (Config cfg : config.getConfigList("atlas.tags")) {
// These are often populated by environment variables that can sometimes be empty
// rather than not set when missing. Empty strings are not allowed by Atlas.
String value = cfg.getString("value");
if (!value.isEmpty()) {
tags.put(cfg.getString("key"), cfg.getString("value"));
}
}
return tags;
}
}
}
| 5,995 |
0 | Create_ds/spectator/spectator-nflx-tagging/src/test/java/com/netflix/spectator/nflx | Create_ds/spectator/spectator-nflx-tagging/src/test/java/com/netflix/spectator/nflx/tagging/NetflixTaggingTest.java | /*
* Copyright 2014-2023 Netflix, Inc.
*
* 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 com.netflix.spectator.nflx.tagging;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
public class NetflixTaggingTest {
private static Map<String, String> sampleEnvironmentVars() {
Map<String, String> vars = new HashMap<>();
vars.put("NETFLIX_ACCOUNT_ID", "1234567890");
vars.put("EC2_AMI_ID", "ami-54321");
vars.put("NETFLIX_APP", "foo");
vars.put("NETFLIX_AUTO_SCALE_GROUP", "foo-bar-s1abc-s2def-v001");
vars.put("NETFLIX_CLUSTER", "foo-bar-s1abc-s2def");
vars.put("NETFLIX_INSTANCE_ID", "i-12345");
vars.put("NETFLIX_PROCESS_NAME", "www");
vars.put("NETFLIX_REGION", "us-east-1");
vars.put("NETFLIX_SHARD1", "abc");
vars.put("NETFLIX_SHARD2", "def");
vars.put("NETFLIX_STACK", "bar");
vars.put("EC2_INSTANCE_TYPE", "m5.large");
vars.put("EC2_AVAILABILITY_ZONE", "us-east-1e");
vars.put("TITUS_CONTAINER_NAME", "main");
vars.put("NETFLIX_ACCOUNT_TYPE", "example");
vars.put("NETFLIX_BUILD_JOB", "http://build/foo/42");
vars.put("NETFLIX_BUILD_SOURCE_REPO", "http://source/foo/42");
vars.put("NETFLIX_BUILD_BRANCH", "main");
vars.put("NETFLIX_BUILD_COMMIT", "abcd1234");
vars.put("MANTIS_JOB_NAME", "foo");
vars.put("MANTIS_JOB_ID", "12");
vars.put("MANTIS_WORKER_INDEX", "0");
vars.put("MANTIS_WORKER_NUMBER", "4");
vars.put("MANTIS_WORKER_STAGE_NUMBER", "5");
vars.put("MANTIS_USER", "bob@example.com");
return vars;
}
private static Map<String, String> sampleExpectedTags() {
Map<String, String> vars = new HashMap<>();
vars.put("nf.account", "1234567890");
vars.put("nf.ami", "ami-54321");
vars.put("nf.app", "foo");
vars.put("nf.asg", "foo-bar-s1abc-s2def-v001");
vars.put("nf.cluster", "foo-bar-s1abc-s2def");
vars.put("nf.container", "main");
vars.put("nf.node", "i-12345");
vars.put("nf.process", "www");
vars.put("nf.region", "us-east-1");
vars.put("nf.shard1", "abc");
vars.put("nf.shard2", "def");
vars.put("nf.stack", "bar");
vars.put("nf.vmtype", "m5.large");
vars.put("nf.zone", "us-east-1e");
vars.put("accountType", "example");
vars.put("buildUrl", "http://build/foo/42");
vars.put("sourceRepo", "http://source/foo/42");
vars.put("branch", "main");
vars.put("commit", "abcd1234");
vars.put("mantisJobName", "foo");
vars.put("mantisJobId", "12");
vars.put("mantisWorkerIndex", "0");
vars.put("mantisWorkerNumber", "4");
vars.put("mantisWorkerStageNumber", "5");
vars.put("mantisUser", "bob@example.com");
return vars;
}
private static Map<String, String> atlasExpectedTags() {
Map<String, String> expected = sampleExpectedTags();
expected.remove("nf.ami");
expected.remove("accountType");
expected.remove("buildUrl");
expected.remove("sourceRepo");
expected.remove("branch");
expected.remove("commit");
expected.put("mantisUser", "bob_example.com");
return expected;
}
@Test
public void commonTags() {
Map<String, String> vars = sampleEnvironmentVars();
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsWhitespaceIgnored() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("NETFLIX_APP", " foo \t\t");
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsNullIgnored() {
Map<String, String> vars = sampleEnvironmentVars();
vars.remove("NETFLIX_SHARD2");
Map<String, String> expected = sampleExpectedTags();
expected.remove("nf.shard2");
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsEmptyIgnored() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("NETFLIX_SHARD2", "");
Map<String, String> expected = sampleExpectedTags();
expected.remove("nf.shard2");
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsForAtlas() {
Map<String, String> vars = sampleEnvironmentVars();
Map<String, String> expected = atlasExpectedTags();
Map<String, String> actual = NetflixTagging.commonTagsForAtlas(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsForAtlasSkipNode() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("ATLAS_SKIP_COMMON_TAGS", "nf.node");
Map<String, String> expected = atlasExpectedTags();
expected.remove("nf.node");
Map<String, String> actual = NetflixTagging.commonTagsForAtlas(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsForAtlasSkipMultiple() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("ATLAS_SKIP_COMMON_TAGS", "nf.node, , nf.zone\n\t,nf.asg,,");
Map<String, String> expected = atlasExpectedTags();
expected.remove("nf.asg");
expected.remove("nf.node");
expected.remove("nf.zone");
Map<String, String> actual = NetflixTagging.commonTagsForAtlas(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsForAtlasSkipEmpty() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("ATLAS_SKIP_COMMON_TAGS", "");
Map<String, String> expected = atlasExpectedTags();
Map<String, String> actual = NetflixTagging.commonTagsForAtlas(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsFallbackToEc2Region() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("EC2_REGION", vars.get("NETFLIX_REGION"));
vars.remove("NETFLIX_REGION");
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsFallbackToOwnerId() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("EC2_OWNER_ID", vars.get("NETFLIX_ACCOUNT_ID"));
vars.remove("NETFLIX_ACCOUNT_ID");
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsFallbackToTitusTaskId() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("TITUS_TASK_INSTANCE_ID", vars.get("NETFLIX_INSTANCE_ID"));
vars.remove("NETFLIX_INSTANCE_ID");
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsFallbackToEc2InstanceId() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("EC2_INSTANCE_ID", vars.get("NETFLIX_INSTANCE_ID"));
vars.remove("NETFLIX_INSTANCE_ID");
Map<String, String> expected = sampleExpectedTags();
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
@Test
public void commonTagsTitusOverridesEc2InstanceId() {
Map<String, String> vars = sampleEnvironmentVars();
vars.put("EC2_INSTANCE_ID", vars.get("NETFLIX_INSTANCE_ID"));
vars.put("TITUS_TASK_INSTANCE_ID", "titus-12345");
vars.remove("NETFLIX_INSTANCE_ID");
Map<String, String> expected = sampleExpectedTags();
expected.put("nf.node", "titus-12345");
Map<String, String> actual = NetflixTagging.commonTags(vars::get);
Assertions.assertEquals(expected, actual);
}
}
| 5,996 |
0 | Create_ds/spectator/spectator-nflx-tagging/src/main/java/com/netflix/spectator/nflx | Create_ds/spectator/spectator-nflx-tagging/src/main/java/com/netflix/spectator/nflx/tagging/NetflixTagging.java | /*
* Copyright 2014-2023 Netflix, Inc.
*
* 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 com.netflix.spectator.nflx.tagging;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Helper utility to extract common tags from the environment.
*/
public final class NetflixTagging {
private NetflixTagging() {
}
/**
* Set of common tag keys that should be used for metrics by default. Other contexts
* like logs could use a larger set that are inappropriate for use on metrics.
*/
private static final Set DEFAULT_ATLAS_TAG_KEYS;
static {
Set<String> tagKeys = new HashSet<>();
tagKeys.add("mantisJobId");
tagKeys.add("mantisJobName");
tagKeys.add("mantisUser");
tagKeys.add("mantisWorkerIndex");
tagKeys.add("mantisWorkerNumber");
tagKeys.add("mantisWorkerStageNumber");
tagKeys.add("nf.account");
tagKeys.add("nf.app");
tagKeys.add("nf.asg");
tagKeys.add("nf.cluster");
tagKeys.add("nf.container");
tagKeys.add("nf.node");
tagKeys.add("nf.process");
tagKeys.add("nf.region");
tagKeys.add("nf.shard1");
tagKeys.add("nf.shard2");
tagKeys.add("nf.stack");
tagKeys.add("nf.vmtype");
tagKeys.add("nf.zone");
DEFAULT_ATLAS_TAG_KEYS = Collections.unmodifiableSet(tagKeys);
}
/** Replace characters not allowed by Atlas with underscore. */
private static String fixTagString(String str) {
return str.replaceAll("[^-._A-Za-z0-9~^]", "_");
}
/** Fix tag strings for map to ensure they are valid for Atlas. */
private static Map<String, String> fixTagStrings(Map<String, String> tags) {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : tags.entrySet()) {
result.put(fixTagString(entry.getKey()), fixTagString(entry.getValue()));
}
return result;
}
/**
* Extract common infrastructure tags for use with metrics, logs, etc from the
* Netflix environment variables.
*
* @return
* Common tags based on the environment.
*/
public static Map<String, String> commonTags() {
return commonTags(System::getenv);
}
/**
* Extract common infrastructure tags for use with metrics, logs, etc from the
* Netflix environment variables.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @return
* Common tags based on the environment.
*/
public static Map<String, String> commonTags(Function<String, String> getenv) {
// Note, these extract from the environment directly rather than use the helper
// methods that access the reference config. This is done because the helpers
// assign default values to many of the entries which can be convenient for testing,
// but are not appropriate for inclusion with tags.
Map<String, String> tags = new HashMap<>();
// Generic infrastructure
putIfNotEmptyOrNull(getenv, tags, "nf.account",
"NETFLIX_ACCOUNT_ID",
"EC2_OWNER_ID");
putIfNotEmptyOrNull(getenv, tags, "nf.ami", "EC2_AMI_ID");
putIfNotEmptyOrNull(getenv, tags, "nf.app", "NETFLIX_APP");
putIfNotEmptyOrNull(getenv, tags, "nf.asg", "NETFLIX_AUTO_SCALE_GROUP");
putIfNotEmptyOrNull(getenv, tags, "nf.cluster", "NETFLIX_CLUSTER");
putIfNotEmptyOrNull(getenv, tags, "nf.container", "TITUS_CONTAINER_NAME");
putIfNotEmptyOrNull(getenv, tags, "nf.node",
"NETFLIX_INSTANCE_ID",
"TITUS_TASK_INSTANCE_ID",
"EC2_INSTANCE_ID");
putIfNotEmptyOrNull(getenv, tags, "nf.process", "NETFLIX_PROCESS_NAME");
putIfNotEmptyOrNull(getenv, tags, "nf.region",
"NETFLIX_REGION",
"EC2_REGION");
putIfNotEmptyOrNull(getenv, tags, "nf.shard1", "NETFLIX_SHARD1");
putIfNotEmptyOrNull(getenv, tags, "nf.shard2", "NETFLIX_SHARD2");
putIfNotEmptyOrNull(getenv, tags, "nf.stack", "NETFLIX_STACK");
putIfNotEmptyOrNull(getenv, tags, "nf.vmtype", "EC2_INSTANCE_TYPE");
putIfNotEmptyOrNull(getenv, tags, "nf.zone", "EC2_AVAILABILITY_ZONE");
// Build info
putIfNotEmptyOrNull(getenv, tags, "accountType", "NETFLIX_ACCOUNT_TYPE");
putIfNotEmptyOrNull(getenv, tags, "buildUrl", "NETFLIX_BUILD_JOB");
putIfNotEmptyOrNull(getenv, tags, "sourceRepo", "NETFLIX_BUILD_SOURCE_REPO");
putIfNotEmptyOrNull(getenv, tags, "branch", "NETFLIX_BUILD_BRANCH");
putIfNotEmptyOrNull(getenv, tags, "commit", "NETFLIX_BUILD_COMMIT");
// Mantis info
putIfNotEmptyOrNull(getenv, tags, "mantisJobName", "MANTIS_JOB_NAME");
putIfNotEmptyOrNull(getenv, tags, "mantisJobId", "MANTIS_JOB_ID");
putIfNotEmptyOrNull(getenv, tags, "mantisWorkerIndex", "MANTIS_WORKER_INDEX");
putIfNotEmptyOrNull(getenv, tags, "mantisWorkerNumber", "MANTIS_WORKER_NUMBER");
putIfNotEmptyOrNull(getenv, tags, "mantisWorkerStageNumber", "MANTIS_WORKER_STAGE_NUMBER");
putIfNotEmptyOrNull(getenv, tags, "mantisUser", "MANTIS_USER");
return tags;
}
/**
* Extract common infrastructure tags for use with Atlas metrics from the
* Netflix environment variables. This may be a subset of those used for other
* contexts like logs.
*
* @return
* Common tags based on the environment.
*/
public static Map<String, String> commonTagsForAtlas() {
return commonTagsForAtlas(System::getenv);
}
/**
* Extract common infrastructure tags for use with Atlas metrics from the
* Netflix environment variables. This may be a subset of those used for other
* contexts like logs.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @return
* Common tags based on the environment.
*/
public static Map<String, String> commonTagsForAtlas(Function<String, String> getenv) {
return fixTagStrings(commonTagsForAtlas(getenv, defaultAtlasKeyPredicate(getenv)));
}
/**
* Extract common infrastructure tags for use with Atlas metrics from the
* Netflix environment variables. This may be a subset of those used for other
* contexts like logs.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @param keyPredicate
* Predicate to determine if a common tag key should be included as part of
* the Atlas tags.
* @return
* Common tags based on the environment.
*/
public static Map<String, String> commonTagsForAtlas(
Function<String, String> getenv, Predicate<String> keyPredicate) {
Map<String, String> tags = commonTags(getenv);
tags.keySet().removeIf(keyPredicate.negate());
return tags;
}
/**
* Returns the recommended predicate to use for filtering out the set of common tags
* to the set that should be used on Atlas metrics.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @return
* Predicate that evaluates to true if a tag key should be included.
*/
public static Predicate<String> defaultAtlasKeyPredicate(Function<String, String> getenv) {
Predicate<String> skipPredicate = atlasSkipTagsPredicate(getenv);
return k -> DEFAULT_ATLAS_TAG_KEYS.contains(k) && skipPredicate.test(k);
}
/**
* Returns the recommended predicate to use for skipping common tags based on the
* {@code ATLAS_SKIP_COMMON_TAGS} environment variable.
*
* @param getenv
* Function used to retrieve the value of an environment variable.
* @return
* Predicate that evaluates to true if a tag key should be included.
*/
public static Predicate<String> atlasSkipTagsPredicate(Function<String, String> getenv) {
Set<String> tagsToSkip = parseAtlasSkipTags(getenv);
return k -> !tagsToSkip.contains(k);
}
private static boolean isEmptyOrNull(String s) {
if (s == null) {
return true;
}
for (int i = 0; i < s.length(); ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
private static void putIfNotEmptyOrNull(
Function<String, String> getenv, Map<String, String> tags, String key, String... envVars) {
for (String envVar : envVars) {
String value = getenv.apply(envVar);
if (!isEmptyOrNull(value)) {
tags.put(key, value.trim());
break;
}
}
}
private static Set<String> parseAtlasSkipTags(Function<String, String> getenv) {
return parseAtlasSkipTags(getenv.apply("ATLAS_SKIP_COMMON_TAGS"));
}
private static Set<String> parseAtlasSkipTags(String skipTags) {
if (isEmptyOrNull(skipTags)) {
return Collections.emptySet();
} else {
Set<String> set = new HashSet<>();
String[] parts = skipTags.split(",");
for (String s : parts) {
if (!isEmptyOrNull(s)) {
set.add(s.trim());
}
}
return set;
}
}
}
| 5,997 |
0 | Create_ds/spectator/spectator-ext-log4j2/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j2/src/test/java/com/netflix/spectator/log4j/LevelTagTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.log4j;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.spi.StandardLevel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LevelTagTest {
@Test
public void levels() {
for (StandardLevel std : StandardLevel.values()) {
Level level = Level.getLevel(std.name());
Assertions.assertEquals(std, LevelTag.get(level).standardLevel());
}
}
@Test
public void values() {
for (LevelTag tag : LevelTag.values()) {
String v = tag.ordinal() + "_" + tag.name();
Assertions.assertEquals(v, tag.value());
}
}
}
| 5,998 |
0 | Create_ds/spectator/spectator-ext-log4j2/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j2/src/test/java/com/netflix/spectator/log4j/SpectatorAppenderTest.java | /*
* Copyright 2014-2019 Netflix, Inc.
*
* 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 com.netflix.spectator.log4j;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SpectatorAppenderTest {
private Registry registry;
private SpectatorAppender appender;
private LogEvent newEvent(Level level, Throwable t) {
return newEvent(level, t, true);
}
private LogEvent newEvent(Level level, Throwable t, boolean includeSource) {
final String cname = SpectatorAppenderTest.class.getName();
final StackTraceElement e = (t == null || !includeSource) ? null : t.getStackTrace()[0];
return new Log4jLogEvent.Builder()
.setLoggerName(cname)
.setLoggerFqcn(cname)
.setLevel(level)
.setThrown(t)
.setSource(e)
.setTimeMillis(0L)
.build();
}
@BeforeEach
public void before() {
registry = new DefaultRegistry();
appender = new SpectatorAppender(
registry, "foo", null, null, false, Property.EMPTY_ARRAY);
appender.start();
}
@Test
public void numMessagesERROR() {
Counter c = registry.counter("log4j.numMessages", "appender", "foo", "loglevel", "2_ERROR");
Assertions.assertEquals(0, c.count());
appender.append(newEvent(Level.ERROR, null));
Assertions.assertEquals(1, c.count());
}
@Test
public void numMessagesDEBUG() {
Counter c = registry.counter("log4j.numMessages", "appender", "foo", "loglevel", "5_DEBUG");
Assertions.assertEquals(0, c.count());
appender.append(newEvent(Level.DEBUG, null));
Assertions.assertEquals(1, c.count());
}
@Test
public void numStackTraces() {
Counter c = registry.counter("log4j.numStackTraces",
"appender", "foo",
"loglevel", "5_DEBUG",
"exception", "IllegalArgumentException",
"file", "SpectatorAppenderTest.java");
Assertions.assertEquals(0, c.count());
appender.append(newEvent(Level.DEBUG, new IllegalArgumentException("foo")));
Assertions.assertEquals(1, c.count());
}
@Test
public void numStackTracesNoSource() {
Counter c = registry.counter("log4j.numStackTraces",
"appender", "foo",
"loglevel", "5_DEBUG",
"exception", "IllegalArgumentException",
"file", "unknown");
Assertions.assertEquals(0, c.count());
appender.append(newEvent(Level.DEBUG, new IllegalArgumentException("foo"), false));
Assertions.assertEquals(1, c.count());
}
@Test
public void ignoreExceptions() {
appender = new SpectatorAppender(
registry, "foo", null, null, true, Property.EMPTY_ARRAY);
appender.start();
Counter c = registry.counter("log4j.numStackTraces",
"appender", "foo",
"loglevel", "5_DEBUG",
"exception", "IllegalArgumentException",
"file", "SpectatorAppenderTest.java");
Assertions.assertEquals(0, c.count());
appender.append(newEvent(Level.DEBUG, new IllegalArgumentException("foo")));
Assertions.assertEquals(0, c.count());
}
@Test
public void nullFilename() {
Counter c = registry.counter("log4j.numStackTraces",
"appender", "foo",
"loglevel", "2_ERROR",
"exception", "RuntimeException",
"file", "unknown");
Assertions.assertEquals(0, c.count());
String cname = SpectatorAppender.class.getName();
Throwable t = new RuntimeException("test");
t.fillInStackTrace();
StackTraceElement source = new StackTraceElement(cname, "foo", null, 0);
LogEvent event = new Log4jLogEvent.Builder()
.setLoggerName(cname)
.setLoggerFqcn(cname)
.setLevel(Level.ERROR)
.setThrown(t)
.setSource(source)
.setTimeMillis(0L)
.build();
appender.append(event);
Assertions.assertEquals(1, c.count());
}
}
| 5,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.