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-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DoubleFunction.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.api;
import java.util.function.ToDoubleFunction;
/**
* Function to extract a double value from an object.
*/
public abstract class DoubleFunction<T extends Number> implements ToDoubleFunction<T> {
@Override public double applyAsDouble(T n) {
return apply(n.doubleValue());
}
/**
* Apply a transform to the value `v`.
*
* @param v
* Double value to transform.
* @return
* Result of applying this function to `v`.
*/
public abstract double apply(double v);
}
| 5,800 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeGauge.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.api;
import java.util.Collection;
import java.util.Iterator;
/** Counter implementation for the composite registry. */
final class CompositeGauge extends CompositeMeter<Gauge> implements Gauge {
/** Create a new instance. */
CompositeGauge(Id id, Collection<Gauge> gauges) {
super(id, gauges);
}
@Override public void set(double v) {
for (Gauge g : meters) {
g.set(v);
}
}
@Override public double value() {
Iterator<Gauge> it = meters.iterator();
return it.hasNext() ? it.next().value() : Double.NaN;
}
}
| 5,801 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SystemClock.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.api;
/**
* Clock implementation that uses {@link System#currentTimeMillis()} and {@link System#nanoTime()}.
* Implemented as an enum to that the clock instance will be serializable if using in environments
* like Spark or Flink.
*/
enum SystemClock implements Clock {
/** Singleton instance for the system clock. */
INSTANCE;
@Override public long wallTime() {
return System.currentTimeMillis();
}
@Override public long monotonicTime() {
return System.nanoTime();
}
}
| 5,802 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Counter.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.api;
/**
* Measures the rate of change based on calls to increment.
*/
public interface Counter extends Meter {
/** Update the counter by one. */
default void increment() {
add(1.0);
}
/**
* Update the counter by {@code amount}.
*
* @param amount
* Amount to add to the counter.
*/
default void increment(long amount) {
add(amount);
}
/** Update the counter by the specified amount. */
void add(double amount);
/**
* The cumulative count since this counter was last reset. How often a counter
* is reset depends on the underlying registry implementation.
*/
default long count() {
return (long) actualCount();
}
/**
* The cumulative count as a floating point value since this counter was last reset. How
* often a counter is reset depends on the underlying registry implementation.
*/
double actualCount();
/**
* Returns a helper that can be used to more efficiently update the counter within a
* single thread. For example, if you need to update a meter within a loop where the
* rest of the loop body is fairly cheap, the instrumentation code may add considerable
* overhead if done in the loop body. A batched updater can offset a fair amount of that
* cost, but the updates may be delayed a bit in reaching the meter. The updates will only
* be seen after the updater is explicitly flushed.
*
* The caller should ensure that the updater is closed after using to guarantee any resources
* associated with it are cleaned up. In some cases failure to close the updater could result
* in a memory leak.
*
* @param batchSize
* Number of updates to batch before forcing a flush to the meter.
* @return
* Batch updater implementation for this meter.
*/
default BatchUpdater batchUpdater(int batchSize) {
return new CounterBatchUpdater(this, batchSize);
}
/** See {@link #batchUpdater(int)}. */
interface BatchUpdater extends AutoCloseable {
/** Update the counter by one. */
default void increment() {
add(1.0);
}
/**
* Update the counter by {@code amount}.
*
* @param amount
* Amount to add to the counter.
*/
default void increment(long amount) {
add(amount);
}
/** Update the counter by the specified amount. */
void add(double amount);
/** Push updates to the associated counter. */
void flush();
}
}
| 5,803 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopDistributionSummary.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.api;
import java.util.Collections;
/** Distribution summary implementation for the no-op registry. */
enum NoopDistributionSummary implements DistributionSummary {
/** Singleton instance. */
INSTANCE;
@Override public Id id() {
return NoopId.INSTANCE;
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount) {
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public long count() {
return 0L;
}
@Override public long totalAmount() {
return 0L;
}
}
| 5,804 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/ObjectGauge.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.api;
import java.util.Collections;
import java.util.function.ToDoubleFunction;
/**
* Gauge that is defined by executing a {@link ToDoubleFunction} on an object.
*/
class ObjectGauge<T> extends AbstractMeter<T> {
private final ToDoubleFunction<T> f;
/**
* Create a gauge that samples the provided number for the value.
*
* @param clock
* Clock used for accessing the current time.
* @param id
* Identifier for the gauge.
* @param obj
* {@link Object} used to access the value.
* @param f
* Function that is applied on the value for the number. The operation {@code f.apply(obj)}
* should be thread-safe.
*/
ObjectGauge(Clock clock, Id id, T obj, ToDoubleFunction<T> f) {
super(clock, id, obj);
this.f = f;
}
@Override public Iterable<Measurement> measure() {
return Collections.singleton(new Measurement(id, clock.wallTime(), value()));
}
/** Return the current value for evaluating `f` over `obj`. */
double value() {
final T obj = ref.get();
return (obj == null) ? Double.NaN : f.applyAsDouble(obj);
}
}
| 5,805 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/TimerBatchUpdater.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.api;
import java.util.concurrent.TimeUnit;
final class TimerBatchUpdater implements Timer.BatchUpdater {
private final Timer timer;
private final int batchSize;
private int count;
private final long[] amounts;
TimerBatchUpdater(Timer timer, int batchSize) {
this.timer = timer;
this.batchSize = batchSize;
this.count = 0;
this.amounts = new long[batchSize];
}
@Override
public void record(long amount, TimeUnit unit) {
if (amount >= 0L) {
amounts[count++] = unit.toNanos(amount);
if (count >= batchSize) {
flush();
}
}
}
@Override
public void flush() {
timer.record(amounts, count, TimeUnit.NANOSECONDS);
count = 0;
}
@Override
public void close() throws Exception {
flush();
}
}
| 5,806 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Measurement.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.api;
/**
* A measurement sampled from a meter.
*/
public final class Measurement {
private final Id id;
private final long timestamp;
private final double value;
/** Create a new instance. */
public Measurement(Id id, long timestamp, double value) {
this.id = id;
this.timestamp = timestamp;
this.value = value;
}
/** Identifier for the measurement. */
public Id id() {
return id;
}
/**
* The timestamp in milliseconds since the epoch for when the measurement was taken.
*/
public long timestamp() {
return timestamp;
}
/** Value for the measurement. */
public double value() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || !(obj instanceof Measurement)) return false;
Measurement other = (Measurement) obj;
return id.equals(other.id)
&& timestamp == other.timestamp
&& Double.compare(value, other.value) == 0;
}
@Override
public int hashCode() {
final int prime = 31;
int hc = prime;
hc = prime * hc + id.hashCode();
hc = prime * hc + Long.valueOf(timestamp).hashCode();
hc = prime * hc + Double.valueOf(value).hashCode();
return hc;
}
@Override
public String toString() {
return "Measurement(" + id.toString() + "," + timestamp + "," + value + ")";
}
}
| 5,807 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Meter.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.api;
/**
* A device for collecting a set of measurements. Note, this interface is only intended to be
* implemented by registry implementations.
*/
public interface Meter {
/**
* Identifier used to lookup this meter in the registry.
*/
Id id();
/**
* Get the set of measurements for this meter.
*/
Iterable<Measurement> measure();
/**
* Indicates whether the meter is expired. For example, a counter might expire if there is no
* activity within a given time frame.
*/
boolean hasExpired();
}
| 5,808 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/LongTaskTimer.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.api;
/**
* Timer intended to track a small number of long running tasks. Example would be something like
* a batch hadoop job. Though "long running" is a bit subjective the assumption is that anything
* over a minute is long running.
*/
public interface LongTaskTimer extends Meter {
/**
* Start keeping time for a task and return a task id that can be used to look up how long
* it has been running.
*/
long start();
/**
* Indicates that a given task has completed.
*
* @param task
* Id for the task to stop. This should be the value returned from {@link #start()}.
* @return
* Duration for the task in nanoseconds. A -1 value will be returned for an unknown task.
*/
long stop(long task);
/**
* Returns the current duration for a given active task.
*
* @param task
* Id for the task to stop. This should be the value returned from {@link #start()}.
* @return
* Duration for the task in nanoseconds. A -1 value will be returned for an unknown task.
*/
long duration(long task);
/** Returns the cumulative duration of all current tasks in nanoseconds. */
long duration();
/** Returns the current number of tasks being executed. */
int activeTasks();
}
| 5,809 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.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.api;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.spectator.impl.Cache;
import com.netflix.spectator.impl.Config;
import com.netflix.spectator.impl.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.Map;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.LongSupplier;
/**
* Base class to make it easier to implement a simple registry that only needs to customise the
* types returned for Counter, DistributionSummary, and Timer calls.
*/
public abstract class AbstractRegistry implements Registry {
/** Not used for this registry, always return 0. */
private static final LongSupplier VERSION = () -> 0L;
/** Logger instance for the class. */
protected final Logger logger;
private final Clock clock;
private final RegistryConfig config;
private final ConcurrentHashMap<Id, Meter> meters;
private final ConcurrentHashMap<Id, Object> state;
private final Cache<Id, Id> idNormalizationCache;
// The lambdas for creating a new meter are stored as member variables to avoid
// allocating a lambda that captures the "this" pointer on every invocation.
private final Function<Id, Counter> counterFactory = this::newCounter;
private final Function<Id, DistributionSummary> distSummaryFactory = this::newDistributionSummary;
private final Function<Id, Timer> timerFactory = this::newTimer;
private final Function<Id, Gauge> gaugeFactory = this::newGauge;
private final Function<Id, Gauge> maxGaugeFactory = this::newMaxGauge;
/**
* Create a new instance.
*
* @param clock
* Clock used for performing all timing measurements.
*/
public AbstractRegistry(Clock clock) {
this(clock, Config.defaultConfig());
}
/**
* Create a new instance.
*
* @param clock
* Clock used for performing all timing measurements.
* @param config
* Configuration settings for the registry.
*/
public AbstractRegistry(Clock clock, RegistryConfig config) {
this.logger = LoggerFactory.getLogger(getClass());
this.clock = clock;
this.config = config;
this.meters = new ConcurrentHashMap<>();
this.state = new ConcurrentHashMap<>();
this.idNormalizationCache = Cache.lfu(new NoopRegistry(), "spectator-id", 1000, 10000);
}
/**
* Create a new counter instance for a given id.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @return
* New counter instance.
*/
protected abstract Counter newCounter(Id id);
/**
* Create a new distribution summary instance for a given id.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @return
* New distribution summary instance.
*/
protected abstract DistributionSummary newDistributionSummary(Id id);
/**
* Create a new timer instance for a given id.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @return
* New timer instance.
*/
protected abstract Timer newTimer(Id id);
/**
* Create a new gauge instance for a given id.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @return
* New gauge instance.
*/
protected abstract Gauge newGauge(Id id);
/**
* Create a new max gauge instance for a given id.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @return
* New gauge instance.
*/
protected abstract Gauge newMaxGauge(Id id);
@Override public final Clock clock() {
return clock;
}
@Override public final RegistryConfig config() {
return config;
}
@Override public final Id createId(String name) {
try {
return new DefaultId(name);
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
@Override public final Id createId(String name, Iterable<Tag> tags) {
try {
return new DefaultId(name, ArrayTagSet.create(tags));
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
@Override public Id createId(String name, String... tags) {
try {
return new DefaultId(name, ArrayTagSet.create(tags));
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
@Override public Id createId(String name, Map<String, String> tags) {
try {
return new DefaultId(name, ArrayTagSet.create(tags));
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
/**
* Ensure a the id type is correct. While not recommended, nothing stops users from using a
* custom implementation of the {@link Id} interface. This can create unexpected and strange
* problems with the lookups failing, duplicate counters, etc. To avoid issues, this method
* should be called to sanitize Id values coming from the user. If it is already a valid id,
* then it will not create a new instance.
*/
private Id normalizeId(Id id) {
return (id instanceof DefaultId)
? id
: idNormalizationCache.computeIfAbsent(id, i -> createId(i.name(), i.tags()));
}
private void logTypeError(Id id, Class<?> desired, Class<?> found) {
final String dtype = desired.getName();
final String ftype = found.getName();
final String msg = String.format("cannot access '%s' as a %s, it already exists as a %s",
id, dtype, ftype);
propagate(new IllegalStateException(msg));
}
private Meter compute(Meter m, Meter fallback) {
return (meters.size() >= config.maxNumberOfMeters()) ? fallback : m;
}
@Deprecated
@Override public void register(Meter meter) {
PolledMeter.monitorMeter(this, meter);
}
@Override public ConcurrentMap<Id, Object> state() {
return state;
}
@Override public final Counter counter(Id id) {
Counter c = getOrCreate(id, Counter.class, NoopCounter.INSTANCE, counterFactory);
return new SwapCounter(this, VERSION, c.id(), c);
}
@Override public final DistributionSummary distributionSummary(Id id) {
DistributionSummary ds = getOrCreate(
id,
DistributionSummary.class,
NoopDistributionSummary.INSTANCE,
distSummaryFactory);
return new SwapDistributionSummary(this, VERSION, ds.id(), ds);
}
@Override public final Timer timer(Id id) {
Timer t = getOrCreate(id, Timer.class, NoopTimer.INSTANCE, timerFactory);
return new SwapTimer(this, VERSION, t.id(), t);
}
@Override public final Gauge gauge(Id id) {
Gauge g = getOrCreate(id, Gauge.class, NoopGauge.INSTANCE, gaugeFactory);
return new SwapGauge(this, VERSION, g.id(), g);
}
@Override public final Gauge maxGauge(Id id) {
Gauge g = getOrCreate(id, Gauge.class, NoopGauge.INSTANCE, maxGaugeFactory);
return new SwapMaxGauge(this, VERSION, g.id(), g);
}
/**
* Helper used to get or create an instance of a core meter type. This is mostly used
* internally to this implementation, but may be useful in rare cases for creating
* customizations based on a core type in a sub-class.
*
* @param id
* Identifier used to lookup this meter in the registry.
* @param cls
* Type of the meter.
* @param dflt
* Default value used if there is a failure during the lookup and it is not configured
* to propagate.
* @param factory
* Function for creating a new instance of the meter type if one is not already available
* in the registry.
* @return
* Instance of the meter.
*/
@SuppressWarnings("unchecked")
protected <T extends Meter> T getOrCreate(Id id, Class<T> cls, T dflt, Function<Id, T> factory) {
// Typically means the user had an error with a call to createId when propagateWarnings
// is false.
if (id == NoopId.INSTANCE) {
return dflt;
}
// Handle the normal processing and ensure exceptions are not propagated
try {
Preconditions.checkNotNull(id, "id");
Id normId = normalizeId(id);
Meter m = Utils.computeIfAbsent(meters, normId, i -> compute(factory.apply(i), dflt));
if (!cls.isAssignableFrom(m.getClass())) {
logTypeError(normId, cls, m.getClass());
m = dflt;
}
return (T) m;
} catch (Exception e) {
propagate(e);
return dflt;
}
}
@Override public final Meter get(Id id) {
try {
return meters.get(normalizeId(id));
} catch (Exception e) {
propagate(e);
return null;
}
}
@Override public final Iterator<Meter> iterator() {
return meters.values().iterator();
}
@Override
public final Spliterator<Meter> spliterator() {
return meters.values().spliterator();
}
/**
* Can be called by sub-classes to remove expired meters from the internal map.
* The SwapMeter types that are returned will lookup a new copy on the next access.
*/
protected void removeExpiredMeters() {
int total = 0;
int expired = 0;
Iterator<Meter> it = meters.values().iterator();
while (it.hasNext()) {
++total;
Meter m = it.next();
if (m.hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired meters out of {} total", expired, total);
cleanupCachedState();
}
/**
* Cleanup any expired meter patterns stored in the state. It should only be used as
* a cache so the entry should get recreated if needed.
*/
protected void cleanupCachedState() {
int total = 0;
int expired = 0;
Iterator<Map.Entry<Id, Object>> it = state.entrySet().iterator();
while (it.hasNext()) {
++total;
Map.Entry<Id, Object> entry = it.next();
Object obj = entry.getValue();
if (obj instanceof Meter && ((Meter) obj).hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired entries from cache out of {} total", expired, total);
}
/**
* This can be called be sub-classes to reset all state for the registry. Typically this
* should only be exposed for test registries as most users should not be able to reset the
* state and interrupt metrics collection for the overall system.
*/
protected void reset() {
meters.clear();
state.clear();
}
}
| 5,810 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SwapDistributionSummary.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.api;
import com.netflix.spectator.impl.SwapMeter;
import java.util.function.Consumer;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
/** Wraps another distribution summary allowing the underlying type to be swapped. */
final class SwapDistributionSummary extends SwapMeter<DistributionSummary> implements DistributionSummary {
/** Create a new instance. */
SwapDistributionSummary(
Registry registry,
LongSupplier versionSupplier,
Id id,
DistributionSummary underlying) {
super(registry, versionSupplier, id, underlying);
}
@Override public DistributionSummary lookup() {
return registry.distributionSummary(id);
}
@Override public void record(long amount) {
get().record(amount);
}
@Override public void record(long[] amounts, int n) {
get().record(amounts, n);
}
@Override
public long count() {
return get().count();
}
@Override
public long totalAmount() {
return get().totalAmount();
}
@SuppressWarnings("unchecked")
@Override public BatchUpdater batchUpdater(int batchSize) {
BatchUpdater updater = get().batchUpdater(batchSize);
// Registry implementations can implement `Consumer<Supplier<DistributionSummary>>` to
// allow the meter to be resolved when flushed and avoid needing to hold on to a particular
// instance of the meter that might have expired and been removed from the registry.
if (updater instanceof Consumer<?>) {
((Consumer<Supplier<DistributionSummary>>) updater).accept(this::get);
}
return updater;
}
}
| 5,811 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeCounter.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.api;
import java.util.Collection;
import java.util.Iterator;
/** Counter implementation for the composite registry. */
final class CompositeCounter extends CompositeMeter<Counter> implements Counter {
/** Create a new instance. */
CompositeCounter(Id id, Collection<Counter> counters) {
super(id, counters);
}
@Override public void add(double amount) {
for (Counter c : meters) {
c.add(amount);
}
}
@Override public double actualCount() {
Iterator<Counter> it = meters.iterator();
return it.hasNext() ? it.next().actualCount() : 0.0;
}
}
| 5,812 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/ManualClock.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.api;
import java.util.concurrent.atomic.AtomicLong;
/**
* Clock implementation that allows the user to explicitly control the time. Typically used for
* unit tests.
*/
public class ManualClock implements Clock {
private final AtomicLong wall;
private final AtomicLong monotonic;
/** Create a new instance. */
public ManualClock() {
this(0L, 0L);
}
/**
* Create a new instance.
*
* @param wallInit
* Initial value for the wall time.
* @param monotonicInit
* Initial value for the monotonic time.
*/
public ManualClock(long wallInit, long monotonicInit) {
wall = new AtomicLong(wallInit);
monotonic = new AtomicLong(monotonicInit);
}
@Override public long wallTime() {
return wall.get();
}
@Override public long monotonicTime() {
return monotonic.get();
}
/** Set the wall time to the value {@code t}. */
public void setWallTime(long t) {
wall.set(t);
}
/** Set the monotonic time to the value {@code t}. */
public void setMonotonicTime(long t) {
monotonic.set(t);
}
}
| 5,813 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/SwapGauge.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.api;
import com.netflix.spectator.impl.SwapMeter;
import java.util.function.LongSupplier;
/** Wraps another gauge allowing the underlying type to be swapped. */
final class SwapGauge extends SwapMeter<Gauge> implements Gauge {
/** Create a new instance. */
SwapGauge(Registry registry, LongSupplier versionSupplier, Id id, Gauge underlying) {
super(registry, versionSupplier, id, underlying);
}
@Override public Gauge lookup() {
return registry.gauge(id);
}
@Override public void set(double value) {
get().set(value);
}
@Override public double value() {
return get().value();
}
}
| 5,814 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/ExtendedRegistry.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.api;
import com.netflix.spectator.impl.Preconditions;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;
/**
* Wraps a registry and provides additional helper methods to make it easier to use.
*
* @deprecated This class was used prior to java 8 for adding extension methods to the registry
* without breaking all classes implementing the interface. The extension methods have now been
* moved to Registry interface as default methods. This class is scheduled for removal in a future
* release.
*/
@Deprecated
public final class ExtendedRegistry implements Registry {
private final Registry impl;
/** Create a new instance. */
public ExtendedRegistry(Registry impl) {
this.impl = Preconditions.checkNotNull(impl, "impl");
}
/** Returns the underlying registry implementation that is being wrapped. */
public Registry underlying() {
return impl;
}
@Override public Clock clock() {
return impl.clock();
}
@Override public Id createId(String name) {
return impl.createId(name);
}
@Override public Id createId(String name, Iterable<Tag> tags) {
return impl.createId(name, tags);
}
@Override public void register(Meter meter) {
impl.register(meter);
}
@Override public ConcurrentMap<Id, Object> state() {
return impl.state();
}
@Override public Counter counter(Id id) {
return impl.counter(id);
}
@Override public DistributionSummary distributionSummary(Id id) {
return impl.distributionSummary(id);
}
@Override public Timer timer(Id id) {
return impl.timer(id);
}
@Override public Gauge gauge(Id id) {
return impl.gauge(id);
}
@Override public Gauge maxGauge(Id id) {
return impl.maxGauge(id);
}
@Override public Meter get(Id id) {
return impl.get(id);
}
@Override public Iterator<Meter> iterator() {
return impl.iterator();
}
/////////////////////////////////////////////////////////////////
// Additional helper methods below
@Override
public String toString() {
return "ExtendedRegistry(impl=" + impl + ')';
}
}
| 5,815 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CounterBatchUpdater.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.api;
final class CounterBatchUpdater implements Counter.BatchUpdater {
private final Counter counter;
private final int batchSize;
private int count;
private double sum;
CounterBatchUpdater(Counter counter, int batchSize) {
this.counter = counter;
this.batchSize = batchSize;
this.count = 0;
this.sum = 0.0;
}
@Override
public void add(double amount) {
if (Double.isFinite(amount) && amount > 0.0) {
sum += amount;
++count;
if (count >= batchSize) {
flush();
}
}
}
@Override
public void flush() {
counter.add(sum);
sum = 0.0;
count = 0;
}
@Override
public void close() throws Exception {
flush();
}
}
| 5,816 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/FilteredIterator.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.api;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
/**
* Wraps an iterator with one that will filter the values using the specified predicate.
*/
class FilteredIterator<T> implements Iterator<T> {
private final Iterator<T> it;
private final Predicate<T> p;
private T item;
/**
* Create a new instance.
*
* @param it
* Inner iterator that should be filtered.
* @param p
* Predicate for finding matching results.
*/
FilteredIterator(Iterator<T> it, Predicate<T> p) {
this.it = it;
this.p = p;
findNext();
}
private void findNext() {
while (it.hasNext()) {
item = it.next();
if (p.test(item)) {
return;
}
}
item = null;
}
@Override public boolean hasNext() {
return item != null;
}
@SuppressWarnings("PMD.UnnecessaryLocalBeforeReturn")
@Override public T next() {
if (item == null) {
throw new NoSuchElementException("next() called after reaching end of iterator");
}
// Note: PMD flags this, but the local tmp is necessary because findNext will change
// the value of item
T tmp = item;
findNext();
return tmp;
}
@Override public void remove() {
throw new UnsupportedOperationException("remove");
}
}
| 5,817 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultId.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.api;
import com.netflix.spectator.impl.Preconditions;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiPredicate;
/** Id implementation for the default registry. */
final class DefaultId implements Id {
private final String name;
private final ArrayTagSet tags;
/** Create a new instance. */
DefaultId(String name) {
this(name, ArrayTagSet.EMPTY);
}
/** Create a new instance. */
DefaultId(String name, ArrayTagSet tags) {
this.name = Preconditions.checkNotNull(name, "name");
this.tags = Preconditions.checkNotNull(tags, "tags");
}
@Override public String name() {
return name;
}
@Override public Iterable<Tag> tags() {
return tags;
}
@Override public DefaultId withTag(Tag tag) {
return new DefaultId(name, tags.add(tag));
}
@Override public DefaultId withTag(String key, String value) {
return new DefaultId(name, tags.add(key, value));
}
@Override public DefaultId withTags(String... ts) {
return new DefaultId(name, tags.addAll(ts));
}
@Override public DefaultId withTags(Tag... ts) {
return new DefaultId(name, tags.addAll(ts));
}
@Override public DefaultId withTags(Iterable<Tag> ts) {
return new DefaultId(name, tags.addAll(ts));
}
@Override public DefaultId withTags(Map<String, String> ts) {
return new DefaultId(name, tags.addAll(ts));
}
@Override public String getKey(int i) {
return i == 0 ? "name" : tags.getKey(i - 1);
}
@Override public String getValue(int i) {
return i == 0 ? name : tags.getValue(i - 1);
}
@Override public int size() {
return tags.size() + 1;
}
@Override public Id filter(BiPredicate<String, String> predicate) {
return new DefaultId(name, tags.filter(predicate));
}
/**
* Returns a new id with the tag list sorted by key and with no duplicate keys. This is equivalent to
* {@code rollup(Collections.<String>emptySet(), false)}.
*/
DefaultId normalize() {
return rollup(Collections.emptySet(), false);
}
/**
* Create a new id by possibly removing tags from the list. This operation will:<br/>
* 1) remove keys as specified by the parameters<br/>
* 2) dedup entries that have the same key, the first value associated with the key will be the one kept,<br/>
* 3) sort the list by the tag keys.
*
* @param keys
* Set of keys to either keep or remove.
* @param keep
* If true, then the new id can only have tag keys in the provided set. Otherwise the new id
* can only have ids not in that set.
* @return
* New identifier after applying the rollup.
*/
DefaultId rollup(Set<String> keys, boolean keep) {
if (tags.isEmpty()) {
return this;
} else {
Map<String, String> ts = new TreeMap<>();
for (Tag t : tags) {
if (keys.contains(t.key()) == keep && !ts.containsKey(t.key())) {
ts.put(t.key(), t.value());
}
}
return new DefaultId(name, ArrayTagSet.create(ts));
}
}
@Override public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || !(obj instanceof DefaultId)) return false;
DefaultId other = (DefaultId) obj;
return name.equals(other.name) && tags.equals(other.tags);
}
@Override public int hashCode() {
int result = name.hashCode();
result = 31 * result + tags.hashCode();
return result;
}
@Override public String toString() {
return name + tags;
}
}
| 5,818 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/CompositeRegistry.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.api;
import com.netflix.spectator.api.patterns.PolledMeter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import java.util.function.LongSupplier;
/**
* Maps calls to zero or more sub-registries. If zero then it will act similar to the noop
* registry. Otherwise activity will be sent to all registries that are part of the composite.
*/
public final class CompositeRegistry implements Registry {
private final Lock lock = new ReentrantLock();
private final Clock clock;
private final AtomicReference<Registry[]> registries;
private final AtomicLong version;
private final LongSupplier versionSupplier;
private final ConcurrentHashMap<Id, Object> state;
/** Creates a new instance. */
CompositeRegistry(Clock clock) {
this.clock = clock;
this.registries = new AtomicReference<>(new Registry[0]);
this.version = new AtomicLong();
this.versionSupplier = version::get;
this.state = new ConcurrentHashMap<>();
}
/**
* Find the first registry in the composite that is an instance of {@code c}. If no match is
* found then null will be returned.
*/
@SuppressWarnings("unchecked")
<T extends Registry> T find(Class<T> c) {
for (Registry r : registries.get()) {
if (c.isAssignableFrom(r.getClass())) {
return (T) r;
}
}
return null;
}
private int indexOf(Registry[] rs, Registry registry) {
for (int i = 0; i < rs.length; ++i) {
if (rs[i].equals(registry))
return i;
}
return -1;
}
/** Add a registry to the composite. */
public void add(Registry registry) {
lock.lock();
try {
Registry[] rs = registries.get();
int pos = indexOf(rs, registry);
if (pos == -1) {
Registry[] tmp = new Registry[rs.length + 1];
System.arraycopy(rs, 0, tmp, 0, rs.length);
tmp[rs.length] = registry;
registries.set(tmp);
version.incrementAndGet();
}
} finally {
lock.unlock();
}
}
/** Remove a registry from the composite. */
public void remove(Registry registry) {
lock.lock();
try {
Registry[] rs = registries.get();
int pos = indexOf(rs, registry);
if (pos >= 0) {
Registry[] tmp = new Registry[rs.length - 1];
if (pos > 0)
System.arraycopy(rs, 0, tmp, 0, pos);
if (pos < tmp.length)
System.arraycopy(rs, pos + 1, tmp, pos, rs.length - pos - 1);
registries.set(tmp);
version.incrementAndGet();
}
} finally {
lock.unlock();
}
}
/** Remove all registries from the composite. */
public void removeAll() {
lock.lock();
try {
registries.set(new Registry[0]);
state.clear();
} finally {
lock.unlock();
}
}
@Override public Clock clock() {
return clock;
}
@Override public Id createId(String name) {
return new DefaultId(name);
}
@Override public Id createId(String name, Iterable<Tag> tags) {
return new DefaultId(name, ArrayTagSet.create(tags));
}
@Override public Id createId(String name, String... tags) {
return new DefaultId(name, ArrayTagSet.create(tags));
}
@Override public Id createId(String name, Map<String, String> tags) {
return new DefaultId(name, ArrayTagSet.create(tags));
}
@Deprecated
@Override public void register(Meter meter) {
PolledMeter.monitorMeter(this, meter);
}
@Override public ConcurrentMap<Id, Object> state() {
return state;
}
private <T> List<T> meters(Registry[] rs, Id id, BiFunction<Registry, Id, T> f) {
List<T> ms = new ArrayList<>(rs.length);
for (Registry r : rs) {
ms.add(f.apply(r, id));
}
return ms;
}
private Counter newCounter(Id id) {
Registry[] rs = registries.get();
Counter c;
switch (rs.length) {
case 0:
c = NoopCounter.INSTANCE;
break;
case 1:
c = rs[0].counter(id);
break;
default:
List<Counter> cs = meters(rs, id, Registry::counter);
c = new CompositeCounter(id, cs);
break;
}
return c;
}
@Override public Counter counter(Id id) {
return new SwapCounter(this, versionSupplier, id, newCounter(id));
}
private DistributionSummary newDistributionSummary(Id id) {
Registry[] rs = registries.get();
DistributionSummary t;
switch (rs.length) {
case 0:
t = NoopDistributionSummary.INSTANCE;
break;
case 1:
t = rs[0].distributionSummary(id);
break;
default:
List<DistributionSummary> ds = meters(rs, id, Registry::distributionSummary);
t = new CompositeDistributionSummary(id, ds);
break;
}
return t;
}
@Override public DistributionSummary distributionSummary(Id id) {
return new SwapDistributionSummary(this, versionSupplier, id, newDistributionSummary(id));
}
private Timer newTimer(Id id) {
Registry[] rs = registries.get();
Timer t;
switch (rs.length) {
case 0:
t = NoopTimer.INSTANCE;
break;
case 1:
t = rs[0].timer(id);
break;
default:
List<Timer> ts = meters(rs, id, Registry::timer);
t = new CompositeTimer(id, clock, ts);
break;
}
return t;
}
@Override public Timer timer(Id id) {
return new SwapTimer(this, versionSupplier, id, newTimer(id));
}
private Gauge newGauge(Id id) {
Registry[] rs = registries.get();
Gauge t;
switch (rs.length) {
case 0:
t = NoopGauge.INSTANCE;
break;
case 1:
t = rs[0].gauge(id);
break;
default:
List<Gauge> gs = meters(rs, id, Registry::gauge);
t = new CompositeGauge(id, gs);
break;
}
return t;
}
@Override public Gauge gauge(Id id) {
return new SwapGauge(this, versionSupplier, id, newGauge(id));
}
private Gauge newMaxGauge(Id id) {
Registry[] rs = registries.get();
Gauge t;
switch (rs.length) {
case 0:
t = NoopGauge.INSTANCE;
break;
case 1:
t = rs[0].maxGauge(id);
break;
default:
List<Gauge> gs = meters(rs, id, Registry::maxGauge);
t = new CompositeGauge(id, gs);
break;
}
return t;
}
@Override public Gauge maxGauge(Id id) {
return new SwapGauge(this, versionSupplier, id, newMaxGauge(id));
}
@Override public Meter get(Id id) {
for (Registry r : registries.get()) {
Meter m = r.get(id);
if (m != null) {
if (m instanceof Counter) {
return counter(id);
} else if (m instanceof Timer) {
return timer(id);
} else if (m instanceof DistributionSummary) {
return distributionSummary(id);
} else if (m instanceof Gauge) {
return gauge(id);
} else {
return null;
}
}
}
return null;
}
@Override public Iterator<Meter> iterator() {
Registry[] rs = registries.get();
if (rs.length == 0) {
return Collections.emptyIterator();
} else {
final Set<Id> ids = new HashSet<>();
for (Registry r : rs) {
for (Meter m : r) ids.add(m.id());
}
return new Iterator<Meter>() {
private final Iterator<Id> idIter = ids.iterator();
@Override
public boolean hasNext() {
return idIter.hasNext();
}
@Override
public Meter next() {
return get(idIter.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
}
| 5,819 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Registry.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.api;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.spectator.impl.Config;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.ToDoubleFunction;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Registry to manage a set of meters.
*/
public interface Registry extends Iterable<Meter> {
/**
* The clock used by the registry for timing events.
*/
Clock clock();
/**
* Configuration settings used for this registry.
*/
default RegistryConfig config() {
return Config.defaultConfig();
}
/**
* Creates an identifier for a meter. All ids passed into other calls should be created by the
* registry.
*
* @param name
* Description of the measurement that is being collected.
*/
Id createId(String name);
/**
* Creates an identifier for a meter. All ids passed into other calls should be created by the
* registry.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
*/
Id createId(String name, Iterable<Tag> tags);
/**
* Register a passive gauge. In most cases users should not use this method directly. Use
* one of the helper methods for working with gauges.
*
* @see #gauge(Id, Number)
* @see #gauge(Id, Object, ToDoubleFunction)
* @see #collectionSize(Id, Collection)
* @see #mapSize(Id, Map)
*
* @deprecated Code outside of Spectator should not implement the Meter interface. This
* method is scheduled for removal in a future release.
*/
@Deprecated
void register(Meter meter);
/**
* Returns a map that can be used to associate state with the registry. Users instrumenting
* their application will most likely never need to use this method.
*
* The primary use case is for building custom meter types that need some additional state
* beyond the core types supported by the registry. This map can be used to store the state
* so that the lifecycle of the data is connected to the registry. For an example, see some
* of the built in patterns such as {@link com.netflix.spectator.api.patterns.LongTaskTimer}.
*/
ConcurrentMap<Id, Object> state();
/**
* Measures the rate of some activity. A counter is for continuously incrementing sources like
* the number of requests that are coming into a server.
*
* @param id
* Identifier created by a call to {@link #createId}
*/
Counter counter(Id id);
/**
* Measures the rate and variation in amount for some activity. For example, it could be used to
* get insight into the variation in response sizes for requests to a server.
*
* @param id
* Identifier created by a call to {@link #createId}
*/
DistributionSummary distributionSummary(Id id);
/**
* Measures the rate and time taken for short running tasks.
*
* @param id
* Identifier created by a call to {@link #createId}
*/
Timer timer(Id id);
/**
* Represents a value sampled from another source. For example, the size of queue. The caller
* is responsible for sampling the value regularly and calling {@link Gauge#set(double)}.
* Registry implementations are free to expire the gauge if it has not been updated in the
* last minute. If you do not want to worry about the sampling, then use {@link PolledMeter}
* instead.
*
* @param id
* Identifier created by a call to {@link #createId}
*/
Gauge gauge(Id id);
/**
* Measures the maximum value recorded since the last reset. For example, to measure the
* maximum number of concurrent requests to a service. In many cases it is better to use
* a {@link #distributionSummary(Id)} which provides a max along with other stats for most
* registry implementations.
*
* @param id
* Identifier created by a call to {@link #createId}
*/
Gauge maxGauge(Id id);
/**
* Returns the meter associated with a given id.
*
* @param id
* Identifier for the meter.
* @return
* Instance of the meter or null if there is no match.
*/
Meter get(Id id);
/** Iterator for traversing the set of meters in the registry. */
@Override Iterator<Meter> iterator();
/////////////////////////////////////////////////////////////////
// Additional helper methods below
/**
* Returns the first underlying registry that is an instance of {@code c}.
*/
@SuppressWarnings("unchecked")
default <T extends Registry> T underlying(Class<T> c) {
if (c == null) {
return null;
} else if (c.isAssignableFrom(getClass())) {
return (T) this;
} else if (this instanceof CompositeRegistry) {
return ((CompositeRegistry) this).find(c);
} else {
return null;
}
}
/**
* Creates an identifier for a meter.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Identifier for a meter.
*/
default Id createId(String name, String... tags) {
try {
return createId(name, Utils.toIterable(tags));
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
/**
* Creates an identifier for a meter.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Identifier for a meter.
*/
default Id createId(String name, Map<String, String> tags) {
try {
return createId(name).withTags(tags);
} catch (Exception e) {
propagate(e);
return NoopId.INSTANCE;
}
}
/**
* Measures the rate of some activity.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Counter instance with the corresponding id.
*/
default Counter counter(String name) {
return counter(createId(name));
}
/**
* Measures the rate of some activity.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Counter instance with the corresponding id.
*/
default Counter counter(String name, Iterable<Tag> tags) {
return counter(createId(name, tags));
}
/**
* Measures the rate of some activity.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Counter instance with the corresponding id.
*/
default Counter counter(String name, String... tags) {
return counter(createId(name, tags));
}
/**
* Measures the sample distribution of events.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Summary instance with the corresponding id.
*/
default DistributionSummary distributionSummary(String name) {
return distributionSummary(createId(name));
}
/**
* Measures the sample distribution of events.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Summary instance with the corresponding id.
*/
default DistributionSummary distributionSummary(String name, Iterable<Tag> tags) {
return distributionSummary(createId(name, tags));
}
/**
* Measures the sample distribution of events.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Summary instance with the corresponding id.
*/
default DistributionSummary distributionSummary(String name, String... tags) {
return distributionSummary(createId(name, tags));
}
/**
* Measures the time taken for short tasks.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Timer instance with the corresponding id.
*/
default Timer timer(String name) {
return timer(createId(name));
}
/**
* Measures the time taken for short tasks.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Timer instance with the corresponding id.
*/
default Timer timer(String name, Iterable<Tag> tags) {
return timer(createId(name, tags));
}
/**
* Measures the time taken for short tasks.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Timer instance with the corresponding id.
*/
default Timer timer(String name, String... tags) {
return timer(createId(name, tags));
}
/**
* Represents a value sampled from another source.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge gauge(String name) {
return gauge(createId(name));
}
/**
* Represents a value sampled from another source.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge gauge(String name, Iterable<Tag> tags) {
return gauge(createId(name, tags));
}
/**
* Represents a value sampled from another source.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge gauge(String name, String... tags) {
return gauge(createId(name, tags));
}
/**
* Measures the maximum value recorded since the last reset.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge maxGauge(String name) {
return maxGauge(createId(name));
}
/**
* Measures the maximum value recorded since the last reset.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge maxGauge(String name, Iterable<Tag> tags) {
return maxGauge(createId(name, tags));
}
/**
* Measures the maximum value recorded since the last reset.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Gauge instance with the corresponding id.
*/
default Gauge maxGauge(String name, String... tags) {
return maxGauge(createId(name, tags));
}
/**
* Measures the time taken for long tasks.
*
* @param id
* Identifier for the metric being registered.
* @return
* Timer instance with the corresponding id.
* @deprecated
* Use {@link com.netflix.spectator.api.patterns.LongTaskTimer#get(Registry, Id)}
* instead. This method is scheduled for removal in a future release.
*/
@Deprecated
default LongTaskTimer longTaskTimer(Id id) {
// Note: this method is only included in the registry for historical reasons to
// maintain compatibility. Future patterns should just use the registry not be
// created by the registry.
try {
return com.netflix.spectator.api.patterns.LongTaskTimer.get(this, id);
} catch (Exception e) {
propagate(e);
return com.netflix.spectator.api.patterns.LongTaskTimer.get(this, NoopId.INSTANCE);
}
}
/**
* Measures the time taken for long tasks.
*
* @param name
* Description of the measurement that is being collected.
* @return
* Timer instance with the corresponding id.
* @deprecated
* Use {@link com.netflix.spectator.api.patterns.LongTaskTimer#get(Registry, Id)}
* instead. This method is scheduled for removal in a future release.
*/
@Deprecated
default LongTaskTimer longTaskTimer(String name) {
return longTaskTimer(createId(name));
}
/**
* Measures the time taken for long tasks.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Timer instance with the corresponding id.
* @deprecated
* Use {@link com.netflix.spectator.api.patterns.LongTaskTimer#get(Registry, Id)}
* instead. This method is scheduled for removal in a future release.
*/
@Deprecated
default LongTaskTimer longTaskTimer(String name, Iterable<Tag> tags) {
return longTaskTimer(createId(name, tags));
}
/**
* Measures the time taken for long tasks.
*
* @param name
* Description of the measurement that is being collected.
* @param tags
* Other dimensions that can be used to classify the measurement.
* @return
* Timer instance with the corresponding id.
* @deprecated
* Use {@link com.netflix.spectator.api.patterns.LongTaskTimer#get(Registry, Id)}
* instead. This method is scheduled for removal in a future release.
*/
@Deprecated
default LongTaskTimer longTaskTimer(String name, String... tags) {
return longTaskTimer(createId(name, tags));
}
/**
* Tells the registry to regularly poll the value of a {@link java.lang.Number} and report
* it as a gauge.
*
* @param id
* Identifier for the metric being registered.
* @param number
* Thread-safe implementation of {@link Number} used to access the value.
* @return
* The number that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Number> T gauge(Id id, T number) {
return PolledMeter.using(this).withId(id).monitorValue(number);
}
/**
* Tells the registry to regularly poll the value of a {@link java.lang.Number} and report
* it as a gauge. See {@link PolledMeter.Builder#monitorValue(Number)} for more information.
*
* @param name
* Name of the metric being registered.
* @param number
* Thread-safe implementation of {@link Number} used to access the value.
* @return
* The number that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Number> T gauge(String name, T number) {
return gauge(createId(name), number);
}
/**
* Tells the registry to regularly poll the value of a {@link java.lang.Number} and report
* it as a gauge. See {@link #gauge(Id, Number)} for more information.
*
* @param name
* Name of the metric being registered.
* @param tags
* Sequence of dimensions for breaking down the name.
* @param number
* Thread-safe implementation of {@link Number} used to access the value.
* @return
* The number that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Number> T gauge(String name, Iterable<Tag> tags, T number) {
return gauge(createId(name, tags), number);
}
/**
* See {@link #gauge(Id, Object, ToDoubleFunction)} for more information.
*
* @param id
* Identifier for the metric being registered.
* @param obj
* Object used to compute a value.
* @param f
* Function that is applied on the value for the number.
* @return
* The object that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T> T gauge(Id id, T obj, ToDoubleFunction<T> f) {
return PolledMeter.using(this).withId(id).monitorValue(obj, f);
}
/**
* See {@link #gauge(Id, Object, ToDoubleFunction)} for more information.
*
* @param name
* Name of the metric being registered.
* @param obj
* Object used to compute a value.
* @param f
* Function that is applied on the value for the number.
* @return
* The object that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T> T gauge(String name, T obj, ToDoubleFunction<T> f) {
return gauge(createId(name), obj, f);
}
/**
* Tells the registry to regularly poll the collection and report its size as a gauge.
* The registration will keep a weak reference to the collection so it will not prevent
* garbage collection. The collection implementation used should be thread safe. Note that
* calling {@link java.util.Collection#size()} can be expensive for some collection
* implementations and should be considered before registering.
*
* For more information see {@link #gauge(Id, Object, ToDoubleFunction)}.
*
* @param id
* Identifier for the metric being registered.
* @param collection
* Thread-safe implementation of {@link Collection} used to access the value.
* @return
* The collection that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Collection<?>> T collectionSize(Id id, T collection) {
return PolledMeter.using(this).withId(id).monitorSize(collection);
}
/**
* Tells the registry to regularly poll the collection and report its size as a gauge.
* See {@link #collectionSize(Id, Collection)} for more information.
*
* @param name
* Name of the metric being registered.
* @param collection
* Thread-safe implementation of {@link Collection} used to access the value.
* @return
* The collection that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Collection<?>> T collectionSize(String name, T collection) {
return collectionSize(createId(name), collection);
}
/**
* Tells the registry to regularly poll the map and report its size as a gauge.
* The registration will keep a weak reference to the map so it will not prevent
* garbage collection. The collection implementation used should be thread safe. Note that
* calling {@link java.util.Map#size()} can be expensive for some map
* implementations and should be considered before registering.
*
* For more information see {@link #gauge(Id, Object, ToDoubleFunction)}.
*
* @param id
* Identifier for the metric being registered.
* @param collection
* Thread-safe implementation of {@link Map} used to access the value.
* @return
* The map that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Map<?, ?>> T mapSize(Id id, T collection) {
return PolledMeter.using(this).withId(id).monitorSize(collection);
}
/**
* Tells the registry to regularly poll the collection and report its size as a gauge.
* See {@link #mapSize(Id, Map)} for more information.
*
* @param name
* Name of the metric being registered.
* @param collection
* Thread-safe implementation of {@link Map} used to access the value.
* @return
* The map that was passed in so the registration can be done as part of an assignment
* statement.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default <T extends Map<?, ?>> T mapSize(String name, T collection) {
return mapSize(createId(name), collection);
}
/**
* Tells the registry to regularly poll the object by by using reflection to invoke the named
* method and report the returned value as a gauge. The registration will keep a weak reference
* to the object so it will not prevent garbage collection. The registered method should be
* thread safe and cheap to invoke. <b>Never perform any potentially long running or expensive
* activity such as IO inline</b>.
*
* To get better compile time type safety, {@link #gauge(Id, Object, ToDoubleFunction)}
* should be preferred. Use this technique only if there access or other restrictions prevent
* using a proper function reference. However, keep in mind that makes your code more brittle
* and prone to failure in the future.
*
* For more information see {@link #gauge(Id, Object, ToDoubleFunction)}.
*
* @param id
* Identifier for the metric being registered.
* @param obj
* Object used to compute a value.
* @param method
* Name of the method to invoke on the object.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default void methodValue(Id id, Object obj, String method) {
final Method m = Utils.getGaugeMethod(this, id, obj, method);
if (m != null) {
PolledMeter.using(this).withId(id).monitorValue(obj, Functions.invokeMethod(m));
}
}
/**
* Tells the registry to regularly poll the object by by using reflection to invoke the named
* method and report the returned value as a gauge. See {@link #methodValue(Id, Object, String)}
* for more information.
*
* @param name
* Name of the metric being registered.
* @param obj
* Object used to compute a value.
* @param method
* Name of the method to invoke on the object.
* @deprecated
* Use {@link PolledMeter} instead. This method has been deprecated to help
* reduce confusion between active gauges that are explicitly updated by the
* user and passive gauges that are polled in the background. Going forward
* the registry methods will only be used for the core types directly updated
* by the user. Other patterns such as {@link PolledMeter}s will be handled
* separately. This method is scheduled for removal in a future release.
*/
@Deprecated
default void methodValue(String name, Object obj, String method) {
methodValue(createId(name), obj, method);
}
/**
* Returns a stream with the current flattened set of measurements across all meters.
* This should typically be preferred over {@link #stream()} to get the data as it will
* automatically handle expired meters, NaN values, etc.
*/
default Stream<Measurement> measurements() {
return stream()
.filter(m -> !m.hasExpired())
.flatMap(m -> StreamSupport.stream(m.measure().spliterator(), false))
.filter(m -> !Double.isNaN(m.value()));
}
/** Returns a stream of all registered meters. */
default Stream<Meter> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Returns a stream of all registered counters. This operation is mainly used for testing as
* a convenient way to get an aggregated value. For example, to generate a summary of all
* counters with name "foo":
*
* <pre>
* LongSummaryStatistics summary = r.counters()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingLong(Counter::count));
* </pre>
*/
default Stream<Counter> counters() {
return stream().filter(m -> m instanceof Counter).map(m -> (Counter) m);
}
/**
* Returns a stream of all registered distribution summaries. This operation is mainly used for
* testing as a convenient way to get an aggregated value. For example, to generate a summary of
* the counts and total amounts for all distribution summaries with name "foo":
*
* <pre>
* LongSummaryStatistics countSummary = r.distributionSummaries()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingLong(DistributionSummary::count));
*
* LongSummaryStatistics totalSummary = r.distributionSummaries()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingLong(DistributionSummary::totalAmount));
*
* double avgAmount = (double) totalSummary.getSum() / countSummary.getSum();
* </pre>
*/
default Stream<DistributionSummary> distributionSummaries() {
return stream().filter(m -> m instanceof DistributionSummary).map(m -> (DistributionSummary) m);
}
/**
* Returns a stream of all registered timers. This operation is mainly used for testing as a
* convenient way to get an aggregated value. For example, to generate a summary of
* the counts and total amounts for all timers with name "foo":
*
* <pre>
* LongSummaryStatistics countSummary = r.timers()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingLong(Timer::count));
*
* LongSummaryStatistics totalSummary = r.timers()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingLong(Timer::totalTime));
*
* double avgTime = (double) totalSummary.getSum() / countSummary.getSum();
* </pre>
*/
default Stream<Timer> timers() {
return stream().filter(m -> m instanceof Timer).map(m -> (Timer) m);
}
/**
* Returns a stream of all registered gauges. This operation is mainly used for testing as a
* convenient way to get an aggregated value. For example, to generate a summary of
* the values for all gauges with name "foo":
*
* <pre>
* DoubleSummaryStatistics valueSummary = r.gauges()
* .filter(Functions.nameEquals("foo"))
* .collect(Collectors.summarizingDouble(Gauge::value));
*
* double sum = (double) valueSummary.getSum();
* </pre>
*/
default Stream<Gauge> gauges() {
return stream().filter(m -> m instanceof Gauge).map(m -> (Gauge) m);
}
/**
* Log a warning and if enabled propagate the exception {@code t}. As a general rule
* instrumentation code should degrade gracefully and avoid impacting the core application. If
* the user makes a mistake and causes something to break, then it should not impact the
* application unless that mistake triggers a problem outside of the instrumentation code.
* However, in test code it is often better to throw so that mistakes are caught and corrected.
*
* This method is used to handle exceptions internal to the instrumentation code. Propagation
* is controlled by the {@link RegistryConfig#propagateWarnings()} setting. If the setting
* is true, then the exception will be propagated. Otherwise the exception will only get logged
* as a warning.
*
* @param msg
* Message written out to the log.
* @param t
* Exception to log and optionally propagate.
*/
default void propagate(String msg, Throwable t) {
LoggerFactory.getLogger(getClass()).warn(msg, t);
if (config().propagateWarnings()) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new RuntimeException(t);
}
}
}
/**
* Log a warning using the message from the exception and if enabled propagate the
* exception {@code t}. For more information see {@link #propagate(String, Throwable)}.
*
* @param t
* Exception to log and optionally propagate.
*/
default void propagate(Throwable t) {
if (t != null) {
propagate(t.getMessage(), t);
}
}
}
| 5,820 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/Clock.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.api;
/**
* A timing source that can be used to access the current wall time as well as a high resolution
* monotonic time to measuring elapsed times. Most of the time the {@link #SYSTEM} implementation
* that calls the builtin java methods is probably the right one to use. Other implementations
* would typically only get used for unit tests or other cases where precise control of the clock
* is needed.
*/
public interface Clock {
/**
* Current wall time in milliseconds since the epoch. Typically equivalent to
* System.currentTimeMillis.
*/
long wallTime();
/**
* Current time from a monotonic clock source. The value is only meaningful when compared with
* another snapshot to determine the elapsed time for an operation. The difference between two
* samples will have a unit of nanoseconds. The returned value is typically equivalent to
* System.nanoTime.
*/
long monotonicTime();
/**
* Default clock implementation based on corresponding calls in {@link java.lang.System}.
*/
Clock SYSTEM = SystemClock.INSTANCE;
}
| 5,821 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/TagList.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.api;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
/**
* Base type for a collection of tags. Allows access to the keys and values without allocations
* if the underlying implementation does not store them as Tag objects.
*/
public interface TagList extends Iterable<Tag>, Comparable<TagList> {
/** Create a new tag list from a map. */
static TagList create(Map<String, String> tags) {
return ArrayTagSet.create(tags);
}
/** Return the key at the specified index. */
String getKey(int i);
/** Return the value at the specified index. */
String getValue(int i);
/** Return the number of tags in the list. */
int size();
/** Return the tag at the specified index. */
default Tag getTag(int i) {
return Tag.of(getKey(i), getValue(i));
}
/** Return a new tag list with only tags that match the predicate. */
default TagList filter(BiPredicate<String, String> predicate) {
final int n = size();
List<Tag> result = new ArrayList<>(n);
for (int i = 0; i < n; ++i) {
final String k = getKey(i);
final String v = getValue(i);
if (predicate.test(k, v)) {
result.add(Tag.of(k, v));
}
}
return ArrayTagSet.create(result);
}
/** Return a new tag list with only tags with keys that match the predicate. */
default TagList filterByKey(Predicate<String> predicate) {
return filter((k, v) -> predicate.test(k));
}
/** Apply the consumer function for each tag in the list. */
default void forEach(BiConsumer<String, String> consumer) {
final int n = size();
for (int i = 0; i < n; ++i) {
consumer.accept(getKey(i), getValue(i));
}
}
@Override default Iterator<Tag> iterator() {
final int length = size();
return new Iterator<Tag>() {
private int i = 0;
@Override public boolean hasNext() {
return i < length;
}
@Override public Tag next() {
if (i >= length) {
throw new NoSuchElementException("next called after end of iterator");
}
return getTag(i++);
}
};
}
@Override default int compareTo(TagList other) {
if (this == other) {
return 0;
} else {
int n = Math.min(size(), other.size());
for (int i = 0; i < n; ++i) {
// Check key
int cmp = getKey(i).compareTo(other.getKey(i));
if (cmp != 0)
return cmp;
// Check value
cmp = getValue(i).compareTo(other.getValue(i));
if (cmp != 0)
return cmp;
}
// If they are equal up to this point, then remaining items in one list should
// put it after the other
return size() - other.size();
}
}
@Override
default Spliterator<Tag> spliterator() {
return Spliterators.spliterator(iterator(), size(), Spliterator.ORDERED);
}
}
| 5,822 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/NoopRegistry.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.api;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;
/**
* Registry implementation that does nothing. This is typically used to allow for performance tests
* to see how much overhead is being added by instrumentation. This implementation tries to do the
* minimum amount possible without requiring code changes for users.
*/
public final class NoopRegistry implements Registry {
// Since we don't know how callers might be using this a noop implementation
// of the map could cause unexpected issues.
private final ConcurrentMap<Id, Object> state = new ConcurrentHashMap<>();
@Override public Clock clock() {
return Clock.SYSTEM;
}
@Override public Id createId(String name) {
return NoopId.INSTANCE;
}
@Override public Id createId(String name, Iterable<Tag> tags) {
return NoopId.INSTANCE;
}
@Override public Id createId(String name, String... tags) {
return NoopId.INSTANCE;
}
@Override public Id createId(String name, Map<String, String> tags) {
return NoopId.INSTANCE;
}
@Deprecated
@Override public void register(Meter meter) {
}
@Override public ConcurrentMap<Id, Object> state() {
return state;
}
@Override public Counter counter(Id id) {
return NoopCounter.INSTANCE;
}
@Override public DistributionSummary distributionSummary(Id id) {
return NoopDistributionSummary.INSTANCE;
}
@Override public Timer timer(Id id) {
return NoopTimer.INSTANCE;
}
@Override public Gauge gauge(Id id) {
return NoopGauge.INSTANCE;
}
@Override public Gauge maxGauge(Id id) {
return NoopGauge.INSTANCE;
}
@Override public Meter get(Id id) {
return null;
}
@Override public Iterator<Meter> iterator() {
return Collections.emptyIterator();
}
@Override public Spliterator<Meter> spliterator() {
return Spliterators.emptySpliterator();
}
@Override public Stream<Measurement> measurements() {
return Stream.empty();
}
@Override public Stream<Meter> stream() {
return Stream.empty();
}
@Override public Stream<Counter> counters() {
return Stream.empty();
}
@Override public Stream<DistributionSummary> distributionSummaries() {
return Stream.empty();
}
@Override public Stream<Timer> timers() {
return Stream.empty();
}
@Override public Stream<Gauge> gauges() {
return Stream.empty();
}
@Override public void propagate(String msg, Throwable t) {
// Since everything will have the same id when using this registry, it can result
// in type errors when checking against the state, see #503.
}
@Override public void propagate(Throwable t) {
}
}
| 5,823 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/package-info.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.
*/
/**
* Primary interfaces for working with spectator. To get started, here is a small code sample:
*
* <pre>
* Server s = new Server(new DefaultRegistry());
*
* class Server {
* private final Registry registry;
* private final Id requestCountId;
* private final Timer requestLatency;
* private final DistributionSummary responseSizes;
*
* public Server(Registry registry) {
* this.registry = registry;
* requestCountId = registry.createId("server.requestCount");
* requestLatency = registry.timer("server.requestLatency");
* responseSizes = registry.distributionSummary("server.responseSizes");
* registry.gauge("server.numConnections", this, Server::getNumConnections);
* }
*
* public Response handle(Request req) {
* final long s = System.nanoTime();
* try {
* Response res = doSomething(req);
*
* final Id cntId = requestCountId
* .withTag("country", req.country())
* .withTag("status", res.status());
* registry.counter(cntId).increment();
*
* responseSizes.record(res.body().size());
*
* return res;
* } catch (Exception e) {
* final Id cntId = requestCountId
* .withTag("country", req.country())
* .withTag("status", "exception")
* .withTag("error", e.getClass().getSimpleName());
* registry.counter(cntId).increment();
* throw e;
* } finally {
* requestLatency.record(System.nanoTime() - s, TimeUnit.NANOSECONDS);
* }
* }
*
* public int getNumConnections() {
* // however we determine the current number of connections on the server
* }
* }
* </pre>
*
* The main classes you will need to understand:
*
* <ul>
* <li>{@link com.netflix.spectator.api.Spectator}: static entrypoint to access the registry.</li>
* <li>{@link com.netflix.spectator.api.Registry}: registry class used to create meters.</li>
* <li>{@link com.netflix.spectator.api.Counter}: meter type for measuring a rate of change.</li>
* <li>{@link com.netflix.spectator.api.Timer}: meter type for measuring the time for many short
* events.</li>
* <li>{@link com.netflix.spectator.api.LongTaskTimer}: meter type for measuring the time for a
* few long events.</li>
* <li>{@link com.netflix.spectator.api.DistributionSummary}: meter type for measuring the sample
* distribution of some type of events.</li>
* </ul>
*/
package com.netflix.spectator.api;
| 5,824 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/DefaultTimer.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.api;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** Timer implementation for the default registry. */
final class DefaultTimer extends AbstractTimer {
private final Id id;
private final AtomicLong count;
private final AtomicLong totalTime;
/** Create a new instance. */
DefaultTimer(Clock clock, Id id) {
super(clock);
this.id = id;
count = new AtomicLong(0L);
totalTime = new AtomicLong(0L);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount, TimeUnit unit) {
if (amount >= 0L) {
final long nanos = TimeUnit.NANOSECONDS.convert(amount, unit);
totalTime.addAndGet(nanos);
count.incrementAndGet();
}
}
@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.totalTime), now, totalTime.get()));
return ms;
}
@Override public long count() {
return count.get();
}
@Override public long totalTime() {
return totalTime.get();
}
}
| 5,825 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/ThreadPoolMonitor.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.api.patterns;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.impl.Preconditions;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Monitors and reports a common set of metrics for thread pools.
*
* <p>The following is the list of metrics reported followed by which {@link ThreadPoolExecutor}
* method populates it.</p>
*
* <pre>
* +-----------------------------------------------------------------------------+
* | Metric Name | Data Source |
* +------------------------------+----------------------------------------------+
* |threadpool.taskCount | {@link ThreadPoolExecutor#getTaskCount()} |
* +------------------------------+----------------------------------------------+
* |threadpool.completedTaskCount | {@link ThreadPoolExecutor#getCompletedTaskCount()} |
* +------------------------------+----------------------------------------------+
* |threadpool.currentThreadsBusy | {@link ThreadPoolExecutor#getActiveCount()} |
* +------------------------------+----------------------------------------------+
* |threadpool.maxThreads | {@link ThreadPoolExecutor#getMaximumPoolSize()} |
* +------------------------------+----------------------------------------------+
* |threadpool.poolSize | {@link ThreadPoolExecutor#getPoolSize()} |
* +------------------------------+----------------------------------------------+
* |threadpool.corePoolSize | {@link ThreadPoolExecutor#getCorePoolSize()} |
* +------------------------------+----------------------------------------------+
* |threadpool.queueSize | {@link ThreadPoolExecutor#getQueue()}.size() |
* +-----------------------------------------------------------------------------+
* </pre>
*/
public final class ThreadPoolMonitor {
/**
* The default ID tag name.
*/
static final String ID_TAG_NAME = "id";
/**
* The default ID value.
*/
static final String DEFAULT_ID = "default";
/**
* Task count meter name.
*/
static final String TASK_COUNT = "threadpool.taskCount";
/**
* Completed task count meter name.
*/
static final String COMPLETED_TASK_COUNT = "threadpool.completedTaskCount";
/**
* Rejected task count meter name.
*/
static final String REJECTED_TASK_COUNT = "threadpool.rejectedTaskCount";
/**
* Current threads busy meter name.
*/
static final String CURRENT_THREADS_BUSY = "threadpool.currentThreadsBusy";
/**
* Max threads meter name.
*/
static final String MAX_THREADS = "threadpool.maxThreads";
/**
* Pool size meter name.
*/
static final String POOL_SIZE = "threadpool.poolSize";
/**
* Core pool size meter name.
*/
static final String CORE_POOL_SIZE = "threadpool.corePoolSize";
/**
* Queue size meter name.
*/
static final String QUEUE_SIZE = "threadpool.queueSize";
// prevent direct instantiation.
private ThreadPoolMonitor() { }
/**
* Register the provided thread pool, optionally tagged with a name. If a custom
* {@link RejectedExecutionHandler} is going to be used, then it should be set on the pool
* prior to attaching. Otherwise it will overwrite the wrapped rejection handler used to
* track the number of rejected tasks from this pool.
*
* @param registry
* The registry to use.
* @param threadPool
* The thread pool to monitor.
* @param threadPoolName
* A name with which to tag the metrics (default name used if {@code null} or empty).
*/
public static void attach(
final Registry registry,
final ThreadPoolExecutor threadPool,
final String threadPoolName) {
Preconditions.checkNotNull(registry, "registry");
Preconditions.checkNotNull(threadPool, "threadPool");
final String idValue;
if (threadPoolName == null || threadPoolName.isEmpty()) {
idValue = DEFAULT_ID;
} else {
idValue = threadPoolName;
}
final Tag idTag = new BasicTag(ID_TAG_NAME, idValue);
PolledMeter.using(registry)
.withName(TASK_COUNT)
.withTag(idTag)
.monitorMonotonicCounter(threadPool, ThreadPoolExecutor::getTaskCount);
PolledMeter.using(registry)
.withName(COMPLETED_TASK_COUNT)
.withTag(idTag)
.monitorMonotonicCounter(threadPool, ThreadPoolExecutor::getCompletedTaskCount);
PolledMeter.using(registry)
.withName(CURRENT_THREADS_BUSY)
.withTag(idTag)
.monitorValue(threadPool, ThreadPoolExecutor::getActiveCount);
PolledMeter.using(registry)
.withName(MAX_THREADS)
.withTag(idTag)
.monitorValue(threadPool, ThreadPoolExecutor::getMaximumPoolSize);
PolledMeter.using(registry)
.withName(POOL_SIZE)
.withTag(idTag)
.monitorValue(threadPool, ThreadPoolExecutor::getPoolSize);
PolledMeter.using(registry)
.withName(CORE_POOL_SIZE)
.withTag(idTag)
.monitorValue(threadPool, ThreadPoolExecutor::getCorePoolSize);
PolledMeter.using(registry)
.withName(QUEUE_SIZE)
.withTag(idTag)
.monitorValue(threadPool, tp -> tp.getQueue().size());
// Handler is not allowed to be null, checked internally to thread pool
Counter rejected = registry.counter(registry.createId(REJECTED_TASK_COUNT).withTag(idTag));
RejectedExecutionHandler handler = threadPool.getRejectedExecutionHandler();
RejectedExecutionHandler monitoredHandler = (Runnable r, ThreadPoolExecutor exec) -> {
rejected.increment();
handler.rejectedExecution(r, exec);
};
threadPool.setRejectedExecutionHandler(monitoredHandler);
}
}
| 5,826 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/IdBuilder.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.api.patterns;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
/**
* Base type for builders that are required to construct an {@link Id} object. This class
* assists with the creation of a base id and then returns another builder type that can
* be used for further refinement. By following this pattern the builder will force the
* user to satisfy the minimal constraints of the id before a final option to construct
* or complete the operation is provided.
*
* <p>Sample usage:</p>
*
* <pre>
* return new IdBuilder<Builder>(registry) {
* {@literal @}Override protected Builder createTypeBuilder(Id id) {
* return new Builder(registry, id);
* }
* };
* </pre>
*
* <p>The type returned by {@link #createTypeBuilder(Id)} can extend {@link TagsBuilder}
* to easily support additional tags being added after the base id requirements are
* satisfied.</p>
*/
public abstract class IdBuilder<T> {
/** Registry used for created ids. */
protected final Registry registry;
/** Create a new instance. */
protected IdBuilder(Registry registry) {
this.registry = registry;
}
/** Sub-classes should override this method to create the more specific builder type. */
protected abstract T createTypeBuilder(Id id);
/**
* Create a new identifier with the provide name.
*
* @param name
* Name used in the identifier.
* @return
* Builder object to allow for method chaining.
*/
public T withName(String name) {
return createTypeBuilder(registry.createId(name));
}
/**
* Set the base identifier for the type being constructed.
*
* @param id
* Identifier for the type being constructed.
* @return
* Builder object to allow for method chaining.
*/
public T withId(Id id) {
if (id == null) {
registry.propagate(new NullPointerException("parameter 'id' cannot be null"));
return createTypeBuilder(registry.createId(null));
} else {
return createTypeBuilder(id);
}
}
}
| 5,827 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/GaugePoller.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.api.patterns;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Helper for polling gauges in a background thread. A shared executor is used with a
* single thread. If registered gauge methods are cheap as they should be, then this
* should be plenty of capacity to process everything regularly. If not, then this will
* help limit the damage to a single core and avoid causing problems for the application.
*/
final class GaugePoller {
private static final ThreadFactory FACTORY = new ThreadFactory() {
private final AtomicInteger next = new AtomicInteger();
@Override public Thread newThread(Runnable r) {
final String name = "spectator-gauge-polling-" + next.getAndIncrement();
final Thread t = new Thread(r, name);
t.setDaemon(true);
return t;
}
};
private static final ScheduledExecutorService DEFAULT_EXECUTOR =
Executors.newSingleThreadScheduledExecutor(FACTORY);
static ScheduledFuture<?> schedule(long delay, Runnable task) {
return DEFAULT_EXECUTOR.scheduleWithFixedDelay(task, delay, delay, TimeUnit.MILLISECONDS);
}
/** Schedule collection of gauges for a registry. */
static <T> Future<?> schedule(WeakReference<T> ref, long delay, Consumer<T> poll) {
return schedule(DEFAULT_EXECUTOR, ref, delay, poll);
}
/** Schedule collection of gauges for a registry. */
@SuppressWarnings("PMD")
static <T> Future<?> schedule(
ScheduledExecutorService executor, WeakReference<T> ref, long delay, Consumer<T> poll) {
final AtomicReference<Future<?>> futureRef = new AtomicReference<>();
final Runnable cancel = () -> {
Future<?> f = futureRef.get();
if (f != null) {
f.cancel(false);
}
};
final Runnable task = () -> {
try {
T r = ref.get();
if (r != null) {
poll.accept(r);
} else {
cancel.run();
}
} catch (Throwable t) {
cancel.run();
}
};
futureRef.set(executor.scheduleWithFixedDelay(task, delay, delay, TimeUnit.MILLISECONDS));
return futureRef.get();
}
private GaugePoller() {
}
}
| 5,828 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/CardinalityLimiters.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.api.patterns;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Utils;
import com.netflix.spectator.impl.PatternMatcher;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Helper functions to help manage the cardinality of tag values. This should be used
* anywhere you cannot guarantee that the tag values being used are strictly bounded.
* There is support for two different modes, 1) selecting the first N values that are
* seen, or 2) selecting the most frequent N values that are seen.
*
* <p>Sample usage:</p>
*
* <pre>
* class WebServer {
*
* // Limiter instance, should be shared for all uses of that
* // tag value
* private final Function<String, String> pathLimiter =
* CardinalityLimiters.mostFrequent(10);
*
* private final Registry registry;
* private final Id baseId;
*
* public WebServer(Registry registry) {
* this.registry = registry;
* this.baseId = registry.createId("server.requestCount");
* }
*
* public Response handleRequest(Request req) {
* Response res = doSomething(req);
*
* // Update metrics, use limiter to restrict the set of values
* // for the path and avoid an explosion
* String pathValue = pathLimiter.apply(req.getPath());
* Id id = baseId
* .withTag("path", pathValue)
* .withTag("status", res.getStatus());
* registry.counter(id).increment();
* }
* }
* </pre>
*/
public final class CardinalityLimiters {
/** How often to refresh the frequencies. */
private static final long REFRESH_INTERVAL = 10 * 60000;
/** Bound on how large N can be for the limiter. */
private static final int MAX_LIMIT = 100;
/** Replacement value that is used if the number of values exceeds the limit. */
public static final String OTHERS = "--others--";
/** Replacement value that is used if the values are rolled up. */
public static final String AUTO_ROLLUP = "--auto-rollup--";
/**
* Order in descending order based on the count and then alphabetically based on the
* key if there is a tie.
*/
private static final Comparator<Map.Entry<String, AtomicLong>> FREQUENT_ENTRY_COMPARATOR =
(a, b) -> {
int countCmp = Long.compareUnsigned(b.getValue().get(), a.getValue().get());
return countCmp != 0
? countCmp
: a.getKey().compareTo(b.getKey());
};
private CardinalityLimiters() {
}
/**
* Restrict the cardinality of the input to the first {@code n} values that are seen.
*
* @param n
* Number of values to select.
* @return
* The input value if it is within the bounds or is selected. Otherwise map to
* {@link #OTHERS}.
*/
public static Function<String, String> first(int n) {
return new FirstLimiter(Math.min(n, MAX_LIMIT));
}
/**
* Restrict the cardinality of the input to the top {@code n} values based on the
* frequency of the lookup. This limiter is useful when the frequency of the values
* is non-uniform and the most common are the most important. If there are many
* values with roughly the same frequency, then it will use a {@link #first(int)}
* limiter to keep the number of values within bounds.
*
* <p>The limiter will adjust to changes in the frequency over time, but it must also
* protect against high rates of churn in the values. Keep in mind that this can cause
* a delay in new high frequency value being used instead of being grouped as part of
* {@link #OTHERS}.</p>
*
* @param n
* Number of values to select.
* @return
* The input value if it is within the bounds or is selected. Otherwise map to
* {@link #OTHERS}.
*/
public static Function<String, String> mostFrequent(int n) {
return mostFrequent(n, Clock.SYSTEM);
}
/**
* Allows the clock to be specified for testing. See {@link #mostFrequent(int)} for
* details on the usage.
*/
static Function<String, String> mostFrequent(int n, Clock clock) {
return new MostFrequentLimiter(Math.min(n, MAX_LIMIT), clock);
}
/**
* Rollup the values if the cardinality exceeds {@code n}. This limiter will leave the
* values alone as long as the cardinality stays within the limit. After that all values
* will get mapped to {@link #AUTO_ROLLUP}.
*
* @param n
* Maximum number of distinct values allowed for the lifetime of the limiter.
* @return
* The input value if it is within the bounds or is selected. Otherwise map to
* {@link #AUTO_ROLLUP}.
*/
public static Function<String, String> rollup(int n) {
return new RollupLimiter(n);
}
/**
* Restrict the cardinality independently for values which appear to be IP literals,
* which are likely high-cardinality and low value, and Registered names (eg: Eureka
* VIPs or DNS names), which are low-to-mid cardinality and high value. Values should
* be RFC3986 3.2.2 hosts, behavior with non-host strings is not guaranteed.
*
* @param registeredNameLimiter
* The limiter applied to values which appear to be registered names.
* @param ipLimiter
* The limiter applied to values which appear to be IP literals.
*
* @return
* The result according to the the matched limiter.
*/
public static Function<String, String> registeredNameOrIp(Function<String, String> registeredNameLimiter,
Function<String, String> ipLimiter) {
return new RegisteredNameOrIpLimiter(registeredNameLimiter, ipLimiter);
}
private static class FirstLimiter implements Function<String, String>, Serializable {
private static final long serialVersionUID = 1L;
private final ReentrantLock lock = new ReentrantLock();
private final ConcurrentHashMap<String, String> values = new ConcurrentHashMap<>();
private final AtomicInteger remaining;
FirstLimiter(int n) {
remaining = new AtomicInteger(n);
}
private void add(String s) {
if (remaining.get() > 0) {
// Lock to keep hashmap consistent with counter for remaining
lock.lock();
try {
if (remaining.get() > 0) {
values.put(s, s);
remaining.decrementAndGet();
}
} finally {
lock.unlock();
}
}
}
@Override public String apply(String s) {
if (remaining.get() <= 0) {
return values.getOrDefault(s, OTHERS);
} else {
String v = values.get(s);
if (v == null) {
add(s);
v = values.getOrDefault(s, OTHERS);
}
return v;
}
}
@Override public String toString() {
final String vs = values.keySet()
.stream()
.sorted()
.collect(Collectors.joining(","));
return "FirstLimiter(" + vs + ")";
}
}
private static class MostFrequentLimiter implements Function<String, String>, Serializable {
private static final long serialVersionUID = 1L;
// With a 10m refresh interval this is ~2h for it to return to normal if there
// is a temporary window with lots of churn
private static final int MAX_UPDATES = 12;
private final ReentrantLock lock = new ReentrantLock();
private final ConcurrentHashMap<String, AtomicLong> values = new ConcurrentHashMap<>();
private final int n;
private final Clock clock;
private volatile Function<String, String> limiter;
private volatile long limiterTimestamp;
private volatile long cutoff;
private int updatesWithHighChurn;
MostFrequentLimiter(int n, Clock clock) {
this.n = n;
this.clock = clock;
this.limiter = first(n);
this.limiterTimestamp = clock.wallTime();
this.cutoff = 0L;
this.updatesWithHighChurn = 0;
}
private void updateCutoff() {
long now = clock.wallTime();
if (now - limiterTimestamp > REFRESH_INTERVAL && values.size() > n) {
lock.lock();
try {
if (now - limiterTimestamp > REFRESH_INTERVAL) {
limiterTimestamp = clock.wallTime();
List<Map.Entry<String, AtomicLong>> sorted = values.entrySet()
.stream()
.sorted(FREQUENT_ENTRY_COMPARATOR)
.collect(Collectors.toList());
final long maxCount = sorted.get(0).getValue().get();
Map.Entry<String, AtomicLong> min = sorted.get(Math.min(n - 1, sorted.size() - 1));
final String minKey = min.getKey();
final long minCount = min.getValue().get();
final long delta = Math.max(minCount / 2L, 1L);
final int numCloseToMin = (int) sorted.stream()
.map(e -> e.getValue().get())
.filter(v -> Math.abs(v - minCount) <= delta)
.count();
// Check for high churn
long previousCutoff = cutoff;
if (numCloseToMin > n) {
if (maxCount - minCount <= maxCount / 2L) {
// Max is close to min indicating more likelihood for churn with all values
cutoff = Math.max(previousCutoff, maxCount + delta);
updatesWithHighChurn = MAX_UPDATES;
} else {
// Try to cutoff the noisy tail without impacting higher frequency values
cutoff = Math.max(previousCutoff, minCount + delta);
updatesWithHighChurn += updatesWithHighChurn >= MAX_UPDATES ? 0 : 1;
}
sorted.stream().skip(10L * n).forEach(e -> values.remove(e.getKey()));
// Update the limiter and ensure highest frequency values are preserved
Function<String, String> newLimiter = first(n);
sorted.stream().limit(n).forEach(e -> newLimiter.apply(e.getKey()));
limiter = newLimiter;
} else {
cutoff = minCount - minCount / 10L;
values
.entrySet()
.removeIf(e -> e.getValue().get() <= minCount && e.getKey().compareTo(minKey) > 0);
// Decay the counts so new items will have a chance to catch up
values.values().forEach(v -> v.set(v.get() - v.get() / 10L));
// Replace the fallback limiter instance so new values will be allowed
updatesWithHighChurn -= updatesWithHighChurn > 0 ? 1 : 0;
if (updatesWithHighChurn == 0) {
limiter = first(n);
}
}
}
} finally {
lock.unlock();
}
}
}
@Override public String apply(String s) {
AtomicLong count = Utils.computeIfAbsent(values, s, k -> new AtomicLong(0L));
long num = count.incrementAndGet();
if (num >= cutoff) {
updateCutoff();
// cutoff may have been updated, double check it would still make the cut
String v = limiter.apply(s);
return num >= cutoff ? v : OTHERS;
} else {
return OTHERS;
}
}
@Override public String toString() {
final String vs = values.entrySet()
.stream()
.filter(e -> e.getValue().get() >= cutoff)
.map(e -> "(" + e.getKey() + "," + e.getValue() + ")")
.sorted()
.collect(Collectors.joining(","));
return "MostFrequentLimiter(" + cutoff + "," + limiter + ",values=[" + vs + "])";
}
}
private static class RollupLimiter implements Function<String, String>, Serializable {
private static final long serialVersionUID = 1L;
private final int n;
private final Set<String> values;
private final AtomicInteger count;
private volatile boolean rollup;
RollupLimiter(int n) {
this.n = n;
this.values = ConcurrentHashMap.newKeySet();
this.count = new AtomicInteger();
this.rollup = false;
}
@Override public String apply(String s) {
if (rollup) {
return AUTO_ROLLUP;
}
if (values.add(s) && count.incrementAndGet() > n) {
rollup = true;
values.clear();
return AUTO_ROLLUP;
} else {
return s;
}
}
@Override public String toString() {
final String state = rollup ? "true" : values.size() + " of " + n;
return "RollupLimiter(" + state + ")";
}
}
private static class RegisteredNameOrIpLimiter implements Function<String, String>, Serializable {
private static final long serialVersionUID = 1L;
//From RFC 3986 3.2.2, we can quickly identify IP literals (other than IPv4) from the first and last characters.
private static final Predicate<String> IS_IP_LITERAL = s -> s.startsWith("[") && s.endsWith("]");
//Approximating the logic from RFC 3986 3.2.2 without strictly enforcing the octect range
private static final Predicate<String> IS_IPV4_ADDRESS = PatternMatcher.compile(
"^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")::matches;
private final Function<String, String> registeredNameLimiter;
private final Function<String, String> ipLimiter;
RegisteredNameOrIpLimiter(Function<String, String> registeredNameLimiter, Function<String, String> ipLimiter) {
this.registeredNameLimiter = registeredNameLimiter;
this.ipLimiter = ipLimiter;
}
@Override public String apply(String input) {
if (IS_IP_LITERAL.test(input) || IS_IPV4_ADDRESS.test(input)) {
return ipLimiter.apply(input);
} else {
return registeredNameLimiter.apply(input);
}
}
@Override public String toString() {
return "RegisteredNameOrIpLimiter(registeredNameLimiter=" + registeredNameLimiter.toString()
+ ", ipLimiter=" + ipLimiter.toString() + ")";
}
}
}
| 5,829 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/LongTaskTimer.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.api.patterns;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Utils;
import com.netflix.spectator.impl.Preconditions;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Timer intended to track a small number of long running tasks. Example would be something like
* a batch hadoop job. Though "long running" is a bit subjective the assumption is that anything
* over a minute is long running.
*/
public final class LongTaskTimer implements com.netflix.spectator.api.LongTaskTimer {
/**
* Creates a timer for tracking long running tasks.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @return
* Timer instance.
*/
public static LongTaskTimer get(Registry registry, Id id) {
Preconditions.checkNotNull(registry, "registry");
Preconditions.checkNotNull(id, "id");
ConcurrentMap<Id, Object> state = registry.state();
Object obj = Utils.computeIfAbsent(state, id, i -> {
LongTaskTimer timer = new LongTaskTimer(registry, id);
PolledMeter.using(registry)
.withId(id)
.withTag(Statistic.activeTasks)
.monitorValue(timer, LongTaskTimer::activeTasks);
PolledMeter.using(registry)
.withId(id)
.withTag(Statistic.duration)
.monitorValue(timer, t -> t.duration() / NANOS_PER_SECOND);
return timer;
});
if (!(obj instanceof LongTaskTimer)) {
Utils.propagateTypeError(registry, id, LongTaskTimer.class, obj.getClass());
obj = new LongTaskTimer(new NoopRegistry(), id);
}
return (LongTaskTimer) obj;
}
private static final double NANOS_PER_SECOND = (double) TimeUnit.SECONDS.toNanos(1L);
private final Clock clock;
private final Id id;
private final ConcurrentMap<Long, Long> tasks = new ConcurrentHashMap<>();
private final AtomicLong nextTask = new AtomicLong(0L);
/** Create a new instance. */
private LongTaskTimer(Registry registry, Id id) {
this.clock = registry.clock();
this.id = id;
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public long start() {
long task = nextTask.getAndIncrement();
tasks.put(task, clock.monotonicTime());
return task;
}
@Override public long stop(long task) {
Long startTime = tasks.get(task);
if (startTime != null) {
tasks.remove(task);
return clock.monotonicTime() - startTime;
} else {
return -1L;
}
}
@Override public long duration(long task) {
Long startTime = tasks.get(task);
return (startTime != null) ? (clock.monotonicTime() - startTime) : -1L;
}
@Override public long duration() {
long now = clock.monotonicTime();
long sum = 0L;
for (long startTime : tasks.values()) {
sum += now - startTime;
}
return sum;
}
@Override public int activeTasks() {
return tasks.size();
}
@Override public Iterable<Measurement> measure() {
final List<Measurement> ms = new ArrayList<>(2);
final long now = clock.wallTime();
final double durationSeconds = duration() / NANOS_PER_SECOND;
ms.add(new Measurement(id.withTag(Statistic.duration), now, durationSeconds));
ms.add(new Measurement(id.withTag(Statistic.activeTasks), now, activeTasks()));
return ms;
}
}
| 5,830 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/IntervalCounter.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.api.patterns;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Functions;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Utils;
import java.util.Collections;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* A counter that also keeps track of the time since last update.
*/
public final class IntervalCounter implements Counter {
private static final double MILLIS_PER_SECOND = (double) TimeUnit.SECONDS.toMillis(1L);
/**
* Create a new instance.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @return
* Counter instance.
*/
public static IntervalCounter get(Registry registry, Id id) {
ConcurrentMap<Id, Object> state = registry.state();
Object c = Utils.computeIfAbsent(state, id, i -> new IntervalCounter(registry, i));
if (!(c instanceof IntervalCounter)) {
Utils.propagateTypeError(registry, id, IntervalCounter.class, c.getClass());
c = new IntervalCounter(new NoopRegistry(), id);
}
return (IntervalCounter) c;
}
private final Clock clock;
private final Id id;
private final Counter counter;
private final AtomicLong lastUpdated;
/**
* Create a new IntervalCounter using the given registry and base id.
*/
IntervalCounter(Registry registry, Id id) {
this.clock = registry.clock();
this.id = id;
this.counter = registry.counter(id.withTag(Statistic.count));
this.lastUpdated = PolledMeter.using(registry)
.withId(id)
.withTag(Statistic.duration)
.monitorValue(new AtomicLong(0L), Functions.age(clock));
}
@Override public void add(double amount) {
counter.add(amount);
lastUpdated.set(clock.wallTime());
}
@Override public double actualCount() {
return counter.actualCount();
}
@Override public Id id() {
return id;
}
/**
* Return the number of seconds since the last time the counter was incremented.
*/
public double secondsSinceLastUpdate() {
final long now = clock.wallTime();
return (now - lastUpdated.get()) / MILLIS_PER_SECOND;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return false;
}
}
| 5,831 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/PolledMeter.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.api.patterns;
import com.netflix.spectator.api.Counter;
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.Utils;
import com.netflix.spectator.impl.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.function.DoubleSupplier;
import java.util.function.LongSupplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToLongFunction;
/**
* Helper for configuring a meter that will receive a value by regularly polling the
* source in the background.
*
* <p>Example usage:</p>
*
* <pre>
* Registry registry = ...
* AtomicLong connections = PolledMeter.using(registry)
* .withName("server.currentConnections")
* .monitorValue(new AtomicLong());
*
* // When a connection is added
* connections.incrementAndGet();
*
* // When a connection is removed
* connections.decrementAndGet();
* </pre>
*
* <p>Polling frequency will depend on the underlying registry implementation, but users should
* assume it will be frequently checked and that the provided function is cheap. Users should
* keep in mind that polling will not capture all activity, just sample it at some frequency.
* For example, if monitoring a queue, then a meter will only tell you the last sampled size
* when the value is reported. If more details are needed, then use an alternative type
* and ensure that all changes are reported when they occur.</p>
*
* <p>For example, consider tracking the number of currently established connections to a server.
* Using a polled meter will show the last sampled number when reported. An alternative would
* be to report the number of connections to a {@link com.netflix.spectator.api.DistributionSummary}
* every time a connection is added or removed. The distribution summary would provide more
* accurate tracking such as max and average number of connections across an interval of time.
* The polled meter would not provide that level of detail.</p>
*
* <p>If multiple values are monitored with the same id, then the values will be aggregated and
* the sum will be reported. For example, registering multiple meters for active threads in
* a thread pool with the same id would produce a value that is the overall number
* of active threads. For other behaviors, manage it on the user side and avoid multiple
* registrations.</p>
*/
public final class PolledMeter {
private static final Logger LOGGER = LoggerFactory.getLogger(PolledMeter.class);
private PolledMeter() {
}
/**
* Return a builder for configuring a polled meter reporting to the provided registry.
*
* @param registry
* Registry that will maintain the state and receive the sampled values for the
* configured meter.
* @return
* Builder for configuring a polled meter.
*/
public static IdBuilder<Builder> using(Registry registry) {
return new IdBuilder<Builder>(registry) {
@Override protected Builder createTypeBuilder(Id id) {
return new Builder(registry, id);
}
};
}
/** Force the polling of all meters associated with the registry. */
public static void update(Registry registry) {
Iterator<Map.Entry<Id, Object>> iter = registry.state().entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Id, Object> entry = iter.next();
if (entry.getValue() instanceof AbstractMeterState) {
AbstractMeterState tuple = (AbstractMeterState) entry.getValue();
tuple.doUpdate(registry);
if (tuple.hasExpired()) {
iter.remove();
}
}
}
}
/**
* Explicitly disable polling for the meter registered with {@code id}. This is optional
* and is mostly used if it is desirable for the meter to go away immediately. The polling
* will stop automatically when the referred object is garbage collected. See
* {@link Builder#monitorValue(Object, ToDoubleFunction)} for more information.
*/
public static void remove(Registry registry, Id id) {
Object obj = registry.state().get(id);
if (obj instanceof AbstractMeterState) {
((AbstractMeterState) obj).cleanup(registry);
}
}
/**
* Poll by executing {@code f.accept(registry)} using the default thread pool for polling
* gauges at the default frequency configured for the registry. If more customization is
* needed, then it can be done by using a {@code ScheduledExecutorService} directly and
* updating meters in the registry. The common use-case is being able to update multiple
* meters based on sampling a single time.
*
* <p>The provided function must be thread safe and cheap to execute. Expensive operations,
* including any IO or network calls, should not be performed inline. Assume that the function
* will be called frequently and may be called concurrently.
*
* @param registry
* Registry that will maintain the state and receive the sampled values for the
* configured meter.
* @param f
* Function to call to update the registry.
* @return
* Future that can be used to cancel the polling.
*/
public static ScheduledFuture<?> poll(Registry registry, Runnable f) {
// Call once to initialize meters and quickly fail if something is broken
// with the function
f.run();
long delay = registry.config().gaugePollingFrequency().toMillis();
return GaugePoller.schedule(delay, f);
}
/**
* Builder for configuring a polled meter value.
*/
public static final class Builder extends TagsBuilder<Builder> {
private final Registry registry;
private final Id baseId;
private ScheduledExecutorService executor;
private long delay;
/** Create a new instance. */
Builder(Registry registry, Id baseId) {
super();
this.registry = registry;
this.baseId = baseId;
this.delay = registry.config().gaugePollingFrequency().toMillis();
}
/**
* Set the executor to be used for polling the value. If not set, then the default
* executor will be used which is limited to a single thread to minimize the worst
* case resource usage for collecting the meter data. Use a custom executor if more
* resources are needed or if the polling operation is expensive.
*
* @return
* This builder instance to allow chaining of operations.
*/
public Builder scheduleOn(ScheduledExecutorService executor) {
this.executor = executor;
return this;
}
/**
* Set the delay at which the value should be refreshed. If not set, then
* the default value will be the gauge polling frequency set in the registry
* configuration.
*
* @see
* com.netflix.spectator.api.RegistryConfig#gaugePollingFrequency()
*
* @return
* This builder instance to allow chaining of operations.
*/
public Builder withDelay(Duration delay) {
this.delay = delay.toMillis();
return this;
}
/**
* Poll the value of the provided {@link Number}. The implementation provided must
* be thread safe. The most common usages of this are to monitor instances of
* {@link java.util.concurrent.atomic.AtomicInteger}
* or {@link java.util.concurrent.atomic.AtomicLong}.
*
* @param number
* Thread-safe implementation of {@link Number} used to access the value.
* @return
* The number that was passed in to allow the builder to be used inline as part
* of an assignment.
*/
public <T extends Number> T monitorValue(T number) {
try {
return monitorValue(number, Number::doubleValue);
} catch (Exception e) {
registry.propagate(e);
return number;
}
}
/**
* Poll by executing {@code f(obj)} and reporting the returned value. The provided
* function must be thread safe and cheap to execute. Expensive operations, including
* any IO or network calls, should not be performed inline unless using a custom
* executor by calling {@link #scheduleOn(ScheduledExecutorService)}. Assume that the
* function will be called frequently and may be called concurrently.
*
* <p>A weak reference will be kept to {@code obj} so that monitoring the object will
* not prevent garbage collection. The meter will go away when {@code obj} is collected.
* If {@code obj} is null, then it will be treated as an already collected object and a
* warning will be logged.</p>
*
* <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
* with this builder.</p>
*
* @param obj
* Object used to compute a value.
* @param f
* Function that is applied on the value for the number.
* @return
* The object that was passed in so the registration can be done as part of an assignment
* statement.
*/
@SuppressWarnings("unchecked")
public <T> T monitorValue(T obj, ToDoubleFunction<T> f) {
final Id id = baseId.withTags(extraTags);
if (obj == null) {
registry.propagate(new IllegalArgumentException(
"obj is null for PolledMeter (id = " + id + "), no data will be reported. "
+ "See the API docs for monitorValue for guidance on how to fix the code."));
return null;
}
final Gauge gauge = registry.gauge(id);
final ValueState<T> tuple = new ValueState<>(gauge);
ConcurrentMap<Id, Object> state = registry.state();
Object c = Utils.computeIfAbsent(state, id, i -> tuple);
if (!(c instanceof ValueState)) {
Utils.propagateTypeError(registry, id, PolledMeter.class, c.getClass());
} else {
ValueState<T> t = (ValueState<T>) c;
t.add(obj, f);
t.schedule(registry, executor, delay);
}
return obj;
}
/**
* Poll by executing {@code supplier.getAsDouble()} and reporting the returned value. The
* provided function must be thread safe and cheap to execute. Expensive operations, including
* any IO or network calls, should not be performed inline unless using a custom executor by
* calling {@link #scheduleOn(ScheduledExecutorService)}. Assume that the function will be
* called frequently and may be called concurrently.
*
* <p>This helper should only be used with static method references. It will keep a strong
* reference to any enclosed objects and they will never get garbage collected unless removed
* explicitly by the user.</p>
*
* <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
* with this builder.</p>
*
* @param supplier
* Supplier that will be called to access the value.
*/
public void monitorStaticMethodValue(DoubleSupplier supplier) {
monitorValue(supplier, DoubleSupplier::getAsDouble);
}
/**
* Poll the value of the provided {@link Number} and update a counter with the delta
* since the last time the value was sampled. The implementation provided must
* be thread safe. The most common usages of this are to monitor instances of
* {@link java.util.concurrent.atomic.AtomicInteger},
* {@link java.util.concurrent.atomic.AtomicLong}, or
* {@link java.util.concurrent.atomic.LongAdder}. For more information see
* {@link #monitorMonotonicCounter(Object, ToLongFunction)}.
*
* @param number
* Thread-safe implementation of {@link Number} used to access the value.
* @return
* The number that was passed in to allow the builder to be used inline as part
* of an assignment.
*/
public <T extends Number> T monitorMonotonicCounter(T number) {
return monitorMonotonicCounter(number, Number::longValue);
}
/**
* Map a monotonically increasing long or int value to a counter. Monotonic counters
* are frequently used as a simple way for exposing the amount of change. In order to be
* useful, they need to be polled frequently so the change can be measured regularly over
* time.
*
* <p>Example monotonic counters provided by the JDK:</p>
*
* <ul>
* <li>{@link java.util.concurrent.ThreadPoolExecutor#getCompletedTaskCount()}</li>
* <li>{@link java.lang.management.GarbageCollectorMXBean#getCollectionCount()}</li>
* </ul>
*
* <p>Example usage:</p>
*
* <pre>
* Registry registry = ...
* MonotonicCounter.using(registry)
* .withName("pool.completedTasks")
* .monitorMonotonicCounter(executor, ThreadPoolExecutor::getCompletedTaskCount);
* </pre>
*
* <p>The value is polled by executing {@code f(obj)} and a counter will be updated with
* the delta since the last time the value was sampled. The provided function must be
* thread safe and cheap to execute. Expensive operations, including any IO or network
* calls, should not be performed inline unless using a custom executor by calling
* {@link #scheduleOn(ScheduledExecutorService)}. Assume that the function will be called
* frequently and may be called concurrently.</p>
*
* <p>A weak reference will be kept to {@code obj} so that monitoring the object will
* not prevent garbage collection. The meter will go away when {@code obj} is collected.
* If {@code obj} is null, then it will be treated as an already collected object and a
* warning will be logged.</p>
*
* <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
* with this builder.</p>
*
* @param obj
* Object used to compute a value.
* @param f
* Function that is applied on the value for the number.
* @return
* The object that was passed in so the registration can be done as part of an assignment
* statement.
*/
public <T> T monitorMonotonicCounter(T obj, ToLongFunction<T> f) {
return monitorMonotonicCounterDouble(obj, o -> (double) f.applyAsLong(o));
}
/**
* Map a monotonically increasing double value to a counter. Monotonic counters
* are frequently used as a simple way for exposing the amount of change. In order to be
* useful, they need to be polled frequently so the change can be measured regularly over
* time.
*
* <p>The value is polled by executing {@code f(obj)} and a counter will be updated with
* the delta since the last time the value was sampled. The provided function must be
* thread safe and cheap to execute. Expensive operations, including any IO or network
* calls, should not be performed inline unless using a custom executor by calling
* {@link #scheduleOn(ScheduledExecutorService)}. Assume that the function will be called
* frequently and may be called concurrently.</p>
*
* <p>A weak reference will be kept to {@code obj} so that monitoring the object will
* not prevent garbage collection. The meter will go away when {@code obj} is collected.
* If {@code obj} is null, then it will be treated as an already collected object and a
* warning will be logged.</p>
*
* <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
* with this builder.</p>
*
* @param obj
* Object used to compute a value.
* @param f
* Function that is applied on the value for the number.
* @return
* The object that was passed in so the registration can be done as part of an assignment
* statement.
*/
@SuppressWarnings("unchecked")
public <T> T monitorMonotonicCounterDouble(T obj, ToDoubleFunction<T> f) {
final Id id = baseId.withTags(extraTags);
if (obj == null) {
registry.propagate(new IllegalArgumentException(
"obj is null for PolledMeter (id = " + id + "), no data will be reported. "
+ "See the API docs for monitorMonotonicCounter for guidance on how to "
+ "fix the code."));
return null;
}
final Counter counter = registry.counter(id);
final CounterState<T> tuple = new CounterState<>(counter);
ConcurrentMap<Id, Object> state = registry.state();
Object c = Utils.computeIfAbsent(state, id, i -> tuple);
if (!(c instanceof CounterState)) {
Utils.propagateTypeError(registry, id, PolledMeter.class, c.getClass());
} else {
CounterState<T> t = (CounterState<T>) c;
t.add(obj, f);
t.schedule(registry, executor, delay);
}
return obj;
}
/**
* Map a monotonically increasing long or int value to a counter. Monotonic counters
* are frequently used as a simple way for exposing the amount of change. In order to be
* useful, they need to be polled frequently so the change can be measured regularly over
* time.
*
* <p>Poll by executing {@code supplier.getAsLong()} and reporting the returned value. The
* provided function must be thread safe and cheap to execute. Expensive operations, including
* any IO or network calls, should not be performed inline unless using a custom executor by
* calling {@link #scheduleOn(ScheduledExecutorService)}. Assume that the function will be
* called frequently and may be called concurrently.</p>
*
* <p>This helper should only be used with static method references. It will keep a strong
* reference to any enclosed objects and they will never get garbage collected unless removed
* explicitly by the user.</p>
*
* <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
* with this builder.</p>
*
* @param supplier
* Supplier that will be called to access the value.
*/
public void monitorStaticMethodMonotonicCounter(LongSupplier supplier) {
monitorMonotonicCounter(supplier, LongSupplier::getAsLong);
}
/**
* Poll the value of the provided {@link Collection}. The implementation provided must
* be thread safe. Keep in mind that computing the size can be an expensive operation
* for some collection types.
*
* @param collection
* Thread-safe implementation of {@link Collection}.
* @return
* The collection that was passed in to allow the builder to be used inline as part
* of an assignment.
*/
public <T extends Collection<?>> T monitorSize(T collection) {
return monitorValue(collection, Collection::size);
}
/**
* Poll the value of the provided {@link Map}. The implementation provided must
* be thread safe. Keep in mind that computing the size can be an expensive operation
* for some map types.
*
* @param map
* Thread-safe implementation of {@link Map}.
* @return
* The collection that was passed in to allow the builder to be used inline as part
* of an assignment.
*/
public <T extends Map<?, ?>> T monitorSize(T map) {
return monitorValue(map, Map::size);
}
}
/**
* Provided for backwards compatibility to support the {@link Registry#register(Meter)}
* method. Use the builder created with {@link #using(Registry)} instead.
*
* @deprecated This method only exists to allow for backwards compatibility and should
* be considered an internal detail. This method is scheduled for removal in a future release.
*/
@Deprecated
public static void monitorMeter(Registry registry, Meter meter) {
Preconditions.checkNotNull(registry, "registry");
try {
Preconditions.checkNotNull(registry, "meter");
ConcurrentMap<Id, Object> state = registry.state();
Object c = Utils.computeIfAbsent(state, meter.id(), MeterState::new);
if (!(c instanceof MeterState)) {
Utils.propagateTypeError(registry, meter.id(), MeterState.class, c.getClass());
} else {
MeterState t = (MeterState) c;
t.add(meter);
long delay = registry.config().gaugePollingFrequency().toMillis();
t.schedule(registry, null, delay);
}
} catch (Exception e) {
registry.propagate(e);
}
}
/** Base class for meter state used for bookkeeping. */
abstract static class AbstractMeterState {
private Future<?> future = null;
/** Return the id for the meter. */
protected abstract Id id();
/** Return the true if this meter has expired. */
protected abstract boolean hasExpired();
/** Sample the meter and send updates to the registry. */
protected abstract void update(Registry registry);
/** Cleanup any state associated with this meter and stop polling. */
void cleanup(Registry registry) {
if (future != null) {
future.cancel(true);
}
registry.state().remove(id());
}
/**
* Update the registry if this meter is not expired, otherwise cleanup any state
* associated with this meter.
*/
@SuppressWarnings("PMD.AvoidCatchingThrowable")
void doUpdate(Registry registry) {
if (hasExpired()) {
cleanup(registry);
} else {
try {
update(registry);
} catch (Throwable t) {
LOGGER.trace("uncaught exception from gauge function for [{}]", id(), t);
throw t;
}
}
}
/** Schedule a task to regularly update the registry. */
void schedule(Registry registry, ScheduledExecutorService executor, long delay) {
if (future == null) {
WeakReference<AbstractMeterState> tupleRef = new WeakReference<>(this);
if (executor == null) {
future = GaugePoller.schedule(tupleRef, delay, t -> t.doUpdate(registry));
} else {
future = GaugePoller.schedule(executor, tupleRef, delay, t -> t.doUpdate(registry));
}
}
}
}
/** Keep track of the object reference, counter, and other associated bookkeeping info. */
static final class ValueState<T> extends AbstractMeterState {
private final Gauge gauge;
private final ConcurrentLinkedQueue<ValueEntry<T>> pairs;
/** Create new instance. */
ValueState(Gauge gauge) {
super();
this.gauge = gauge;
this.pairs = new ConcurrentLinkedQueue<>();
}
private void add(T obj, ToDoubleFunction<T> f) {
pairs.add(new ValueEntry<>(obj, f));
}
@Override protected Id id() {
return gauge.id();
}
@Override protected boolean hasExpired() {
return pairs.isEmpty();
}
@Override protected void update(Registry registry) {
double sum = Double.NaN;
Iterator<ValueEntry<T>> iter = pairs.iterator();
while (iter.hasNext()) {
final ValueEntry<T> pair = iter.next();
final T obj = pair.ref.get();
if (obj != null) {
double v = pair.f.applyAsDouble(obj);
if (!Double.isNaN(v)) {
sum = Double.isNaN(sum) ? v : sum + v;
}
} else {
iter.remove();
}
}
if (pairs.isEmpty()) {
LOGGER.trace("gauge [{}] has expired", gauge.id());
}
LOGGER.trace("setting gauge [{}] to {}", gauge.id(), sum);
gauge.set(sum);
}
}
/**
* Pair consisting of weak reference to an object and a function to sample a numeric
* value from the object.
*/
static final class ValueEntry<T> {
private final WeakReference<T> ref;
private final ToDoubleFunction<T> f;
/** Create new instance. */
ValueEntry(T obj, ToDoubleFunction<T> f) {
this.ref = new WeakReference<>(obj);
this.f = f;
}
}
/** Keep track of a meter and associated metadata. */
static final class MeterState extends AbstractMeterState {
private final Id id;
private final ConcurrentLinkedQueue<Meter> queue;
/** Create a new instance. */
MeterState(Id id) {
super();
this.id = id;
this.queue = new ConcurrentLinkedQueue<>();
}
/** Adds a meter to the set included in the aggregate. */
void add(Meter m) {
queue.add(m);
}
@Override protected Id id() {
return id;
}
@Override protected boolean hasExpired() {
return queue.isEmpty();
}
private Iterable<Measurement> measure() {
Map<Id, Measurement> measurements = new HashMap<>();
Iterator<Meter> iter = queue.iterator();
while (iter.hasNext()) {
Meter meter = iter.next();
if (meter.hasExpired()) {
iter.remove();
} else {
for (Measurement m : meter.measure()) {
Measurement prev = measurements.get(m.id());
if (prev == null) {
measurements.put(m.id(), m);
} else {
double v = prev.value() + m.value();
measurements.put(prev.id(), new Measurement(prev.id(), prev.timestamp(), v));
}
}
}
}
if (queue.isEmpty()) {
LOGGER.trace("meter [{}] has expired", id);
}
return measurements.values();
}
@Override protected void update(Registry registry) {
for (Measurement m : measure()) {
LOGGER.trace("setting gauge [{}] to {}", m.id(), m.value());
registry.gauge(m.id()).set(m.value());
}
}
}
/** Keep track of the object reference, counter, and other associated bookkeeping info. */
static final class CounterState<T> extends AbstractMeterState {
private final Counter counter;
private final ConcurrentLinkedQueue<CounterEntry<T>> entries;
/** Create new instance. */
CounterState(Counter counter) {
super();
this.counter = counter;
this.entries = new ConcurrentLinkedQueue<>();
}
private void add(T obj, ToDoubleFunction<T> f) {
entries.add(new CounterEntry<>(obj, f));
}
@Override protected Id id() {
return counter.id();
}
@Override protected boolean hasExpired() {
return entries.isEmpty();
}
@Override protected void update(Registry registry) {
Iterator<CounterEntry<T>> iter = entries.iterator();
while (iter.hasNext()) {
CounterEntry<T> state = iter.next();
if (state.ref.get() == null) {
iter.remove();
} else {
state.update(counter);
}
}
if (entries.isEmpty()) {
LOGGER.trace("monotonic counter [{}] has expired", id());
}
}
}
/** State for counter entry. */
static final class CounterEntry<T> {
private final WeakReference<T> ref;
private final ToDoubleFunction<T> f;
private double previous;
/** Create new instance. */
CounterEntry(T obj, ToDoubleFunction<T> f) {
this.ref = new WeakReference<>(obj);
this.f = f;
this.previous = f.applyAsDouble(obj);
}
private void update(Counter counter) {
T obj = ref.get();
if (obj != null) {
double current = f.applyAsDouble(obj);
if (current > previous) {
final double delta = current - previous;
LOGGER.trace("incrementing counter [{}] by {}", counter.id(), delta);
counter.add(delta);
} else {
LOGGER.trace("no update to counter [{}]: previous = {}, current = {}",
counter.id(), previous, current);
}
previous = current;
}
}
}
}
| 5,832 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/patterns/TagsBuilder.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.api.patterns;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Tag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Base class used for builders that need to allow for additional tagging to be
* added onto a base id. This is typically used in conjunction with {@link IdBuilder}.
*/
@SuppressWarnings("unchecked")
public class TagsBuilder<T extends TagsBuilder<T>> {
/** Create a new instance. */
protected TagsBuilder() {
// This class is only intended to be created by a sub-class. Since there are no
// abstract methods at this time it is documented via the protected constructor
// rather than making the class abstract.
}
/** Set of extra tags that the sub-class should add in to the id. */
protected final List<Tag> extraTags = new ArrayList<>();
/** Add an additional tag value. */
public T withTag(String k, String v) {
extraTags.add(new BasicTag(k, v));
return (T) this;
}
/** Add an additional tag value. */
public T withTag(String k, Boolean v) {
return withTag(k, Boolean.toString(v));
}
/** Add an additional tag value based on the name of the enum. */
public <E extends Enum<E>> T withTag(String k, Enum<E> v) {
return withTag(k, v.name());
}
/** Add an additional tag value. */
public T withTag(Tag t) {
extraTags.add(t);
return (T) this;
}
/** Add additional tag values. */
public T withTags(String... tags) {
for (int i = 0; i < tags.length; i += 2) {
extraTags.add(new BasicTag(tags[i], tags[i + 1]));
}
return (T) this;
}
/** Add additional tag values. */
public T withTags(Tag... tags) {
Collections.addAll(extraTags, tags);
return (T) this;
}
/** Add additional tag values. */
public T withTags(Iterable<Tag> tags) {
for (Tag t : tags) {
extraTags.add(t);
}
return (T) this;
}
/** Add additional tag values. */
public T withTags(Map<String, String> tags) {
for (Map.Entry<String, String> entry : tags.entrySet()) {
extraTags.add(new BasicTag(entry.getKey(), entry.getValue()));
}
return (T) this;
}
}
| 5,833 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/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.api.histogram;
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.Timer;
import com.netflix.spectator.api.Utils;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.LongFunction;
/** Timers that get updated based on the bucket for recorded values. */
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 registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets. See {@link BucketFunctions} for more information.
* @return
* Timer that manages sub-timers based on the bucket function.
*/
public static BucketTimer get(Registry registry, Id id, LongFunction<String> f) {
return new BucketTimer(registry, id, f);
}
private final Registry registry;
private final Id id;
private final LongFunction<String> f;
private final ConcurrentHashMap<String, Timer> timers;
private final Function<String, Timer> timerFactory;
/** Create a new instance. */
BucketTimer(Registry registry, Id id, LongFunction<String> f) {
this.registry = registry;
this.id = id;
this.f = f;
this.timers = new ConcurrentHashMap<>();
this.timerFactory = k -> registry.timer(id.withTag("bucket", k));
}
@Override public Id id() {
return id;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return false;
}
@Override public Clock clock() {
return registry.clock();
}
@Override public void record(long amount, TimeUnit unit) {
final long nanos = unit.toNanos(amount);
timer(f.apply(nanos)).record(amount, unit);
}
/** Return the timer for a given bucket. */
Timer timer(String bucket) {
return Utils.computeIfAbsent(timers, bucket, timerFactory);
}
/** Not supported, will always return 0. */
@Override public long count() {
return 0L;
}
/** Not supported, will always return 0. */
@Override public long totalTime() {
return 0L;
}
}
| 5,834 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.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.api.histogram;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Counter;
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.Statistic;
import com.netflix.spectator.api.Utils;
import com.netflix.spectator.api.patterns.IdBuilder;
import com.netflix.spectator.api.patterns.TagsBuilder;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Distribution summary that buckets the counts to allow for estimating percentiles. This
* distribution summary type will track the data distribution for the summary by maintaining a
* set of counters. The distribution can then be used on the server side to estimate percentiles
* while still allowing for arbitrary slicing and dicing based on dimensions.
*
* <p><b>Percentile distribution summaries are expensive compared to basic distribution summaries
* from the registry.</b> In particular they have a higher storage cost, worst case ~300x, to
* maintain the data distribution. Be diligent about any additional dimensions added to percentile
* distribution summaries and ensure they have a small bounded cardinality. In addition it is
* highly recommended to set a threshold (see {@link Builder#withRange(long, long)}) whenever
* possible to greatly restrict the worst case overhead.</p>
*/
public final class PercentileDistributionSummary implements DistributionSummary {
// Precomputed values for the corresponding buckets. This is done to avoid expensive
// String.format calls when creating new instances of a percentile variant. The
// String.format calls uses regex internally to parse out the `%` substitutions which
// has a lot of overhead.
private static final String[] TAG_VALUES;
static {
int length = PercentileBuckets.length();
TAG_VALUES = new String[length];
for (int i = 0; i < length; ++i) {
TAG_VALUES[i] = String.format("D%04X", i);
}
}
/**
* Only create a new instance of the counter if there is not a cached copy. The array for
* keeping track of the counter per bucket is quite large (1-2k depending on pointer size)
* and can lead to a high allocation rate if the timer is not reused in a high volume call
* site.
*/
private static PercentileDistributionSummary computeIfAbsent(
Registry registry, Id id, long min, long max) {
Object summary = Utils.computeIfAbsent(
registry.state(), id, i -> new PercentileDistributionSummary(registry, id, min, max));
return (summary instanceof PercentileDistributionSummary)
? ((PercentileDistributionSummary) summary).withRange(min, max)
: new PercentileDistributionSummary(registry, id, min, max);
}
/**
* Creates a distribution summary object that can be used for estimating percentiles.
* <b>Percentile distribution summaries are expensive compared to basic distribution summaries
* from the registry.</b> Be diligent with ensuring that any additional dimensions have a small
* bounded cardinality. It is also highly recommended to explicitly set the threshold
* (see {@link Builder#withRange(long, long)}) whenever possible.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @return
* Distribution summary that keeps track of counts by buckets that can be used to estimate
* the percentiles for the distribution.
*/
public static PercentileDistributionSummary get(Registry registry, Id id) {
return computeIfAbsent(registry, id, 0L, Long.MAX_VALUE);
}
/**
* Return a builder for configuring and retrieving and instance of a percentile distribution
* summary. If the distribution summary has dynamic dimensions, then the builder can be used
* with the new dimensions. If the id is the same as an existing distribution summary, then it
* will update the same underlying distribution summaries in the registry.
*/
public static IdBuilder<Builder> builder(Registry registry) {
return new IdBuilder<Builder>(registry) {
@Override protected Builder createTypeBuilder(Id id) {
return new Builder(registry, id);
}
};
}
/**
* Helper for getting instances of a PercentileDistributionSummary.
*/
public static final class Builder extends TagsBuilder<Builder> {
private Registry registry;
private Id baseId;
private long min;
private long max;
/** Create a new instance. */
Builder(Registry registry, Id baseId) {
super();
this.registry = registry;
this.baseId = baseId;
this.min = 0L;
this.max = Long.MAX_VALUE;
}
/**
* Sets the range for this summary. The range is should be the SLA boundary or
* failure point for the activity. Explicitly setting the threshold allows us to optimize
* for the important range of values and reduce the overhead associated with tracking the
* data distribution.
*
* For example, suppose you are making a client call and the max payload size is 8mb. Setting
* the threshold to 8mb will restrict the possible set of buckets used to those approaching
* the boundary. So we can still detect if it is nearing failure, but percentiles
* that are further away from the range may be inflated compared to the actual value.
*
* @param min
* Amount indicating the minimum allowed value for this summary.
* @param max
* Amount indicating the maximum allowed value for this summary.
* @return
* This builder instance to allow chaining of operations.
*/
public Builder withRange(long min, long max) {
this.min = min;
this.max = max;
return this;
}
/**
* Create or get an instance of the percentile distribution summary with the specified
* settings.
*/
public PercentileDistributionSummary build() {
final Id id = baseId.withTags(extraTags);
return computeIfAbsent(registry, id, min, max);
}
}
private final Registry registry;
private final Id id;
private final DistributionSummary summary;
private final long min;
private final long max;
private final AtomicReferenceArray<Counter> counters;
/** Create a new instance. */
private PercentileDistributionSummary(Registry registry, Id id, long min, long max) {
this(registry, id, min, max, new AtomicReferenceArray<>(PercentileBuckets.length()));
}
/** Create a new instance. */
private PercentileDistributionSummary(
Registry registry,
Id id,
long min,
long max,
AtomicReferenceArray<Counter> counters) {
this.registry = registry;
this.id = id;
this.summary = registry.distributionSummary(id);
this.min = min;
this.max = max;
this.counters = counters;
}
/** Returns a PercentileTimer limited to the specified range. */
private PercentileDistributionSummary withRange(long min, long max) {
return (this.min == min && this.max == max)
? this
: new PercentileDistributionSummary(registry, id, min, max, counters);
}
@Override public Id id() {
return id;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return summary.hasExpired();
}
// Lazily load the counter for a given bucket. This avoids the allocation for
// creating the id and the map lookup after the first time a given bucket is
// accessed for a distribution summary.
private Counter counterFor(int i) {
Counter c = counters.get(i);
if (c == null) {
Id counterId = id.withTags(Statistic.percentile, new BasicTag("percentile", TAG_VALUES[i]));
c = registry.counter(counterId);
counters.set(i, c);
}
return c;
}
private long restrict(long amount) {
long v = Math.min(amount, max);
return Math.max(v, min);
}
@Override public void record(long amount) {
if (amount >= 0L) {
summary.record(amount);
counterFor(PercentileBuckets.indexOf(restrict(amount))).increment();
}
}
@Override public void record(long[] amounts, int n) {
// update core summary
summary.record(amounts, n);
// If 'n' is really large, it might pay to allocate and accumulate
// an array of counts, and then issue the increment() calls once per
// bucket. However, it also requires generating an array of ints of
// PercentileBuckets.length() (275 entries), ~1KB, so for the moment
// we defer this optimisation until someone can do the homework
// on where the right memory / CPU crossover is.
final int limit = Math.min(n, amounts.length);
for (int i = 0; i < limit; i++) {
if (amounts[i] > 0) {
counterFor(PercentileBuckets.indexOf(restrict(amounts[i]))).increment();
}
}
}
/**
* Computes the specified percentile for this distribution summary.
*
* @param p
* Percentile to compute, value must be {@code 0.0 <= p <= 100.0}.
* @return
* An approximation of the {@code p}`th percentile in seconds.
*/
public double percentile(double p) {
long[] counts = new long[PercentileBuckets.length()];
for (int i = 0; i < counts.length; ++i) {
counts[i] = counterFor(i).count();
}
return PercentileBuckets.percentile(counts, p);
}
@Override public long count() {
return summary.count();
}
@Override public long totalAmount() {
return summary.totalAmount();
}
}
| 5,835 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileTimer.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.api.histogram;
import com.netflix.spectator.api.BasicTag;
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.api.Registry;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.Utils;
import com.netflix.spectator.api.patterns.IdBuilder;
import com.netflix.spectator.api.patterns.TagsBuilder;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Timer that buckets the counts to allow for estimating percentiles. This timer type will track
* the data distribution for the timer by maintaining a set of counters. The distribution
* can then be used on the server side to estimate percentiles while still allowing for
* arbitrary slicing and dicing based on dimensions.
*
* <p><b>Percentile timers are expensive compared to basic timers from the registry.</b> In
* particular they have a higher storage cost, worst case ~300x, to maintain the data
* distribution. Be diligent about any additional dimensions added to percentile timers and
* ensure they have a small bounded cardinality. In addition it is highly recommended to
* set a range (see {@link Builder#withRange(long, long, TimeUnit)}) whenever possible to
* greatly restrict the worst case overhead.</p>
*
* <p>When using the builder ({@link #builder(Registry)}), the range will default from 10 ms
* to 1 minute. Based on data at Netflix this is the most common range for request latencies
* and restricting to this window reduces the worst case multiple from 276 to 58</p>
*/
public final class PercentileTimer implements Timer {
// Precomputed values for the corresponding buckets. This is done to avoid expensive
// String.format calls when creating new instances of a percentile variant. The
// String.format calls uses regex internally to parse out the `%` substitutions which
// has a lot of overhead.
private static final String[] TAG_VALUES;
static {
int length = PercentileBuckets.length();
TAG_VALUES = new String[length];
for (int i = 0; i < length; ++i) {
TAG_VALUES[i] = String.format("T%04X", i);
}
}
/**
* Only create a new instance of the counter if there is not a cached copy. The array for
* keeping track of the counter per bucket is quite large (1-2k depending on pointer size)
* and can lead to a high allocation rate if the timer is not reused in a high volume call
* site.
*/
private static PercentileTimer computeIfAbsent(Registry registry, Id id, long min, long max) {
Object timer = Utils.computeIfAbsent(
registry.state(), id, i -> new PercentileTimer(registry, id, min, max));
return (timer instanceof PercentileTimer)
? ((PercentileTimer) timer).withRange(min, max)
: new PercentileTimer(registry, id, min, max);
}
/**
* Creates a timer object that can be used for estimating percentiles. <b>Percentile timers
* are expensive compared to basic timers from the registry.</b> Be diligent with ensuring
* that any additional dimensions have a small bounded cardinality. It is also highly
* recommended to explicitly set a range
* (see {@link Builder#withRange(long, long, TimeUnit)}) whenever possible.
*
* @param registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @return
* Timer that keeps track of counts by buckets that can be used to estimate
* the percentiles for the distribution.
*/
public static PercentileTimer get(Registry registry, Id id) {
return computeIfAbsent(registry, id, 0L, Long.MAX_VALUE);
}
/**
* Return a builder for configuring and retrieving and instance of a percentile timer. If
* the timer has dynamic dimensions, then the builder can be used with the new dimensions.
* If the id is the same as an existing timer, then it will update the same underlying timers
* in the registry.
*/
public static IdBuilder<Builder> builder(Registry registry) {
return new IdBuilder<Builder>(registry) {
@Override protected Builder createTypeBuilder(Id id) {
return new Builder(registry, id);
}
};
}
/**
* Helper for getting instances of a PercentileTimer.
*/
public static final class Builder extends TagsBuilder<Builder> {
private Registry registry;
private Id baseId;
private long min;
private long max;
/** Create a new instance. */
Builder(Registry registry, Id baseId) {
super();
this.registry = registry;
this.baseId = baseId;
this.min = TimeUnit.MILLISECONDS.toNanos(10);
this.max = TimeUnit.MINUTES.toNanos(1);
}
/**
* Sets the threshold for this timer. For more information see
* {@link #withRange(long, long, TimeUnit)}.
*
* @param min
* Duration indicating the minimum value for this timer.
* @param max
* Duration indicating the maximum value for this timer.
* @return
* This builder instance to allow chaining of operations.
*/
public Builder withRange(Duration min, Duration max) {
return withRange(min.toNanos(), max.toNanos(), TimeUnit.NANOSECONDS);
}
/**
* Sets the range for this timer. The range should be the SLA boundary or
* failure point for the activity. Explicitly setting the range allows us to optimize
* for the important range of values and reduce the overhead associated with tracking the
* data distribution.
*
* <p>For example, suppose you are making a client call and timeout after 10 seconds. Setting
* the range to 10 seconds will restrict the possible set of buckets used to those
* approaching the boundary. So we can still detect if it is nearing failure, but percentiles
* that are further away from the range may be inflated compared to the actual value.
*
* @param min
* Amount indicating the minimum allowed value for this timer.
* @param max
* Amount indicating the maximum allowed value for this timer.
* @param unit
* Unit for the specified amount.
* @return
* This builder instance to allow chaining of operations.
*/
public Builder withRange(long min, long max, TimeUnit unit) {
this.min = unit.toNanos(min);
this.max = unit.toNanos(max);
return this;
}
/**
* Create or get an instance of the percentile timer with the specified settings.
*/
public PercentileTimer build() {
final Id id = baseId.withTags(extraTags);
return computeIfAbsent(registry, id, min, max);
}
}
private final Registry registry;
private final Id id;
private final Timer timer;
private final long min;
private final long max;
private final AtomicReferenceArray<Counter> counters;
/** Create a new instance. */
private PercentileTimer(Registry registry, Id id, long min, long max) {
this(registry, id, min, max, new AtomicReferenceArray<>(PercentileBuckets.length()));
}
/** Create a new instance. */
private PercentileTimer(
Registry registry,
Id id,
long min,
long max,
AtomicReferenceArray<Counter> counters) {
this.registry = registry;
this.id = id;
this.timer = registry.timer(id);
this.min = min;
this.max = max;
this.counters = counters;
}
/** Returns a PercentileTimer limited to the specified range. */
private PercentileTimer withRange(long min, long max) {
return (this.min == min && this.max == max)
? this
: new PercentileTimer(registry, id, min, max, counters);
}
@Override public Id id() {
return id;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return timer.hasExpired();
}
// Lazily load the counter for a given bucket. This avoids the allocation for
// creating the id and the map lookup after the first time a given bucket is
// accessed for a timer.
private Counter counterFor(int i) {
Counter c = counters.get(i);
if (c == null) {
Id counterId = id.withTags(Statistic.percentile, new BasicTag("percentile", TAG_VALUES[i]));
c = registry.counter(counterId);
counters.set(i, c);
}
return c;
}
private long restrict(long amount) {
long v = Math.min(amount, max);
return Math.max(v, min);
}
@Override public Clock clock() {
return registry.clock();
}
@Override public void record(long amount, TimeUnit unit) {
final long nanos = restrict(unit.toNanos(amount));
timer.record(amount, unit);
counterFor(PercentileBuckets.indexOf(nanos)).increment();
}
/**
* Computes the specified percentile for this timer. The unit will be seconds.
*
* @param p
* Percentile to compute, value must be {@code 0.0 <= p <= 100.0}.
* @return
* An approximation of the {@code p}`th percentile in seconds.
*/
public double percentile(double p) {
long[] counts = new long[PercentileBuckets.length()];
for (int i = 0; i < counts.length; ++i) {
counts[i] = counterFor(i).count();
}
double v = PercentileBuckets.percentile(counts, p);
return v / 1e9;
}
@Override public long count() {
return timer.count();
}
@Override public long totalTime() {
return timer.totalTime();
}
}
| 5,836 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/BucketCounter.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.api.histogram;
import com.netflix.spectator.api.Counter;
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.Utils;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.LongFunction;
/** Counters that get incremented based on the bucket for recorded values. */
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 registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets. See {@link BucketFunctions} for more information.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketCounter get(Registry registry, Id id, LongFunction<String> f) {
return new BucketCounter(registry, id, f);
}
private final Id id;
private final LongFunction<String> f;
private final ConcurrentHashMap<String, Counter> counters;
private final Function<String, Counter> counterFactory;
/** Create a new instance. */
BucketCounter(Registry registry, Id id, LongFunction<String> f) {
this.id = id;
this.f = f;
this.counters = new ConcurrentHashMap<>();
this.counterFactory = k -> registry.counter(id.withTag("bucket", k));
}
@Override public Id id() {
return id;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount) {
counter(f.apply(amount)).increment();
}
/**
* Update the counter associated with the amount by {@code n}.
*
* @param amount
* Amount to use for determining the bucket.
* @param n
* The delta to apply to the counter.
*/
public void increment(long amount, int n) {
counter(f.apply(amount)).increment(n);
}
/** Return the count for a given bucket. */
Counter counter(String bucket) {
return Utils.computeIfAbsent(counters, bucket, counterFactory);
}
/** Not supported, will always return 0. */
@Override public long count() {
return 0L;
}
/** Not supported, will always return 0. */
@Override public long totalAmount() {
return 0L;
}
}
| 5,837 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/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.api.histogram;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongFunction;
import java.util.function.LongUnaryOperator;
/**
* Helpers for creating bucketing functions.
*/
public final class BucketFunctions {
/**
* Predefined time formatters used to create the bucket labels.
*/
static final List<ValueFormatter> TIME_FORMATTERS = new ArrayList<>();
/**
* Predefined binary formatters used to create bucket labels. For more information see
* <a href="https://en.wikipedia.org/wiki/Binary_prefix">binary prefixes wiki</a>.
*/
static final List<ValueFormatter> BINARY_FORMATTERS = new ArrayList<>();
/**
* Predefined decimal formatters used to created bucket labels. For more informations see
* <a href="https://en.wikipedia.org/wiki/Metric_prefix">metric prefixes wiki</a>.
*/
static final List<ValueFormatter> DECIMAL_FORMATTERS = new ArrayList<>();
static {
TIME_FORMATTERS.add(fmt(TimeUnit.NANOSECONDS.toNanos(10), 1, "ns", TimeUnit.NANOSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.NANOSECONDS.toNanos(100), 2, "ns", TimeUnit.NANOSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MICROSECONDS.toNanos(1), 3, "ns", TimeUnit.NANOSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MICROSECONDS.toNanos(8), 4, "ns", TimeUnit.NANOSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MICROSECONDS.toNanos(10), 1, "us", TimeUnit.MICROSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MICROSECONDS.toNanos(100), 2, "us", TimeUnit.MICROSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MILLISECONDS.toNanos(1), 3, "us", TimeUnit.MICROSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MILLISECONDS.toNanos(8), 4, "us", TimeUnit.MICROSECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MILLISECONDS.toNanos(10), 1, "ms", TimeUnit.MILLISECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MILLISECONDS.toNanos(100), 2, "ms", TimeUnit.MILLISECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.SECONDS.toNanos(1), 3, "ms", TimeUnit.MILLISECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.SECONDS.toNanos(8), 4, "ms", TimeUnit.MILLISECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.SECONDS.toNanos(10), 1, "s", TimeUnit.SECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.SECONDS.toNanos(100), 2, "s", TimeUnit.SECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MINUTES.toNanos(8), 3, "s", TimeUnit.SECONDS));
TIME_FORMATTERS.add(fmt(TimeUnit.MINUTES.toNanos(10), 1, "min", TimeUnit.MINUTES));
TIME_FORMATTERS.add(fmt(TimeUnit.MINUTES.toNanos(100), 2, "min", TimeUnit.MINUTES));
TIME_FORMATTERS.add(fmt(TimeUnit.HOURS.toNanos(8), 3, "min", TimeUnit.MINUTES));
TIME_FORMATTERS.add(fmt(TimeUnit.HOURS.toNanos(10), 1, "h", TimeUnit.HOURS));
TIME_FORMATTERS.add(fmt(TimeUnit.HOURS.toNanos(100), 2, "h", TimeUnit.HOURS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(8), 1, "h", TimeUnit.HOURS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(10), 1, "d", TimeUnit.DAYS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(100), 2, "d", TimeUnit.DAYS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(1000), 3, "d", TimeUnit.DAYS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(10000), 4, "d", TimeUnit.DAYS));
TIME_FORMATTERS.add(fmt(TimeUnit.DAYS.toNanos(100000), 5, "d", TimeUnit.DAYS));
TIME_FORMATTERS.add(fmt(Long.MAX_VALUE, 6, "d", TimeUnit.DAYS));
// TimeUnit.NANOSECONDS.toDays(java.lang.Long.MAX_VALUE) == 106751
final String[] binaryUnits = {"B", "KiB", "MiB", "GiB", "TiB", "PiB"};
for (int i = 0; i < binaryUnits.length; ++i) {
BINARY_FORMATTERS.add(bin(10, i, 1, "_" + binaryUnits[i]));
BINARY_FORMATTERS.add(bin(100, i, 2, "_" + binaryUnits[i]));
BINARY_FORMATTERS.add(bin(1000, i, 3, "_" + binaryUnits[i]));
BINARY_FORMATTERS.add(bin(10000, i, 4, "_" + binaryUnits[i]));
}
BINARY_FORMATTERS.add(new ValueFormatter(Long.MAX_VALUE, 4, "_PiB", v -> v >> 50));
final String[] decimalUnits = {"", "_k", "_M", "_G", "_T", "_P"};
for (int i = 0; i < decimalUnits.length; ++i) {
final int pow = i * 3;
DECIMAL_FORMATTERS.add(dec(10, pow, 1, decimalUnits[i]));
DECIMAL_FORMATTERS.add(dec(100, pow, 2, decimalUnits[i]));
DECIMAL_FORMATTERS.add(dec(1000, pow, 3, decimalUnits[i]));
DECIMAL_FORMATTERS.add(dec(10000, pow, 4, decimalUnits[i]));
}
DECIMAL_FORMATTERS.add(new ValueFormatter(Long.MAX_VALUE, 1, "_E", v -> v / pow10(1, 18)));
}
private static ValueFormatter fmt(long max, int width, String suffix, TimeUnit unit) {
return new ValueFormatter(max, width, suffix, v -> unit.convert(v, TimeUnit.NANOSECONDS));
}
private static ValueFormatter bin(long max, int pow, int width, String suffix) {
final int shift = pow * 10;
final long maxBytes = (shift == 0) ? max : max << shift;
return new ValueFormatter(maxBytes, width, suffix, v -> v >> shift);
}
private static ValueFormatter dec(long max, int pow, int width, String suffix) {
final long factor = pow10(1, pow);
final long maxBytes = max * factor;
return new ValueFormatter(maxBytes, width, suffix, v -> v / factor);
}
private static long pow10(long a, int b) {
long r = a;
for (int i = 0; i < b; ++i) {
r *= 10;
}
return r;
}
private BucketFunctions() {
}
private static ValueFormatter getFormatter(List<ValueFormatter> fmts, long max) {
for (ValueFormatter f : fmts) {
if (max < f.max) {
return f;
}
}
return fmts.get(fmts.size() - 1);
}
private static LongFunction<String> biasZero(
String ltZero, String gtMax, long max, ValueFormatter f) {
List<Bucket> buckets = new ArrayList<>();
buckets.add(new Bucket(ltZero, -1L));
buckets.add(f.newBucket(max / 8));
buckets.add(f.newBucket(max / 4));
buckets.add(f.newBucket(max / 2));
buckets.add(f.newBucket(max));
return new ListBucketFunction(buckets, gtMax);
}
private static LongFunction<String> timeBiasZero(
String ltZero, String gtMax, long max, TimeUnit unit) {
final long v = unit.toNanos(max);
final ValueFormatter f = getFormatter(TIME_FORMATTERS, v);
return biasZero(ltZero, gtMax, v, f);
}
private static LongFunction<String> biasMax(
String ltZero, String gtMax, long max, ValueFormatter f) {
List<Bucket> buckets = new ArrayList<>();
buckets.add(new Bucket(ltZero, -1L));
buckets.add(f.newBucket(max - max / 2));
buckets.add(f.newBucket(max - max / 4));
buckets.add(f.newBucket(max - max / 8));
buckets.add(f.newBucket(max));
return new ListBucketFunction(buckets, gtMax);
}
private static LongFunction<String> timeBiasMax(
String ltZero, String gtMax, long max, TimeUnit unit) {
final long v = unit.toNanos(max);
final ValueFormatter f = getFormatter(TIME_FORMATTERS, v);
return biasMax(ltZero, gtMax, v, f);
}
/**
* 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 LongFunction<String> age(long max, TimeUnit unit) {
return timeBiasZero("future", "old", 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 LongFunction<String> latency(long max, TimeUnit unit) {
return timeBiasZero("negative_latency", "slow", 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 LongFunction<String> ageBiasOld(long max, TimeUnit unit) {
return timeBiasMax("future", "old", 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 LongFunction<String> latencyBiasSlow(long max, TimeUnit unit) {
return timeBiasMax("negative_latency", "slow", max, unit);
}
/**
* Returns a function that maps size values in bytes to a set of buckets. The buckets will
* use <a href="https://en.wikipedia.org/wiki/Binary_prefix">binary prefixes</a> representing
* powers of 1024. If you want powers of 1000, then see {@link #decimal(long)}.
*
* @param max
* Maximum expected size of data being recorded. Values greater than this amount will be
* mapped to a "large" bucket.
* @return
* Function mapping size values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static LongFunction<String> bytes(long max) {
ValueFormatter f = getFormatter(BINARY_FORMATTERS, max);
return biasZero("negative", "large", max, f);
}
/**
* Returns a function that maps size values to a set of buckets. The buckets will
* use <a href="https://en.wikipedia.org/wiki/Metric_prefix">decimal prefixes</a> representing
* powers of 1000. If you are measuring quantities in bytes and want powers of 1024, then see
* {@link #bytes(long)}.
*
* @param max
* Maximum expected size of data being recorded. Values greater than this amount will be
* mapped to a "large" bucket.
* @return
* Function mapping size values to string labels. The labels for buckets will sort
* so they can be used with a simple group by.
*/
public static LongFunction<String> decimal(long max) {
ValueFormatter f = getFormatter(DECIMAL_FORMATTERS, max);
return biasZero("negative", "large", max, f);
}
/**
* Format a value as a bucket label.
*/
static class ValueFormatter {
private final long max;
private final String fmt;
private final LongUnaryOperator cnv;
/**
* Create a new instance.
*
* @param max
* Maximum value intended to be passed into the apply method. Max value is in nanoseconds.
* @param width
* Number of digits to use for the numeric part of the label.
* @param suffix
* Unit suffix appended to the label.
* @param cnv
* Value conversion function. Converts the input value to the right units for the label.
*/
ValueFormatter(long max, int width, String suffix, LongUnaryOperator cnv) {
this.max = max;
this.fmt = "%0" + width + "d" + suffix;
this.cnv = cnv;
}
/** Return the max value intended for this formatter. */
long max() {
return max;
}
/** Apply conversion function to value. */
long convert(long v) {
return cnv.applyAsLong(v);
}
/** Convert the value {@code v} into a bucket label string. */
String apply(long v) {
return String.format(fmt, cnv.applyAsLong(v));
}
/** Return a new bucket for the specified value. */
Bucket newBucket(long v) {
return new Bucket(apply(v), v);
}
}
private static class ListBucketFunction implements LongFunction<String> {
private final List<Bucket> buckets;
private final String fallback;
ListBucketFunction(List<Bucket> buckets, String fallback) {
this.buckets = buckets;
this.fallback = fallback;
}
@Override public String apply(long amount) {
for (Bucket b : buckets) {
if (amount <= b.upperBoundary) {
return b.name;
}
}
return fallback;
}
}
private static class Bucket {
private final String name;
private final long upperBoundary;
Bucket(String name, long upperBoundary) {
this.name = name;
this.upperBoundary = upperBoundary;
}
@Override public String toString() {
return String.format("Bucket(%s,%d)", name, upperBoundary);
}
}
}
| 5,838 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/BucketDistributionSummary.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.api.histogram;
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.Utils;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.LongFunction;
/** Distribution summaries that get updated based on the bucket for recorded values. */
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 registry
* Registry to use.
* @param id
* Identifier for the metric being registered.
* @param f
* Function to map values to buckets. See {@link BucketFunctions} for more information.
* @return
* Distribution summary that manages sub-counters based on the bucket function.
*/
public static BucketDistributionSummary get(Registry registry, Id id, LongFunction<String> f) {
return new BucketDistributionSummary(registry, id, f);
}
private final Id id;
private final LongFunction<String> f;
private final ConcurrentHashMap<String, DistributionSummary> summaries;
private final Function<String, DistributionSummary> distSummaryFactory;
/** Create a new instance. */
BucketDistributionSummary(Registry registry, Id id, LongFunction<String> f) {
this.id = id;
this.f = f;
this.summaries = new ConcurrentHashMap<>();
this.distSummaryFactory = k -> registry.distributionSummary(id.withTag("bucket", k));
}
@Override public Id id() {
return id;
}
@Override public Iterable<Measurement> measure() {
return Collections.emptyList();
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount) {
distributionSummary(f.apply(amount)).record(amount);
}
/** Return the distribution summary for a given bucket. */
DistributionSummary distributionSummary(String bucket) {
return Utils.computeIfAbsent(summaries, bucket, distSummaryFactory);
}
/** Not supported, will always return 0. */
@Override public long count() {
return 0L;
}
/** Not supported, will always return 0. */
@Override public long totalAmount() {
return 0L;
}
}
| 5,839 |
0 | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api | Create_ds/spectator/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileBuckets.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.api.histogram;
import com.netflix.spectator.impl.Preconditions;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.function.Function;
/**
* Bucket values for estimating a percentile from a set of non-negative long values. This class
* acts as an immutable array of the buckets along with providing some helper functions.
*/
public final class PercentileBuckets {
private PercentileBuckets() {
}
/** Returns a copy of the bucket values array. */
public static long[] asArray() {
long[] values = new long[BUCKET_VALUES.length];
System.arraycopy(BUCKET_VALUES, 0, values, 0, BUCKET_VALUES.length);
return values;
}
/** Map the bucket values to a new array of a different type. */
public static <T> T[] map(Class<T> c, Function<Long, T> f) {
@SuppressWarnings("unchecked")
T[] values = (T[]) Array.newInstance(c, BUCKET_VALUES.length);
for (int i = 0; i < BUCKET_VALUES.length; ++i) {
values[i] = f.apply(BUCKET_VALUES[i]);
}
return values;
}
/** Return the value of the bucket at index {@code i}. */
public static long get(int i) {
return BUCKET_VALUES[i];
}
/** Returns the number of buckets. */
public static int length() {
return BUCKET_VALUES.length;
}
/**
* Returns the value the index of the bucket that should be used for {@code v}. The bucket value
* can be retrieved using {@link #get(int)}.
*/
public static int indexOf(long v) {
if (v <= 0) {
return 0;
} else if (v <= 4) {
return (int) v;
} else {
int lz = Long.numberOfLeadingZeros(v);
int shift = 64 - lz - 1;
long prevPowerOf2 = (v >> shift) << shift;
long prevPowerOf4 = prevPowerOf2;
if (shift % 2 != 0) {
shift--;
prevPowerOf4 = prevPowerOf2 >> 1;
}
long base = prevPowerOf4;
long delta = base / 3;
int offset = (int) ((v - base) / delta);
int pos = offset + POWER_OF_4_INDEX[shift / 2];
return (pos >= BUCKET_VALUES.length - 1) ? BUCKET_VALUES.length - 1 : pos + 1;
}
}
/** Returns the value of the bucket that should be used for {@code v}. */
public static long bucket(long v) {
return BUCKET_VALUES[indexOf(v)];
}
/**
* Compute a set of percentiles based on the counts for the buckets.
*
* @param counts
* Counts for each of the buckets. The size must be the same as {@link #length()} and the
* positions must correspond to the positions of the bucket values.
* @param pcts
* Array with the requested percentile values. The length must be at least 1 and the
* array should be sorted. Each value, {@code v}, should adhere to {@code 0.0 <= v <= 100.0}.
* @param results
* The calculated percentile values will be written to the results array. It should have the
* same length as {@code pcts}.
*/
public static void percentiles(long[] counts, double[] pcts, double[] results) {
Preconditions.checkArg(counts.length == BUCKET_VALUES.length,
"counts is not the same size as buckets array");
Preconditions.checkArg(pcts.length > 0, "pct array cannot be empty");
Preconditions.checkArg(pcts.length == results.length,
"pcts is not the same size as results array");
long total = 0L;
for (long c : counts) {
total += c;
}
int pctIdx = 0;
long prev = 0;
double prevP = 0.0;
long prevB = 0;
for (int i = 0; i < BUCKET_VALUES.length; ++i) {
long next = prev + counts[i];
double nextP = 100.0 * next / total;
long nextB = BUCKET_VALUES[i];
while (pctIdx < pcts.length && nextP >= pcts[pctIdx]) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB;
++pctIdx;
}
if (pctIdx >= pcts.length) break;
prev = next;
prevP = nextP;
prevB = nextB;
}
double nextP = 100.0;
long nextB = Long.MAX_VALUE;
while (pctIdx < pcts.length) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB;
++pctIdx;
}
}
/**
* Compute a percentile based on the counts for the buckets.
*
* @param counts
* Counts for each of the buckets. The size must be the same as {@link #length()} and the
* positions must correspond to the positions of the bucket values.
* @param p
* Percentile to compute, the value should be {@code 0.0 <= p <= 100.0}.
* @return
* The calculated percentile value.
*/
public static double percentile(long[] counts, double p) {
double[] pcts = {p};
double[] results = new double[1];
percentiles(counts, pcts, results);
return results[0];
}
// Number of positions of base-2 digits to shift when iterating over the long space.
private static final int DIGITS = 2;
// Bucket values to use, see static block for initialization.
private static final long[] BUCKET_VALUES;
// Keeps track of the positions for even powers of 4 within BUCKET_VALUES. This is used to
// quickly compute the offset for a long without traversing the array.
private static final int[] POWER_OF_4_INDEX;
// The set of buckets is generated by using powers of 4 and incrementing by one-third of the
// previous power of 4 in between as long as the value is less than the next power of 4 minus
// the delta.
//
// <pre>
// Base: 1, 2, 3
//
// 4 (4^1), delta = 1
// 5, 6, 7, ..., 14,
//
// 16 (4^2), delta = 5
// 21, 26, 31, ..., 56,
//
// 64 (4^3), delta = 21
// ...
// </pre>
static {
ArrayList<Integer> powerOf4Index = new ArrayList<>();
powerOf4Index.add(0);
ArrayList<Long> buckets = new ArrayList<>();
buckets.add(1L);
buckets.add(2L);
buckets.add(3L);
int exp = DIGITS;
while (exp < 64) {
long current = 1L << exp;
long delta = current / 3;
long next = (current << DIGITS) - delta;
powerOf4Index.add(buckets.size());
while (current < next) {
buckets.add(current);
current += delta;
}
exp += DIGITS;
}
buckets.add(Long.MAX_VALUE);
BUCKET_VALUES = new long[buckets.size()];
for (int i = 0; i < buckets.size(); ++i) {
BUCKET_VALUES[i] = buckets.get(i);
}
POWER_OF_4_INDEX = new int[powerOf4Index.size()];
for (int i = 0; i < powerOf4Index.size(); ++i) {
POWER_OF_4_INDEX[i] = powerOf4Index.get(i);
}
}
}
| 5,840 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/IdHash.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.perf;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.impl.Hash64;
import net.openhft.hashing.LongHashFunction;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
/**
* Benchmark Mode Cnt Score Error Units
* IdHash.hash64 thrpt 5 2379245.474 ± 7379.034 ops/s
* IdHash.hash64_2 thrpt 5 4817014.307 ± 5704.027 ops/s
* IdHash.openhft thrpt 5 4910133.221 ± 100296.076 ops/s
*
* Benchmark Mode Cnt Score Error Units
* IdHash.hash64:·gc.alloc.rate.norm thrpt 5 0.188 ± 0.002 B/op
* IdHash.hash64_2:·gc.alloc.rate.norm thrpt 5 1152.095 ± 0.001 B/op
* IdHash.openhft:·gc.alloc.rate.norm thrpt 5 1128.095 ± 0.002 B/op
*/
@State(Scope.Thread)
public class IdHash {
private final Id id = Id.create("http.req.complete")
.withTag( "nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag( "nf.asg", "test_app-main-v042")
.withTag( "nf.stack", "main")
.withTag( "nf.ami", "ami-0987654321")
.withTag( "nf.region", "us-east-1")
.withTag( "nf.zone", "us-east-1e")
.withTag( "nf.node", "i-1234567890")
.withTag( "country", "US")
.withTag( "device", "xbox")
.withTag( "status", "200")
.withTag( "client", "ab");
private final Hash64 h64 = new Hash64();
private final LongHashFunction xx = LongHashFunction.xx();
@Benchmark
public void hash64(Blackhole bh) {
h64.updateString(id.name());
for (int i = 1; i < id.size(); ++i) {
h64.updateChar(':');
h64.updateString(id.getKey(i));
h64.updateChar('=');
h64.updateString(id.getValue(i));
}
bh.consume(h64.computeAndReset());
}
@Benchmark
public void hash64_2(Blackhole bh) {
bh.consume(h64.updateString(id.toString()).computeAndReset());
}
@Benchmark
public void openhft(Blackhole bh) {
bh.consume(xx.hashChars(id.toString()));
}
}
| 5,841 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/Caching.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.perf;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.impl.Cache;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Compare performance of simple caching implementation to Caffeine. In some cases we have
* see Caffeine/Guava implementations cause quite a bit of thread contention for concurrent
* access of a LoadingCache.
*
* Also the enabling the registry causes updating the hits/misses counters for each access.
* This can potentially be quite a bit of overhead compared to just the lookup, so enabling
* the monitoring may significantly reduce performance.
*/
public class Caching {
@State(Scope.Benchmark)
public static class AllMissesState {
private final Registry registry = new NoopRegistry();
final Cache<String, String> spectator = Cache.lfu(registry, "jmh", 200, 1000);
final LoadingCache<String, String> caffeine = Caffeine.newBuilder()
.recordStats()
.maximumSize(1000)
.build(String::toUpperCase);
private final String[] missData = createTestData(10000);
private AtomicInteger pos = new AtomicInteger();
private String[] createTestData(int n) {
String[] values = new String[n];
for (int i = 0; i < values.length; ++i) {
values[i] = UUID.randomUUID().toString();
}
return values;
}
public String next() {
int i = Integer.remainderUnsigned(pos.getAndIncrement(), missData.length);
return missData[i];
}
}
@State(Scope.Benchmark)
public static class TypicalState {
private final Registry registry = new NoopRegistry();
final Cache<String, String> spectator = Cache.lfu(registry, "jmh", 200, 1000);
final LoadingCache<String, String> caffeine = Caffeine.newBuilder()
.recordStats()
.maximumSize(1000)
.build(String::toUpperCase);
private final String[] data = createTestData();
private AtomicInteger pos = new AtomicInteger();
private String[] createTestData() {
int n = 10000;
String[] values = new String[n];
int i = 0;
int amount = 140;
while (i < n && amount > 0) {
String v = UUID.randomUUID().toString();
for (int j = 0; j < amount; ++j) {
values[i] = v;
++i;
}
--amount;
}
for (; i < values.length; ++i) {
values[i] = UUID.randomUUID().toString();
}
List<String> list = Arrays.asList(values);
Collections.shuffle(list);
return list.toArray(new String[0]);
}
public String next() {
int i = Integer.remainderUnsigned(pos.getAndIncrement(), data.length);
return data[i];
}
}
@Threads(8)
@Benchmark
public void allMissesSpectator(Blackhole bh, AllMissesState state) {
String s = state.next();
bh.consume(state.spectator.computeIfAbsent(s, String::toUpperCase));
}
@Threads(8)
@Benchmark
public void allMissesCaffeine(Blackhole bh, AllMissesState state) {
String s = state.next();
bh.consume(state.caffeine.get(s));
}
@Threads(8)
@Benchmark
public void typicalSpectator(Blackhole bh, TypicalState state) {
String s = state.next();
bh.consume(state.spectator.computeIfAbsent(s, String::toUpperCase));
}
@Threads(8)
@Benchmark
public void typicalCaffeine(Blackhole bh, TypicalState state) {
String s = state.next();
bh.consume(state.caffeine.get(s));
}
}
| 5,842 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/BucketMeters.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.perf;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.histogram.BucketCounter;
import com.netflix.spectator.api.histogram.BucketDistributionSummary;
import com.netflix.spectator.api.histogram.BucketFunctions;
import com.netflix.spectator.api.histogram.BucketTimer;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
public class BucketMeters {
private final Registry registry = new DefaultRegistry();
private final BucketCounter counter = BucketCounter.get(
registry,
registry.createId("test.counter"),
BucketFunctions.ageBiasOld(60, TimeUnit.MILLISECONDS)
);
private final BucketTimer timer = BucketTimer.get(
registry,
registry.createId("test.timer"),
BucketFunctions.ageBiasOld(60, TimeUnit.MILLISECONDS)
);
private final BucketDistributionSummary dist= BucketDistributionSummary.get(
registry,
registry.createId("test.dist"),
BucketFunctions.bytes(60)
);
@Threads(1)
@Benchmark
public void counterRecord() {
counter.record(47000L);
}
@Threads(1)
@Benchmark
public void timerRecord() {
timer.record(47000L, TimeUnit.MILLISECONDS);
}
@Threads(1)
@Benchmark
public void distRecord() {
dist.record(47L);
}
}
| 5,843 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/StringReplace.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.perf;
import com.netflix.spectator.impl.AsciiSet;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.util.BitSet;
import java.util.UUID;
/**
* Compares a number of approaches for quickly replacing invalid characters that are part
* of a string. The goal is to be fast and preferably minimize the number of allocations.
*
* The {@link AsciiSet} class uses a combination of array approach, check first, and method
* handle to avoid an additional allocation and array copy when creating the string (see
* {@link StringCreate} benchmark for more details).
*
* <pre>
* Benchmark Mode Cnt Score Error Units
*
* bad_array thrpt 5 20960080.404 ± 2528326.088 ops/s
* bad_asciiSet thrpt 5 28525355.999 ± 1110328.417 ops/s
* bad_bitSet thrpt 5 25384526.493 ± 399471.760 ops/s
* bad_checkFirst thrpt 5 28570631.420 ± 413296.441 ops/s
* bad_naive thrpt 5 798526.522 ± 24004.695 ops/s
* bad_stringBuilder thrpt 5 10592798.051 ± 500514.554 ops/s
*
* ok_array thrpt 5 19738313.781 ± 2000737.155 ops/s
* ok_asciiSet thrpt 5 47503468.615 ± 2395740.563 ops/s
* ok_bitSet thrpt 5 37388017.571 ± 2415574.832 ops/s
* ok_checkFirst thrpt 5 47555675.336 ± 1323382.528 ops/s
* ok_naive thrpt 5 641579.313 ± 10920.803 ops/s
* ok_stringBuilder thrpt 5 13520065.966 ± 925254.484 ops/s
* </pre>
*/
@State(Scope.Thread)
public class StringReplace {
private static BitSet toBitSet(AsciiSet set) {
BitSet bits = new BitSet();
for (int i = 0; i < 128; ++i) {
char c = (char) i;
if (set.contains(c))
bits.set(i);
}
return bits;
}
private final AsciiSet set = AsciiSet.fromPattern("-._A-Za-z0-9");
private final BitSet members = toBitSet(set);
private final String ok = UUID.randomUUID().toString();
private final String bad = ok.replace('-', ' ');
private void replace(StringBuilder buf, String input, char replacement) {
final int n = input.length();
for (int i = 0; i < n; ++i) {
final char c = input.charAt(i);
if (set.contains(c)) {
buf.append(c);
} else {
buf.append(replacement);
}
}
}
private void replace(char[] buf, String input, char replacement) {
final int n = input.length();
for (int i = 0; i < n; ++i) {
final char c = input.charAt(i);
if (!set.contains(c)) {
buf[i] = replacement;
}
}
}
private String naive(String input, char replacement) {
return input.replaceAll("[-._A-Za-z0-9]", "" + replacement);
}
private String stringBuilder(String input, char replacement) {
StringBuilder buf = new StringBuilder(input.length());
replace(buf, input, replacement);
return buf.toString();
}
private String array(String input, char replacement) {
char[] buf = input.toCharArray();
replace(buf, input, replacement);
return new String(buf);
}
private String checkFirst(String input, char replacement) {
return set.containsAll(input) ? input : array(input, replacement);
}
private String asciiSet(String input, char replacement) {
return set.replaceNonMembers(input, replacement);
}
boolean contains(char c) {
return members.get(c);
}
private boolean containsAll(CharSequence str) {
final int n = str.length();
for (int i = 0; i < n; ++i) {
if (!contains(str.charAt(i))) {
return false;
}
}
return true;
}
private String bitSet(String input, char replacement) {
if (containsAll(input)) {
return input;
} else {
final int n = input.length();
final char[] buf = input.toCharArray();
for (int i = 0; i < n; ++i) {
final char c = buf[i];
if (!contains(c)) {
buf[i] = replacement;
}
}
return new String(buf);
}
}
@Threads(1)
@Benchmark
public void ok_naive(Blackhole bh) {
bh.consume(naive(ok, '_'));
}
@Threads(1)
@Benchmark
public void ok_stringBuilder(Blackhole bh) {
bh.consume(stringBuilder(ok, '_'));
}
@Threads(1)
@Benchmark
public void ok_array(Blackhole bh) {
bh.consume(array(ok, '_'));
}
@Threads(1)
@Benchmark
public void ok_checkFirst(Blackhole bh) {
bh.consume(checkFirst(ok, '_'));
}
@Threads(1)
@Benchmark
public void ok_asciiSet(Blackhole bh) {
bh.consume(asciiSet(ok, '_'));
}
@Threads(1)
@Benchmark
public void ok_bitSet(Blackhole bh) {
bh.consume(bitSet(ok, '_'));
}
@Threads(1)
@Benchmark
public void bad_naive(Blackhole bh) {
bh.consume(naive(bad, '_'));
}
@Threads(1)
@Benchmark
public void bad_stringBuilder(Blackhole bh) {
bh.consume(stringBuilder(bad, '_'));
}
@Threads(1)
@Benchmark
public void bad_array(Blackhole bh) {
bh.consume(array(bad, '_'));
}
@Threads(1)
@Benchmark
public void bad_checkFirst(Blackhole bh) {
bh.consume(checkFirst(bad, '_'));
}
@Threads(1)
@Benchmark
public void bad_asciiSet(Blackhole bh) {
bh.consume(asciiSet(bad, '_'));
}
@Threads(1)
@Benchmark
public void bad_bitSet(Blackhole bh) {
bh.consume(bitSet(bad, '_'));
}
}
| 5,844 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/Counters.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.perf;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
/**
* Summary of results on m4.16xlarge:
*
* <pre>
* ### T1 Composite(Empty)
*
* ```
* Benchmark Mode Cnt Score Error Units
* Counters.cached thrpt 10 222995027.222 ± 5812215.685 ops/s
* Counters.lookup thrpt 10 34596370.526 ± 7975715.214 ops/s
* Counters.random thrpt 10 5699426.669 ± 604639.108 ops/s
* ```
*
* ### T1 Composite(Noop)
*
* ```
* Benchmark Mode Cnt Score Error Units
* Counters.cached thrpt 10 221034201.857 ± 9204618.077 ops/s
* Counters.lookup thrpt 10 33410400.013 ± 7828970.416 ops/s
* Counters.random thrpt 10 5977032.777 ± 679753.009 ops/s
* ```
*
* ### T1 Composite(Default)
*
* ```
* Benchmark Mode Cnt Score Error Units
* Counters.cached thrpt 10 61043422.331 ± 3085269.565 ops/s
* Counters.lookup thrpt 10 25989379.563 ± 4981909.126 ops/s
* Counters.random thrpt 10 4299422.647 ± 394069.294 ops/s
* ```
*
* ### T1 Composite(Noop, Noop)
*
* ```
* Benchmark Mode Cnt Score Error Units
* Counters.cached thrpt 10 65781502.616 ± 3124211.952 ops/s
* Counters.lookup thrpt 10 23914193.535 ± 6256980.210 ops/s
* Counters.random thrpt 10 3907696.564 ± 383335.366 ops/s
* ```
*
* ### T1 Composite(Default, Default)
*
* ```
* Benchmark Mode Cnt Score Error Units
* Counters.cached thrpt 10 37594426.749 ± 1302829.135 ops/s
* Counters.lookup thrpt 10 17151030.656 ± 3776435.406 ops/s
* Counters.random thrpt 10 2228890.157 ± 186029.279 ops/s
* ```
* </pre>
*/
@State(Scope.Thread)
public class Counters {
@State(Scope.Benchmark)
public static class Data {
Registry registry = new DefaultRegistry();
Counter cached = registry.counter("cached");
String[] names;
String[] newNames;
public Data() {
names = new String[100000];
newNames = new String[100000];
for (int i = 0; i < 100000; ++i) {
names[i] = UUID.randomUUID().toString();
registry.counter(names[i]).increment();
newNames[i] = UUID.randomUUID().toString();
}
}
}
@State(Scope.Thread)
public static class Metrics {
private Random random = ThreadLocalRandom.current();
Counter get(Data data) {
// Assumes about 5% of lookups will be for a new or expired counter. This is
// mostly just to have some activity that will cause an addition to the map
// mixed in with the reads.
String name = (random.nextDouble() < 0.05)
? data.newNames[random.nextInt(data.newNames.length)]
: data.names[random.nextInt(data.names.length)];
return data.registry.counter(name);
}
}
private long incrementAndGet(Counter c) {
c.increment();
return c.count();
}
@Benchmark
public long cached(Data data) {
return incrementAndGet(data.cached);
}
@Benchmark
public long lookup(Data data) {
return incrementAndGet(data.registry.counter("lookup"));
}
@Benchmark
public long random(Data data, Metrics metrics) {
return incrementAndGet(metrics.get(data));
}
@TearDown
public void check(Data data) {
final long cv = data.cached.count();
final long lv = data.registry.counter("lookup").count();
assert cv > 0 || lv > 0 : "counters haven't been incremented";
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*")
.forks(1)
.build();
new Runner(opt).run();
}
}
| 5,845 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/PercentileTimers.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.perf;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.histogram.PercentileTimer;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
public class PercentileTimers {
private final Registry registry = new DefaultRegistry();
private final Timer defaultTimerCached = registry.timer("default-cached");
private final PercentileTimer percentileTimerCached =
PercentileTimer.get(registry, registry.createId("percentile-cached"));
private final Id dfltId = registry.createId("default");
private final Id pctId = registry.createId("percentile");
@Threads(1)
@Benchmark
public void defaultTimerGet() {
registry.timer(dfltId).record(31, TimeUnit.MILLISECONDS);
}
@Threads(1)
@Benchmark
public void percentileTimerGet() {
PercentileTimer.get(registry, pctId).record(31, TimeUnit.MILLISECONDS);
}
@Threads(1)
@Benchmark
public void percentileTimerBuilder() {
PercentileTimer.builder(registry)
.withId(pctId)
.withRange(10, 10000, TimeUnit.MILLISECONDS)
.build()
.record(31, TimeUnit.MILLISECONDS);
}
@Threads(1)
@Benchmark
public void defaultTimerReuse() {
defaultTimerCached.record(31, TimeUnit.MILLISECONDS);
}
@Threads(1)
@Benchmark
public void percentileTimerReuse() {
percentileTimerCached.record(31, TimeUnit.MILLISECONDS);
}
}
| 5,846 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/ArrayTagSetSort.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.perf;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Arrays;
/**
* <pre>
* sort1_single thrpt 5 231987417.092 ± 1461766.430 ops/s
* sort2_single thrpt 5 231390816.374 ± 2900091.223 ops/s
*
* sort1_two thrpt 5 127862169.706 ± 3004299.720 ops/s
* sort2_two thrpt 5 107286992.610 ± 499836.589 ops/s
*
* sort1_four thrpt 5 45448061.771 ± 214688.930 ops/s
* sort2_four thrpt 5 45801768.604 ± 399120.395 ops/s
*
* sort1_many thrpt 5 7013914.451 ± 476174.932 ops/s
* sort2_many thrpt 5 7093001.872 ± 136273.382 ops/s
* </pre>
*/
@State(Scope.Thread)
public class ArrayTagSetSort {
private static void insertionSort1(String[] ts, int length) {
if (length == 4) {
// Two key/value pairs, swap if needed
if (ts[0].compareTo(ts[2]) > 0) {
// Swap key
String tmp = ts[0];
ts[0] = ts[2];
ts[2] = tmp;
// Swap value
tmp = ts[1];
ts[1] = ts[3];
ts[3] = tmp;
}
} else if (length > 4) {
// One entry is already sorted. Two entries handled above, for larger arrays
// use insertion sort.
for (int i = 2; i < length; i += 2) {
String k = ts[i];
String v = ts[i + 1];
int j = i - 2;
for (; j >= 0 && ts[j].compareTo(k) > 0; j -= 2) {
ts[j + 2] = ts[j];
ts[j + 3] = ts[j + 1];
}
ts[j + 2] = k;
ts[j + 3] = v;
}
}
}
private static void insertionSort2(String[] ts, int length) {
for (int i = 2; i < length; i += 2) {
String k = ts[i];
String v = ts[i + 1];
int j = i - 2;
for (; j >= 0 && ts[j].compareTo(k) > 0; j -= 2) {
ts[j + 2] = ts[j];
ts[j + 3] = ts[j + 1];
}
ts[j + 2] = k;
ts[j + 3] = v;
}
}
private final String[] tagsArraySingle = new String[] {
"country", "US"
};
private final String[] tagsArrayTwo = new String[] {
"status", "200",
"client", "ab"
};
private final String[] tagsArrayFour = new String[] {
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab"
};
private final String[] tagsArrayMany = new String[] {
"nf.app", "test_app",
"nf.cluster", "test_app-main",
"nf.asg", "test_app-main-v042",
"nf.stack", "main",
"nf.ami", "ami-0987654321",
"nf.region", "us-east-1",
"nf.zone", "us-east-1e",
"nf.node", "i-1234567890",
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab"
};
@Benchmark
public void sort1_single(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArraySingle, tagsArraySingle.length);
insertionSort1(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort2_single(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArraySingle, tagsArraySingle.length);
insertionSort2(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort1_two(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayTwo, tagsArrayTwo.length);
insertionSort1(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort2_two(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayTwo, tagsArrayTwo.length);
insertionSort2(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort1_four(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayFour, tagsArrayFour.length);
insertionSort1(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort2_four(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayFour, tagsArrayFour.length);
insertionSort2(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort1_many(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayMany, tagsArrayMany.length);
insertionSort1(tags, tags.length);
bh.consume(tags);
}
@Benchmark
public void sort2_many(Blackhole bh) {
String[] tags = Arrays.copyOf(tagsArrayMany, tagsArrayMany.length);
insertionSort2(tags, tags.length);
bh.consume(tags);
}
}
| 5,847 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/StringCreate.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.perf;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.util.UUID;
/**
* Compares methods for creating a string based on an existing character array that we
* know will not get modified after the string is created.
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* StringCreate.methodHandle thrpt 10 176057226.160 ± 5069495.131 ops/s
* StringCreate.naive thrpt 10 58188947.972 ± 1284066.194 ops/s
* StringCreate.reflection thrpt 10 75278354.480 ± 9173452.172 ops/s
* </pre>
*/
@State(Scope.Thread)
public class StringCreate {
private final String str = UUID.randomUUID().toString();
private final char[] arr = str.toCharArray();
private static final Constructor<String> STRING_CONSTRUCTOR;
private static final MethodHandle STRING_CONSTRUCTOR_HANDLE;
static {
Constructor<String> constructor;
MethodHandle handle;
try {
constructor = String.class.getDeclaredConstructor(char[].class, boolean.class);
constructor.setAccessible(true);
handle = MethodHandles.lookup().unreflectConstructor(constructor);
} catch (Exception e) {
constructor = null;
handle = null;
}
STRING_CONSTRUCTOR = constructor;
STRING_CONSTRUCTOR_HANDLE = handle;
}
/**
* Creates a new string without copying the buffer if possible. The String class has a
* package private constructor that allows the buffer to be shared.
*/
private static String newStringReflection(char[] buf) {
if (STRING_CONSTRUCTOR != null) {
try {
return STRING_CONSTRUCTOR.newInstance(buf, true);
} catch (Exception e) {
return new String(buf);
}
} else {
return new String(buf);
}
}
/**
* Creates a new string without copying the buffer if possible. The String class has a
* package private constructor that allows the buffer to be shared.
*/
private static String newStringMethodHandle(char[] buf) {
if (STRING_CONSTRUCTOR_HANDLE != null) {
try {
return (String) STRING_CONSTRUCTOR_HANDLE.invokeExact(buf, true);
} catch (Throwable t) {
return new String(buf);
}
} else {
return new String(buf);
}
}
@Threads(1)
@Benchmark
public void naive(Blackhole bh) {
bh.consume(new String(arr));
}
@Threads(1)
@Benchmark
public void reflection(Blackhole bh) {
bh.consume(newStringReflection(arr));
}
@Threads(1)
@Benchmark
public void methodHandle(Blackhole bh) {
bh.consume(newStringMethodHandle(arr));
}
}
| 5,848 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/StringForeach.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.perf;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.util.OptionalInt;
import java.util.UUID;
/**
* Sanity check on iterating over a string using newer language features. Streams are
* really slow and should be avoided for the time being.
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* StringForeach.arrayForLoop thrpt 10 69226595.071 ± 3958789.722 ops/s
* StringForeach.arrayForeach thrpt 10 69282507.672 ± 2090321.612 ops/s
* StringForeach.strForLoop thrpt 10 55900971.604 ± 2190481.894 ops/s
* StringForeach.stream thrpt 10 4337780.512 ± 102242.727 ops/s
* </pre>
*/
@State(Scope.Thread)
public class StringForeach {
private final String str = UUID.randomUUID().toString();
private final char[] arr = str.toCharArray();
@Threads(1)
@Benchmark
public void arrayForLoop(Blackhole bh) {
int v = 0;
int n = arr.length;
for (int i = 0; i < n; ++i) {
v += arr[i];
}
bh.consume(v);
}
@Threads(1)
@Benchmark
public void arrayForeach(Blackhole bh) {
int v = 0;
for (char c : arr) {
v += c;
}
bh.consume(v);
}
@Threads(1)
@Benchmark
public void strForLoop(Blackhole bh) {
int v = 0;
int n = str.length();
for (int i = 0; i < n; ++i) {
v += str.charAt(i);
}
bh.consume(v);
}
@Threads(1)
@Benchmark
public void stream(Blackhole bh) {
OptionalInt v = str.chars().reduce(Integer::sum);
bh.consume(v.isPresent() ? v.getAsInt() : 0);
}
}
| 5,849 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/PatternMatching.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.perf;
import com.netflix.spectator.impl.PatternMatcher;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* <h2>Results on JDK 8</h2>
*
* <p>Throughput:</p>
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* listCustom thrpt 10 1,184,089.314 ± 4676.725 ops/s
* listJava thrpt 10 0.413 ± 0.003 ops/s
* listRe2j thrpt 10 58,429.201 ± 694.491 ops/s
* multiIndexOfCustom thrpt 10 31,317,074.616 ± 705692.514 ops/s
* multiIndexOfJava thrpt 10 5,435,456.864 ± 555843.469 ops/s
* multiIndexOfRe2j thrpt 10 10,192,683.276 ± 61955.336 ops/s
* orCustom thrpt 10 2,551,727.306 ± 38841.717 ops/s
* orJava thrpt 10 531,411.598 ± 7586.830 ops/s
* orRe2j thrpt 10 37,810.449 ± 730.444 ops/s
* prefixCustom thrpt 10 30,195,549.356 ± 568710.896 ops/s
* prefixJava thrpt 10 12,893,094.010 ± 270093.866 ops/s
* prefixRe2j thrpt 10 554,569.782 ± 16160.948 ops/s
* prefixString thrpt 10 33,232,503.056 ± 228206.044 ops/s
* startIndexOfCustom thrpt 10 112,775,842.584 ± 215497.926 ops/s
* startIndexOfJava thrpt 10 17,022,118.214 ± 84772.399 ops/s
* startIndexOfRe2j thrpt 10 6,581,951.985 ± 25517.793 ops/s
* substrCustom thrpt 10 26,131,737.230 ± 2912006.864 ops/s
* substrJava thrpt 10 10,513,474.004 ± 840593.331 ops/s
* substrRe2j thrpt 10 1,018,590.095 ± 16433.087 ops/s
* substrString thrpt 10 56,422,980.648 ± 436020.762 ops/s
* </pre>
*
* <p>Normalized allocation rate:</p>
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* listCustom alloc 10 0.349 ± 0.002 B/op
* listJava alloc 10 1,448,867.200 ± 15217.592 B/op
* listRe2j alloc 10 342.870 ± 0.117 B/op
* multiIndexOfCustom alloc 10 0.012 ± 0.001 B/op
* multiIndexOfJava alloc 10 176.074 ± 0.007 B/op
* multiIndexOfRe2j alloc 10 152.039 ± 0.001 B/op
* orCustom alloc 10 0.153 ± 0.003 B/op
* orJava alloc 10 184.716 ± 0.011 B/op
* orRe2j alloc 10 651.068 ± 0.343 B/op
* prefixCustom alloc 10 0.013 ± 0.001 B/op
* prefixJava alloc 10 176.031 ± 0.001 B/op
* prefixRe2j alloc 10 120.711 ± 0.029 B/op
* prefixString alloc 10 0.012 ± 0.001 B/op
* startIndexOfCustom alloc 10 0.004 ± 0.001 B/op
* startIndexOfJava alloc 10 176.022 ± 0.001 B/op
* startIndexOfRe2j alloc 10 144.054 ± 0.001 B/op
* substrCustom alloc 10 0.015 ± 0.002 B/op
* substrJava alloc 10 176.038 ± 0.004 B/op
* substrRe2j alloc 10 192.386 ± 0.007 B/op
* substrString alloc 10 0.007 ± 0.001 B/op
* </pre>
*
* <h2>Results on JDK 11</h2>
*
* <p>Throughput:</p>
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* listCustom thrpt 10 1,105,261.438 ± 13049.048 ops/s
* listJava thrpt 10 50,259.108 ± 1570.899 ops/s
* listRe2j thrpt 10 54,232.563 ± 2421.550 ops/s
* multiIndexOfCustom thrpt 10 48,693,040.830 ± 1106840.217 ops/s
* multiIndexOfJava thrpt 10 4,914,153.254 ± 765062.246 ops/s
* multiIndexOfRe2j thrpt 10 18,065,868.666 ± 82044.767 ops/s
* orCustom thrpt 10 5,248,226.617 ± 15211.949 ops/s
* orJava thrpt 10 506,365.079 ± 1997.129 ops/s
* orRe2j thrpt 10 34,912.433 ± 911.282 ops/s
* prefixCustom thrpt 10 48,187,119.321 ± 223668.543 ops/s
* prefixJava thrpt 10 11,970,315.701 ± 660308.379 ops/s
* prefixRe2j thrpt 10 612,792.800 ± 2379.586 ops/s
* prefixString thrpt 10 49,950,762.117 ± 94219.634 ops/s
* startIndexOfCustom thrpt 10 96,287,237.291 ± 353185.161 ops/s
* startIndexOfJava thrpt 10 16,658,780.670 ± 84494.346 ops/s
* startIndexOfRe2j thrpt 10 8,508,848.674 ± 60718.796 ops/s
* substrCustom thrpt 10 72,951,403.975 ± 1641257.446 ops/s
* substrJava thrpt 10 10,459,477.330 ± 176745.602 ops/s
* substrRe2j thrpt 10 1,030,064.491 ± 3626.560 ops/s
* substrString thrpt 10 89,500,023.812 ± 3758203.795 ops/s
* </pre>
*
* <p>Normalized allocation rate:</p>
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* listCustom alloc 10 1.419 ± 0.028 B/op
* listJava alloc 10 2,855.522 ± 1.760 B/op
* listRe2j alloc 10 333.558 ± 1.505 B/op
* multiIndexOfCustom alloc 10 0.030 ± 0.001 B/op
* multiIndexOfJava alloc 10 200.300 ± 0.047 B/op
* multiIndexOfRe2j alloc 10 72.084 ± 0.001 B/op
* orCustom alloc 10 0.284 ± 0.002 B/op
* orJava alloc 10 211.120 ± 0.030 B/op
* orRe2j alloc 10 608.525 ± 1.269 B/op
* prefixCustom alloc 10 0.030 ± 0.001 B/op
* prefixJava alloc 10 200.125 ± 0.007 B/op
* prefixRe2j alloc 10 122.511 ± 0.021 B/op
* prefixString alloc 10 0.029 ± 0.001 B/op
* startIndexOfCustom alloc 10 0.015 ± 0.001 B/op
* startIndexOfJava alloc 10 200.088 ± 0.001 B/op
* startIndexOfRe2j alloc 10 144.180 ± 0.002 B/op
* substrCustom alloc 10 0.020 ± 0.001 B/op
* substrJava alloc 10 200.143 ± 0.004 B/op
* substrRe2j alloc 10 217.494 ± 0.012 B/op
* substrString alloc 10 0.016 ± 0.001 B/op
* </pre>
*/
@State(Scope.Thread)
public class PatternMatching {
private final String example = UUID.randomUUID().toString();
// Needs to be a separate String instance to avoid short circuiting for the
// String.{startsWith, contains} tests
private final String exampleCopy = new String(example);
private final String substr = example.substring(example.length() - 17, example.length() - 4);
private final Pattern javaMatcherPrefix = Pattern.compile("^" + example);
private final com.google.re2j.Pattern re2jMatcherPrefix = com.google.re2j.Pattern.compile("^" + example);
private final PatternMatcher customMatcherPrefix = PatternMatcher.compile("^" + example);
private final Pattern javaMatcherSubstr = Pattern.compile(substr);
private final com.google.re2j.Pattern re2jMatcherSubstr = com.google.re2j.Pattern.compile(substr);
private final PatternMatcher customMatcherSubstr = PatternMatcher.compile(substr);
private final String startIndexOf = "^ab.*123";
private final Pattern javaMatcherStartIndexOf = Pattern.compile(startIndexOf);
private final com.google.re2j.Pattern re2jMatcherStartIndexOf =
com.google.re2j.Pattern.compile(startIndexOf);
private final PatternMatcher customMatcherStartIndexOf = PatternMatcher.compile(startIndexOf);
private final String multiIndexOf = "ab.*45.*123";
private final Pattern javaMatcherMultiIndexOf = Pattern.compile(multiIndexOf);
private final com.google.re2j.Pattern re2jMatcherMultiIndexOf =
com.google.re2j.Pattern.compile(multiIndexOf);
private final PatternMatcher customMatcherMultiIndexOf = PatternMatcher.compile(multiIndexOf);
private final String or = "(abc|bcd|cde|def|ef0|f01|012|123|234|456|567|678|789|890|90a|0ab)";
private final Pattern javaMatcherOr = Pattern.compile(or);
private final com.google.re2j.Pattern re2jMatcherOr = com.google.re2j.Pattern.compile(or);
private final PatternMatcher customMatcherOr = PatternMatcher.compile(or);
// Example of really expensive case for java pattern matcher
private final String list =
"[1234567],[89023432],[124534543],[4564362],[1234543],[12234567],[124567],[1234567],[1234567]]";
private final String listPattern = "^\\[((\\d*\\]\\,\\[\\d*)*|\\d*)\\]$";
private final Pattern javaMatcherList = Pattern.compile(listPattern);
private final com.google.re2j.Pattern re2jMatcherList =
com.google.re2j.Pattern.compile(listPattern);
private final PatternMatcher customMatcherList = PatternMatcher.compile(listPattern);
@Benchmark
public void prefixString(Blackhole bh) {
bh.consume(example.startsWith(exampleCopy));
}
@Benchmark
public void prefixJava(Blackhole bh) {
bh.consume(javaMatcherPrefix.matcher(exampleCopy).find());
}
@Benchmark
public void prefixRe2j(Blackhole bh) {
bh.consume(re2jMatcherPrefix.matcher(exampleCopy).find());
}
@Benchmark
public void prefixCustom(Blackhole bh) {
bh.consume(customMatcherPrefix.matches(exampleCopy));
}
@Benchmark
public void substrString(Blackhole bh) {
bh.consume(exampleCopy.contains(substr));
}
@Benchmark
public void substrJava(Blackhole bh) {
bh.consume(javaMatcherSubstr.matcher(exampleCopy).find());
}
@Benchmark
public void substrRe2j(Blackhole bh) {
bh.consume(re2jMatcherSubstr.matcher(exampleCopy).find());
}
@Benchmark
public void substrCustom(Blackhole bh) {
bh.consume(customMatcherSubstr.matches(exampleCopy));
}
@Benchmark
public void startIndexOfJava(Blackhole bh) {
bh.consume(javaMatcherStartIndexOf.matcher(exampleCopy).find());
}
@Benchmark
public void startIndexOfRe2j(Blackhole bh) {
bh.consume(re2jMatcherStartIndexOf.matcher(exampleCopy).find());
}
@Benchmark
public void startIndexOfCustom(Blackhole bh) {
bh.consume(customMatcherStartIndexOf.matches(exampleCopy));
}
@Benchmark
public void multiIndexOfJava(Blackhole bh) {
bh.consume(javaMatcherMultiIndexOf.matcher(exampleCopy).find());
}
@Benchmark
public void multiIndexOfRe2j(Blackhole bh) {
bh.consume(re2jMatcherMultiIndexOf.matcher(exampleCopy).find());
}
@Benchmark
public void multiIndexOfCustom(Blackhole bh) {
bh.consume(customMatcherMultiIndexOf.matches(exampleCopy));
}
@Benchmark
public void orJava(Blackhole bh) {
bh.consume(javaMatcherOr.matcher(exampleCopy).find());
}
@Benchmark
public void orRe2j(Blackhole bh) {
bh.consume(re2jMatcherOr.matcher(exampleCopy).find());
}
@Benchmark
public void orCustom(Blackhole bh) {
bh.consume(customMatcherOr.matches(exampleCopy));
}
@Benchmark
public void listJava(Blackhole bh) {
bh.consume(javaMatcherList.matcher(list).find());
}
@Benchmark
public void listRe2j(Blackhole bh) {
bh.consume(re2jMatcherList.matcher(list).find());
}
@Benchmark
public void listCustom(Blackhole bh) {
bh.consume(customMatcherList.matches(list));
}
}
| 5,850 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/Ids.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.perf;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* Benchmark Mode Cnt Score Error Units
* Ids.append1 thrpt 10 22,932,447.185 ± 558909.207 ops/s
* Ids.append2 thrpt 10 14,126,066.627 ± 2205349.084 ops/s
* Ids.append4 thrpt 10 5,165,821.740 ± 144524.852 ops/s
* Ids.append4sorted thrpt 10 5,923,827.749 ± 258122.285 ops/s
* Ids.baseline thrpt 10 14,868,887.021 ± 4627616.416 ops/s
* Ids.emptyAppend1 thrpt 10 63,193,729.846 ± 1158843.888 ops/s
* Ids.emptyAppend2 thrpt 10 28,797,024.419 ± 2348775.496 ops/s
* Ids.emptyAppend4 thrpt 10 9,818,389.953 ± 227597.860 ops/s
* Ids.emptyAppend4sorted thrpt 10 11,342,478.015 ± 315543.929 ops/s
* Ids.justName thrpt 10 166,275,032.184 ± 5252541.293 ops/s
* Ids.withTag thrpt 10 1,586,379.085 ± 40204.926 ops/s
* Ids.withTagsMap thrpt 10 1,841,867.329 ± 32378.659 ops/s
* Ids.withTagsVararg thrpt 10 1,946,970.522 ± 37919.937 ops/s
* Ids.withTagsVarargSorted thrpt 10 3,426,008.758 ± 115232.165 ops/s
* </pre>
*/
@State(Scope.Thread)
public class Ids {
private final Registry registry = new DefaultRegistry();
private final Map<String, String> tags = getTags();
private final String[] tagsArray = new String[] {
"nf.app", "test_app",
"nf.cluster", "test_app-main",
"nf.asg", "test_app-main-v042",
"nf.stack", "main",
"nf.ami", "ami-0987654321",
"nf.region", "us-east-1",
"nf.zone", "us-east-1e",
"nf.node", "i-1234567890",
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab"
};
private Map<String, String> getTags() {
Map<String, String> m = new HashMap<>();
m.put( "nf.app", "test_app");
m.put("nf.cluster", "test_app-main");
m.put( "nf.asg", "test_app-main-v042");
m.put( "nf.stack", "main");
m.put( "nf.ami", "ami-0987654321");
m.put( "nf.region", "us-east-1");
m.put( "nf.zone", "us-east-1e");
m.put( "nf.node", "i-1234567890");
m.put( "country", "US");
m.put( "device", "xbox");
m.put( "status", "200");
m.put( "client", "ab");
return m;
}
private final Id emptyId = registry.createId("http.req.complete");
private final Id baseId = emptyId
.withTag( "nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag( "nf.asg", "test_app-main-v042")
.withTag( "nf.stack", "main")
.withTag( "nf.ami", "ami-0987654321")
.withTag( "nf.region", "us-east-1")
.withTag( "nf.zone", "us-east-1e")
.withTag( "nf.node", "i-1234567890");
@Threads(1)
@Benchmark
public void justName(Blackhole bh) {
bh.consume(registry.createId("http.req.complete"));
}
@Threads(1)
@Benchmark
public void unsafeCreate(Blackhole bh) {
bh.consume(Id.unsafeCreate("http.req.complete", tagsArray, tagsArray.length));
}
@Threads(1)
@Benchmark
public void baseline(Blackhole bh) {
PrependId id = new PrependId("http.req.complete", null)
.withTag( "nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag( "nf.asg", "test_app-main-v042")
.withTag( "nf.stack", "main")
.withTag( "nf.ami", "ami-0987654321")
.withTag( "nf.region", "us-east-1")
.withTag( "nf.zone", "us-east-1e")
.withTag( "nf.node", "i-1234567890")
.withTag( "country", "US")
.withTag( "device", "xbox")
.withTag( "status", "200")
.withTag( "client", "ab");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void withTag(Blackhole bh) {
Id id = registry.createId("http.req.complete")
.withTag( "nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag( "nf.asg", "test_app-main-v042")
.withTag( "nf.stack", "main")
.withTag( "nf.ami", "ami-0987654321")
.withTag( "nf.region", "us-east-1")
.withTag( "nf.zone", "us-east-1e")
.withTag( "nf.node", "i-1234567890")
.withTag( "country", "US")
.withTag( "device", "xbox")
.withTag( "status", "200")
.withTag( "client", "ab");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void withTagsVararg(Blackhole bh) {
Id id = registry.createId("http.req.complete").withTags(
"nf.app", "test_app",
"nf.cluster", "test_app-main",
"nf.asg", "test_app-main-v042",
"nf.stack", "main",
"nf.ami", "ami-0987654321",
"nf.region", "us-east-1",
"nf.zone", "us-east-1e",
"nf.node", "i-1234567890",
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void withTagsVarargSorted(Blackhole bh) {
Id id = registry.createId("http.req.complete").withTags(
"client", "ab",
"country", "US",
"device", "xbox",
"nf.ami", "ami-0987654321",
"nf.app", "test_app",
"nf.asg", "test_app-main-v042",
"nf.cluster", "test_app-main",
"nf.node", "i-1234567890",
"nf.region", "us-east-1",
"nf.stack", "main",
"nf.zone", "us-east-1e",
"status", "200"
);
bh.consume(id);
}
@Threads(1)
@Benchmark
public void withTagsMap(Blackhole bh) {
Id id = registry.createId("http.req.complete").withTags(tags);
bh.consume(id);
}
@Threads(1)
@Benchmark
public void append1(Blackhole bh) {
Id id = baseId.withTag("country", "US");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void append2(Blackhole bh) {
Id id = baseId.withTags(
"country", "US",
"device", "xbox");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void append4(Blackhole bh) {
Id id = baseId.withTags(
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void append4sorted(Blackhole bh) {
Id id = baseId.withTags(
"client", "ab",
"country", "US",
"device", "xbox",
"status", "200");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void emptyAppend1(Blackhole bh) {
Id id = emptyId.withTag("country", "US");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void emptyAppend2(Blackhole bh) {
Id id = emptyId.withTags(
"country", "US",
"device", "xbox");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void emptyAppend4(Blackhole bh) {
Id id = emptyId.withTags(
"country", "US",
"device", "xbox",
"status", "200",
"client", "ab");
bh.consume(id);
}
@Threads(1)
@Benchmark
public void emptyAppend4sorted(Blackhole bh) {
Id id = emptyId.withTags(
"client", "ab",
"country", "US",
"device", "xbox",
"status", "200");
bh.consume(id);
}
public static class PrependId {
public final String name;
public final PrependTagList tags;
public PrependId(String name, PrependTagList tags) {
this.name = name;
this.tags = tags;
}
public PrependId withTag(String k, String v) {
return new PrependId(name, new PrependTagList(k, v, tags));
}
}
public static class PrependTagList {
public final String key;
public final String value;
public final PrependTagList next;
public PrependTagList(String key, String value, PrependTagList next) {
this.key = key;
this.value = value;
this.next = next;
}
}
}
| 5,851 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/IdTraversal.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.perf;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Tag;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
/**
* <pre>
* Benchmark Mode Cnt Score Error Units
* IdTraversal.forEach thrpt 10 9804067.543 ± 70757.222 ops/s
* IdTraversal.iterator thrpt 10 6431905.789 ± 814667.475 ops/s
* </pre>
*
* In an actual app we measured a big difference in allocations for the Tag objects. For
* this test hotspot seems to be able to avoid most of them:
*
* https://shipilev.net/jvm/anatomy-quarks/18-scalar-replacement/
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* IdTraversal.forEach gc.alloc.rate.norm 10 0.039 ± 0.001 B/op
* IdTraversal.iterator gc.alloc.rate.norm 10 0.059 ± 0.006 B/op
* </pre>
*/
@State(Scope.Thread)
public class IdTraversal {
private final Id baseId = Id.create("http.req.complete")
.withTag( "nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag( "nf.asg", "test_app-main-v042")
.withTag( "nf.stack", "main")
.withTag( "nf.ami", "ami-0987654321")
.withTag( "nf.region", "us-east-1")
.withTag( "nf.zone", "us-east-1e")
.withTag( "nf.node", "i-1234567890")
.withTag( "country", "US")
.withTag( "device", "xbox")
.withTag( "status", "200")
.withTag( "client", "ab");
@Benchmark
public void iterator(Blackhole bh) {
for (Tag t : baseId) {
bh.consume(t.key());
bh.consume(t.value());
}
}
@Benchmark
public void forEach(Blackhole bh) {
baseId.forEach((k, v) -> {
bh.consume(k);
bh.consume(v);
});
}
}
| 5,852 |
0 | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator | Create_ds/spectator/spectator-api/src/jmh/java/com/netflix/spectator/perf/DefaultStat.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.perf;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Tag;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
/**
* Benchmark different approaches to override the statistic tag if present.
*
* <pre>
* Benchmark Mode Cnt Score Error Units
* DefaultStat.withIdWithTags thrpt 9 2693269.613 ± 189599.585 ops/s
* DefaultStat.withNameWithTags thrpt 9 3485856.299 ± 116456.216 ops/s
* </pre>
*/
@State(Scope.Thread)
public class DefaultStat {
private final Registry registry = new DefaultRegistry();
private final Id baseId = registry.createId("http.req.complete")
.withTag("nf.app", "test_app")
.withTag("nf.cluster", "test_app-main")
.withTag("nf.asg", "test_app-main-v042")
.withTag("nf.stack", "main")
.withTag("nf.ami", "ami-0987654321")
.withTag("nf.region", "us-east-1")
.withTag("nf.zone", "us-east-1e")
.withTag("nf.node", "i-1234567890");
@Threads(1)
@Benchmark
public void withIdWithTags(Blackhole bh) {
bh.consume(baseId.withTag(Statistic.count).withTags(baseId.tags()).withTag(DsType.rate));
}
@Threads(1)
@Benchmark
public void withNameWithTags(Blackhole bh) {
bh.consume(
registry.createId(
baseId.name()).withTag(Statistic.count).withTags(baseId.tags()).withTag(DsType.rate));
}
static enum DsType implements Tag {
gauge,
rate;
@Override
public String key() {
return "atlas.dstype";
}
@Override
public String value() {
return name();
}
}
}
| 5,853 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/test/java/com/netflix/spectator/micrometer/MicrometerRegistryTest.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.micrometer;
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.Statistic;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.Utils;
import com.netflix.spectator.api.patterns.LongTaskTimer;
import com.netflix.spectator.api.patterns.PolledMeter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class MicrometerRegistryTest {
private MockClock clock;
private MeterRegistry meterRegistry;
private MicrometerRegistry registry;
@BeforeEach
public void before() {
clock = new MockClock();
meterRegistry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock);
registry = new MicrometerRegistry(meterRegistry);
}
@Test
public void createIdName() {
Id id = registry.createId("foo");
Assertions.assertEquals("foo", id.name());
Assertions.assertFalse(id.tags().iterator().hasNext());
}
@Test
public void createIdNameAndTags() {
Id id = registry.createId("foo", "a", "1", "b", "2");
Assertions.assertEquals("foo", id.name());
Map<String, String> tags = new HashMap<>();
tags.put("a", "1");
tags.put("b", "2");
for (Tag t : id.tags()) {
Assertions.assertEquals(tags.remove(t.key()), t.value());
}
Assertions.assertTrue(tags.isEmpty());
}
@Test
public void notPresentGet() {
Assertions.assertNull(registry.get(registry.createId("foo")));
}
@Test
public void counterIncrement() {
Counter c = registry.counter("foo");
Assertions.assertEquals(0, c.count());
c.increment();
Assertions.assertEquals(1, c.count());
}
@Test
public void counterAdd() {
Counter c = registry.counter("foo");
Assertions.assertEquals(0.0, c.actualCount(), 1e-12);
c.add(1.5);
Assertions.assertEquals(1.5, c.actualCount(), 1e-12);
}
@Test
public void counterMeasure() {
Counter c = registry.counter("foo");
c.increment();
int i = 0;
for (Measurement m : c.measure()) {
++i;
Assertions.assertEquals("foo", m.id().name());
Assertions.assertEquals(1.0, m.value(), 1e-12);
}
Assertions.assertEquals(1, i);
}
@Test
public void counterWithTags() {
Counter c1 = registry.counter("foo", "a", "1", "b", "2");
c1.increment();
Counter c2 = registry.counter(registry.createId("foo", "a", "1", "b", "2"));
Assertions.assertEquals(1, c2.count());
}
@Test
public void counterGet() {
Counter c1 = registry.counter("foo");
c1.increment();
Counter c2 = (Counter) registry.get(registry.createId("foo"));
Assertions.assertEquals(1, c2.count());
}
@Test
public void timerRecord() {
Timer t = registry.timer("foo");
Assertions.assertEquals(0, t.count());
Assertions.assertEquals(0, t.totalTime());
t.record(42, TimeUnit.SECONDS);
Assertions.assertEquals(1, t.count());
Assertions.assertEquals(TimeUnit.SECONDS.toNanos(42), t.totalTime());
}
@Test
public void timerRecordRunnable() {
Timer t = registry.timer("foo");
t.record((Runnable) () -> clock.add(42, TimeUnit.SECONDS));
Assertions.assertEquals(1, t.count());
Assertions.assertEquals(TimeUnit.SECONDS.toNanos(42), t.totalTime());
}
@Test
public void timerRecordCallable() throws Exception {
Timer t = registry.timer("foo");
t.record(() -> clock.add(42, TimeUnit.SECONDS));
Assertions.assertEquals(1, t.count());
Assertions.assertEquals(TimeUnit.SECONDS.toNanos(42), t.totalTime());
}
@Test
public void timerMeasure() {
Timer t = registry.timer("foo");
t.record(42, TimeUnit.SECONDS);
int i = 0;
for (Measurement m : t.measure()) {
++i;
Assertions.assertEquals("foo", m.id().name());
switch (Utils.getTagValue(m.id(), "statistic")) {
case "count":
Assertions.assertEquals(1.0, m.value(), 1e-12);
break;
case "total":
Assertions.assertEquals(42.0, m.value(), 1e-12);
break;
case "max":
Assertions.assertEquals(42.0, m.value(), 1e-12);
break;
default:
Assertions.fail("invalid statistic for measurment: " + m);
}
}
Assertions.assertEquals(3, i);
}
@Test
public void timerGet() {
Timer t1 = registry.timer("foo");
t1.record(1, TimeUnit.SECONDS);
Timer t2 = (Timer) registry.get(registry.createId("foo"));
Assertions.assertEquals(1, t2.count());
}
@Test
public void summaryRecord() {
DistributionSummary s = registry.distributionSummary("foo");
Assertions.assertEquals(0, s.count());
Assertions.assertEquals(0, s.totalAmount());
s.record(42);
Assertions.assertEquals(1, s.count());
Assertions.assertEquals(42, s.totalAmount());
}
@Test
public void summaryMeasure() {
DistributionSummary s = registry.distributionSummary("foo");
s.record(42);
int i = 0;
for (Measurement m : s.measure()) {
++i;
Assertions.assertEquals("foo", m.id().name());
switch (Utils.getTagValue(m.id(), "statistic")) {
case "count":
Assertions.assertEquals(1.0, m.value(), 1e-12);
break;
case "total":
Assertions.assertEquals(42.0, m.value(), 1e-12);
break;
case "max":
Assertions.assertEquals(42.0, m.value(), 1e-12);
break;
default:
Assertions.fail("invalid statistic for measurment: " + m);
}
}
Assertions.assertEquals(3, i);
}
@Test
public void summaryGet() {
DistributionSummary s1 = registry.distributionSummary("foo");
s1.record(1);
DistributionSummary s2 = (DistributionSummary) registry.get(registry.createId("foo"));
Assertions.assertEquals(1, s2.count());
}
@Test
public void gaugeSet() {
Gauge g = registry.gauge("foo");
Assertions.assertTrue(Double.isNaN(g.value()));
g.set(42.0);
Assertions.assertEquals(42.0, g.value(), 1e-12);
g.set(20.0);
Assertions.assertEquals(20.0, g.value(), 1e-12);
}
@Test
public void gaugeMeasure() {
Gauge g = registry.gauge("foo");
g.set(42.0);
int i = 0;
for (Measurement m : g.measure()) {
++i;
Assertions.assertEquals("foo", m.id().name());
Assertions.assertEquals(42.0, m.value(), 1e-12);
}
Assertions.assertEquals(1, i);
}
@Test
public void gaugeGet() {
Gauge g1 = registry.gauge("foo");
g1.set(1.0);
Gauge g2 = (Gauge) registry.get(registry.createId("foo"));
Assertions.assertEquals(1.0, g2.value(), 1e-12);
}
@Test
public void maxGaugeSet() {
Gauge g = registry.maxGauge("foo");
Assertions.assertTrue(Double.isNaN(g.value()));
g.set(42.0);
g.set(20.0);
clock.addSeconds(60);
Assertions.assertEquals(42.0, g.value(), 1e-12);
}
@Test
public void unknownGet() {
meterRegistry.more().longTaskTimer("foo").record(() -> clock.addSeconds(60));
Assertions.assertNull(registry.get(registry.createId("foo")));
}
@Test
public void iterator() {
registry.counter("c");
registry.timer("t");
registry.distributionSummary("s");
registry.gauge("g");
Set<String> actual = new HashSet<>();
for (Meter m : registry) {
Assertions.assertFalse(m.hasExpired());
actual.add(m.id().name());
}
Set<String> expected = new HashSet<>();
expected.add("c");
expected.add("t");
expected.add("s");
expected.add("g");
Assertions.assertEquals(expected, actual);
}
@Test
public void patternUsingState() {
LongTaskTimer t = LongTaskTimer.get(registry, registry.createId("foo"));
long tid = t.start();
clock.addSeconds(60);
PolledMeter.update(registry);
Gauge g = registry.gauge(registry.createId("foo").withTag(Statistic.duration));
Assertions.assertEquals(60.0, g.value(), 1e-12);
t.stop(tid);
PolledMeter.update(registry);
Assertions.assertEquals(0.0, g.value(), 1e-12);
}
}
| 5,854 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerCounter.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.micrometer;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
/**
* Wraps a Micrometer Counter to make it conform to the Spectator API.
*/
class MicrometerCounter extends MicrometerMeter implements Counter {
private final io.micrometer.core.instrument.Counter impl;
/** Create a new instance. */
MicrometerCounter(Id id, io.micrometer.core.instrument.Counter impl) {
super(id);
this.impl = impl;
}
@Override public Iterable<Measurement> measure() {
return convert(impl.measure());
}
@Override public void add(double amount) {
impl.increment(amount);
}
@Override public double actualCount() {
return impl.count();
}
}
| 5,855 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerRegistry.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.micrometer;
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.Timer;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.spectator.impl.AtomicDouble;
import com.netflix.spectator.impl.StepDouble;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.search.MeterNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
/**
* Wraps a Micrometer MeterRegistry to make it conform to the Spectator API.
*/
public final class MicrometerRegistry implements Registry {
private final MeterRegistry impl;
private final Clock clock;
private final ConcurrentHashMap<Id, Object> state = new ConcurrentHashMap<>();
/** Create a new instance. */
public MicrometerRegistry(MeterRegistry impl) {
this.impl = impl;
this.clock = new MicrometerClock(impl.config().clock());
}
private io.micrometer.core.instrument.Tag convert(Tag t) {
return io.micrometer.core.instrument.Tag.of(t.key(), t.value());
}
private Iterable<io.micrometer.core.instrument.Tag> convert(Iterable<Tag> tags) {
List<io.micrometer.core.instrument.Tag> micrometerTags = new ArrayList<>();
for (Tag t : tags) {
micrometerTags.add(convert(t));
}
return micrometerTags;
}
private Id convert(io.micrometer.core.instrument.Meter.Id id) {
List<Tag> tags = id.getTags()
.stream()
.map(t -> Tag.of(t.getKey(), t.getValue()))
.collect(Collectors.toList());
return Id.create(id.getName()).withTags(tags);
}
private Meter convert(io.micrometer.core.instrument.Meter meter) {
Id id = convert(meter.getId());
if (meter instanceof io.micrometer.core.instrument.Counter) {
return counter(id);
} else if (meter instanceof io.micrometer.core.instrument.Timer) {
return timer(id);
} else if (meter instanceof io.micrometer.core.instrument.DistributionSummary) {
return distributionSummary(id);
} else if (meter instanceof io.micrometer.core.instrument.Gauge) {
return gauge(id);
} else {
return null;
}
}
@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 createId(name).withTags(tags);
}
@Override public void register(Meter meter) {
PolledMeter.monitorMeter(this, meter);
}
@Override public ConcurrentMap<Id, Object> state() {
return state;
}
@Override public Counter counter(Id id) {
return new MicrometerCounter(id, impl.counter(id.name(), convert(id.tags())));
}
@Override public DistributionSummary distributionSummary(Id id) {
return new MicrometerDistributionSummary(id, impl.summary(id.name(), convert(id.tags())));
}
@Override public Timer timer(Id id) {
return new MicrometerTimer(id, impl.timer(id.name(), convert(id.tags())), clock);
}
@Override public Gauge gauge(Id id) {
AtomicDouble value = new AtomicDouble(Double.NaN);
io.micrometer.core.instrument.Gauge gauge = io.micrometer.core.instrument.Gauge
.builder(id.name(), value, AtomicDouble::get)
.tags(convert(id.tags()))
.register(impl);
return new MicrometerGauge(id, value::set, gauge);
}
@Override public Gauge maxGauge(Id id) {
// Note: micrometer doesn't support this type directly so it uses an arbitrary
// window of 1m
StepDouble value = new StepDouble(Double.NaN, clock(), 60000L);
io.micrometer.core.instrument.Gauge gauge = io.micrometer.core.instrument.Gauge
.builder(id.name(), value, StepDouble::poll)
.tags(convert(id.tags()))
.register(impl);
return new MicrometerGauge(id, v -> value.getCurrent().max(v), gauge);
}
@Override public Meter get(Id id) {
try {
return impl.get(id.name())
.tags(convert(id.tags()))
.meters()
.stream()
.filter(m -> id.equals(convert(m.getId())))
.map(this::convert)
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} catch (MeterNotFoundException e) {
return null;
}
}
@Override public Iterator<Meter> iterator() {
return impl.getMeters()
.stream()
.map(this::convert)
.filter(Objects::nonNull)
.iterator();
}
}
| 5,856 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerGauge.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.micrometer;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.function.DoubleConsumer;
/**
* Wraps a Micrometer Gauge to make it conform to the Spectator API.
*/
class MicrometerGauge extends MicrometerMeter implements Gauge {
private final DoubleConsumer updateFunc;
private final io.micrometer.core.instrument.Gauge impl;
/** Create a new instance. */
MicrometerGauge(Id id, DoubleConsumer updateFunc, io.micrometer.core.instrument.Gauge impl) {
super(id);
this.updateFunc = updateFunc;
this.impl = impl;
}
@Override public void set(double v) {
updateFunc.accept(v);
}
@Override public double value() {
return impl.value();
}
@Override public Iterable<Measurement> measure() {
return convert(impl.measure());
}
}
| 5,857 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerClock.java | package com.netflix.spectator.micrometer;
import com.netflix.spectator.api.Clock;
/**
* Wraps a Micrometer Clock to make it conform to the Spectator API.
*/
class MicrometerClock implements Clock {
private final io.micrometer.core.instrument.Clock impl;
/** Create a new instance. */
MicrometerClock(io.micrometer.core.instrument.Clock impl) {
this.impl = impl;
}
@Override public long wallTime() {
return impl.wallTime();
}
@Override public long monotonicTime() {
return impl.monotonicTime();
}
}
| 5,858 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerMeter.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.micrometer;
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 java.util.ArrayList;
import java.util.List;
/** Base class for core meter types used by {@link MicrometerRegistry}. */
abstract class MicrometerMeter implements Meter {
/** Base identifier for all measurements supplied by this meter. */
private final Id id;
/** Create a new instance. */
MicrometerMeter(Id id) {
this.id = id;
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
/** Helper for converting Micrometer measurements to Spectator measurements. */
Iterable<Measurement> convert(Iterable<io.micrometer.core.instrument.Measurement> ms) {
long now = Clock.SYSTEM.wallTime();
List<Measurement> measurements = new ArrayList<>();
for (io.micrometer.core.instrument.Measurement m : ms) {
Id measurementId = id.withTag("statistic", m.getStatistic().getTagValueRepresentation());
measurements.add(new Measurement(measurementId, now, m.getValue()));
}
return measurements;
}
}
| 5,859 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerDistributionSummary.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.micrometer;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
/**
* Wraps a Micrometer DistributionSummary to make it conform to the Spectator API.
*/
class MicrometerDistributionSummary extends MicrometerMeter implements DistributionSummary {
private final io.micrometer.core.instrument.DistributionSummary impl;
/** Create a new instance. */
MicrometerDistributionSummary(Id id, io.micrometer.core.instrument.DistributionSummary impl) {
super(id);
this.impl = impl;
}
@Override public void record(long amount) {
impl.record(amount);
}
@Override public long count() {
return impl.count();
}
@Override public long totalAmount() {
return (long) impl.totalAmount();
}
@Override public Iterable<Measurement> measure() {
return convert(impl.measure());
}
}
| 5,860 |
0 | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerTimer.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.micrometer;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Timer;
import java.util.concurrent.TimeUnit;
/**
* Wraps a Micrometer Timer to make it conform to the Spectator API.
*/
class MicrometerTimer extends MicrometerMeter implements Timer {
private final io.micrometer.core.instrument.Timer impl;
private final Clock clock;
/** Create a new instance. */
MicrometerTimer(Id id, io.micrometer.core.instrument.Timer impl, Clock clock) {
super(id);
this.impl = impl;
this.clock = clock;
}
@Override public Clock clock() {
return clock;
}
@Override public void record(long amount, TimeUnit unit) {
impl.record(amount, unit);
}
@Override public long count() {
return impl.count();
}
@Override public long totalTime() {
return (long) impl.totalTime(TimeUnit.NANOSECONDS);
}
@Override
public Iterable<Measurement> measure() {
return convert(impl.measure());
}
}
| 5,861 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/test/java/com/netflix/spectator/metrics3/MetricsRegistryTest.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.metrics3;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.patterns.PolledMeter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MetricsRegistryTest {
private final ManualClock clock = new ManualClock();
@Test
public void metricName() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
r.counter("foo", "id", "bar", "a", "b", "a", "c").increment();
Assertions.assertTrue(codaRegistry.getMeters().containsKey("foo.a-c.id-bar"));
}
@Test
public void counter() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
r.counter("foo").increment();
Assertions.assertEquals(1, codaRegistry.getMeters().get("foo").getCount());
r.counter("foo").increment(15);
Assertions.assertEquals(16, codaRegistry.getMeters().get("foo").getCount());
}
@Test
public void timer() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
r.timer("foo").record(1, TimeUnit.MILLISECONDS);
Assertions.assertEquals(1, codaRegistry.getTimers().get("foo").getCount());
}
@Test
public void distributionSummary() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
r.distributionSummary("foo").record(1);
Assertions.assertEquals(1, codaRegistry.getHistograms().get("foo").getCount());
}
private void assertGaugeValue(
MetricsRegistry r, MetricRegistry codaRegistry, String name, double expected) {
PolledMeter.update(r);
Assertions.assertEquals(expected, (Double) codaRegistry.getGauges().get(name).getValue(), 1e-12);
}
@Test
public void gaugeNumber() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
AtomicInteger num = r.gauge("foo", new AtomicInteger(42));
assertGaugeValue(r, codaRegistry, "foo", 42.0);
}
@Test
public void gaugeNumberDuplicate() {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
AtomicInteger num1 = r.gauge("foo", new AtomicInteger(42));
AtomicInteger num2 = r.gauge("foo", new AtomicInteger(21));
assertGaugeValue(r, codaRegistry, "foo", 63.0);
}
@Test
public void gaugeCollection() throws Exception {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
final List<Integer> foo = r.collectionSize("foo", Arrays.asList(1, 2, 3, 4, 5));
assertGaugeValue(r, codaRegistry, "foo", 5.0);
}
@Test
public void gaugeMap() throws Exception {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
Map<String, String> map = new HashMap<>();
map.put("foo", "bar");
r.mapSize("fooMap", map);
assertGaugeValue(r, codaRegistry, "fooMap", 1.0);
}
@Test
public void gaugeRegisteredDirectly() throws Exception {
MetricRegistry codaRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, codaRegistry);
// Directly register a gauge with metrics register
codaRegistry.register("foo", (Gauge<Double>) () -> 42.0D);
// Try to register the same gauge via spectator
AtomicInteger num = r.gauge("foo", new AtomicInteger(42));
// Should be registered with the coda
Assertions.assertEquals(42.0, (Double) codaRegistry.getGauges().get("foo").getValue(), 1e-12);
// Should not be registered with spectator
Assertions.assertNull(r.get(r.createId("foo")));
}
}
| 5,862 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsGauge.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.metrics3;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import java.util.Collections;
/**
* Spectator gauge that wraps {@link DoubleGauge}.
*
* @author Kennedy Oliveira
*/
class MetricsGauge implements com.netflix.spectator.api.Gauge {
private final Clock clock;
private final Id id;
private final DoubleGauge gauge;
/**
* Create a gauge that samples the provided number for the value.
*
* @param clock
* Clock used for accessing the current time.
* @param id
* Identifier for the gauge.
* @param gauge
* Gauge object that is registered with metrics3.
*/
MetricsGauge(Clock clock, Id id, DoubleGauge gauge) {
this.clock = clock;
this.id = id;
this.gauge = gauge;
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public Iterable<Measurement> measure() {
return Collections.singleton(new Measurement(id, clock.wallTime(), value()));
}
@Override public void set(double v) {
gauge.set(v);
}
@Override public double value() {
return gauge.getValue();
}
}
| 5,863 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsDistributionSummary.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.metrics3;
import com.codahale.metrics.Snapshot;
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 java.util.Collections;
import java.util.concurrent.atomic.AtomicLong;
/** Distribution summary implementation for the metric3 registry. */
class MetricsDistributionSummary implements DistributionSummary {
private final Clock clock;
private final Id id;
private final com.codahale.metrics.Histogram impl;
private final AtomicLong totalAmount;
/** Create a new instance. */
MetricsDistributionSummary(Clock clock, Id id, com.codahale.metrics.Histogram impl) {
this.clock = clock;
this.id = id;
this.impl = impl;
this.totalAmount = new AtomicLong(0L);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount) {
impl.update(amount);
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
final Snapshot snapshot = impl.getSnapshot();
return Collections.singleton(new Measurement(id, now, snapshot.getMean()));
}
@Override public long count() {
return impl.getCount();
}
@Override public long totalAmount() {
return totalAmount.get();
}
}
| 5,864 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsRegistry.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.metrics3;
import com.netflix.spectator.api.AbstractRegistry;
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.Tag;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.Utils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/** Registry implementation that maps spectator types to the metrics3 library. */
public class MetricsRegistry extends AbstractRegistry {
private final com.codahale.metrics.MetricRegistry impl;
private final Map<String, DoubleGauge> registeredGauges;
private final Function<Id, String> formatNameFn;
/** Create a new instance. */
public MetricsRegistry() {
this(Clock.SYSTEM, new com.codahale.metrics.MetricRegistry());
}
/** Create a new instance. */
public MetricsRegistry(Clock clock, com.codahale.metrics.MetricRegistry impl) {
this(clock, impl, id -> {
Id normalized = Utils.normalize(id);
StringBuilder buf = new StringBuilder();
buf.append(normalized.name());
for (Tag t : normalized.tags()) {
buf.append('.').append(t.key()).append('-').append(t.value());
}
return buf.toString();
});
}
/** Create a new instance. */
public MetricsRegistry(Clock clock, com.codahale.metrics.MetricRegistry impl, Function<Id, String> formatNameFn) {
super(clock);
this.impl = impl;
this.registeredGauges = new ConcurrentHashMap<>();
this.formatNameFn = formatNameFn;
}
private String toMetricName(Id id) {
return formatNameFn.apply(id);
}
@Override protected Counter newCounter(Id id) {
final String name = toMetricName(id);
return new MetricsCounter(clock(), id, impl.meter(name));
}
@Override protected DistributionSummary newDistributionSummary(Id id) {
final String name = toMetricName(id);
return new MetricsDistributionSummary(clock(), id, impl.histogram(name));
}
@Override protected Timer newTimer(Id id) {
final String name = toMetricName(id);
return new MetricsTimer(clock(), id, impl.timer(name));
}
@Override protected Gauge newGauge(Id id) {
final String name = toMetricName(id);
DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
DoubleGauge g = new DoubleGauge();
impl.register(name, g);
return g;
});
return new MetricsGauge(clock(), id, gauge);
}
@Override protected Gauge newMaxGauge(Id id) {
final String name = toMetricName(id);
DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
DoubleMaxGauge g = new DoubleMaxGauge();
impl.register(name, g);
return g;
});
return new MetricsGauge(clock(), id, gauge);
}
}
| 5,865 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsGaugeAggr.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.metrics3;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* <p>Aggregate gauge used to compute the sum of gauges with the same Id.</p>
* <p>This aggregate gauge is only used to register with Metrics, the register with spectator is for each one of
* the registered gauges in this Aggregate gauge.</p>
*
* @author Kennedy Oliveira
*/
class MetricsGaugeAggr implements com.codahale.metrics.Gauge<Double> {
private ConcurrentLinkedQueue<MetricsGauge> gauges;
/**
* Creates a new Aggregate Gauge.
*/
MetricsGaugeAggr() {
this.gauges = new ConcurrentLinkedQueue<>();
}
@Override
public Double getValue() {
double aggregatedValue = Double.NaN;
final Iterator<MetricsGauge> iterator = gauges.iterator();
while (iterator.hasNext()) {
final MetricsGauge gauge = iterator.next();
if (gauge.hasExpired()) {
iterator.remove();
} else {
final double gaugeVal = gauge.value();
// When it's NaN means the gauge can be unregistered due to it's reference to the value to extract value
// was garbage collected or simple the gauge returned a NaN so i don't count it
if (!Double.isNaN(gaugeVal))
aggregatedValue = (Double.isNaN(aggregatedValue) ? 0 : aggregatedValue) + gaugeVal;
}
}
return aggregatedValue;
}
/**
* Add a gauge to be aggragate to the others.
*
* @param gauge Gauge to be added
*/
void addGauge(MetricsGauge gauge) {
this.gauges.add(gauge);
}
}
| 5,866 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/DoubleGauge.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.metrics3;
import com.codahale.metrics.Gauge;
import com.netflix.spectator.impl.AtomicDouble;
/** Metrics3 gauge type based on an {@link AtomicDouble}. */
class DoubleGauge implements Gauge<Double> {
/** Current value for the gauge. */
protected AtomicDouble value = new AtomicDouble(Double.NaN);
/** Update the value. */
void set(double v) {
value.set(v);
}
@Override public Double getValue() {
return value.get();
}
}
| 5,867 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsTimer.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.metrics3;
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 metrics3 registry. */
class MetricsTimer extends AbstractTimer {
private final Id id;
private final com.codahale.metrics.Timer impl;
private final AtomicLong totalTime;
/** Create a new instance. */
MetricsTimer(Clock clock, Id id, com.codahale.metrics.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,868 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/MetricsCounter.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.metrics3;
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 metric3 registry. */
class MetricsCounter implements Counter {
private final Clock clock;
private final Id id;
private final com.codahale.metrics.Meter impl;
/** Create a new instance. */
MetricsCounter(Clock clock, Id id, com.codahale.metrics.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,869 |
0 | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics3/src/main/java/com/netflix/spectator/metrics3/DoubleMaxGauge.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.metrics3;
/** Metrics3 max gauge type. */
class DoubleMaxGauge extends DoubleGauge {
/** Update the value. */
@Override void set(double v) {
value.max(v);
}
}
| 5,870 |
0 | Create_ds/spectator/spectator-ext-log4j1/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j1/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.log4j.Level;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LevelTagTest {
@Test
public void levels() {
Level[] levels = {
Level.OFF,
Level.FATAL,
Level.ERROR,
Level.WARN,
Level.INFO,
Level.DEBUG,
Level.TRACE,
Level.ALL
};
for (Level level : levels) {
Assertions.assertEquals(level, 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,871 |
0 | Create_ds/spectator/spectator-ext-log4j1/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j1/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 com.netflix.spectator.api.Spectator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
public class SpectatorAppenderTest {
private Registry registry;
private SpectatorAppender appender;
private LoggingEvent newEvent(Level level, Throwable t) {
final String cname = SpectatorAppenderTest.class.getName();
final Logger logger = Logger.getLogger(cname);
return new LoggingEvent(logger.getClass().getName(), logger, 0L, level, "foo", t);
}
@BeforeEach
public void before() {
registry = new DefaultRegistry();
appender = new SpectatorAppender(registry);
}
@Test
public void numMessagesERROR() {
Counter c = registry.counter("log4j.numMessages", "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", "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",
"loglevel", "5_DEBUG",
"exception", "IllegalArgumentException",
"file", "?"); // Location is unknown because it is not called via logger
Assertions.assertEquals(0, c.count());
Exception e = new IllegalArgumentException("foo");
e.fillInStackTrace();
appender.append(newEvent(Level.DEBUG, e));
Assertions.assertEquals(1, c.count());
}
@Test
public void properties() {
Spectator.globalRegistry().add(registry);
Properties props = new Properties();
props.setProperty("log4j.rootLogger", "ALL, A1");
props.setProperty("log4j.appender.A1", "com.netflix.spectator.log4j.SpectatorAppender");
PropertyConfigurator.configure(props);
Counter c = registry.counter("log4j.numStackTraces",
"loglevel", "5_DEBUG",
"exception", "IllegalArgumentException",
"file", "SpectatorAppenderTest.java");
Assertions.assertEquals(0, c.count());
Exception e = new IllegalArgumentException("foo");
e.fillInStackTrace();
Logger.getLogger(getClass()).debug("foo", e);
Assertions.assertEquals(1, c.count());
}
}
| 5,872 |
0 | Create_ds/spectator/spectator-ext-log4j1/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j1/src/main/java/com/netflix/spectator/log4j/LevelTag.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.Tag;
import org.apache.log4j.Level;
/**
* Tags based on the standard log4j levels. The key will be {@code loglevel} and the value will
* be the level name prefixed with the order so it will sort correctly.
*/
enum LevelTag implements Tag {
/** 0_OFF. */
OFF(Level.OFF),
/** 1_FATAL. */
FATAL(Level.FATAL),
/** 2_ERROR. */
ERROR(Level.ERROR),
/** 3_WARN. */
WARN(Level.WARN),
/** 4_INFO. */
INFO(Level.INFO),
/** 5_DEBUG. */
DEBUG(Level.DEBUG),
/** 6_TRACE. */
TRACE(Level.TRACE),
/** 7_ALL. */
ALL(Level.ALL);
private final Level std;
private final String value;
/** Create a new instance based on a standard log4j level. */
LevelTag(Level std) {
this.std = std;
this.value = String.format("%d_%s", ordinal(), std.toString());
}
@Override public String key() {
return "loglevel";
}
@Override public String value() {
return value;
}
/** Return the corresponding standard log4j level. */
Level standardLevel() {
return std;
}
/** Get the tag corresponding to the log4j level. */
static LevelTag get(Level level) {
LevelTag tag = OFF;
switch (level.toInt()) {
case Level.OFF_INT: tag = OFF; break;
case Level.FATAL_INT: tag = FATAL; break;
case Level.ERROR_INT: tag = ERROR; break;
case Level.WARN_INT: tag = WARN; break;
case Level.INFO_INT: tag = INFO; break;
case Level.DEBUG_INT: tag = DEBUG; break;
case Level.TRACE_INT: tag = TRACE; break;
case Level.ALL_INT: tag = ALL; break;
default: break;
}
return tag;
}
}
| 5,873 |
0 | Create_ds/spectator/spectator-ext-log4j1/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-ext-log4j1/src/main/java/com/netflix/spectator/log4j/SpectatorAppender.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.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
/**
* Appender that tracks the number of messages that pass through.
*/
public final class SpectatorAppender extends AppenderSkeleton {
private final Registry registry;
private final Id[] numMessages;
private final Id[] numStackTraces;
/** Create a new instance of the appender. */
public SpectatorAppender() {
this(Spectator.globalRegistry());
}
/** Create a new instance of the appender. */
public SpectatorAppender(Registry registry) {
super();
this.registry = registry;
final LevelTag[] levels = LevelTag.values();
numMessages = new Id[levels.length];
numStackTraces = new Id[levels.length];
for (int i = 0; i < levels.length; ++i) {
numMessages[i] = registry.createId("log4j.numMessages")
.withTag(levels[i]);
numStackTraces[i] = registry.createId("log4j.numStackTraces")
.withTag(levels[i]);
}
}
@Override protected void append(LoggingEvent event) {
final LevelTag level = LevelTag.get(event.getLevel());
registry.counter(numMessages[level.ordinal()]).increment();
ThrowableInformation info = event.getThrowableInformation();
if (info != null) {
LocationInfo loc = event.getLocationInformation();
final String file = (loc == null) ? "unknown" : loc.getFileName();
Id stackTraceId = numStackTraces[level.ordinal()]
.withTag("exception", info.getThrowable().getClass().getSimpleName())
.withTag("file", file);
registry.counter(stackTraceId).increment();
}
}
@Override public void close() {
}
@Override public boolean requiresLayout() {
return false;
}
}
| 5,874 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator/nflx/TestModuleTest.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.nflx;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestModuleTest {
public static class Foo {
private final Counter counter;
@Inject
public Foo(Registry registry) {
counter = registry.counter("foo.doSomething");
}
public void doSomething() {
counter.increment();
}
}
private Injector injector;
@BeforeEach
public void setup() {
injector = Guice.createInjector(new TestModule());
}
@Test
public void checkCount() {
Registry r = injector.getInstance(Registry.class);
Counter c = r.counter("foo.doSomething");
Assertions.assertEquals(0, c.count());
Foo f = injector.getInstance(Foo.class);
f.doSomething();
Assertions.assertEquals(1, c.count());
}
@Test
public void notGlobal() {
Registry r = injector.getInstance(Registry.class);
Assertions.assertNotSame(Spectator.globalRegistry(), r);
}
@Test
public void usableIfSpectatorModuleIsInstalled() {
Registry r = Guice
.createInjector(new SpectatorModule(), new TestModule())
.getInstance(Registry.class);
Assertions.assertTrue(r instanceof DefaultRegistry); // SpectatorModule installs ServoRegistry
// Sanity checking global behavior, SpectatorModule will add it to the global
// registry which is not normally done for TestModule because it is all static.
Assertions.assertSame(Spectator.globalRegistry().underlying(DefaultRegistry.class), r);
}
}
| 5,875 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator/nflx/NetflixConfigTest.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.nflx;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.config.MapConfig;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
public class NetflixConfigTest {
@Test
public void defaultEnvVarsAreSet() {
Config config = NetflixConfig.loadPropFiles();
Assertions.assertEquals("test", config.getString("NETFLIX_ENVIRONMENT"));
Assertions.assertEquals("unknown", config.getString("EC2_OWNER_ID"));
Assertions.assertEquals("us-east-1", config.getString("EC2_REGION"));
}
@Test
public void defaultOverrides() {
Config overrides = MapConfig.builder()
.put("NETFLIX_ENVIRONMENT", "prod")
.put("substitutions", "${NETFLIX_ENVIRONMENT}-${EC2_OWNER_ID}")
.build();
Config config = NetflixConfig.createConfig(overrides);
Assertions.assertEquals("prod", config.getString("NETFLIX_ENVIRONMENT"));
Assertions.assertEquals("unknown", config.getString("EC2_OWNER_ID"));
Assertions.assertEquals("us-east-1", config.getString("EC2_REGION"));
Assertions.assertEquals("prod-unknown", config.getString("substitutions"));
}
@Test
public void commonTagsCannotBeEmpty() {
Map<String, String> commonTags = NetflixConfig.commonTags();
commonTags.forEach((k, v) -> Assertions.assertFalse(v.isEmpty()));
}
}
| 5,876 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/test/java/com/netflix/spectator/nflx/SpectatorModuleTest.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.nflx;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.multibindings.OptionalBinder;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.ExtendedRegistry;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.atlas.AtlasRegistry;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SpectatorModuleTest {
@Test
public void atlasRegistryIsBound() {
Injector injector = Guice.createInjector(new SpectatorModule());
Assertions.assertTrue(injector.getInstance(Registry.class) instanceof AtlasRegistry);
}
@Test
public void extendedRegistryIsBound() {
Injector injector = Guice.createInjector(new SpectatorModule());
Assertions.assertNotNull(injector.getInstance(ExtendedRegistry.class));
}
@Test
public void injectedRegistryAddedToGlobal() {
final ManualClock clock = new ManualClock();
Injector injector = Guice.createInjector(
new AbstractModule() {
@Override protected void configure() {
OptionalBinder.newOptionalBinder(binder(), Clock.class)
.setBinding()
.toInstance(clock);
}
},
new SpectatorModule());
Registry registry = injector.getInstance(Registry.class);
Spectator.globalRegistry().counter("test").increment();
clock.setWallTime(5000);
Assertions.assertEquals(1, registry.counter("test").count());
}
@Test
public void equals() {
Assertions.assertEquals(new SpectatorModule(), new SpectatorModule());
}
@Test
public void hashCodeTest() {
Assertions.assertEquals(new SpectatorModule().hashCode(), new SpectatorModule().hashCode());
}
@Test
public void optionalInjectWorksWithOptionalBinder() {
Injector injector = Guice.createInjector(new SpectatorModule());
OptionalInject obj = injector.getInstance(OptionalInject.class);
Assertions.assertNotNull(obj.registry);
}
private static class OptionalInject {
@Inject(optional = true)
Registry registry;
}
}
| 5,877 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator/nflx/NetflixConfig.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.nflx;
import com.netflix.archaius.api.Config;
import com.netflix.archaius.api.config.CompositeConfig;
import com.netflix.archaius.api.exceptions.ConfigException;
import com.netflix.archaius.config.DefaultCompositeConfig;
import com.netflix.archaius.config.EnvironmentConfig;
import com.netflix.archaius.config.MapConfig;
import com.netflix.archaius.config.SystemConfig;
import com.netflix.spectator.nflx.tagging.NetflixTagging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
/**
* Utility class for creating a configuration to be used in the Netflix environment.
* This class is not intended to be relied on by others, and is subject to change at any time.
*/
public final class NetflixConfig {
private NetflixConfig() {
}
private static final Logger LOGGER = LoggerFactory.getLogger(NetflixConfig.class);
/**
* Create a config to be used in the Netflix Cloud.
*/
public static Config createConfig(Config config) {
try {
// We cannot use the libraries layer as the nf-archaius2-platform-bridge
// will delegate the Config binding to archaius1 and the libraries layer
// then wraps that. So anything added to the libraries layer will not get
// picked up by anything injecting Config.
//
// Instead we just create a composite where the injected config will override
// the prop files. If no config binding is present use the environment and
// system properties config.
CompositeConfig cc = new DefaultCompositeConfig(true);
cc.addConfig("ATLAS", loadPropFiles());
cc.addConfig("ENVIRONMENT", EnvironmentConfig.INSTANCE);
cc.addConfig("SYS", SystemConfig.INSTANCE);
if (config != null) {
LOGGER.debug("found injected config, adding as override layer");
cc.addConfig("INJECTED", config);
} else {
LOGGER.debug("no injected config found");
}
return cc;
} catch (ConfigException e) {
throw new IllegalStateException("failed to load atlas config", e);
}
}
static Config loadPropFiles() {
final Properties props = new Properties();
Env.addDefaults(props);
final String env = Env.environment();
final String acctId = Env.accountId();
tryLoadingConfig(props, "atlas_plugin");
tryLoadingConfig(props, "atlas_plugin-" + env);
tryLoadingConfig(props, "atlas_plugin-acct-" + acctId);
return MapConfig.from(props);
}
private static void tryLoadingConfig(Properties props, String name) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = loader.getResources(name + ".properties");
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
LOGGER.info("loading config file: {}", url);
try (InputStream in = url.openStream()) {
props.load(in);
}
}
} catch (IOException e) {
LOGGER.warn("failed to load config file: " + name, e);
}
}
/**
* Infrastructure tags that are common across all metrics. Used for deduplication
* and for providing a scope for the metrics produced.
*/
public static Map<String, String> commonTags() {
return NetflixTagging.commonTagsForAtlas();
}
private static class Env {
private static final String OWNER = "EC2_OWNER_ID";
private static final String REGION = "EC2_REGION";
private static final String ENVIRONMENT = "NETFLIX_ENVIRONMENT";
private static final String APP = "NETFLIX_APP";
private static final String CLUSTER = "NETFLIX_CLUSTER";
private static String getenv(String k, String dflt) {
String v = System.getenv(k);
return (v == null) ? dflt : v;
}
private static String environment() {
return getenv(ENVIRONMENT, "test");
}
private static String accountId() {
return getenv(OWNER, "unknown");
}
/**
* Set default values for environment variables that are used for the basic context
* of where an app is running. Helps avoid startup issues when running locally and
* these are not set.
*/
private static void addDefaults(Properties props) {
props.put(ENVIRONMENT, "test");
props.put(OWNER, "unknown");
props.put(REGION, "us-east-1");
props.put(APP, "local");
props.put(CLUSTER, "local-dev");
}
}
}
| 5,878 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator/nflx/TestModule.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.nflx;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.OptionalBinder;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.ExtendedRegistry;
import com.netflix.spectator.api.Registry;
/**
* Guice module to configure the appropriate bindings for unit tests. Note that this module will
* create a registry that only keeps data in-memory and is scoped to the injector. If used when
* running the application you will not be able to see the data and it will not get reported off
* the instance. In particular, it is completely independent of the main registry accessed by
* calling {@link com.netflix.spectator.api.Spectator#globalRegistry()}. Use the
* {@link com.netflix.spectator.nflx.SpectatorModule} when running code outside of unit tests.
*/
@SuppressWarnings("PMD.TestClassWithoutTestCases")
public final class TestModule extends AbstractModule {
@Override protected void configure() {
final Registry registry = new DefaultRegistry();
OptionalBinder.newOptionalBinder(binder(), ExtendedRegistry.class)
.setBinding()
.toInstance(new ExtendedRegistry(registry));
OptionalBinder.newOptionalBinder(binder(), Registry.class)
.setBinding()
.toInstance(registry);
}
}
| 5,879 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator/nflx/Plugin.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.nflx;
import com.netflix.archaius.api.Config;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.gc.GcLogger;
import com.netflix.spectator.jvm.Jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
/**
* Plugin for setting up spectator to report correctly into the standard Netflix stack.
*/
@Singleton
final class Plugin {
private static final String ENABLED_PROP = "spectator.nflx.enabled";
private static final GcLogger GC_LOGGER = new GcLogger();
private static final Logger LOGGER = LoggerFactory.getLogger(Plugin.class);
/** Create a new instance. */
@Inject
Plugin(Registry registry, @Named("spectator") Config config) {
final boolean enabled = config.getBoolean(ENABLED_PROP, true);
if (enabled) {
if (config.getBoolean("spectator.gc.loggingEnabled", true)) {
GC_LOGGER.start(null);
LOGGER.info("gc logging started");
} else {
LOGGER.info("gc logging is not enabled");
}
Jmx.registerStandardMXBeans(registry);
} else {
LOGGER.debug("plugin not enabled, set " + ENABLED_PROP + "=true to enable");
}
}
}
| 5,880 |
0 | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-nflx-plugin/src/main/java/com/netflix/spectator/nflx/SpectatorModule.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.nflx;
import com.google.inject.Inject;
import com.google.inject.Scopes;
import com.google.inject.multibindings.OptionalBinder;
import com.google.inject.name.Names;
import com.netflix.archaius.api.Config;
import com.netflix.servo.SpectatorContext;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.atlas.AtlasConfig;
import com.netflix.spectator.atlas.AtlasRegistry;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.netflix.spectator.api.ExtendedRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import java.util.Map;
/**
* Guice module to configure the appropriate bindings for running an application. Note that this
* will configure it to use the global registry bindings for reporting. This also means that test
* cases will not be completely isolated. For unit tests see
* {@link com.netflix.spectator.nflx.TestModule}. Typical usage:
*
* <p><b>User code</b></p>
* <pre>
* public class Foo {
* private final Counter counter;
*
* {@literal @}Inject
* public Foo(Registry registry) {
* counter = registry.counter("foo.doSomething");
* }
*
* public void doSomething() {
* counter.increment();
* }
* }
* </pre>
*
* <p><b>Governator</b></p>
* <p>One of the classes requires an {@code javax.annotation.PostConstruct} block to initialize
* so governator should be used to manage the lifecycle as guice doesn't support it directly.</p>
* <pre>
* Injector injector = LifecycleInjector.builder()
* .withModules(new SpectatorModule())
* .build()
* .createInjector();
* injector.getInstance(LifecycleManager.class).start();
* </pre>
*/
public final class SpectatorModule extends AbstractModule {
@Override protected void configure() {
// Servo is all based on static classes. The context for servo needs to be set as early
// as possible to avoid missing metrics because the context has not yet been set.
SpectatorContext.setRegistry(Spectator.globalRegistry());
bind(Plugin.class).asEagerSingleton();
bind(StaticManager.class).asEagerSingleton();
bind(Config.class)
.annotatedWith(Names.named("spectator"))
.toProvider(ConfigProvider.class);
bind(AtlasConfig.class).to(AtlasConfiguration.class);
OptionalBinder.newOptionalBinder(binder(), ExtendedRegistry.class)
.setDefault()
.toInstance(Spectator.registry());
OptionalBinder.newOptionalBinder(binder(), Clock.class)
.setDefault()
.toInstance(Clock.SYSTEM);
OptionalBinder.newOptionalBinder(binder(), Registry.class)
.setDefault()
.to(AtlasRegistry.class)
.in(Scopes.SINGLETON);
}
@Override public boolean equals(Object obj) {
return obj != null && getClass().equals(obj.getClass());
}
@Override public int hashCode() {
return getClass().hashCode();
}
@Singleton
private static class ConfigProvider implements Provider<Config> {
@Inject(optional = true)
private Config config;
private Config atlasConfig;
@Override public Config get() {
if (atlasConfig == null) {
atlasConfig = NetflixConfig.createConfig(config);
}
return atlasConfig;
}
}
private static class StaticManager implements AutoCloseable {
private final Registry registry;
@Inject
StaticManager(Registry registry) {
this.registry = registry;
Spectator.globalRegistry().add(registry);
}
@Override public void close() {
Spectator.globalRegistry().remove(registry);
}
}
@Singleton
private static class AtlasConfiguration implements AtlasConfig {
private final Config cfg;
@Inject
AtlasConfiguration(@Named("spectator") Config cfg) {
this.cfg = cfg;
}
private final Map<String, String> nflxCommonTags = NetflixConfig.commonTags();
@Override public String get(String k) {
final String prop = "netflix.spectator.registry." + k;
return cfg.getString(prop, null);
}
@Override public boolean enabled() {
String v = get("atlas.enabled");
return v != null && Boolean.parseBoolean(v);
}
@Override public boolean autoStart() {
return true;
}
@Override
public Map<String, String> commonTags() {
return nflxCommonTags;
}
}
}
| 5,881 |
0 | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator/stateless/StatelessConfigTest.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.stateless;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class StatelessConfigTest {
@Test
public void enabledByDefault() {
Map<String, String> props = Collections.emptyMap();
StatelessConfig config = props::get;
Assertions.assertTrue(config.enabled());
}
@Test
public void explicitlyEnabled() {
Map<String, String> props = new HashMap<>();
props.put("stateless.enabled", "true");
StatelessConfig config = props::get;
Assertions.assertTrue(config.enabled());
}
@Test
public void explicitlyDisabled() {
Map<String, String> props = new HashMap<>();
props.put("stateless.enabled", "false");
StatelessConfig config = props::get;
Assertions.assertFalse(config.enabled());
}
@Test
public void enabledBadValue() {
Map<String, String> props = new HashMap<>();
props.put("stateless.enabled", "abc");
StatelessConfig config = props::get;
Assertions.assertFalse(config.enabled());
}
@Test
public void frequency() {
Map<String, String> props = new HashMap<>();
props.put("stateless.frequency", "PT5S");
StatelessConfig config = props::get;
Assertions.assertEquals(Duration.ofSeconds(5), config.frequency());
}
}
| 5,882 |
0 | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator/stateless/StatelessRegistryTest.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.stateless;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Measurement;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class StatelessRegistryTest {
private ManualClock clock = new ManualClock();
private StatelessRegistry registry = new StatelessRegistry(clock, newConfig());
private StatelessConfig newConfig() {
ConcurrentHashMap<String, String> props = new ConcurrentHashMap<>();
props.put("stateless.frequency", "PT10S");
props.put("stateless.batchSize", "3");
return props::get;
}
@Test
public void measurementsEmpty() {
Assertions.assertEquals(0, registry.getMeasurements().size());
}
@Test
public void measurementsWithCounter() {
registry.counter("test").increment();
Assertions.assertEquals(1, registry.getMeasurements().size());
}
@Test
public void measurementsWithTimer() {
registry.timer("test").record(42, TimeUnit.NANOSECONDS);
Assertions.assertEquals(4, registry.getMeasurements().size());
}
@Test
public void measurementsWithDistributionSummary() {
registry.distributionSummary("test").record(42);
Assertions.assertEquals(4, registry.getMeasurements().size());
}
@Test
public void measurementsWithGauge() {
registry.gauge("test").set(4.0);
Assertions.assertEquals(1, registry.getMeasurements().size());
}
@Test
public void measurementsWithMaxGauge() {
registry.maxGauge(registry.createId("test")).set(4.0);
Assertions.assertEquals(1, registry.getMeasurements().size());
}
@Test
public void maxGaugeSetNegative() {
registry.maxGauge("test").set(-4.0);
Assertions.assertEquals(-4.0, registry.maxGauge("test").value(), 1e-12);
}
@Test
public void batchesEmpty() {
Assertions.assertEquals(0, registry.getBatches().size());
}
@Test
public void batchesExact() {
for (int i = 0; i < 9; ++i) {
registry.counter("" + i).increment();
}
Assertions.assertEquals(3, registry.getBatches().size());
for (List<Measurement> batch : registry.getBatches()) {
Assertions.assertEquals(3, batch.size());
}
}
@Test
public void batchesLastPartial() {
for (int i = 0; i < 7; ++i) {
registry.counter("" + i).increment();
}
List<List<Measurement>> batches = registry.getBatches();
Assertions.assertEquals(3, batches.size());
for (int i = 0; i < batches.size(); ++i) {
Assertions.assertEquals((i < 2) ? 3 : 1, batches.get(i).size());
}
}
@Test
public void batchesExpiration() {
for (int i = 0; i < 9; ++i) {
registry.counter("" + i).increment();
}
Assertions.assertEquals(3, registry.getBatches().size());
for (List<Measurement> batch : registry.getBatches()) {
Assertions.assertEquals(3, batch.size());
}
clock.setWallTime(Duration.ofMinutes(15).toMillis() + 1);
Assertions.assertEquals(0, registry.getBatches().size());
}
}
| 5,883 |
0 | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/test/java/com/netflix/spectator/stateless/JsonUtilsTest.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.stateless;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Statistic;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonUtilsTest {
private static final JsonFactory FACTORY = new JsonFactory();
private final Registry registry = new DefaultRegistry();
private Measurement unknown(double delta, String name, String... tags) {
Id id = registry.createId(name).withTags(tags);
return new Measurement(id, 0L, delta);
}
private Measurement count(double delta, String name, String... tags) {
Id id = registry.createId(name).withTag(Statistic.count).withTags(tags);
return new Measurement(id, 0L, delta);
}
private Measurement max(double delta, String name, String... tags) {
Id id = registry.createId(name).withTag(Statistic.max).withTags(tags);
return new Measurement(id, 0L, delta);
}
@Test
public void encodeNoCommonTags() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(count(42.0, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> Assertions.assertEquals(42.0, values.get(m.id()).value, 1e-12));
}
@Test
public void encodeCommonTags() throws Exception {
Map<String, String> commonTags = new HashMap<>();
commonTags.put("a", "1");
commonTags.put("b", "2");
List<Measurement> ms = new ArrayList<>();
ms.add(count(42.0, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(commonTags, ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> {
Id id = m.id().withTags(commonTags);
Assertions.assertEquals(42.0, values.get(id).value, 1e-12);
});
}
@Test
public void encodeIgnoresNaN() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(count(Double.NaN, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(0, values.size());
}
@Test
public void encodeIgnoresAdd0() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(count(0, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(0, values.size());
}
@Test
public void encodeSendsMax0() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(max(0, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> {
Id id = m.id();
Assertions.assertEquals(0.0, values.get(id).value, 1e-12);
});
}
@Test
public void encodeInvalidStatisticAsGauge() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(count(42, "test", "statistic", "foo"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> {
Id id = m.id();
Assertions.assertEquals(values.get(id).op, 10);
});
}
@Test
public void encodeAssumesNoStatisticIsGauge() throws Exception {
List<Measurement> ms = new ArrayList<>();
ms.add(unknown(42, "test"));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> {
Id id = m.id();
Assertions.assertEquals(values.get(id).op, 10);
});
}
@Test
public void encodeSupportsKnownStats() throws Exception {
for (Statistic stat : Statistic.values()) {
List<Measurement> ms = new ArrayList<>();
ms.add(count(42, "test", "statistic", stat.value()));
Map<Id, Delta> values = decode(JsonUtils.encode(Collections.emptyMap(), ms));
Assertions.assertEquals(1, values.size());
ms.forEach(m -> {
Id id = m.id();
Assertions.assertEquals(42.0, values.get(id).value, 1e-12);
});
}
}
private Map<Id, Delta> decode(byte[] json) throws IOException {
Map<Id, Delta> values = new HashMap<>();
JsonParser parser = FACTORY.createParser(json);
// Array start
Assertions.assertEquals(JsonToken.START_ARRAY, parser.nextToken());
// String table
String[] strings = new String[parser.nextIntValue(-1)];
for (int i = 0; i < strings.length; ++i) {
strings[i] = parser.nextTextValue();
}
// Read measurements
parser.nextToken();
while (parser.currentToken() != JsonToken.END_ARRAY) {
int n = parser.getIntValue();
Map<String, String> tags = new HashMap<>(n);
for (int i = 0; i < n; ++i) {
String k = strings[parser.nextIntValue(-1)];
String v = strings[parser.nextIntValue(-1)];
tags.put(k, v);
}
String name = tags.get("name");
tags.remove("name");
Id id = registry.createId(name).withTags(tags);
int op = parser.nextIntValue(-1);
parser.nextToken();
double value = parser.getDoubleValue();
values.put(id, new Delta(op, value));
parser.nextToken();
}
return values;
}
private static class Delta {
final int op;
final double value;
Delta(int op, double value) {
this.op = op;
this.value = value;
}
@Override public String toString() {
return (op == 0 ? "add(" : "max(") + value + ")";
}
}
}
| 5,884 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessGauge.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.stateless;
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.api.Statistic;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.Collections;
/**
* Gauge that keeps track of the latest received value since the last time it was measured.
*/
class StatelessGauge extends StatelessMeter implements Gauge {
private final AtomicDouble value;
private final Id stat;
/** Create a new instance. */
StatelessGauge(Id id, Clock clock, long ttl) {
super(id, clock, ttl);
value = new AtomicDouble(Double.NaN);
stat = id.withTag(Statistic.gauge).withTags(id.tags());
}
@Override public void set(double v) {
value.set(v);
updateLastModTime();
}
@Override public double value() {
return value.get();
}
@Override public Iterable<Measurement> measure() {
final double delta = value.getAndSet(Double.NaN);
if (Double.isNaN(delta)) {
return Collections.emptyList();
} else {
final Measurement m = new Measurement(stat, clock.wallTime(), delta);
return Collections.singletonList(m);
}
}
}
| 5,885 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessMaxGauge.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.stateless;
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.api.Statistic;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.Collections;
/**
* Max gauge that keeps track of the maximum value since the last time it was measured.
*/
class StatelessMaxGauge extends StatelessMeter implements Gauge {
private final AtomicDouble value;
private final Id stat;
/** Create a new instance. */
StatelessMaxGauge(Id id, Clock clock, long ttl) {
super(id, clock, ttl);
value = new AtomicDouble(Double.NaN);
stat = id.withTag(Statistic.max).withTags(id.tags());
}
@Override public void set(double v) {
value.max(v);
updateLastModTime();
}
@Override public double value() {
return value.get();
}
@Override public Iterable<Measurement> measure() {
final double delta = value.getAndSet(Double.NaN);
if (Double.isFinite(delta)) {
final Measurement m = new Measurement(stat, clock.wallTime(), delta);
return Collections.singletonList(m);
} else {
return Collections.emptyList();
}
}
}
| 5,886 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessConfig.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.stateless;
import com.netflix.spectator.api.RegistryConfig;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
/**
* Configuration for stateless registry.
*/
public interface StatelessConfig extends RegistryConfig {
/**
* Returns true if publishing is enabled. Default is true.
*/
default boolean enabled() {
String v = get("stateless.enabled");
return v == null || Boolean.parseBoolean(v);
}
/**
* Returns the frequency to collect data and forward to the aggregation service. The
* default is 5 seconds.
*/
default Duration frequency() {
String v = get("stateless.frequency");
return v == null ? Duration.ofSeconds(5) : Duration.parse(v);
}
/**
* Returns the TTL for meters that do not have any activity. After this period the meter
* will be considered expired and will not get reported. Default is 15 minutes.
*/
default Duration meterTTL() {
String v = get("stateless.meterTTL");
return (v == null) ? Duration.ofMinutes(15) : Duration.parse(v);
}
/**
* Returns the connection timeout for requests to the backend. The default is
* 1 second.
*/
default Duration connectTimeout() {
String v = get("stateless.connectTimeout");
return (v == null) ? Duration.ofSeconds(1) : Duration.parse(v);
}
/**
* Returns the read timeout for requests to the backend. The default is
* 10 seconds.
*/
default Duration readTimeout() {
String v = get("stateless.readTimeout");
return (v == null) ? Duration.ofSeconds(10) : Duration.parse(v);
}
/**
* Returns the URI for the aggregation service. The default is
* {@code http://localhost:7101/api/v4/update}.
*/
default String uri() {
String v = get("stateless.uri");
return (v == null) ? "http://localhost:7101/api/v4/update" : v;
}
/**
* Returns the number of measurements per request to use for the backend. If more
* measurements are found, then multiple requests will be made. The default is
* 10,000.
*/
default int batchSize() {
String v = get("stateless.batchSize");
return (v == null) ? 10000 : Integer.parseInt(v);
}
/**
* Returns the common tags to apply to all metrics. The default is an empty map.
*/
default Map<String, String> commonTags() {
return Collections.emptyMap();
}
}
| 5,887 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessRegistry.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.stateless;
import com.netflix.spectator.api.AbstractRegistry;
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.Measurement;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.impl.Scheduler;
import com.netflix.spectator.ipc.http.HttpClient;
import com.netflix.spectator.ipc.http.HttpResponse;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import java.util.zip.Deflater;
/**
* Registry for reporting deltas to an aggregation service. This registry is intended for
* use-cases where the instance cannot maintain state over the step interval. For example,
* if running via a FaaS system like AWS Lambda, the lifetime of an invocation can be quite
* small. Thus this registry would track the deltas and rely on a separate service to
* consolidate the state over time if needed.
*
* The registry should be tied to the lifecyle of the container to ensure that the last set
* of deltas are flushed properly. This will happen automatically when calling {@link #stop()}.
*/
public final class StatelessRegistry extends AbstractRegistry {
private final boolean enabled;
private final Duration frequency;
private final long meterTTL;
private final int connectTimeout;
private final int readTimeout;
private final URI uri;
private final int batchSize;
private final Map<String, String> commonTags;
private final HttpClient client;
private Scheduler scheduler;
/** Create a new instance. */
public StatelessRegistry(Clock clock, StatelessConfig config) {
super(clock, config);
this.enabled = config.enabled();
this.frequency = config.frequency();
this.meterTTL = config.meterTTL().toMillis();
this.connectTimeout = (int) config.connectTimeout().toMillis();
this.readTimeout = (int) config.readTimeout().toMillis();
this.uri = URI.create(config.uri());
this.batchSize = config.batchSize();
this.commonTags = config.commonTags();
this.client = HttpClient.create(this);
}
/**
* Start the scheduler to collect metrics data.
*/
public void start() {
if (scheduler == null) {
if (enabled) {
Scheduler.Options options = new Scheduler.Options()
.withFrequency(Scheduler.Policy.FIXED_DELAY, frequency)
.withInitialDelay(frequency)
.withStopOnFailure(false);
scheduler = new Scheduler(this, "spectator-reg-stateless", 1);
scheduler.schedule(options, this::collectData);
logger.info("started collecting metrics every {} reporting to {}", frequency, uri);
logger.info("common tags: {}", commonTags);
} else {
logger.info("publishing is not enabled");
}
} else {
logger.warn("registry already started, ignoring duplicate request");
}
}
/**
* Stop the scheduler reporting data.
*/
public void stop() {
if (scheduler != null) {
scheduler.shutdown();
scheduler = null;
logger.info("flushing metrics before stopping the registry");
collectData();
logger.info("stopped collecting metrics every {} reporting to {}", frequency, uri);
} else {
logger.warn("registry stopped, but was never started");
}
}
private void collectData() {
try {
for (List<Measurement> batch : getBatches()) {
byte[] payload = JsonUtils.encode(commonTags, batch);
HttpResponse res = client.post(uri)
.withConnectTimeout(connectTimeout)
.withReadTimeout(readTimeout)
.withContent("application/json", payload)
.compress(Deflater.BEST_SPEED)
.send();
if (res.status() != 200) {
logger.warn("failed to send metrics, status {}: {}", res.status(), res.entityAsString());
}
}
removeExpiredMeters();
} catch (Exception e) {
logger.warn("failed to send metrics", e);
}
}
/** Get a list of all measurements from the registry. */
List<Measurement> getMeasurements() {
return stream()
.filter(m -> !m.hasExpired())
.flatMap(m -> StreamSupport.stream(m.measure().spliterator(), false))
.collect(Collectors.toList());
}
/** Get a list of all measurements and break them into batches. */
List<List<Measurement>> getBatches() {
List<List<Measurement>> batches = new ArrayList<>();
List<Measurement> ms = getMeasurements();
for (int i = 0; i < ms.size(); i += batchSize) {
List<Measurement> batch = ms.subList(i, Math.min(ms.size(), i + batchSize));
batches.add(batch);
}
return batches;
}
@Override protected Counter newCounter(Id id) {
return new StatelessCounter(id, clock(), meterTTL);
}
@Override protected DistributionSummary newDistributionSummary(Id id) {
return new StatelessDistributionSummary(id, clock(), meterTTL);
}
@Override protected Timer newTimer(Id id) {
return new StatelessTimer(id, clock(), meterTTL);
}
@Override protected Gauge newGauge(Id id) {
return new StatelessGauge(id, clock(), meterTTL);
}
@Override protected Gauge newMaxGauge(Id id) {
return new StatelessMaxGauge(id, clock(), meterTTL);
}
}
| 5,888 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessCounter.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.stateless;
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.api.Statistic;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.Collections;
/**
* Counter that keeps track of the delta since the last time it was measured.
*/
class StatelessCounter extends StatelessMeter implements Counter {
private final AtomicDouble count;
private final Id stat;
/** Create a new instance. */
StatelessCounter(Id id, Clock clock, long ttl) {
super(id, clock, ttl);
count = new AtomicDouble(0.0);
stat = id.withTag(Statistic.count).withTags(id.tags());
}
@Override public Iterable<Measurement> measure() {
final double delta = count.getAndSet(0.0);
if (delta > 0.0) {
final Measurement m = new Measurement(stat, clock.wallTime(), delta);
return Collections.singletonList(m);
} else {
return Collections.emptyList();
}
}
@Override public void add(double amount) {
if (amount > 0.0) {
count.addAndGet(amount);
updateLastModTime();
}
}
@Override public double actualCount() {
return count.get();
}
}
| 5,889 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessMeter.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.stateless;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Meter;
/** Base class for core meter types used by {@link StatelessRegistry}. */
abstract class StatelessMeter implements Meter {
/** Base identifier for all measurements supplied by this meter. */
protected final Id id;
/** Time source for checking if the meter has expired. */
protected final Clock clock;
/** TTL value for an inactive meter. */
private final long ttl;
/** Last time this meter was updated. */
private volatile long lastUpdated;
/** Create a new instance. */
StatelessMeter(Id id, Clock clock, long ttl) {
this.id = id;
this.clock = clock;
this.ttl = ttl;
lastUpdated = clock.wallTime();
}
/**
* Updates the last updated timestamp for the meter to indicate it is active and should
* not be considered expired.
*/
void updateLastModTime() {
lastUpdated = clock.wallTime();
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return clock.wallTime() - lastUpdated > ttl;
}
}
| 5,890 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessTimer.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.stateless;
import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Statistic;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongToDoubleFunction;
/**
* Timer that keeps track of the deltas since the last time it was measured.
*/
class StatelessTimer extends StatelessMeter implements Timer {
private final AtomicLong count;
private final AtomicDouble totalTime;
private final AtomicDouble totalOfSquares;
private final AtomicDouble max;
private final Id[] stats;
/** Create a new instance. */
StatelessTimer(Id id, Clock clock, long ttl) {
super(id, clock, ttl);
count = new AtomicLong(0);
totalTime = new AtomicDouble(0);
totalOfSquares = new AtomicDouble(0.0);
max = new AtomicDouble(0);
stats = new Id[] {
id.withTags(Statistic.count),
id.withTags(Statistic.totalTime),
id.withTags(Statistic.totalOfSquares),
id.withTags(Statistic.max)
};
}
@Override public void record(long amount, TimeUnit unit) {
final double seconds = unit.toNanos(amount) / 1e9;
if (seconds >= 0.0) {
count.incrementAndGet();
totalTime.addAndGet(seconds);
totalOfSquares.addAndGet(seconds * seconds);
max.max(seconds);
updateLastModTime();
}
}
@Override public <T> T record(Callable<T> f) throws Exception {
final long start = clock.monotonicTime();
try {
return f.call();
} finally {
record(clock.monotonicTime() - start, TimeUnit.NANOSECONDS);
}
}
@Override public void record(Runnable f) {
final long start = clock.monotonicTime();
try {
f.run();
} finally {
record(clock.monotonicTime() - start, TimeUnit.NANOSECONDS);
}
}
@Override public long count() {
return count.get();
}
@Override public long totalTime() {
return (long) (totalTime.get() * 1e9);
}
@Override
public Iterable<Measurement> measure() {
if (count.get() == 0) {
return Collections.emptyList();
} else {
List<Measurement> ms = new ArrayList<>(4);
ms.add(newMeasurement(stats[0], count::getAndSet));
ms.add(newMeasurement(stats[1], totalTime::getAndSet));
ms.add(newMeasurement(stats[2], totalOfSquares::getAndSet));
ms.add(newMeasurement(stats[3], max::getAndSet));
return ms;
}
}
private Measurement newMeasurement(Id mid, LongToDoubleFunction getAndSet) {
double delta = getAndSet.applyAsDouble(0);
long timestamp = clock.wallTime();
return new Measurement(mid, timestamp, delta);
}
}
| 5,891 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/StatelessDistributionSummary.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.stateless;
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 com.netflix.spectator.impl.AtomicDouble;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongToDoubleFunction;
/**
* Distribution summary that keeps track of the deltas since the last time it was measured.
*/
class StatelessDistributionSummary extends StatelessMeter implements DistributionSummary {
private final AtomicLong count;
private final AtomicLong totalAmount;
private final AtomicDouble totalOfSquares;
private final AtomicLong max;
private final Id[] stats;
/** Create a new instance. */
StatelessDistributionSummary(Id id, Clock clock, long ttl) {
super(id, clock, ttl);
count = new AtomicLong(0);
totalAmount = new AtomicLong(0);
totalOfSquares = new AtomicDouble(0.0);
max = new AtomicLong(0);
stats = new Id[] {
id.withTags(Statistic.count),
id.withTags(Statistic.totalAmount),
id.withTags(Statistic.totalOfSquares),
id.withTags(Statistic.max)
};
}
@Override public void record(long amount) {
if (amount >= 0) {
count.incrementAndGet();
totalAmount.addAndGet(amount);
totalOfSquares.addAndGet(1.0 * amount * amount);
updateMax(amount);
updateLastModTime();
}
}
private void updateMax(long v) {
long p = max.get();
while (v > p && !max.compareAndSet(p, v)) {
p = max.get();
}
}
@Override public long count() {
return count.get();
}
@Override public long totalAmount() {
return totalAmount.get();
}
@Override public Iterable<Measurement> measure() {
if (count.get() == 0) {
return Collections.emptyList();
} else {
List<Measurement> ms = new ArrayList<>(4);
ms.add(newMeasurement(stats[0], count::getAndSet));
ms.add(newMeasurement(stats[1], totalAmount::getAndSet));
ms.add(newMeasurement(stats[2], totalOfSquares::getAndSet));
ms.add(newMeasurement(stats[3], max::getAndSet));
return ms;
}
}
private Measurement newMeasurement(Id mid, LongToDoubleFunction getAndSet) {
double delta = getAndSet.applyAsDouble(0);
long timestamp = clock.wallTime();
return new Measurement(mid, timestamp, delta);
}
}
| 5,892 |
0 | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/JsonUtils.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.stateless;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Tag;
import com.netflix.spectator.api.Utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper for encoding measurements into a JSON array that can be read by the aggregator
* service. For more information see:
*
* https://github.com/Netflix-Skunkworks/iep-apps/tree/master/atlas-aggregator
*/
final class JsonUtils {
private static final JsonFactory FACTORY = new JsonFactory();
private static final int ADD = 0;
private static final int MAX = 10;
private JsonUtils() {
}
/** Encode the measurements to a JSON payload that can be sent to the aggregator. */
static byte[] encode(
Map<String, String> commonTags,
List<Measurement> measurements) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator gen = FACTORY.createGenerator(baos);
gen.writeStartArray();
Map<String, Integer> strings = buildStringTable(gen, commonTags, measurements);
for (Measurement m : measurements) {
appendMeasurement(gen, strings, commonTags, m.id(), m.value());
}
gen.writeEndArray();
gen.close();
return baos.toByteArray();
}
private static Map<String, Integer> buildStringTable(
JsonGenerator gen,
Map<String, String> commonTags,
List<Measurement> measurements) throws IOException {
Map<String, Integer> strings = new HashMap<>();
strings.put("name", 0);
commonTags.forEach((k, v) -> {
strings.put(k, 0);
strings.put(v, 0);
});
for (Measurement m : measurements) {
Id id = m.id();
strings.put(id.name(), 0);
for (Tag t : id.tags()) {
strings.put(t.key(), 0);
strings.put(t.value(), 0);
}
}
String[] sorted = strings.keySet().toArray(new String[0]);
Arrays.sort(sorted);
gen.writeNumber(sorted.length);
for (int i = 0; i < sorted.length; ++i) {
gen.writeString(sorted[i]);
strings.put(sorted[i], i);
}
return strings;
}
private static void appendMeasurement(
JsonGenerator gen,
Map<String, Integer> strings,
Map<String, String> commonTags,
Id id,
double value) throws IOException {
int op = operation(id);
if (shouldSend(op, value)) {
// Number of tag entries, commonTags + name + tags
int n = commonTags.size() + 1 + Utils.size(id.tags());
gen.writeNumber(n);
// Write out the key/value pairs for the tags
for (Map.Entry<String, String> entry : commonTags.entrySet()) {
gen.writeNumber(strings.get(entry.getKey()));
gen.writeNumber(strings.get(entry.getValue()));
}
for (Tag t : id.tags()) {
gen.writeNumber(strings.get(t.key()));
gen.writeNumber(strings.get(t.value()));
}
gen.writeNumber(strings.get("name"));
gen.writeNumber(strings.get(id.name()));
// Write out the operation and delta value
gen.writeNumber(op);
gen.writeNumber(value);
}
}
private static int operation(Id id) {
for (Tag t : id.tags()) {
if ("statistic".equals(t.key())) {
return operation(t.value());
}
}
return MAX;
}
private static int operation(String stat) {
int op;
switch (stat) {
case "count":
case "totalAmount":
case "totalTime":
case "totalOfSquares":
case "percentile":
op = ADD; break;
default:
op = MAX; break;
}
return op;
}
private static boolean shouldSend(int op, double value) {
return !Double.isNaN(value) && (value > 0.0 || op == MAX);
}
}
| 5,893 |
0 | Create_ds/spectator/spectator-reg-metrics5/src/test/java/com/netflix/spectator | Create_ds/spectator/spectator-reg-metrics5/src/test/java/com/netflix/spectator/metrics5/MetricsRegistryTest.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 io.dropwizard.metrics5.Gauge;
import io.dropwizard.metrics5.MetricName;
import io.dropwizard.metrics5.MetricRegistry;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Meter;
import com.netflix.spectator.api.patterns.PolledMeter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MetricsRegistryTest {
private final ManualClock clock = new ManualClock();
@Test
public void metricName() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
r.counter("foo", "id", "bar", "a", "b", "a", "c").increment();
final Map<String, String> expectedTags = new HashMap<>();
expectedTags.put("a", "c");
expectedTags.put("id", "bar");
Assertions.assertTrue(dwRegistry.getMeters()
.containsKey(new MetricName("foo", expectedTags)));
}
@Test
public void counter() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
r.counter("foo").increment();
Assertions.assertEquals(1, dwRegistry.getMeters().get(new MetricName("foo", Collections.EMPTY_MAP)).getCount());
r.counter("foo").increment(15);
Assertions.assertEquals(16, dwRegistry.getMeters().get(new MetricName("foo", Collections.EMPTY_MAP)).getCount());
}
@Test
public void timer() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
r.timer("foo").record(1, TimeUnit.MILLISECONDS);
Assertions.assertEquals(1, dwRegistry.getTimers().get(new MetricName("foo", Collections.EMPTY_MAP)).getCount());
}
@Test
public void distributionSummary() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
r.distributionSummary("foo").record(1);
Assertions.assertEquals(1, dwRegistry.getHistograms().get(new MetricName("foo", Collections.EMPTY_MAP)).getCount());
}
private void assertGaugeValue(
MetricsRegistry r, MetricRegistry dwRegistry, String name, double expected) {
PolledMeter.update(r);
Assertions.assertEquals(expected, (Double) dwRegistry.getGauges().get(new MetricName(name, Collections.EMPTY_MAP)).getValue(), 1e-12);
}
@Test
public void gaugeNumber() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
AtomicInteger num = r.gauge("foo", new AtomicInteger(42));
assertGaugeValue(r, dwRegistry, "foo", 42.0);
}
@Test
public void gaugeNumberDuplicate() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
AtomicInteger num1 = r.gauge("foo", new AtomicInteger(42));
AtomicInteger num2 = r.gauge("foo", new AtomicInteger(21));
assertGaugeValue(r, dwRegistry, "foo", 63.0);
}
@Test
public void gaugeCollection() throws Exception {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
final List<Integer> foo = r.collectionSize("foo", Arrays.asList(1, 2, 3, 4, 5));
assertGaugeValue(r, dwRegistry, "foo", 5.0);
}
@Test
public void gaugeMap() throws Exception {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
Map<String, String> map = new HashMap<>();
map.put("foo", "bar");
r.mapSize("fooMap", map);
assertGaugeValue(r, dwRegistry, "fooMap", 1.0);
}
@Test
public void gaugeRegisteredDirectly() throws Exception {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
// Directly register a gauge with metrics register
dwRegistry.registerGauge("foo", () -> 42.0D);
// Try to register the same gauge via spectator
AtomicInteger num = r.gauge("foo", new AtomicInteger(42));
// Should be registered with the Dropwizard registry
Assertions.assertEquals(42.0, (Double) dwRegistry.getGauges().get(new MetricName("foo", Collections.EMPTY_MAP)).getValue(), 1e-12);
// Should not be registered with spectator
Assertions.assertNull(r.get(r.createId("foo")));
}
@Test
public void iterator() {
MetricRegistry dwRegistry = new MetricRegistry();
MetricsRegistry r = new MetricsRegistry(clock, dwRegistry);
r.counter("c");
r.timer("t");
r.distributionSummary("s");
r.gauge("g");
Set<String> actual = new HashSet<>();
for (Meter m : r) {
Assertions.assertFalse(m.hasExpired());
actual.add(m.id().name());
}
Set<String> expected = new HashSet<>();
expected.add("c");
expected.add("t");
expected.add("s");
expected.add("g");
Assertions.assertEquals(expected, actual);
}
}
| 5,894 |
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/MetricsGauge.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.Id;
import com.netflix.spectator.api.Measurement;
import java.util.Collections;
/**
* Spectator gauge that wraps {@link DoubleGauge}.
*
* @author Kennedy Oliveira
*/
class MetricsGauge implements com.netflix.spectator.api.Gauge {
private final Clock clock;
private final Id id;
private final DoubleGauge gauge;
/**
* Create a gauge that samples the provided number for the value.
*
* @param clock
* Clock used for accessing the current time.
* @param id
* Identifier for the gauge.
* @param gauge
* Gauge object that is registered with metrics5.
*/
MetricsGauge(Clock clock, Id id, DoubleGauge gauge) {
this.clock = clock;
this.id = id;
this.gauge = gauge;
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public Iterable<Measurement> measure() {
return Collections.singleton(new Measurement(id, clock.wallTime(), value()));
}
@Override public void set(double v) {
gauge.set(v);
}
@Override public double value() {
return gauge.getValue();
}
}
| 5,895 |
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/MetricsDistributionSummary.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 io.dropwizard.metrics5.Snapshot;
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 java.util.Collections;
import java.util.concurrent.atomic.AtomicLong;
/** Distribution summary implementation for the metrics5 registry. */
class MetricsDistributionSummary implements DistributionSummary {
private final Clock clock;
private final Id id;
private final io.dropwizard.metrics5.Histogram impl;
private final AtomicLong totalAmount;
/** Create a new instance. */
MetricsDistributionSummary(Clock clock, Id id, io.dropwizard.metrics5.Histogram impl) {
this.clock = clock;
this.id = id;
this.impl = impl;
this.totalAmount = new AtomicLong(0L);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public void record(long amount) {
impl.update(amount);
}
@Override public Iterable<Measurement> measure() {
final long now = clock.wallTime();
final Snapshot snapshot = impl.getSnapshot();
return Collections.singleton(new Measurement(id, now, snapshot.getMean()));
}
@Override public long count() {
return impl.getCount();
}
@Override public long totalAmount() {
return totalAmount.get();
}
}
| 5,896 |
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/MetricsRegistry.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.AbstractRegistry;
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.Tag;
import com.netflix.spectator.api.Timer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.dropwizard.metrics5.MetricName;
/** Registry implementation that maps spectator types to the metrics5 library. */
public class MetricsRegistry extends AbstractRegistry {
private final io.dropwizard.metrics5.MetricRegistry impl;
private final Map<MetricName, DoubleGauge> registeredGauges;
/** Create a new instance. */
public MetricsRegistry() {
this(Clock.SYSTEM, new io.dropwizard.metrics5.MetricRegistry());
}
/** Create a new instance. */
public MetricsRegistry(Clock clock, io.dropwizard.metrics5.MetricRegistry impl) {
super(clock);
this.impl = impl;
this.registeredGauges = new ConcurrentHashMap<>();
}
@Override protected Counter newCounter(Id id) {
return new MetricsCounter(clock(), id, impl.meter(toMetricName(id)));
}
@Override protected DistributionSummary newDistributionSummary(Id id) {
return new MetricsDistributionSummary(clock(), id, impl.histogram(toMetricName(id)));
}
@Override protected Timer newTimer(Id id) {
return new MetricsTimer(clock(), id, impl.timer(toMetricName(id)));
}
@Override protected Gauge newGauge(Id id) {
final MetricName name = toMetricName(id);
DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
DoubleGauge g = new DoubleGauge();
impl.register(name, g);
return g;
});
return new MetricsGauge(clock(), id, gauge);
}
@Override protected Gauge newMaxGauge(Id id) {
final MetricName name = toMetricName(id);
DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
DoubleMaxGauge g = new DoubleMaxGauge();
impl.register(name, g);
return g;
});
return new MetricsGauge(clock(), id, gauge);
}
private static MetricName toMetricName(final Id id) {
return new MetricName(id.name(), buildTagMap(id));
}
private static Map<String, String> buildTagMap(final Id id) {
Map<String, String> result = new HashMap<>();
for (Tag tag : id.tags()) {
result.put(tag.key(), tag.value());
}
return result;
}
}
| 5,897 |
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/MetricsGaugeAggr.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 java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* <p>Aggregate gauge used to compute the sum of gauges with the same Id.</p>
* <p>This aggregate gauge is only used to register with Metrics, the register with spectator is for each one of
* the registered gauges in this Aggregate gauge.</p>
*
* @author Kennedy Oliveira
*/
class MetricsGaugeAggr implements io.dropwizard.metrics5.Gauge<Double> {
private ConcurrentLinkedQueue<MetricsGauge> gauges;
/**
* Creates a new Aggregate Gauge.
*/
MetricsGaugeAggr() {
this.gauges = new ConcurrentLinkedQueue<>();
}
@Override
public Double getValue() {
double aggregatedValue = Double.NaN;
final Iterator<MetricsGauge> iterator = gauges.iterator();
while (iterator.hasNext()) {
final MetricsGauge gauge = iterator.next();
if (gauge.hasExpired()) {
iterator.remove();
} else {
final double gaugeVal = gauge.value();
// When it's NaN means the gauge can be unregistered due to it's reference to the value to extract value
// was garbage collected or simple the gauge returned a NaN so i don't count it
if (!Double.isNaN(gaugeVal))
aggregatedValue = (Double.isNaN(aggregatedValue) ? 0 : aggregatedValue) + gaugeVal;
}
}
return aggregatedValue;
}
/**
* Add a gauge to be aggragate to the others.
*
* @param gauge Gauge to be added
*/
void addGauge(MetricsGauge gauge) {
this.gauges.add(gauge);
}
}
| 5,898 |
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/DoubleGauge.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 io.dropwizard.metrics5.Gauge;
import com.netflix.spectator.impl.AtomicDouble;
/** metrics5 gauge type based on an {@link AtomicDouble}. */
class DoubleGauge implements Gauge<Double> {
/** Current value for the gauge. */
protected AtomicDouble value = new AtomicDouble(Double.NaN);
/** Update the value. */
void set(double v) {
value.set(v);
}
@Override public Double getValue() {
return value.get();
}
}
| 5,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.