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/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicDistributionSummary.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.UnmodifiableList; import java.util.List; /** * Track the sample distribution of events. Similar to a BasicTimer without the time unit aspect. */ public class BasicDistributionSummary extends AbstractMonitor<Long> implements CompositeMonitor<Long>, SpectatorMonitor { private static final String STATISTIC = "statistic"; private static final Tag STAT_TOTAL = Tags.newTag(STATISTIC, "totalAmount"); private static final Tag STAT_COUNT = Tags.newTag(STATISTIC, "count"); private static final Tag STAT_MAX = Tags.newTag(STATISTIC, "max"); private static final Tag STAT_MIN = Tags.newTag(STATISTIC, "min"); private final StepCounter totalAmount; private final StepCounter count; private final MaxGauge max; private final MinGauge min; private final List<Monitor<?>> monitors; /** * Create a new instance. */ public BasicDistributionSummary(MonitorConfig config) { super(config); totalAmount = new StepCounter(config.withAdditionalTag(STAT_TOTAL)); count = new StepCounter(config.withAdditionalTag(STAT_COUNT)); max = new MaxGauge(config.withAdditionalTag(STAT_MAX)); min = new MinGauge(config.withAdditionalTag(STAT_MIN)); monitors = UnmodifiableList.<Monitor<?>>of(totalAmount, count, max, min); } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * Updates the statistics kept by the summary with the specified amount. */ public void record(long amount) { if (amount >= 0) { totalAmount.increment(amount); count.increment(); max.update(amount); min.update(amount); } } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIndex) { final long cnt = count.getCurrentCount(pollerIndex); final long total = totalAmount.getCurrentCount(pollerIndex); final long value = (long) ((double) total / cnt); return (cnt == 0) ? 0L : value; } /** * Get the total amount for all updates. */ public Long getTotalAmount() { return totalAmount.getCurrentCount(0); } /** * Get the total number of updates. */ public Long getCount() { return count.getCurrentCount(0); } /** * Get the min value since the last polling interval. */ public Long getMin() { return min.getCurrentValue(0); } /** * Get the max value since the last polling interval. */ public Long getMax() { return max.getCurrentValue(0); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { totalAmount.initializeSpectator(BasicTagList.concat(tags, STAT_TOTAL)); count.initializeSpectator(BasicTagList.concat(tags, STAT_COUNT)); max.initializeSpectator(BasicTagList.concat(tags, STAT_MAX)); } @Override public String toString() { return "BasicDistributionSummary{config=" + config + ", totalAmount=" + totalAmount + ", count=" + count + ", max=" + max + ", min=" + min + '}'; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + totalAmount.hashCode(); result = 31 * result + count.hashCode(); result = 31 * result + max.hashCode(); result = 31 * result + min.hashCode(); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof BasicDistributionSummary)) { return false; } BasicDistributionSummary m = (BasicDistributionSummary) obj; return config.equals(m.getConfig()) && totalAmount.equals(m.totalAmount) && count.equals(m.count) && max.equals(m.max) && min.equals(m.min); } }
2,900
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Informational.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * Monitor with a value type of string. */ public interface Informational extends Monitor<String> { }
2,901
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/StatsTimer.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.stats.StatsConfig; import com.netflix.servo.tag.Tags; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * A {@link Timer} that provides statistics. * <p/> * The statistics are collected periodically and are published according to the configuration * specified by the user using a {@link com.netflix.servo.stats.StatsConfig} object. Please * make sure that the sampleSize corresponds to roughly the number of samples expected in * a reporting interval. While the statistics collected are accurate for this machine they will not * be correct if they are aggregated across groups of machines. * If that is an expected use-case a better * approach is to use buckets that correspond to different times. * For example you might have a counter * that tracks how many calls took &lt; 20ms, one for [ 20ms, 500ms ], and one for &gt; 500ms. * This bucketing approach can be easily aggregated. * See {@link com.netflix.servo.monitor.BucketTimer} */ public class StatsTimer extends StatsMonitor implements Timer { private final TimeUnit timeUnit; private static final String UNIT = "unit"; /** * Creates a new instance of the timer with a unit of milliseconds, using the default executor. */ public StatsTimer(MonitorConfig baseConfig, StatsConfig statsConfig) { this(baseConfig, statsConfig, TimeUnit.MILLISECONDS, DEFAULT_EXECUTOR); } /** * Creates a new instance of the timer with a given unit, using the default executor. */ public StatsTimer(MonitorConfig baseConfig, StatsConfig statsConfig, TimeUnit unit) { this(baseConfig, statsConfig, unit, DEFAULT_EXECUTOR); } /** * Creates a new instance of the timer with a unit of milliseconds, * using the {@link ScheduledExecutorService} provided by * the user. * To avoid memory leaks the ScheduledExecutorService * should have the policy to remove tasks from the work queue. * See {@link java.util.concurrent.ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)} */ public StatsTimer(MonitorConfig config, StatsConfig statsConfig, TimeUnit unit, ScheduledExecutorService executor) { super(config, statsConfig, executor, "totalTime", false, Tags.newTag(UNIT, unit.name())); this.timeUnit = unit; startComputingStats(); } /** * {@inheritDoc} */ @Override public Stopwatch start() { Stopwatch s = new TimedStopwatch(this); s.start(); return s; } /** * {@inheritDoc} */ @Override public TimeUnit getTimeUnit() { return timeUnit; } /** * {@inheritDoc} */ @Override public void record(long duration, TimeUnit timeUnit) { record(this.timeUnit.convert(duration, timeUnit)); } /** * {@inheritDoc} */ @Override public String toString() { return "StatsTimer{StatsMonitor=" + super.toString() + ", timeUnit=" + timeUnit + '}'; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (!(obj instanceof StatsTimer)) { return false; } final StatsTimer m = (StatsTimer) obj; return super.equals(obj) && timeUnit.equals(m.timeUnit); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + timeUnit.hashCode(); return result; } /** * Get the number of times this timer has been updated. */ public long getCount() { return count.getValue().longValue(); } /** * Get the total time recorded for this timer. */ public long getTotalTime() { return getTotalMeasurement(); } }
2,902
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DefaultPublishingPolicy.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * The default publishing policy. Observers must follow the default behaviour when the * {@link MonitorConfig} associated with a {@link Monitor} uses this policy. */ public final class DefaultPublishingPolicy implements PublishingPolicy { private static final DefaultPublishingPolicy INSTANCE = new DefaultPublishingPolicy(); private DefaultPublishingPolicy() { } public static DefaultPublishingPolicy getInstance() { return INSTANCE; } @Override public String toString() { return "DefaultPublishingPolicy"; } }
2,903
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicInformational.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import java.util.concurrent.atomic.AtomicReference; /** * A simple informational implementation that maintains a string value. */ public final class BasicInformational extends AbstractMonitor<String> implements Informational { private final AtomicReference<String> info = new AtomicReference<>(); /** * Creates a new instance of the counter. */ public BasicInformational(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.INFORMATIONAL)); } /** * Set the value to show for this monitor. */ public void setValue(String value) { info.set(value); } /** * {@inheritDoc} */ @Override public String getValue(int pollerIndex) { return info.get(); } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !(o instanceof BasicInformational)) { return false; } BasicInformational that = (BasicInformational) o; String thisInfo = info.get(); String thatInfo = that.info.get(); return config.equals(that.config) && (thisInfo == null ? thatInfo == null : thisInfo.equals(thatInfo)); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); int infoHashcode = info.get() != null ? info.get().hashCode() : 0; result = 31 * result + infoHashcode; return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BasicInformational{config=" + config + ", info=" + info + '}'; } }
2,904
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/StepLong.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.util.Clock; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; /** * Utility class for managing a set of AtomicLong instances mapped to a particular step interval. * The current implementation keeps an array of two items where one is the current value * being updated and the other is the value from the previous interval and is only available for * polling. */ class StepLong { private static final int PREVIOUS = 0; private static final int CURRENT = 1; private final long init; private final Clock clock; private final AtomicLong[] data; private final AtomicLong[] lastInitPos; StepLong(long init, Clock clock) { this.init = init; this.clock = clock; lastInitPos = new AtomicLong[Pollers.NUM_POLLERS]; for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { lastInitPos[i] = new AtomicLong(0L); } data = new AtomicLong[2 * Pollers.NUM_POLLERS]; for (int i = 0; i < data.length; ++i) { data[i] = new AtomicLong(init); } } void addAndGet(long amount) { for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { getCurrent(i).addAndGet(amount); } } private void rollCount(int pollerIndex, long now) { final long step = Pollers.POLLING_INTERVALS[pollerIndex]; final long stepTime = now / step; final long lastInit = lastInitPos[pollerIndex].get(); if (lastInit < stepTime && lastInitPos[pollerIndex].compareAndSet(lastInit, stepTime)) { final int prev = 2 * pollerIndex + PREVIOUS; final int curr = 2 * pollerIndex + CURRENT; final long v = data[curr].getAndSet(init); // Need to check if there was any activity during the previous step interval. If there was // then the init position will move forward by 1, otherwise it will be older. No activity // means the previous interval should be set to the `init` value. data[prev].set((lastInit == stepTime - 1) ? v : init); } } AtomicLong getCurrent(int pollerIndex) { rollCount(pollerIndex, clock.now()); return data[2 * pollerIndex + CURRENT]; } long poll(int pollerIndex) { rollCount(pollerIndex, clock.now()); final int prevPos = 2 * pollerIndex + PREVIOUS; return data[prevPos].get(); } @Override public String toString() { return "StepLong{init=" + init + ", data=" + Arrays.toString(data) + ", lastInitPos=" + Arrays.toString(lastInitPos) + '}'; } }
2,905
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Gauge.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * Monitor type that provides the current value, e.g., the percentage of disk space used. */ public interface Gauge<T extends Number> extends NumericMonitor<T> { }
2,906
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Stopwatch.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import java.util.concurrent.TimeUnit; /** * Measures the time taken for execution of some code. */ public interface Stopwatch { /** * Mark the start time. */ void start(); /** * Mark the end time. */ void stop(); /** * Reset the stopwatch so that it can be used again. */ void reset(); /** * Returns the duration in the specified time unit. */ long getDuration(TimeUnit timeUnit); /** * Returns the duration in nanoseconds. */ long getDuration(); }
2,907
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.base.Function; import com.google.common.cache.Cache; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.MonitorTags; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.TaggingContext; import com.netflix.servo.util.Reflection; import com.netflix.servo.util.Throwables; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.netflix.servo.util.Reflection.getFieldsAnnotatedBy; import static com.netflix.servo.util.Reflection.getMethodsAnnotatedBy; /** * Some helper functions for creating monitor objects. */ public final class Monitors { /** * Name used for composite objects that do not have an explicit id. */ private static final String DEFAULT_ID = "default"; /** * Function to create basic timers. */ private static class TimerFactory implements Function<MonitorConfig, Timer> { private final TimeUnit unit; TimerFactory(TimeUnit unit) { this.unit = unit; } public Timer apply(MonitorConfig config) { return new BasicTimer(config, unit); } } /** * Function to create basic counters. */ private static class CounterFactory implements Function<MonitorConfig, Counter> { public Counter apply(MonitorConfig config) { return new BasicCounter(config); } } private static final CounterFactory COUNTER_FUNCTION = new CounterFactory(); private Monitors() { } /** * Create a new timer with only the name specified. */ public static Timer newTimer(String name) { return newTimer(name, TimeUnit.MILLISECONDS); } /** * Create a new timer with a name and context. The returned timer will maintain separate * sub-monitors for each distinct set of tags returned from the context on an update operation. */ public static Timer newTimer(String name, TaggingContext context) { return newTimer(name, TimeUnit.MILLISECONDS, context); } /** * Create a new timer with only the name specified. */ public static Timer newTimer(String name, TimeUnit unit) { return new BasicTimer(MonitorConfig.builder(name).build(), unit); } /** * Create a new timer with a name and context. The returned timer will maintain separate * sub-monitors for each distinct set of tags returned from the context on an update operation. */ public static Timer newTimer(String name, TimeUnit unit, TaggingContext context) { final MonitorConfig config = MonitorConfig.builder(name).build(); return new ContextualTimer(config, context, new TimerFactory(unit)); } /** * Create a new counter instance. */ public static Counter newCounter(String name) { return new BasicCounter(MonitorConfig.builder(name).build()); } /** * Create a new counter with a name and context. The returned counter will maintain separate * sub-monitors for each distinct set of tags returned from the context on an update operation. */ public static Counter newCounter(String name, TaggingContext context) { final MonitorConfig config = MonitorConfig.builder(name).build(); return new ContextualCounter(config, context, COUNTER_FUNCTION); } /** * Helper function to easily create a composite for all monitor fields and * annotated attributes of a given object. */ public static CompositeMonitor<?> newObjectMonitor(Object obj) { return newObjectMonitor(null, obj); } /** * Helper function to easily create a composite for all monitor fields and * annotated attributes of a given object. * * @param id a unique id associated with this particular instance of the * object. If multiple objects of the same class are registered * they will have the same config and conflict unless the id * values are distinct. * @param obj object to search for monitors on. All fields of type * {@link Monitor} and fields/methods with a * {@link com.netflix.servo.annotations.Monitor} annotation * will be extracted and returned using * {@link CompositeMonitor#getMonitors()}. * @return composite monitor based on the fields of the class */ public static CompositeMonitor<?> newObjectMonitor(String id, Object obj) { final TagList tags = getMonitorTags(obj); List<Monitor<?>> monitors = new ArrayList<>(); addMonitors(monitors, id, tags, obj); final Class<?> c = obj.getClass(); final String objectId = (id == null) ? DEFAULT_ID : id; return new BasicCompositeMonitor(newObjectConfig(c, objectId, tags), monitors); } /** * Creates a new monitor for a thread pool with standard metrics for the pool size, queue size, * task counts, etc. * * @param id id to differentiate metrics for this pool from others. * @param pool thread pool instance to monitor. * @return composite monitor based on stats provided for the pool */ public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) { return newObjectMonitor(id, new MonitoredThreadPool(pool)); } /** * Creates a new monitor for a cache with standard metrics for the hits, misses, and loads. * * @param id id to differentiate metrics for this cache from others. * @param cache cache instance to monitor. * @return composite monitor based on stats provided for the cache */ public static CompositeMonitor<?> newCacheMonitor(String id, Cache<?, ?> cache) { return newObjectMonitor(id, new MonitoredCache(cache)); } /** * Register an object with the default registry. Equivalent to * {@code DefaultMonitorRegistry.getInstance().register(Monitors.newObjectMonitor(obj))}. */ public static void registerObject(Object obj) { registerObject(null, obj); } /** * Unregister an object from the default registry. Equivalent to * {@code DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(obj))}. * * @param obj Previously registered using {@code Monitors.registerObject(obj)} */ public static void unregisterObject(Object obj) { unregisterObject(null, obj); } /** * Unregister an object from the default registry. Equivalent to * {@code DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(id, obj))}. * * @param obj Previously registered using {@code Monitors.registerObject(id, obj)} */ public static void unregisterObject(String id, Object obj) { DefaultMonitorRegistry.getInstance().unregister(newObjectMonitor(id, obj)); } /** * Register an object with the default registry. Equivalent to * {@code DefaultMonitorRegistry.getInstance().register(Monitors.newObjectMonitor(id, obj))}. */ public static void registerObject(String id, Object obj) { DefaultMonitorRegistry.getInstance().register(newObjectMonitor(id, obj)); } /** * Check whether an object is currently registered with the default registry. */ public static boolean isObjectRegistered(Object obj) { return isObjectRegistered(null, obj); } /** * Check whether an object is currently registered with the default registry. */ public static boolean isObjectRegistered(String id, Object obj) { return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); } /** * Returns a new monitor that adds the provided tags to the configuration returned by the * wrapped monitor. */ @SuppressWarnings("unchecked") static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) { Monitor<T> m; if (monitor instanceof CompositeMonitor<?>) { m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor); } else { m = MonitorWrapper.create(tags, monitor); } return m; } /** * Extract all monitors across class hierarchy. */ static void addMonitors(List<Monitor<?>> monitors, String id, TagList tags, Object obj) { addMonitorFields(monitors, id, tags, obj); addAnnotatedFields(monitors, id, tags, obj); } /** * Extract all fields of {@code obj} that are of type {@link Monitor} and add them to * {@code monitors}. */ static void addMonitorFields( List<Monitor<?>> monitors, String id, TagList tags, Object obj) { try { final SortedTagList.Builder builder = SortedTagList.builder(); builder.withTag("class", className(obj.getClass())); if (tags != null) { builder.withTags(tags); } if (id != null) { builder.withTag("id", id); } final TagList classTags = builder.build(); final Set<Field> fields = Reflection.getAllFields(obj.getClass()); for (Field field : fields) { if (isMonitorType(field.getType())) { field.setAccessible(true); final Monitor<?> m = (Monitor<?>) field.get(obj); if (m == null) { throw new NullPointerException("field " + field.getName() + " in class " + field.getDeclaringClass().getName() + " is null, all monitor fields must be" + " initialized before registering"); } monitors.add(wrap(classTags, m)); } } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Extract all fields/methods of {@code obj} that have a monitor annotation and add them to * {@code monitors}. */ static void addAnnotatedFields( List<Monitor<?>> monitors, String id, TagList tags, Object obj) { final Class<com.netflix.servo.annotations.Monitor> annoClass = com.netflix.servo.annotations.Monitor.class; try { Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), annoClass); for (Field field : fields) { final com.netflix.servo.annotations.Monitor anno = field.getAnnotation(annoClass); if (anno != null) { final MonitorConfig config = newConfig(obj.getClass(), field.getName(), id, anno, tags); if (anno.type() == DataSourceType.INFORMATIONAL) { monitors.add(new AnnotatedStringMonitor(config, obj, field)); } else { checkType(anno, field.getType(), field.getDeclaringClass()); monitors.add(new AnnotatedNumberMonitor(config, obj, field)); } } } Set<Method> methods = getMethodsAnnotatedBy(obj.getClass(), annoClass); for (Method method : methods) { final com.netflix.servo.annotations.Monitor anno = method.getAnnotation(annoClass); if (anno != null) { final MonitorConfig config = newConfig(obj.getClass(), method.getName(), id, anno, tags); if (anno.type() == DataSourceType.INFORMATIONAL) { monitors.add(new AnnotatedStringMonitor(config, obj, method)); } else { checkType(anno, method.getReturnType(), method.getDeclaringClass()); monitors.add(new AnnotatedNumberMonitor(config, obj, method)); } } } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Get tags from annotation. */ private static TagList getMonitorTags(Object obj) { try { Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), MonitorTags.class); for (Field field : fields) { field.setAccessible(true); return (TagList) field.get(obj); } Set<Method> methods = getMethodsAnnotatedBy(obj.getClass(), MonitorTags.class); for (Method method : methods) { method.setAccessible(true); return (TagList) method.invoke(obj); } } catch (Exception e) { throw Throwables.propagate(e); } return null; } /** * Verify that the type for the annotated field is numeric. */ private static void checkType( com.netflix.servo.annotations.Monitor anno, Class<?> type, Class<?> container) { if (!isNumericType(type)) { final String msg = "annotation of type " + anno.type().name() + " can only be used" + " with numeric values, " + anno.name() + " in class " + container.getName() + " is applied to a field or method of type " + type.getName(); throw new IllegalArgumentException(msg); } } /** * Returns true if {@code c} can be assigned to a number. */ private static boolean isNumericType(Class<?> c) { return Number.class.isAssignableFrom(c) || double.class == c || float.class == c || long.class == c || int.class == c || short.class == c || byte.class == c; } /** * Returns true if {@code c} can be assigned to a monitor. */ private static boolean isMonitorType(Class<?> c) { return Monitor.class.isAssignableFrom(c); } /** * Creates a monitor config for a composite object. */ private static MonitorConfig newObjectConfig(Class<?> c, String id, TagList tags) { final MonitorConfig.Builder builder = MonitorConfig.builder(id); final String className = className(c); if (!className.isEmpty()) { builder.withTag("class", className); } if (tags != null) { builder.withTags(tags); } return builder.build(); } private static String className(Class c) { final String simpleName = c.getSimpleName(); return simpleName.isEmpty() ? className(c.getEnclosingClass()) : simpleName; } /** * Creates a monitor config based on an annotation. */ private static MonitorConfig newConfig( Class<?> c, String defaultName, String id, com.netflix.servo.annotations.Monitor anno, TagList tags) { String name = anno.name(); if (name.isEmpty()) { name = defaultName; } MonitorConfig.Builder builder = MonitorConfig.builder(name); builder.withTag("class", className(c)); builder.withTag(anno.type()); builder.withTag(anno.level()); if (tags != null) { builder.withTags(tags); } if (id != null) { builder.withTag("id", id); } return builder.build(); } }
2,908
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DynamicGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.tag.TagList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Utility class that dynamically creates gauges based on an arbitrary (name, tagList), * or {@link com.netflix.servo.monitor.MonitorConfig} * Gauges are automatically expired after 15 minutes of inactivity. */ public final class DynamicGauge implements CompositeMonitor<Long>, SpectatorMonitor { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicGauge.class); private static final String DEFAULT_EXPIRATION = "15"; private static final String DEFAULT_EXPIRATION_UNIT = "MINUTES"; private static final String CLASS_NAME = DynamicGauge.class.getCanonicalName(); private static final String EXPIRATION_PROP = CLASS_NAME + ".expiration"; private static final String EXPIRATION_PROP_UNIT = CLASS_NAME + ".expirationUnit"; private static final String INTERNAL_ID = "servoGauges"; private static final String CACHE_MONITOR_ID = "servoGaugesCache"; private static final MonitorConfig BASE_CONFIG = new MonitorConfig.Builder(INTERNAL_ID).build(); private static final DynamicGauge INSTANCE = new DynamicGauge(); private final LoadingCache<MonitorConfig, DoubleGauge> gauges; private final CompositeMonitor<?> cacheMonitor; private DynamicGauge() { final String expiration = System.getProperty(EXPIRATION_PROP, DEFAULT_EXPIRATION); final String expirationUnit = System.getProperty(EXPIRATION_PROP_UNIT, DEFAULT_EXPIRATION_UNIT); final long expirationValue = Long.parseLong(expiration); final TimeUnit expirationUnitValue = TimeUnit.valueOf(expirationUnit); gauges = CacheBuilder.newBuilder() .expireAfterAccess(expirationValue, expirationUnitValue) .build(new CacheLoader<MonitorConfig, DoubleGauge>() { @Override public DoubleGauge load(final MonitorConfig config) throws Exception { return new DoubleGauge(config); } }); cacheMonitor = Monitors.newCacheMonitor(CACHE_MONITOR_ID, gauges); DefaultMonitorRegistry.getInstance().register(this); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { } /** * Set a gauge based on a given {@link MonitorConfig} by a given value. * * @param config The monitoring config * @param value The amount added to the current value */ public static void set(MonitorConfig config, double value) { INSTANCE.get(config).set(value); } /** * Increment a gauge specified by a name. */ public static void set(String name, double value) { set(MonitorConfig.builder(name).build(), value); } /** * Set the gauge for a given name, tagList by a given value. */ public static void set(String name, TagList list, double value) { final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build(); set(config, value); } private DoubleGauge get(MonitorConfig config) { try { return gauges.get(config); } catch (ExecutionException e) { LOGGER.error("Failed to get a gauge for {}: {}", config, e.getMessage()); throw Throwables.propagate(e); } } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { final ConcurrentMap<MonitorConfig, DoubleGauge> gaugesMap = gauges.asMap(); return ImmutableList.copyOf(gaugesMap.values()); } /** * {@inheritDoc} */ @Override public Long getValue() { return (long) gauges.asMap().size(); } @Override public Long getValue(int pollerIndex) { return getValue(); } /** * {@inheritDoc} */ @Override public MonitorConfig getConfig() { return BASE_CONFIG; } @Override public String toString() { ConcurrentMap<MonitorConfig, DoubleGauge> map = gauges.asMap(); return "DynamicGauge{" + "baseConfig=" + BASE_CONFIG + ", totalGauges=" + map.size() + ", gauges=" + map + '}'; } }
2,909
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/ContextualCounter.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.base.Function; import com.netflix.servo.tag.TaggingContext; /** * Composite that maintains separate simple counters for each distinct set of tags returned by the * tagging context. */ public class ContextualCounter extends AbstractContextualMonitor<Number, Counter> implements Counter { /** * Create a new instance of the counter. * * @param config shared configuration * @param context provider for context specific tags * @param newMonitor function to create new counters */ public ContextualCounter( MonitorConfig config, TaggingContext context, Function<MonitorConfig, Counter> newMonitor) { super(config, context, newMonitor); } /** * {@inheritDoc} */ @Override public void increment() { getMonitorForCurrentContext().increment(); } /** * {@inheritDoc} */ @Override public void increment(long amount) { getMonitorForCurrentContext().increment(amount); } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIndex) { return getMonitorForCurrentContext().getValue(pollerIndex); } }
2,910
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DurationTimer.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.UnmodifiableList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * A Monitor for tracking a longer operation that might last for many minutes or hours. For tracking * frequent calls that last less than a polling interval (usually one minute) please use a * {@link com.netflix.servo.monitor.BasicTimer} instead. * <p/> * This monitor will create two gauges: * <ul> * <li>A duration: will report the current duration in seconds. * (defined as the sum of the time of all active tasks.)</li> * <li>Number of active tasks.</li> * </ul> * <p/> * The names for the monitors will be the base name passed to the constructor plus a * suffix of .duration and .activeTasks respectively. */ public class DurationTimer extends AbstractMonitor<Long> implements CompositeMonitor<Long> { private final List<Monitor<?>> monitors; private final AtomicLong nextTaskId = new AtomicLong(0L); private final ConcurrentMap<Long, Long> tasks = new ConcurrentHashMap<>(); private final Clock clock; private static MonitorConfig subId(MonitorConfig config, String sub) { String newName = config.getName() + "." + sub; return MonitorConfig.builder(newName).withTags(config.getTags()) .withPublishingPolicy(config.getPublishingPolicy()) .build(); } /** * Create a new DurationTimer using the provided configuration. */ public DurationTimer(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } /** * Create a new DurationTimer using a specific configuration and clock. This is useful for * unit tests that need to manipulate the clock. */ public DurationTimer(MonitorConfig config, final Clock clock) { super(config); this.clock = clock; Monitor<?> duration = new BasicGauge<>(subId(config, "duration"), () -> getDurationMillis() / 1000L); Monitor<?> activeTasks = new BasicGauge<>(subId(config, "activeTasks"), new Callable<Long>() { @Override public Long call() throws Exception { return (long) tasks.size(); } }); monitors = UnmodifiableList.of(duration, activeTasks); } private long getDurationMillis() { long now = clock.now(); long sum = 0L; for (long startTime : tasks.values()) { sum += now - startTime; } return Math.max(sum, 0L); } /** * {@inheritDoc} */ @Override public Long getValue() { return getValue(0); } @Override public Long getValue(int pollerIndex) { return getDurationMillis() / 1000; } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DurationTimer that = (DurationTimer) o; return getConfig().equals(that.getConfig()) && nextTaskId.get() == that.nextTaskId.get() && tasks.equals(that.tasks); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); long id = nextTaskId.get(); result = 31 * result + (int) (id ^ (id >>> 32)); result = 31 * result + tasks.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "DurationTimer{config=" + getConfig() + ", tasks=" + tasks + ", monitors=" + monitors + ", nextTaskId=" + nextTaskId.get() + '}'; } /** * Returns a stopwatch that has been started and will automatically * record its result to this timer when stopped. Every time this method is called * the number of active tasks for the timer will be incremented. * The number will be decremented when the stopwatch is stopped. */ public Stopwatch start() { Stopwatch s = new DurationStopwatch(); s.start(); return s; } private class DurationStopwatch implements Stopwatch { private long id = -1L; @Override public void start() { this.id = nextTaskId.getAndIncrement(); tasks.put(id, clock.now()); } @Override public void stop() { if (id >= 0) { tasks.remove(id); id = -1L; } } @Override public void reset() { if (id >= 0) { tasks.put(id, clock.now()); } } @Override public long getDuration(TimeUnit timeUnit) { long durationMs = 0L; if (id >= 0) { long start = tasks.get(id); durationMs = clock.now() - start; } durationMs = Math.max(0L, durationMs); return timeUnit.convert(durationMs, TimeUnit.MILLISECONDS); } @Override public long getDuration() { return getDuration(TimeUnit.SECONDS); } } }
2,911
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/StatsMonitor.java
/* * Copyright 2011-2018 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.servo.monitor; import com.netflix.servo.stats.StatsBuffer; import com.netflix.servo.stats.StatsConfig; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ThreadFactories; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * A {@link Timer} that provides statistics. * <p> * The statistics are collected periodically and are published according to the configuration * specified by the user using a {@link com.netflix.servo.stats.StatsConfig} object. */ public class StatsMonitor extends AbstractMonitor<Long> implements CompositeMonitor<Long>, NumericMonitor<Long>, SpectatorMonitor { protected static final ScheduledExecutorService DEFAULT_EXECUTOR; private static final long EXPIRE_AFTER_MS; static { final String className = StatsMonitor.class.getCanonicalName(); final String expirationProp = className + ".expiration"; final String expirationPropUnit = className + ".expirationUnit"; final String expiration = System.getProperty(expirationProp, "15"); final String expirationUnit = System.getProperty(expirationPropUnit, "MINUTES"); final long expirationValue = Long.parseLong(expiration); final TimeUnit expirationUnitValue = TimeUnit.valueOf(expirationUnit); EXPIRE_AFTER_MS = expirationUnitValue.toMillis(expirationValue); final ThreadFactory threadFactory = ThreadFactories.withName("StatsMonitor-%d"); final ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(1, threadFactory); poolExecutor.setRemoveOnCancelPolicy(true); DEFAULT_EXECUTOR = poolExecutor; } private static final Logger LOGGER = LoggerFactory.getLogger(StatsMonitor.class); private final MonitorConfig baseConfig; protected final Counter count; protected final Counter totalMeasurement; private final List<Monitor<?>> monitors; private final List<GaugeWrapper> gaugeWrappers; private final Runnable startComputingAction; private final Object updateLock = new Object(); private StatsBuffer cur; private StatsBuffer prev; private static final String STATISTIC = "statistic"; private static final String PERCENTILE_FMT = "percentile_%.2f"; private static final Tag STAT_COUNT = Tags.newTag(STATISTIC, "count"); private static final Tag STAT_MIN = Tags.newTag(STATISTIC, "min"); private static final Tag STAT_MAX = Tags.newTag(STATISTIC, "max"); private static final Tag STAT_MEAN = Tags.newTag(STATISTIC, "avg"); private static final Tag STAT_VARIANCE = Tags.newTag(STATISTIC, "variance"); private static final Tag STAT_STDDEV = Tags.newTag(STATISTIC, "stdDev"); private final Clock clock; private volatile long lastUsed; private final ScheduledExecutorService executor; private final StatsConfig statsConfig; private AtomicReference<ScheduledFuture<?>> myFutureRef = new AtomicReference<>(); private interface GaugeWrapper { void update(StatsBuffer buffer); Monitor<?> getMonitor(); } private abstract static class LongGaugeWrapper implements GaugeWrapper { protected final LongGauge gauge; protected LongGaugeWrapper(MonitorConfig config) { gauge = new LongGauge(config); } @Override public Monitor<?> getMonitor() { return gauge; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LongGaugeWrapper)) { return false; } final LongGaugeWrapper that = (LongGaugeWrapper) o; return gauge.equals(that.gauge); } @Override public int hashCode() { return gauge.hashCode(); } @Override public String toString() { return "LongGaugeWrapper{gauge=" + gauge + '}'; } } private abstract static class DoubleGaugeWrapper implements GaugeWrapper { protected final DoubleGauge gauge; protected DoubleGaugeWrapper(MonitorConfig config) { gauge = new DoubleGauge(config); } @Override public Monitor<?> getMonitor() { return gauge; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DoubleGaugeWrapper)) { return false; } final DoubleGaugeWrapper that = (DoubleGaugeWrapper) o; return gauge.equals(that.gauge); } @Override public int hashCode() { return gauge.hashCode(); } @Override public String toString() { return "DoubleGaugeWrapper{gauge=" + gauge + '}'; } } private static class MinStatGaugeWrapper extends LongGaugeWrapper { MinStatGaugeWrapper(MonitorConfig baseConfig) { super(baseConfig.withAdditionalTag(STAT_MIN)); } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getMin()); } } private static class MaxGaugeWrapper extends LongGaugeWrapper { MaxGaugeWrapper(MonitorConfig baseConfig) { super(baseConfig.withAdditionalTag(STAT_MAX)); } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getMax()); } } private static class MeanGaugeWrapper extends DoubleGaugeWrapper { MeanGaugeWrapper(MonitorConfig baseConfig) { super(baseConfig.withAdditionalTag(STAT_MEAN)); } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getMean()); } } private static class VarianceGaugeWrapper extends DoubleGaugeWrapper { VarianceGaugeWrapper(MonitorConfig baseConfig) { super(baseConfig.withAdditionalTag(STAT_VARIANCE)); } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getVariance()); } } private static class StdDevGaugeWrapper extends DoubleGaugeWrapper { StdDevGaugeWrapper(MonitorConfig baseConfig) { super(baseConfig.withAdditionalTag(STAT_STDDEV)); } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getStdDev()); } } private static class PercentileGaugeWrapper extends DoubleGaugeWrapper { private final double percentile; private final int index; private static Tag percentileTag(double percentile) { String percentileStr = String.format(PERCENTILE_FMT, percentile); if (percentileStr.endsWith(".00")) { percentileStr = percentileStr.substring(0, percentileStr.length() - 3); } return Tags.newTag(STATISTIC, percentileStr); } PercentileGaugeWrapper(MonitorConfig baseConfig, double percentile, int index) { super(baseConfig.withAdditionalTag(percentileTag(percentile))); this.percentile = percentile; this.index = index; } @Override public void update(StatsBuffer buffer) { gauge.set(buffer.getPercentileValueForIdx(index)); } @Override public String toString() { return "PercentileGaugeWrapper{gauge=" + gauge + "percentile=" + percentile + '}'; } } private List<Counter> getCounters(StatsConfig config) { final List<Counter> counters = new ArrayList<>(); if (config.getPublishCount()) { counters.add(count); } if (config.getPublishTotal()) { counters.add(totalMeasurement); } return counters; } private List<GaugeWrapper> getGaugeWrappers(StatsConfig config) { final List<GaugeWrapper> wrappers = new ArrayList<>(); if (config.getPublishMax()) { wrappers.add(new MaxGaugeWrapper(baseConfig)); } if (config.getPublishMin()) { wrappers.add(new MinStatGaugeWrapper(baseConfig)); } if (config.getPublishVariance()) { wrappers.add(new VarianceGaugeWrapper(baseConfig)); } if (config.getPublishStdDev()) { wrappers.add(new StdDevGaugeWrapper(baseConfig)); } if (config.getPublishMean()) { wrappers.add(new MeanGaugeWrapper(baseConfig)); } final double[] percentiles = config.getPercentiles(); for (int i = 0; i < percentiles.length; ++i) { wrappers.add(new PercentileGaugeWrapper(baseConfig, percentiles[i], i)); } // do a sanity check to prevent duplicated monitor configurations final Set<MonitorConfig> seen = new HashSet<>(); for (final GaugeWrapper wrapper : wrappers) { final MonitorConfig cfg = wrapper.getMonitor().getConfig(); if (seen.contains(cfg)) { throw new IllegalArgumentException("Duplicated monitor configuration found: " + cfg); } seen.add(cfg); } return wrappers; } /** * Creates a new instance of the timer with a unit of milliseconds, * using the {@link ScheduledExecutorService} provided by the user, * and the default Clock. * To avoid memory leaks the ScheduledExecutorService * should have the policy to remove tasks from the work queue. * See {@link ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)} */ public StatsMonitor(final MonitorConfig config, final StatsConfig statsConfig, final ScheduledExecutorService executor, final String totalTagName, final boolean autoStart, final Tag... additionalTags) { this(config, statsConfig, executor, totalTagName, autoStart, Clock.WALL, additionalTags); } /** * Creates a new instance of the timer with a unit of milliseconds, * using the {@link ScheduledExecutorService} provided by the user. * To avoid memory leaks the ScheduledExecutorService * should have the policy to remove tasks from the work queue. * See {@link ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)} */ public StatsMonitor(final MonitorConfig config, final StatsConfig statsConfig, final ScheduledExecutorService executor, final String totalTagName, final boolean autoStart, final Clock clock, final Tag... additionalTags) { super(config); final Tag statsTotal = Tags.newTag(STATISTIC, totalTagName); this.baseConfig = config.withAdditionalTags(new BasicTagList(Arrays.asList(additionalTags))); this.clock = clock; this.lastUsed = clock.now(); this.executor = executor; this.statsConfig = statsConfig; this.cur = new StatsBuffer(statsConfig.getSampleSize(), statsConfig.getPercentiles()); this.prev = new StatsBuffer(statsConfig.getSampleSize(), statsConfig.getPercentiles()); this.count = new BasicCounter(baseConfig.withAdditionalTag(STAT_COUNT)); this.totalMeasurement = new BasicCounter(baseConfig.withAdditionalTag(statsTotal)); this.gaugeWrappers = getGaugeWrappers(statsConfig); final List<Monitor<?>> gaugeMonitors = gaugeWrappers.stream() .map(GaugeWrapper::getMonitor).collect(Collectors.toList()); List<Monitor<?>> monitorList = new ArrayList<>(); monitorList.addAll(getCounters(statsConfig)); monitorList.addAll(gaugeMonitors); this.monitors = Collections.unmodifiableList(monitorList); this.startComputingAction = () -> startComputingStats(executor, statsConfig.getFrequencyMillis()); if (autoStart) { startComputingStats(); } } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { monitors.forEach(m -> { if (m instanceof SpectatorMonitor) { ((SpectatorMonitor) m).initializeSpectator(tags); } }); } void computeStats() { try { if (myFutureRef.get() == null) { return; } final boolean expired = (clock.now() - lastUsed) > EXPIRE_AFTER_MS; if (expired) { final ScheduledFuture<?> future = myFutureRef.getAndSet(null); if (future != null) { LOGGER.debug("Expiring unused StatsMonitor {}", getConfig().getName()); future.cancel(true); } return; } synchronized (updateLock) { final StatsBuffer tmp = prev; prev = cur; cur = tmp; } prev.computeStats(); updateGauges(); prev.reset(); } catch (Exception e) { handleException(e); } } /** * starts computation. * Because of potential race conditions, derived classes may wish * to define initial state before calling this function which starts the executor */ public void startComputingStats() { this.startComputingAction.run(); } private void startComputingStats(ScheduledExecutorService executor, long frequencyMillis) { this.myFutureRef.set(executor.scheduleWithFixedDelay(this::computeStats, frequencyMillis, frequencyMillis, TimeUnit.MILLISECONDS)); } private void updateGauges() { for (GaugeWrapper gauge : gaugeWrappers) { gauge.update(prev); } } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * Record the measurement we want to perform statistics on. */ public void record(long measurement) { lastUsed = clock.now(); if (isExpired()) { LOGGER.info("Attempting to get the value for an expired monitor: {}.Will start computing stats again.", getConfig().getName()); startComputingStats(executor, statsConfig.getFrequencyMillis()); } synchronized (updateLock) { cur.record(measurement); } count.increment(); totalMeasurement.increment(measurement); } /** * Get the value of the measurement. */ @Override public Long getValue(int pollerIndex) { final long n = getCount(pollerIndex); return n > 0 ? totalMeasurement.getValue(pollerIndex).longValue() / n : 0L; } @Override public Long getValue() { return getValue(0); } /** * This is called when we encounter an exception while processing the values * recorded to compute the stats. * * @param e Exception encountered. */ protected void handleException(Exception e) { LOGGER.warn("Unable to compute stats: ", e); } /** * {@inheritDoc} */ @Override public String toString() { return "StatsMonitor{baseConfig=" + baseConfig + ", monitors=" + monitors + '}'; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof StatsMonitor)) { return false; } final StatsMonitor m = (StatsMonitor) obj; return baseConfig.equals(m.baseConfig) && monitors.equals(m.monitors); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = baseConfig.hashCode(); result = 31 * result + monitors.hashCode(); return result; } /** * Get the number of times this timer has been updated. */ public long getCount(int pollerIndex) { return count.getValue(pollerIndex).longValue(); } /** * Get the total time recorded for this timer. */ public long getTotalMeasurement() { return totalMeasurement.getValue().longValue(); } /** * Whether the current monitor has expired, and its task removed from * the executor. */ boolean isExpired() { return myFutureRef.get() == null; } }
2,912
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MonitoredCache.java
/* * Copyright 2014 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.servo.monitor; import com.google.common.cache.Cache; import com.google.common.cache.CacheStats; import com.netflix.servo.util.Memoizer; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static com.netflix.servo.annotations.DataSourceType.COUNTER; import static com.netflix.servo.annotations.DataSourceType.GAUGE; /** * Wraps a cache to provide common metrics. */ class MonitoredCache { private static final int CACHE_TIME = 10; /** * When polling metrics each monitor gets called independently. If we call cache.stats directly * each monitor call will create a new stats object. This supplier is used to control the calls * for updated stats so that typically it will only need to be done once per sampling interval * for all exposed monitors. */ private final Memoizer<CacheStats> memoStats; MonitoredCache(final Cache<?, ?> cache) { final Callable<CacheStats> supplier = cache::stats; memoStats = Memoizer.create(supplier, CACHE_TIME, TimeUnit.SECONDS); } @com.netflix.servo.annotations.Monitor(name = "averageLoadPenalty", type = GAUGE) double averageLoadPenalty() { return memoStats.get().averageLoadPenalty(); } @com.netflix.servo.annotations.Monitor(name = "evictionCount", type = COUNTER) long evictionCount() { return memoStats.get().evictionCount(); } @com.netflix.servo.annotations.Monitor(name = "hitCount", type = COUNTER) long hitCount() { return memoStats.get().hitCount(); } @com.netflix.servo.annotations.Monitor(name = "loadCount", type = COUNTER) long loadCount() { return memoStats.get().loadCount(); } @com.netflix.servo.annotations.Monitor(name = "loadExceptionCount", type = COUNTER) long loadExceptionCount() { return memoStats.get().loadExceptionCount(); } @com.netflix.servo.annotations.Monitor(name = "loadSuccessCount", type = COUNTER) long loadSuccessCount() { return memoStats.get().loadSuccessCount(); } @com.netflix.servo.annotations.Monitor(name = "missCount", type = COUNTER) long missCount() { return memoStats.get().missCount(); } @com.netflix.servo.annotations.Monitor(name = "requestCount", type = COUNTER) long requestCount() { return memoStats.get().requestCount(); } @com.netflix.servo.annotations.Monitor(name = "totalLoadTime", type = COUNTER) long totalLoadTime() { return memoStats.get().totalLoadTime(); } }
2,913
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/NumberGauge.java
/* * Copyright 2011-2018 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.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Preconditions; import java.lang.ref.WeakReference; /** * A {@link Gauge} that returns the value stored in {@link Number}. */ public class NumberGauge extends AbstractMonitor<Number> implements Gauge<Number>, SpectatorMonitor { private final MonitorConfig baseConfig; private WeakReference<Number> numberRef; /** * Construct a gauge that will store a weak reference to a number. The number * should be set by the subclass immediately after the call to super(config); * using the {@link #setBackingNumber(Number)} method. */ protected NumberGauge(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; } /** * Construct a gauge that will store a weak reference to the number. The value returned * by the monitor will be the value stored in {@code number} or {@code Double.NaN} in case * the referred Number has been garbage collected. */ public NumberGauge(MonitorConfig config, Number number) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; Preconditions.checkNotNull(number, "number"); this.numberRef = new WeakReference<>(number); } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIdx) { Number n = numberRef.get(); return n != null ? n : Double.NaN; } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Number n = numberRef.get(); if (n != null) { SpectatorContext.polledGauge(baseConfig.withAdditionalTags(tags)).monitorValue(n); } } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NumberGauge)) { return false; } final NumberGauge that = (NumberGauge) o; return config.equals(that.config) && getValue().equals(that.getValue()); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + getValue(0).hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "NumberGauge{config=" + config + ", number=" + numberRef.get() + '}'; } /** * Returns the {@link Number} hold or null if it has been garbage collected. */ protected Number getBackingNumber() { return numberRef.get(); } /** * Sets a new {@link Number} to hold. We keep a week reference to this value * allowing it to be GC. */ protected void setBackingNumber(Number number) { numberRef = new WeakReference<>(number); } }
2,914
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MonitorConfig.java
/* * Copyright 2014 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.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.SmallTagMap; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.UnmodifiableList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * Configuration settings associated with a monitor. A config consists of a name that is required * and an optional set of tags. */ public final class MonitorConfig { /** * A builder to assist in creating monitor config objects. */ public static class Builder { private final String name; private SmallTagMap.Builder tagsBuilder = SmallTagMap.builder(); private PublishingPolicy policy = DefaultPublishingPolicy.getInstance(); /** * Create a new builder initialized with the specified config. */ public Builder(MonitorConfig config) { this(config.getName()); withTags(config.getTags()); withPublishingPolicy(config.getPublishingPolicy()); } /** * Create a new builder initialized with the specified name. */ public Builder(String name) { this.name = name; } /** * Add a tag to the config. */ public Builder withTag(String key, String val) { tagsBuilder.add(Tags.newTag(key, val)); return this; } /** * Add a tag to the config. */ public Builder withTag(Tag tag) { tagsBuilder.add(tag); return this; } /** * Add all tags in the list to the config. */ public Builder withTags(TagList tagList) { if (tagList != null) { for (Tag t : tagList) { tagsBuilder.add(t); } } return this; } /** * Add all tags in the list to the config. */ public Builder withTags(Collection<Tag> tagCollection) { tagsBuilder.addAll(tagCollection); return this; } /** * Add all tags from a given SmallTagMap. */ public Builder withTags(SmallTagMap.Builder tagsBuilder) { this.tagsBuilder = tagsBuilder; return this; } /** * Add the publishing policy to the config. */ public Builder withPublishingPolicy(PublishingPolicy policy) { this.policy = policy; return this; } /** * Create the monitor config object. */ public MonitorConfig build() { return new MonitorConfig(this); } /** * Get the name for this monitor config. */ public String getName() { return name; } /** * Get the list of tags for this monitor config. */ public List<Tag> getTags() { return UnmodifiableList.copyOf(tagsBuilder.result()); } /** * Get the publishingPolicy. */ public PublishingPolicy getPublishingPolicy() { return policy; } } /** * Return a builder instance with the specified name. */ public static Builder builder(String name) { return new Builder(name); } private final String name; private final TagList tags; private final PublishingPolicy policy; /** * Config is immutable, cache the hash code to improve performance. */ private final AtomicInteger cachedHashCode = new AtomicInteger(0); /** * Creates a new instance with a given name and tags. If {@code tags} is * null an empty tag list will be used. */ private MonitorConfig(Builder builder) { this.name = Preconditions.checkNotNull(builder.name, "name"); this.tags = (builder.tagsBuilder.isEmpty()) ? BasicTagList.EMPTY : new BasicTagList(builder.tagsBuilder.result()); this.policy = builder.policy; } /** * Returns the name of the metric. */ public String getName() { return name; } /** * Returns the tags associated with the metric. */ public TagList getTags() { return tags; } /** * Returns the publishing policy. */ public PublishingPolicy getPublishingPolicy() { return policy; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof MonitorConfig)) { return false; } MonitorConfig m = (MonitorConfig) obj; return name.equals(m.getName()) && tags.equals(m.getTags()) && policy.equals(m.getPublishingPolicy()); } /** * This class is immutable so we cache the hash code after the first time it is computed. The * value 0 is used as an indicator that the hash code has not yet been computed, this means the * cache won't work for a small set of inputs, but the impact should be minimal for a decent * hash function. Similar technique is used for java String class. */ @Override public int hashCode() { int hash = cachedHashCode.get(); if (hash == 0) { hash = name.hashCode(); hash = 31 * hash + tags.hashCode(); hash = 31 * hash + policy.hashCode(); cachedHashCode.set(hash); } return hash; } /** * {@inheritDoc} */ @Override public String toString() { return "MonitorConfig{name=" + name + ", tags=" + tags + ", policy=" + policy + '}'; } /** * Returns a copy of the current MonitorConfig. */ private MonitorConfig.Builder copy() { return MonitorConfig.builder(name).withTags(tags).withPublishingPolicy(policy); } /** * Returns a copy of the monitor config with an additional tag. */ public MonitorConfig withAdditionalTag(Tag tag) { return copy().withTag(tag).build(); } /** * Returns a copy of the monitor config with additional tags. */ public MonitorConfig withAdditionalTags(TagList newTags) { return copy().withTags(newTags).build(); } }
2,915
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MinGauge.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import java.util.concurrent.atomic.AtomicLong; /** * Gauge that keeps track of the minimum value seen since the last reset. The reset value is * Long.MAX_VALUE. If no update has been received since the last reset, then {@link #getValue} * will return 0. */ public class MinGauge extends AbstractMonitor<Long> implements Gauge<Long> { private final StepLong min; /** * Creates a new instance of the gauge. */ public MinGauge(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } /** * Creates a new instance of the gauge using a specific Clock. Useful for unit testing. */ MinGauge(MonitorConfig config, Clock clock) { super(config.withAdditionalTag(DataSourceType.GAUGE)); min = new StepLong(Long.MAX_VALUE, clock); } private void updateMin(int idx, long v) { AtomicLong current = min.getCurrent(idx); long m = current.get(); while (v < m) { if (current.compareAndSet(m, v)) { break; } m = current.get(); } } /** * Update the min if the provided value is smaller than the current min. */ public void update(long v) { for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { updateMin(i, v); } } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIdx) { long v = min.poll(pollerIdx); return (v == Long.MAX_VALUE) ? 0L : v; } /** * Returns the current min value since the last reset. */ public long getCurrentValue(int nth) { long v = min.getCurrent(nth).get(); return (v == Long.MAX_VALUE) ? 0L : v; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof MinGauge)) { return false; } MinGauge m = (MinGauge) obj; return config.equals(m.getConfig()) && getValue(0).equals(m.getValue(0)); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + getValue(0).hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "MinGauge{config=" + config + ", min=" + min + '}'; } }
2,916
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Throwables; import java.util.concurrent.Callable; /** * A gauge implementation that invokes a specified callable to get the current value. */ public final class BasicGauge<T extends Number> extends AbstractMonitor<T> implements Gauge<T>, SpectatorMonitor { private final MonitorConfig baseConfig; private final Callable<T> function; /** * Creates a new instance of the gauge. * * @param config configuration for this monitor * @param function a function used to fetch the value on demand */ public BasicGauge(MonitorConfig config, Callable<T> function) { super(config.withAdditionalTag(DataSourceType.GAUGE)); this.baseConfig = config; this.function = function; } /** * {@inheritDoc} */ @Override public T getValue(int pollerIndex) { try { return function.call(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { SpectatorContext.polledGauge(baseConfig) .monitorValue(this, m -> m.getValue(0).doubleValue()); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof BasicGauge)) { return false; } BasicGauge m = (BasicGauge) obj; return config.equals(m.getConfig()) && function.equals(m.function); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + function.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BasicGauge{config=" + config + ", function=" + function + '}'; } }
2,917
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DynamicCounter.java
/* * Copyright 2011-2018 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.servo.monitor; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.ExpiringCache; import com.netflix.servo.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.TimeUnit; /** * Utility class that dynamically creates counters based on an arbitrary (name, tagList), or * {@link MonitorConfig}. Counters are automatically expired after 15 minutes of inactivity. */ public final class DynamicCounter extends AbstractMonitor<Long> implements CompositeMonitor<Long>, SpectatorMonitor { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicCounter.class); private static final String DEFAULT_EXPIRATION = "15"; private static final String DEFAULT_EXPIRATION_UNIT = "MINUTES"; private static final String CLASS_NAME = DynamicCounter.class.getCanonicalName(); private static final String EXPIRATION_PROP = CLASS_NAME + ".expiration"; private static final String EXPIRATION_PROP_UNIT = CLASS_NAME + ".expirationUnit"; private static final String INTERNAL_ID = "servoCounters"; private static final MonitorConfig BASE_CONFIG = new MonitorConfig.Builder(INTERNAL_ID).build(); private static final DynamicCounter INSTANCE = new DynamicCounter(); private final ExpiringCache<MonitorConfig, Counter> counters; private DynamicCounter() { super(BASE_CONFIG); final String expiration = System.getProperty(EXPIRATION_PROP, DEFAULT_EXPIRATION); final String expirationUnit = System.getProperty(EXPIRATION_PROP_UNIT, DEFAULT_EXPIRATION_UNIT); final long expirationValue = Long.parseLong(expiration); final TimeUnit expirationUnitValue = TimeUnit.valueOf(expirationUnit); final long expireAfterMs = expirationUnitValue.toMillis(expirationValue); counters = new ExpiringCache<>(expireAfterMs, StepCounter::new); DefaultMonitorRegistry.getInstance().register(this); } private Counter get(final MonitorConfig config) { return counters.get(config); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { } /** * Increment a counter based on a given {@link MonitorConfig}. */ public static void increment(MonitorConfig config) { INSTANCE.get(config).increment(); } /** * Increment a counter specified by a name, and a sequence of (key, value) pairs. */ public static void increment(String name, String... tags) { final MonitorConfig.Builder configBuilder = MonitorConfig.builder(name); Preconditions.checkArgument(tags.length % 2 == 0, "The sequence of (key, value) pairs must have even size: one key, one value"); try { for (int i = 0; i < tags.length; i += 2) { configBuilder.withTag(tags[i], tags[i + 1]); } increment(configBuilder.build()); } catch (IllegalArgumentException e) { LOGGER.warn("Failed to get a counter to increment: {}", e.getMessage()); } } /** * Increment a counter based on a given {@link MonitorConfig} by a given delta. * * @param config The monitoring config * @param delta The amount added to the current value */ public static void increment(MonitorConfig config, long delta) { INSTANCE.get(config).increment(delta); } /** * Increment the counter for a given name, tagList. */ public static void increment(String name, TagList list) { final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build(); increment(config); } /** * Increment the counter for a given name, tagList by a given delta. */ public static void increment(String name, TagList list, long delta) { final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build(); increment(config, delta); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<Monitor<?>> getMonitors() { List list = counters.values(); return (List<Monitor<?>>) list; } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIndex) { return (long) counters.size(); } /** * {@inheritDoc} */ @Override public String toString() { return "DynamicCounter{baseConfig" + BASE_CONFIG + ", totalCounters=" + counters.size() + ", counters=" + counters + '}'; } }
2,918
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Timer.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import java.util.concurrent.TimeUnit; /** * Monitor type for tracking how much time something is taking. */ public interface Timer extends NumericMonitor<Long> { /** * Returns a stopwatch that has been started and will automatically * record its result to this timer when stopped. */ Stopwatch start(); /** * The time unit reported by this timer. */ TimeUnit getTimeUnit(); /** * Record a new value for this timer. * * @deprecated Use record(duration, timeUnit). By always providing a timeUnit to record() * you can have a base time unit of seconds, but * use recordings with timeunit of milliseconds for example. */ @Deprecated void record(long duration); /** * Record a new value that was collected with the given TimeUnit. */ void record(long duration, TimeUnit timeUnit); }
2,919
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DoubleGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.util.concurrent.AtomicDouble; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.spectator.api.Id; /** * A {@link Gauge} that reports a double value. */ public class DoubleGauge extends AbstractMonitor<Double> implements Gauge<Double>, SpectatorMonitor { private final MonitorConfig baseConfig; private final AtomicDouble number; private final SpectatorContext.LazyGauge spectatorGauge; /** * Create a new instance with the specified configuration. * * @param config configuration for this gauge */ public DoubleGauge(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; number = new AtomicDouble(0.0); spectatorGauge = SpectatorContext.gauge(config); } /** * Set the current value. */ public void set(Double n) { spectatorGauge.set(n); number.set(n); } /** * Returns a reference to the {@link com.google.common.util.concurrent.AtomicDouble}. */ public AtomicDouble getNumber() { return number; } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorGauge.setId(id); } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DoubleGauge that = (DoubleGauge) o; return getConfig().equals(that.getConfig()) && getValue().equals(that.getValue()); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); final int n = Double.valueOf(number.get()).hashCode(); result = 31 * result + n; return result; } /** * {@inheritDoc} */ @Override public Double getValue(int pollerIdx) { // we return the actual value at the time of the call and not a reference // to the atomic number so the value doesn't change and is also available to jmx viewers return number.get(); } /** * {@inheritDoc} */ @Override public String toString() { return "DoubleGauge{config=" + config + ", number=" + number + '}'; } }
2,920
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Counter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * Monitor type for tracking how often some event is occurring. */ public interface Counter extends NumericMonitor<Number> { /** * Update the count by one. */ void increment(); /** * Update the count by the specified amount. */ void increment(long amount); }
2,921
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/ResettableCounter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * Counter implementation that keeps track of updates since the last reset. * This class will be removed in the next release. Use a StepCounter directly * if you specifically need the functionality previously provided by this class. * * @deprecated Use Monitors.newCounter() instead to get a default implementation */ @Deprecated public class ResettableCounter extends StepCounter { /** * Creates a new instance. Prefer a {@link com.netflix.servo.monitor.StepCounter} */ public ResettableCounter(MonitorConfig config) { super(config); } /** * Creates a new instance configured for a given polling interval. Note that the 'l' parameter * is ignored. The functionality has been replaced by {@link com.netflix.servo.monitor.Pollers} * and {@link com.netflix.servo.monitor.StepCounter}. * <p/> * Prefer a {@link com.netflix.servo.monitor.StepCounter} */ public ResettableCounter(MonitorConfig config, long l) { super(config); } }
2,922
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MaxGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.spectator.api.Id; import java.util.concurrent.atomic.AtomicLong; /** * Gauge that keeps track of the maximum value seen since the last reset. Updates should be * non-negative, the reset value is 0. */ public class MaxGauge extends AbstractMonitor<Long> implements Gauge<Long>, SpectatorMonitor { private final MonitorConfig baseConfig; private final StepLong max; private final SpectatorContext.LazyGauge spectatorGauge; /** * Creates a new instance of the gauge. */ public MaxGauge(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } /** * Creates a new instance of the gauge using a specific clock. Useful for unit testing. */ MaxGauge(MonitorConfig config, Clock clock) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; max = new StepLong(0L, clock); spectatorGauge = SpectatorContext.maxGauge(config); } /** * Update the max for the given index if the provided value is larger than the current max. */ private void updateMax(int idx, long v) { AtomicLong current = max.getCurrent(idx); long m = current.get(); while (v > m) { if (current.compareAndSet(m, v)) { break; } m = current.get(); } } /** * Update the max if the provided value is larger than the current max. */ public void update(long v) { spectatorGauge.set(v); for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { updateMax(i, v); } } /** * {@inheritDoc} */ @Override public Long getValue(int nth) { return max.poll(nth); } /** * Returns the current max value since the last reset. */ public long getCurrentValue(int nth) { return max.getCurrent(nth).get(); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorGauge.setId(id); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof MaxGauge)) { return false; } MaxGauge m = (MaxGauge) obj; return config.equals(m.getConfig()) && getValue(0).equals(m.getValue(0)); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + getValue(0).hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "MaxGauge{config=" + config + ", max=" + max + '}'; } }
2,923
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Pollers.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.netflix.servo.monitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Poller configuration. This class provides the mechanism * to know how many pollers will be used, and at their estimated polling intervals. */ public final class Pollers { private Pollers() { } /** * A comma separated list of longs indicating the frequency of the pollers. For example: <br/> * {@code 60000, 10000 }<br/> * indicates that the main poller runs every 60s and a secondary * poller will run every 10 seconds. * This is used to deal with monitors that need to get reset after they're polled. * For example a MinGauge or a MaxGauge. */ public static final String POLLERS = System.getProperty("servo.pollers", "60000,10000"); static final long[] DEFAULT_PERIODS = new long[]{60000L, 10000L}; /** * Polling intervals in milliseconds. */ static final long[] POLLING_INTERVALS = parse(POLLERS); private static final List<Long> POLLING_INTERVALS_AS_LIST; /** * Get list of polling intervals in milliseconds. */ public static List<Long> getPollingIntervals() { return POLLING_INTERVALS_AS_LIST; } /** * Number of pollers that will run. */ public static final int NUM_POLLERS = POLLING_INTERVALS.length; /** * For debugging. Simple toString for non-empty arrays */ private static String join(long[] a) { assert (a.length > 0); StringBuilder builder = new StringBuilder(); builder.append(a[0]); for (int i = 1; i < a.length; ++i) { builder.append(','); builder.append(a[i]); } return builder.toString(); } /** * Parse the content of the system property that describes the polling intervals, * and in case of errors * use the default of one poller running every minute. */ static long[] parse(String pollers) { String[] periods = pollers.split(",\\s*"); long[] result = new long[periods.length]; boolean errors = false; Logger logger = LoggerFactory.getLogger(Pollers.class); for (int i = 0; i < periods.length; ++i) { String period = periods[i]; try { result[i] = Long.parseLong(period); if (result[i] <= 0) { logger.error("Invalid polling interval: {} must be positive.", period); errors = true; } } catch (NumberFormatException e) { logger.error("Cannot parse '{}' as a long: {}", period, e.getMessage()); errors = true; } } if (errors || periods.length == 0) { logger.info("Using a default configuration for poller intervals: {}", join(DEFAULT_PERIODS)); return DEFAULT_PERIODS; } else { return result; } } static { List<Long> intervals = new ArrayList<>(POLLING_INTERVALS.length); for (Long interval : POLLING_INTERVALS) { intervals.add(interval); } POLLING_INTERVALS_AS_LIST = Collections.unmodifiableList(intervals); } }
2,924
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/ContextualTimer.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.base.Function; import com.netflix.servo.tag.TaggingContext; import java.util.concurrent.TimeUnit; /** * Composite that maintains separate simple timers for each distinct set of tags returned by the * tagging context. */ public class ContextualTimer extends AbstractContextualMonitor<Long, Timer> implements Timer { /** * Create a new instance of the timer. * * @param config shared configuration * @param context provider for context specific tags * @param newMonitor function to create new timers */ public ContextualTimer( MonitorConfig config, TaggingContext context, Function<MonitorConfig, Timer> newMonitor) { super(config, context, newMonitor); } /** * {@inheritDoc} */ @Override public Stopwatch start() { Stopwatch s = new TimedStopwatch(getMonitorForCurrentContext()); s.start(); return s; } /** * {@inheritDoc} */ @Override public TimeUnit getTimeUnit() { return getMonitorForCurrentContext().getTimeUnit(); } /** * {@inheritDoc} */ @Override @Deprecated public void record(long duration) { Timer monitor = getMonitorForCurrentContext(); monitor.record(duration, monitor.getTimeUnit()); } /** * {@inheritDoc} */ @Override public void record(long duration, TimeUnit timeUnit) { getMonitorForCurrentContext().record(duration, timeUnit); } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIndex) { return getMonitorForCurrentContext().getValue(); } }
2,925
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/NumericMonitorWrapper.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.TagList; /** * Wraps another monitor object providing an alternative configuration. */ class NumericMonitorWrapper<T extends Number> extends MonitorWrapper<T> implements NumericMonitor<T> { /** * Creates a new instance of the wrapper. */ NumericMonitorWrapper(TagList tags, NumericMonitor<T> monitor) { super(tags, monitor); } }
2,926
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DoubleCounter.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.VisibleForTesting; import com.netflix.spectator.api.Id; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; /** * A simple counter implementation backed by a StepLong but using doubles. * The value returned is a rate for the * previous interval as defined by the step. */ class DoubleCounter extends AbstractMonitor<Number> implements NumericMonitor<Number>, SpectatorMonitor { private final MonitorConfig baseConfig; private final StepLong count; private final SpectatorContext.LazyCounter spectatorCounter; /** * Creates a new instance of the counter. */ DoubleCounter(MonitorConfig config, Clock clock) { // This class will reset the value so it is not a monotonically increasing value as // expected for type=COUNTER. This class looks like a counter to the user and a gauge to // the publishing pipeline receiving the value. super(config.withAdditionalTag(DataSourceType.NORMALIZED)); this.baseConfig = config; count = new StepLong(0L, clock); spectatorCounter = SpectatorContext.counter(config); } private void add(AtomicLong num, double amount) { long v; double d; long next; do { v = num.get(); d = Double.longBitsToDouble(v); next = Double.doubleToLongBits(d + amount); } while (!num.compareAndSet(v, next)); } /** * Increment the value by the specified amount. */ void increment(double amount) { spectatorCounter.add(amount); if (amount >= 0.0) { for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { add(count.getCurrent(i), amount); } } } @Override public Number getValue(int pollerIndex) { final long n = count.poll(pollerIndex); final double stepSeconds = Pollers.POLLING_INTERVALS[pollerIndex] / 1000.0; return Double.longBitsToDouble(n) / stepSeconds; } /** * Get the current count for the given poller index. */ @VisibleForTesting public double getCurrentCount(int pollerIndex) { return Double.longBitsToDouble(count.getCurrent(pollerIndex).get()); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorCounter.setId(id); } @Override public String toString() { return "DoubleCounter{" + "config=" + config + "count=" + Double.longBitsToDouble(count.getCurrent(0).longValue()) + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DoubleCounter that = (DoubleCounter) o; return config.equals(that.config) && Objects.equals(getValue(0), that.getValue(0)); } @Override public int hashCode() { return Objects.hash(config, getValue(0)); } }
2,927
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/PeakRateCounter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import java.util.concurrent.atomic.AtomicLong; /** * The value is the maximum count per second within the specified interval. */ public class PeakRateCounter extends AbstractMonitor<Number> implements Counter { private final Clock clock; private final AtomicLong currentSecond = new AtomicLong(); private final AtomicLong currentCount = new AtomicLong(); /** * Creates a counter implementation that records the maximum count per second * within a specific interval. */ public PeakRateCounter(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } private final StepLong peakRate; PeakRateCounter(MonitorConfig config, Clock clock) { super(config.withAdditionalTag(DataSourceType.GAUGE)); this.clock = clock; this.peakRate = new StepLong(0L, clock); } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIdx) { return peakRate.getCurrent(pollerIdx); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof PeakRateCounter)) { return false; } final PeakRateCounter c = (PeakRateCounter) obj; final double v = getValue().doubleValue(); final double otherV = c.getValue().doubleValue(); return config.equals(c.getConfig()) && Double.compare(v, otherV) == 0; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); final long n = Double.doubleToLongBits(getValue().doubleValue()); result = 31 * result + (int) (n ^ (n >>> 32)); return result; } /** * {@inheritDoc} */ public String toString() { return "PeakRateCounter{config=" + config + ", max rate per second=" + getValue() + '}'; } /** * {@inheritDoc} */ @Override public void increment() { increment(1L); } private void updatePeakPoller(int idx, long v) { AtomicLong current = peakRate.getCurrent(idx); long m = current.get(); while (v > m) { if (current.compareAndSet(m, v)) { break; } m = current.get(); } } private void updatePeak(long v) { for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { updatePeakPoller(i, v); } } /** * {@inheritDoc} */ @Override public void increment(long amount) { long now = clock.now() / 1000L; if (now != currentSecond.get()) { currentCount.set(0); currentSecond.set(now); } long count = currentCount.addAndGet(amount); updatePeak(count); } }
2,928
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/CompositeMonitorWrapper.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.TagList; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Wraps another composite monitor object providing an alternative configuration. */ class CompositeMonitorWrapper<T> extends AbstractMonitor<T> implements CompositeMonitor<T>, SpectatorMonitor { private final TagList tags; private final CompositeMonitor<T> monitor; /** * Creates a new instance of the wrapper. */ CompositeMonitorWrapper(TagList tags, CompositeMonitor<T> monitor) { super(monitor.getConfig().withAdditionalTags(tags)); this.tags = tags; this.monitor = monitor; if (monitor instanceof SpectatorMonitor) { ((SpectatorMonitor) monitor).initializeSpectator(tags); } } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { List<Monitor<?>> monitors = monitor.getMonitors(); List<Monitor<?>> wrappedMonitors = new ArrayList<>(monitors.size()); for (Monitor<?> m : monitors) { wrappedMonitors.add(Monitors.wrap(tags, m)); } return Collections.unmodifiableList(wrappedMonitors); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { // This class is only used internally when wrapping a monitor registered with // Monitors.register } /** * {@inheritDoc} */ @Override public T getValue(int pollerIdx) { return monitor.getValue(pollerIdx); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof CompositeMonitorWrapper<?>)) { return false; } @SuppressWarnings("unchecked") CompositeMonitorWrapper<T> m = (CompositeMonitorWrapper<T>) obj; return config.equals(m.getConfig()) && monitor.equals(m.monitor); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + monitor.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "CompositeMonitorWrapper{config=" + config + ", monitor=" + monitor + '}'; } }
2,929
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/PublishingPolicy.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * A publishing policy allows us to customize the behavior of different observers. */ public interface PublishingPolicy { }
2,930
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicTimer.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.UnmodifiableList; import java.util.List; import java.util.concurrent.TimeUnit; /** * A simple timer implementation providing the total time, count, min, and max for the times that * have been recorded. */ public class BasicTimer extends AbstractMonitor<Long> implements Timer, CompositeMonitor<Long>, SpectatorMonitor { private static final String STATISTIC = "statistic"; private static final String UNIT = "unit"; private static final Tag STAT_TOTAL = Tags.newTag(STATISTIC, "totalTime"); private static final Tag STAT_COUNT = Tags.newTag(STATISTIC, "count"); private static final Tag STAT_TOTAL_SQ = Tags.newTag(STATISTIC, "totalOfSquares"); private static final Tag STAT_MAX = Tags.newTag(STATISTIC, "max"); private final TimeUnit timeUnit; private final double timeUnitNanosFactor; private final DoubleCounter totalTime; private final StepCounter count; private final DoubleCounter totalOfSquares; private final DoubleMaxGauge max; private final List<Monitor<?>> monitors; /** * Creates a new instance of the timer with a unit of milliseconds. */ public BasicTimer(MonitorConfig config) { this(config, TimeUnit.MILLISECONDS); } /** * Creates a new instance of the timer. */ BasicTimer(MonitorConfig config, TimeUnit unit, Clock clock) { super(config); final Tag unitTag = Tags.newTag(UNIT, unit.name()); final MonitorConfig unitConfig = config.withAdditionalTag(unitTag); timeUnit = unit; timeUnitNanosFactor = 1.0 / timeUnit.toNanos(1); totalTime = new DoubleCounter(unitConfig.withAdditionalTag(STAT_TOTAL), clock); count = new StepCounter(unitConfig.withAdditionalTag(STAT_COUNT), clock); totalOfSquares = new DoubleCounter(unitConfig.withAdditionalTag(STAT_TOTAL_SQ), clock); max = new DoubleMaxGauge(unitConfig.withAdditionalTag(STAT_MAX), clock); monitors = UnmodifiableList.<Monitor<?>>of(totalTime, count, totalOfSquares, max); } /** * Creates a new instance of the timer. */ public BasicTimer(MonitorConfig config, TimeUnit unit) { this(config, unit, ClockWithOffset.INSTANCE); } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * {@inheritDoc} */ @Override public Stopwatch start() { Stopwatch s = new TimedStopwatch(this); s.start(); return s; } /** * {@inheritDoc} */ @Override public TimeUnit getTimeUnit() { return timeUnit; } private void recordNanos(long nanos) { if (nanos >= 0) { double amount = nanos * timeUnitNanosFactor; totalTime.increment(amount); count.increment(); totalOfSquares.increment(amount * amount); max.update(amount); } } /** * {@inheritDoc} */ @Override @Deprecated public void record(long duration) { long nanos = timeUnit.toNanos(duration); recordNanos(nanos); } /** * {@inheritDoc} */ @Override public void record(long duration, TimeUnit unit) { recordNanos(unit.toNanos(duration)); } private double getTotal(int pollerIndex) { return totalTime.getCurrentCount(pollerIndex); } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIndex) { final long cnt = count.getCurrentCount(pollerIndex); final long value = (long) (getTotal(pollerIndex) / cnt); return (cnt == 0) ? 0L : value; } /** * Get the total time for all updates. */ public Double getTotalTime() { return getTotal(0); } /** * Get the total number of updates. */ public Long getCount() { return count.getCurrentCount(0); } /** * Get the max value since the last reset. */ public Double getMax() { return max.getCurrentValue(0); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { totalTime.initializeSpectator(BasicTagList.concat(tags, STAT_TOTAL)); count.initializeSpectator(BasicTagList.concat(tags, STAT_COUNT)); totalOfSquares.initializeSpectator(BasicTagList.concat(tags, STAT_TOTAL_SQ)); max.initializeSpectator(BasicTagList.concat(tags, STAT_MAX)); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof BasicTimer)) { return false; } BasicTimer m = (BasicTimer) obj; return config.equals(m.getConfig()) && totalTime.equals(m.totalTime) && count.equals(m.count) && totalOfSquares.equals(m.totalOfSquares) && max.equals(m.max); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + totalTime.hashCode(); result = 31 * result + count.hashCode(); result = 31 * result + totalOfSquares.hashCode(); result = 31 * result + max.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BasicTimer{config=" + config + ", totalTime=" + totalTime + ", count=" + count + ", totalOfSquares=" + totalOfSquares + ", max=" + max + '}'; } }
2,931
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MonitorWrapper.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.TagList; /** * Wraps another monitor object providing an alternative configuration. */ class MonitorWrapper<T> extends AbstractMonitor<T> { @SuppressWarnings("unchecked") static <T> MonitorWrapper<T> create(TagList tags, Monitor<T> monitor) { if (monitor instanceof NumericMonitor<?>) { return (MonitorWrapper<T>) ((monitor instanceof SpectatorMonitor) ? new SpectatorMonitorWrapper(tags, (NumericMonitor<?>) monitor) : new NumericMonitorWrapper(tags, (NumericMonitor<?>) monitor)); } else { return new MonitorWrapper<>(tags, monitor); } } private final Monitor<T> monitor; /** * Creates a new instance of the wrapper. */ MonitorWrapper(TagList tags, Monitor<T> monitor) { super(monitor.getConfig().withAdditionalTags(tags)); this.monitor = monitor; } /** * {@inheritDoc} */ @Override public T getValue(int pollerIdx) { return monitor.getValue(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof MonitorWrapper<?>)) { return false; } MonitorWrapper m = (MonitorWrapper) obj; return config.equals(m.getConfig()) && monitor.equals(m.monitor); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + monitor.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "MonitorWrapper{config=" + config + ", monitor=" + monitor + '}'; } }
2,932
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/NumericMonitor.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * A monitor type that has a numeric value. */ public interface NumericMonitor<T extends Number> extends Monitor<T> { }
2,933
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/StepCounter.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.VisibleForTesting; import com.netflix.spectator.api.Id; /** * A simple counter implementation backed by a StepLong. The value returned is a rate for the * previous interval as defined by the step. */ public class StepCounter extends AbstractMonitor<Number> implements Counter, SpectatorMonitor { private final MonitorConfig baseConfig; private final StepLong count; private SpectatorContext.LazyCounter spectatorCounter; /** * Creates a new instance of the counter. */ public StepCounter(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } /** * Creates a new instance of the counter. */ @VisibleForTesting public StepCounter(MonitorConfig config, Clock clock) { // This class will reset the value so it is not a monotonically increasing value as // expected for type=COUNTER. This class looks like a counter to the user and a gauge to // the publishing pipeline receiving the value. super(config.withAdditionalTag(DataSourceType.NORMALIZED)); this.baseConfig = config; count = new StepLong(0L, clock); spectatorCounter = SpectatorContext.counter(config); } /** * {@inheritDoc} */ @Override public void increment() { spectatorCounter.increment(); count.addAndGet(1L); } /** * {@inheritDoc} */ @Override public void increment(long amount) { spectatorCounter.increment(amount); if (amount > 0L) { count.addAndGet(amount); } } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIndex) { final long n = count.poll(pollerIndex); final double stepSeconds = Pollers.POLLING_INTERVALS[pollerIndex] / 1000.0; return n / stepSeconds; } /** * Get the count for the last completed polling interval for the given poller index. */ public long getCount(int pollerIndex) { return count.poll(pollerIndex); } /** * Get the current count for the given poller index. */ @VisibleForTesting public long getCurrentCount(int pollerIndex) { return count.getCurrent(pollerIndex).get(); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorCounter.setId(id); } /** * {@inheritDoc} */ @Override public String toString() { return "StepCounter{config=" + config + ", count=" + count + '}'; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StepCounter that = (StepCounter) o; return config.equals(that.config) && getCount(0) == that.getCount(0); } /** * {@inheritDoc} */ @Override public int hashCode() { return config.hashCode(); } }
2,934
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/MonitoredThreadPool.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import java.util.concurrent.ThreadPoolExecutor; import static com.netflix.servo.annotations.DataSourceType.COUNTER; import static com.netflix.servo.annotations.DataSourceType.GAUGE; /** * Wraps a thread pool to provide common metrics. */ class MonitoredThreadPool { private final ThreadPoolExecutor pool; MonitoredThreadPool(ThreadPoolExecutor pool) { this.pool = pool; } @com.netflix.servo.annotations.Monitor(name = "activeCount", type = GAUGE) int getActiveCount() { return pool.getActiveCount(); } @com.netflix.servo.annotations.Monitor(name = "completedTaskCount", type = COUNTER) long getCompletedTaskCount() { return pool.getCompletedTaskCount(); } @com.netflix.servo.annotations.Monitor(name = "corePoolSize", type = GAUGE) int getCorePoolSize() { return pool.getCorePoolSize(); } @com.netflix.servo.annotations.Monitor(name = "maximumPoolSize", type = GAUGE) int getMaximumPoolSize() { return pool.getMaximumPoolSize(); } @com.netflix.servo.annotations.Monitor(name = "poolSize", type = GAUGE) int getPoolSize() { return pool.getPoolSize(); } @com.netflix.servo.annotations.Monitor(name = "queueSize", type = GAUGE) int getQueueSize() { return pool.getQueue().size(); } @com.netflix.servo.annotations.Monitor(name = "taskCount", type = COUNTER) long getTaskCount() { return pool.getTaskCount(); } }
2,935
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicCompositeMonitor.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.util.UnmodifiableList; import java.util.List; /** * Simple composite monitor type with a static list of sub-monitors. The value for the composite * is the number of sub-monitors. */ public final class BasicCompositeMonitor extends AbstractMonitor<Integer> implements CompositeMonitor<Integer> { private final List<Monitor<?>> monitors; /** * Create a new composite. * * @param config configuration for the composite. It is recommended that the configuration * shares common tags with the sub-monitors, but it is not enforced. * @param monitors list of sub-monitors */ public BasicCompositeMonitor(MonitorConfig config, List<Monitor<?>> monitors) { super(config); this.monitors = UnmodifiableList.copyOf(monitors); } /** * {@inheritDoc} */ @Override public Integer getValue(int pollerIdx) { return monitors.size(); } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof BasicCompositeMonitor)) { return false; } BasicCompositeMonitor m = (BasicCompositeMonitor) obj; return config.equals(m.getConfig()) && monitors.equals(m.getMonitors()); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + monitors.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BasicCompositeMonitor{config=" + config + ", monitors=" + monitors + '}'; } }
2,936
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BucketConfig.java
/* * Copyright 2014 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.servo.monitor; import com.netflix.servo.util.Preconditions; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * Configuration options for buckets for a {@link BucketTimer} * <p/> * For example: * <p/> * <pre> * BucketConfig cfg = new BucketConfig.Builder().withBuckets(new long[]{10L, 20L}).build()); * </pre> * <p/> * will create a configuration that will report buckets for &lt;= 10ms, (10ms, 20ms], and higher * than 20ms. The default timeUnit is milliseconds but can be changed using the * {@link BucketConfig.Builder#withTimeUnit(TimeUnit)} method. * <p/> * <p> * The user must specify buckets otherwise a {@link NullPointerException} will be generated. * </p> * <p/> * See {@link BucketTimer} for more details. */ public final class BucketConfig { /** * Helper class for constructing BucketConfigs. */ public static class Builder { private TimeUnit timeUnit = TimeUnit.MILLISECONDS; private long[] buckets = null; /** * Sets the timeUnit for the buckets. */ public Builder withTimeUnit(TimeUnit timeUnit) { this.timeUnit = Preconditions.checkNotNull(timeUnit, "timeUnit"); return this; } /** * Sets the buckets to be used. * <p/> * <p><ul> * <li>Each bucket must be unique. * <li>Buckets must be in ascending order (smallest-to-largest). * <li>All bucket counts will be namespaced under the "servo.bucket" tag. * <li>Buckets are incremented in the following way: Given a set of n * ordered buckets, let n1 = the first bucket. If a given duration is * less than or equal to n1, the counter for n1 is incremented; else * perform the same check on n2, n3, etc. If the duration is greater * the largest bucket, it is added to the 'overflow' bucket. The overflow * bucket is automatically created. * </ul> */ public Builder withBuckets(long[] buckets) { Preconditions.checkNotNull(buckets, "buckets"); this.buckets = Arrays.copyOf(buckets, buckets.length); Preconditions.checkArgument(this.buckets.length > 0, "buckets cannot be empty"); Preconditions.checkArgument(isAscending(this.buckets), "buckets must be in ascending order"); return this; } private boolean isAscending(long[] values) { long last = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] <= last) { return false; } last = values[i]; } return true; } /** * Builds a new {@link com.netflix.servo.monitor.BucketConfig}. */ public BucketConfig build() { return new BucketConfig(this); } } private final TimeUnit timeUnit; private final long[] buckets; BucketConfig(Builder builder) { this.timeUnit = builder.timeUnit; this.buckets = Arrays.copyOf(builder.buckets, builder.buckets.length); } /** * Get the TimeUnit of the buckets. */ public TimeUnit getTimeUnit() { return timeUnit; } /** * Returns an abbreviation for the Bucket's TimeUnit. */ public String getTimeUnitAbbreviation() { switch (timeUnit) { case DAYS: return "day"; case HOURS: return "hr"; case MICROSECONDS: return "\u00B5s"; case MILLISECONDS: return "ms"; case MINUTES: return "min"; case NANOSECONDS: return "ns"; case SECONDS: return "s"; default: return "unkwn"; } } /** * Get a copy of the array that holds the bucket values. */ public long[] getBuckets() { return Arrays.copyOf(buckets, buckets.length); } /** * {@inheritDoc} */ @Override public String toString() { return "BucketConfig{timeUnit=" + timeUnit + ", buckets=" + Arrays.toString(buckets) + '}'; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BucketConfig)) { return false; } final BucketConfig that = (BucketConfig) o; return timeUnit == that.timeUnit && Arrays.equals(buckets, that.buckets); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = timeUnit.hashCode(); result = 31 * result + Arrays.hashCode(buckets); return result; } }
2,937
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/Monitor.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; /** * Provides a way to sample a value tied to a particular configuration. */ public interface Monitor<T> { /** * Returns the current value for the monitor for the default polling interval. */ T getValue(); /** * Returns the current value for the monitor for the nth poller. */ T getValue(int pollerIndex); /** * Configuration used to identify a monitor and provide metadata used in aggregations. */ MonitorConfig getConfig(); }
2,938
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicCounter.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import java.util.concurrent.atomic.AtomicLong; /** * A simple counter implementation backed by an {@link java.util.concurrent.atomic.AtomicLong}. * The value is the total count for the life of the counter. Observers are responsible * for converting to a rate and handling overflows if they occur. */ public final class BasicCounter extends AbstractMonitor<Number> implements Counter, SpectatorMonitor { private final MonitorConfig baseConfig; private final AtomicLong count = new AtomicLong(); private final SpectatorContext.LazyCounter spectatorCounter; /** * Creates a new instance of the counter. */ public BasicCounter(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.COUNTER)); this.baseConfig = config; spectatorCounter = SpectatorContext.counter(config); } /** * {@inheritDoc} */ @Override public void increment() { spectatorCounter.increment(); count.incrementAndGet(); } /** * {@inheritDoc} */ @Override public void increment(long amount) { spectatorCounter.increment(amount); count.getAndAdd(amount); } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIdx) { return count.get(); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { spectatorCounter.setId(SpectatorContext.createId(baseConfig.withAdditionalTags(tags))); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof BasicCounter)) { return false; } BasicCounter m = (BasicCounter) obj; return config.equals(m.getConfig()) && count.get() == m.count.get(); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); long n = count.get(); result = 31 * result + (int) (n ^ (n >>> 32)); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BasicCounter{config=" + config + ", count=" + count.get() + '}'; } }
2,939
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/CompositeMonitor.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import java.util.List; /** * Used as a mixin for monitors that are composed of a number of sub-monitors. */ public interface CompositeMonitor<T> extends Monitor<T> { /** * Returns a list of sub-monitors for this composite. */ List<Monitor<?>> getMonitors(); }
2,940
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java
/* * Copyright 2011-2018 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.servo.monitor; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.ExpiringCache; import com.netflix.servo.util.Preconditions; import java.util.List; import java.util.concurrent.TimeUnit; /** * Utility class that dynamically creates {@link BasicTimer}s based on an arbitrary * (name, tagList), or {@link MonitorConfig}. Timers are automatically expired after 15 minutes of * inactivity. */ public final class DynamicTimer extends AbstractMonitor<Long> implements CompositeMonitor<Long>, SpectatorMonitor { private static final String DEFAULT_EXPIRATION = "15"; private static final String DEFAULT_EXPIRATION_UNIT = "MINUTES"; private static final String CLASS_NAME = DynamicTimer.class.getCanonicalName(); private static final String EXPIRATION_PROP = CLASS_NAME + ".expiration"; private static final String EXPIRATION_PROP_UNIT = CLASS_NAME + ".expirationUnit"; private static final String INTERNAL_ID = "servoTimers"; private static final MonitorConfig BASE_CONFIG = new MonitorConfig.Builder(INTERNAL_ID).build(); private static final DynamicTimer INSTANCE = new DynamicTimer(); private final ExpiringCache<ConfigUnit, Timer> timers; static class ConfigUnit { private final MonitorConfig config; private final TimeUnit unit; ConfigUnit(MonitorConfig config, TimeUnit unit) { this.config = config; this.unit = unit; } MonitorConfig getConfig() { return config; } TimeUnit getUnit() { return unit; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ConfigUnit that = (ConfigUnit) o; return config.equals(that.config) && unit == that.unit; } @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + unit.hashCode(); return result; } } private DynamicTimer() { super(BASE_CONFIG); final String expiration = System.getProperty(EXPIRATION_PROP, DEFAULT_EXPIRATION); final String expirationUnit = System.getProperty(EXPIRATION_PROP_UNIT, DEFAULT_EXPIRATION_UNIT); final long expirationValue = Long.parseLong(expiration); final TimeUnit expirationUnitValue = TimeUnit.valueOf(expirationUnit); final long expireAfterMs = expirationUnitValue.toMillis(expirationValue); timers = new ExpiringCache<>(expireAfterMs, this::newTimer); DefaultMonitorRegistry.getInstance().register(this); } private BasicTimer newTimer(ConfigUnit configUnit) { return new BasicTimer(configUnit.config, configUnit.unit); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { } private Timer get(MonitorConfig config, TimeUnit unit) { return timers.get(new ConfigUnit(config, unit)); } /** * Returns a stopwatch that has been started and will automatically * record its result to the dynamic timer specified by the given config. * * @param config Config to identify a particular timer instance to update. * @param unit The unit to use when reporting values to observers. For example if sent to * a typical time series graphing system this would be the unit for the y-axis. * It is generally recommended to use base units for reporting, so * {@link TimeUnit#SECONDS} is the preferred value. */ public static Stopwatch start(MonitorConfig config, TimeUnit unit) { return INSTANCE.get(config, unit).start(); } /** * Returns a stopwatch that has been started and will automatically * record its result to the dynamic timer specified by the given config. The timer * will report the times in milliseconds to observers. * * @see #start(MonitorConfig, TimeUnit) */ public static Stopwatch start(MonitorConfig config) { return INSTANCE.get(config, TimeUnit.MILLISECONDS).start(); } /** * Record result to the dynamic timer indicated by the provided config * with a TimeUnit of milliseconds. */ public static void record(MonitorConfig config, long duration) { INSTANCE.get(config, TimeUnit.MILLISECONDS).record(duration, TimeUnit.MILLISECONDS); } /** * Record a duration to the dynamic timer indicated by the provided config. * The units in which the timer is reported and the duration unit are the same. * * @deprecated Use {@link DynamicTimer#record(MonitorConfig, java.util.concurrent.TimeUnit, * long, java.util.concurrent.TimeUnit)} instead. * The new method allows you to be specific about the units used for reporting the timer and * the units in which the duration is measured. */ public static void record(MonitorConfig config, long duration, TimeUnit unit) { INSTANCE.get(config, unit).record(duration, unit); } /** * Record a duration to the dynamic timer indicated by the provided config/reportUnit. * * @param config Config to identify a particular timer instance to update. * @param reportUnit The unit to use when reporting values to observers. For example if sent to * a typical time series graphing system this would be the unit * for the y-axis. * It is generally recommended to use base units for reporting, so * {@link TimeUnit#SECONDS} is the preferred value. * @param duration Measured duration to record. * @param durationUnit Unit for the measured duration. This should typically be the unit used for * timing source. For example if using {@link System#nanoTime()} * the unit would be nanoseconds. */ public static void record(MonitorConfig config, TimeUnit reportUnit, long duration, TimeUnit durationUnit) { INSTANCE.get(config, reportUnit).record(duration, durationUnit); } /** * Returns a stopwatch that has been started and will automatically * record its result to the dynamic timer specified by the given name, and sequence of (key, * value) pairs. The timer uses a TimeUnit of milliseconds. */ public static Stopwatch start(String name, String... tags) { final MonitorConfig.Builder configBuilder = MonitorConfig.builder(name); Preconditions.checkArgument(tags.length % 2 == 0, "The sequence of (key, value) pairs must have even size: one key, one value"); for (int i = 0; i < tags.length; i += 2) { configBuilder.withTag(tags[i], tags[i + 1]); } return INSTANCE.get(configBuilder.build(), TimeUnit.MILLISECONDS).start(); } /** * Returns a stopwatch that has been started and will automatically * record its result to the dynamic timer specified by the given config. The timer * uses a TimeUnit of milliseconds. */ public static Stopwatch start(String name, TagList list) { final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build(); return INSTANCE.get(config, TimeUnit.MILLISECONDS).start(); } /** * Returns a stopwatch that has been started and will automatically * record its result to the dynamic timer specified by the given config. The timer * uses a TimeUnit of milliseconds. */ public static Stopwatch start(String name, TagList list, TimeUnit unit) { final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build(); return INSTANCE.get(config, unit).start(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<Monitor<?>> getMonitors() { List list = timers.values(); return (List<Monitor<?>>) list; } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIdx) { return (long) timers.size(); } /** * {@inheritDoc} */ @Override public String toString() { return "DynamicCounter{baseConfig" + BASE_CONFIG + ", totalTimers=" + timers.size() + ", timers=" + timers + '}'; } }
2,941
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/AnnotatedNumberMonitor.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Throwables; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Wraps an annotated field and exposes it as a numeric monitor object. */ class AnnotatedNumberMonitor extends AbstractMonitor<Number> implements NumericMonitor<Number>, SpectatorMonitor { private final Object object; private final AccessibleObject field; AnnotatedNumberMonitor(MonitorConfig config, Object object, AccessibleObject field) { super(config); this.object = object; this.field = field; if ("COUNTER".equals(config.getTags().getValue("type"))) { SpectatorContext.polledGauge(config) .monitorMonotonicCounter(this, m -> m.getValue(0).longValue()); } else { SpectatorContext.polledGauge(config) .monitorValue(this, m -> m.getValue(0).doubleValue()); } } /** * {@inheritDoc} */ @Override public Number getValue(int pollerIdx) { try { field.setAccessible(true); if (field instanceof Field) { return (Number) ((Field) field).get(object); } else { return (Number) ((Method) field).invoke(object); } } catch (Exception e) { throw Throwables.propagate(e); } } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof AnnotatedNumberMonitor)) { return false; } AnnotatedNumberMonitor m = (AnnotatedNumberMonitor) obj; return config.equals(m.getConfig()) && field.equals(m.field); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + field.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "AnnotatedNumberMonitor{config=" + config + ", field=" + field + '}'; } }
2,942
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/AbstractMonitor.java
/* * Copyright 2014 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.servo.monitor; import com.netflix.servo.util.Preconditions; /** * Base type to simplify implementing monitors. */ public abstract class AbstractMonitor<T> implements Monitor<T> { protected final MonitorConfig config; /** * Create a new instance with the specified configuration. */ protected AbstractMonitor(MonitorConfig config) { this.config = Preconditions.checkNotNull(config, "config"); } /** * {@inheritDoc} */ @Override public MonitorConfig getConfig() { return config; } /** * {@inheritDoc} */ @Override public T getValue() { return getValue(0); } }
2,943
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/AbstractContextualMonitor.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.google.common.base.Function; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.TaggingContext; import com.netflix.servo.util.UnmodifiableList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Base class used to simplify creation of contextual monitors. */ public abstract class AbstractContextualMonitor<T, M extends Monitor<T>> implements CompositeMonitor<T>, SpectatorMonitor { /** * Base configuration shared across all contexts. */ protected final MonitorConfig baseConfig; /** * Additional tags to add to spectator monitors. */ protected TagList spectatorTags = BasicTagList.EMPTY; /** * Context to query when accessing a monitor. */ protected final TaggingContext context; /** * Factory function used to create a new instance of a monitor. */ protected final Function<MonitorConfig, M> newMonitor; /** * Thread-safe map keeping track of the distinct monitors that have been created so far. */ protected final ConcurrentMap<MonitorConfig, M> monitors; /** * Create a new instance of the monitor. * * @param baseConfig shared configuration * @param context provider for context specific tags * @param newMonitor function to create new monitors */ protected AbstractContextualMonitor( MonitorConfig baseConfig, TaggingContext context, Function<MonitorConfig, M> newMonitor) { this.baseConfig = baseConfig; this.context = context; this.newMonitor = newMonitor; monitors = new ConcurrentHashMap<>(); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { spectatorTags = tags; } /** * {@inheritDoc} */ @Override public T getValue() { return getValue(0); } /** * Returns a monitor instance for the current context. If no monitor exists for the current * context then a new one will be created. */ protected M getMonitorForCurrentContext() { MonitorConfig contextConfig = getConfig(); M monitor = monitors.get(contextConfig); if (monitor == null) { M newMon = newMonitor.apply(contextConfig); if (newMon instanceof SpectatorMonitor) { ((SpectatorMonitor) newMon).initializeSpectator(spectatorTags); } monitor = monitors.putIfAbsent(contextConfig, newMon); if (monitor == null) { monitor = newMon; } } return monitor; } /** * {@inheritDoc} */ @Override public MonitorConfig getConfig() { TagList contextTags = context.getTags(); return MonitorConfig.builder(baseConfig.getName()) .withTags(baseConfig.getTags()) .withTags(contextTags) .build(); } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return UnmodifiableList.<Monitor<?>>copyOf(monitors.values()); } }
2,944
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/SpectatorMonitor.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.tag.TagList; /** * Indicates that the monitor implementation will automatically update the spectator * registry defined in {@code SpectatorContext}. Other monitors need to get polled and * update the registry. */ public interface SpectatorMonitor { /** * Servo registration can add tags based on the context. This method will be called * during the registration to apply that context to the underlying Spectator ids. */ void initializeSpectator(TagList tags); }
2,945
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/package-info.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * <p/> * Subinterfaces and implementations for {@link com.netflix.servo.monitor.Monitor}. * <p/> * Subinterfaces and implementations for {@link com.netflix.servo.monitor.Monitor}. * <p/> * Subinterfaces and implementations for {@link com.netflix.servo.monitor.Monitor}. */ /** * Subinterfaces and implementations for {@link com.netflix.servo.monitor.Monitor}. */ package com.netflix.servo.monitor;
2,946
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BasicStopwatch.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * This class does not enforce starting or stopping once and only once without a reset. */ public class BasicStopwatch implements Stopwatch { private final AtomicLong startTime = new AtomicLong(0L); private final AtomicLong endTime = new AtomicLong(0L); private final AtomicBoolean running = new AtomicBoolean(false); /** * {@inheritDoc} */ @Override public void start() { startTime.set(System.nanoTime()); running.set(true); } /** * {@inheritDoc} */ @Override public void stop() { endTime.set(System.nanoTime()); running.set(false); } /** * {@inheritDoc} */ @Override public void reset() { startTime.set(0L); endTime.set(0L); running.set(false); } /** * {@inheritDoc} */ @Override public long getDuration(TimeUnit timeUnit) { return timeUnit.convert(getDuration(), TimeUnit.NANOSECONDS); } /** * Returns the duration in nanoseconds. No checks are performed to ensure that the stopwatch * has been properly started and stopped before executing this method. If called before stop * it will return the current duration. */ @Override public long getDuration() { final long end = running.get() ? System.nanoTime() : endTime.get(); return end - startTime.get(); } }
2,947
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/LongGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.spectator.api.Id; import java.util.concurrent.atomic.AtomicLong; /** * A {@link Gauge} that reports a long value. */ public class LongGauge extends AbstractMonitor<Long> implements Gauge<Long>, SpectatorMonitor { private final MonitorConfig baseConfig; private final AtomicLong number; private final SpectatorContext.LazyGauge spectatorGauge; /** * Create a new instance with the specified configuration. * * @param config configuration for this gauge */ public LongGauge(MonitorConfig config) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; number = new AtomicLong(0L); spectatorGauge = SpectatorContext.gauge(config); } /** * Set the current value. */ public void set(Long n) { spectatorGauge.set(n); AtomicLong number = getNumber(); number.set(n); } /** * Returns a reference to the {@link java.util.concurrent.atomic.AtomicLong}. */ public AtomicLong getNumber() { return number; } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorGauge.setId(id); } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LongGauge that = (LongGauge) o; return getConfig().equals(that.getConfig()) && getValue(0).equals(that.getValue(0)); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + getValue(0).hashCode(); return result; } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIdx) { // we return the actual value at the time of the call and not a reference // to the atomic number so the value doesn't change and is also available to jmx viewers return number.get(); } /** * {@inheritDoc} */ @Override public String toString() { return "LongGauge{config=" + config + ", number=" + number + '}'; } }
2,948
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/DoubleMaxGauge.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.monitor; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.spectator.api.Id; import java.util.concurrent.atomic.AtomicLong; /** * Gauge that keeps track of the maximum value seen since the last reset. Updates should be * non-negative, the reset value is 0. */ public class DoubleMaxGauge extends AbstractMonitor<Double> implements Gauge<Double>, SpectatorMonitor { private final MonitorConfig baseConfig; private final StepLong max; private final SpectatorContext.LazyGauge spectatorGauge; /** * Creates a new instance of the gauge. */ public DoubleMaxGauge(MonitorConfig config) { this(config, ClockWithOffset.INSTANCE); } /** * Creates a new instance of the gauge using a specific clock. Useful for unit testing. */ DoubleMaxGauge(MonitorConfig config, Clock clock) { super(config.withAdditionalTag(DataSourceType.GAUGE)); baseConfig = config; max = new StepLong(Double.doubleToLongBits(0.0), clock); spectatorGauge = SpectatorContext.maxGauge(config); } /** * Update the max for the given index if the provided value is larger than the current max. */ private void updateMax(int idx, double v) { AtomicLong current = max.getCurrent(idx); long m = current.get(); while (v > Double.longBitsToDouble(m)) { if (current.compareAndSet(m, Double.doubleToLongBits(v))) { break; } m = current.get(); } } /** * Update the max if the provided value is larger than the current max. */ public void update(double v) { spectatorGauge.set(v); for (int i = 0; i < Pollers.NUM_POLLERS; ++i) { updateMax(i, v); } } /** * {@inheritDoc} */ @Override public Double getValue(int nth) { return Double.longBitsToDouble(max.poll(nth)); } /** * Returns the current max value since the last reset. */ public double getCurrentValue(int nth) { return Double.longBitsToDouble(max.getCurrent(nth).get()); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { Id id = SpectatorContext.createId(baseConfig.withAdditionalTags(tags)); spectatorGauge.setId(id); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof DoubleMaxGauge)) { return false; } DoubleMaxGauge m = (DoubleMaxGauge) obj; return config.equals(m.getConfig()) && getValue(0).equals(m.getValue(0)); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getConfig().hashCode(); result = 31 * result + getValue(0).hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "MaxGauge{config=" + config + ", max=" + max + '}'; } }
2,949
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Preconditions.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; /** * Internal convenience methods that help a method or constructor check whether it was invoked * correctly. Please notice that this should be considered an internal implementation detail, and * it is subject to change without notice. */ public final class Preconditions { private Preconditions() { } /** * Ensures the object reference is not null. */ public static <T> T checkNotNull(T obj, String name) { if (obj == null) { String msg = String.format("parameter '%s' cannot be null", name); throw new NullPointerException(msg); } return obj; } /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, String errorMessage) { checkArgument(expression, errorMessage, (String) null); } /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * * @param expression a boolean expression * @param errorMessage the error message that can be a formattable string * @param arg argument if using a formatted string * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, String errorMessage, String arg) { if (!expression) { if (arg != null) { String message = String.format(errorMessage, arg); throw new IllegalArgumentException(message); } else { throw new IllegalArgumentException(errorMessage); } } } /** * Ensures the truth of an expression involving one or more parameters to the * calling method. * * * @param expression a boolean expression * @param errorMessage the error message that can be a formattable string * @param args arguments if using a formatted string * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, String errorMessage, String... args) { if (!expression) { if (args != null && args.length > 0) { String message = String.format(errorMessage, args); throw new IllegalArgumentException(message); } else { throw new IllegalArgumentException(errorMessage); } } } }
2,950
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Iterables.java
/* * Copyright 2014 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.servo.util; import java.util.ArrayList; import java.util.List; /** * Utility class for dealing with Iterables. For internal use of servo only. */ public final class Iterables { private Iterables() { } /** * Creates a new {@link Iterable} by concatenating two iterables. */ public static <E> Iterable<E> concat(Iterable<E> a, Iterable<E> b) { List<E> result = new ArrayList<>(); for (E e : a) { result.add(e); } for (E e : b) { result.add(e); } return result; } }
2,951
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Objects.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; import java.util.Arrays; /** * Utility methods for dealing with objects. */ public final class Objects { /** * Generates a hash code for a sequence of input values. * * @param values the values to be hashed * @return a hash value of the sequence of input values */ public static int hash(Object... values) { return Arrays.hashCode(values); } private Objects() { } }
2,952
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/ClockWithOffset.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; /** * A {@link Clock} that provides a way to modify the time returned by * {@link System#currentTimeMillis()}. * <p/> * This can be used during application shutdown to force the clock forward and get the * latest values which normally * would not be returned until the next step boundary is crossed. */ public enum ClockWithOffset implements Clock { /** * Singleton. */ INSTANCE; private volatile long offset = 0L; /** * Sets the offset for the clock. * * @param offset Number of milliseconds to add to the current time. */ public void setOffset(long offset) { if (offset >= 0) { this.offset = offset; } } /** * {@inheritDoc} */ @Override public long now() { return offset + System.currentTimeMillis(); } }
2,953
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/TimeLimiter.java
/* * Copyright 2014 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.servo.util; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Invoke a callable aborting after a certain timout. */ public final class TimeLimiter { private final ExecutorService executor; /** * Create a new TimeLimiter that will use the provided executor to invoke the Callable. * * @param executor {@link ExecutorService} used to invoke the callable */ public TimeLimiter(ExecutorService executor) { this.executor = Preconditions.checkNotNull(executor, "executor"); } /** * Invokes a specified Callable, timing out after the specified time limit. * If the target method call finished before the limit is reached, the return * value or exception is propagated to the caller exactly as-is. If, on the * other hand, the time limit is reached, we attempt to abort the call to the * Callable and throw an exception. */ public <T> T callWithTimeout(Callable<T> callable, long duration, TimeUnit unit) throws Exception { Future<T> future = executor.submit(callable); try { return future.get(duration, unit); } catch (InterruptedException e) { future.cancel(true); throw e; } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause == null) { cause = e; } if (cause instanceof Exception) { throw (Exception) cause; } if (cause instanceof Error) { throw (Error) cause; } throw e; } catch (TimeoutException e) { future.cancel(true); throw new UncheckedTimeoutException(e); } } /** * Unchecked version of {@link java.util.concurrent.TimeoutException}. */ public static class UncheckedTimeoutException extends RuntimeException { /** * Create a new instance with a given cause. */ public UncheckedTimeoutException(Exception cause) { super(cause); } } }
2,954
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/UnmodifiableList.java
/* * Copyright 2014 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.servo.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Utility class to create umodifiable views for lists. */ public final class UnmodifiableList { private UnmodifiableList() { } /** * Returns an unmodifiable view of the list composed of elements. * * @param elements Array of elements. * @param <E> Type of the elements of the list. * @return an unmodifiable view of the list composed of elements. */ @SafeVarargs public static <E> List<E> of(E... elements) { Preconditions.checkNotNull(elements, "elements"); return Collections.unmodifiableList(Arrays.asList(elements)); } /** * Returns an unmodifiable view of the list composed of elements. * * @param elements Array of elements. * @param <E> Type of the elements of the list. * @return an unmodifiable view of the list composed of elements. */ public static <E> List<E> copyOf(E[] elements) { Preconditions.checkNotNull(elements, "elements"); List<E> result = new ArrayList<>(elements.length); Collections.addAll(result, elements); return Collections.unmodifiableList(result); } // hack to simplify casting static <T> Collection<T> cast(Iterable<T> iterable) { return (Collection<T>) iterable; } /** * Returns an unmodifiable view of the list composed of elements. * * @param elements Iterable of elements. * @param <E> Type of the elements of the list. * @return an unmodifiable view of the list composed of elements. */ public static <E> List<E> copyOf(Iterable<? extends E> elements) { Preconditions.checkNotNull(elements, "elements"); List<E> result = (elements instanceof Collection) // can pre-allocate the array ? new ArrayList<>(cast(elements).size()) // cannot : new ArrayList<>(); for (E e : elements) { result.add(e); } return Collections.unmodifiableList(result); } }
2,955
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Reflection.java
/** * Copyright 2018 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Utility methods for dealing with reflection. */ public final class Reflection { private Reflection() { } /** * Gets all fields from class and its super classes. * * @param classs class to get fields from * @return set of fields */ public static Set<Field> getAllFields(Class<?> classs) { Set<Field> set = new HashSet<>(); Class<?> c = classs; while (c != null) { set.addAll(Arrays.asList(c.getDeclaredFields())); c = c.getSuperclass(); } return set; } /** * Gets all methods from class and its super classes. * * @param classs class to get methods from * @return set of methods */ public static Set<Method> getAllMethods(Class<?> classs) { Set<Method> set = new HashSet<>(); Class<?> c = classs; while (c != null) { set.addAll(Arrays.asList(c.getDeclaredMethods())); c = c.getSuperclass(); } return set; } /** * Gets all fields annotated by annotation. * * @param classs class to get fields from * @param ann annotation that must be present on the field * @return set of fields */ public static Set<Field> getFieldsAnnotatedBy(Class<?> classs, Class<? extends Annotation> ann) { Set<Field> set = new HashSet<>(); for (Field field : getAllFields(classs)) { if (field.isAnnotationPresent(ann)) { set.add(field); } } return set; } /** * Gets all methods annotated by annotation. * * @param classs class to get fields from * @param ann annotation that must be present on the method * @return set of methods */ public static Set<Method> getMethodsAnnotatedBy( Class<?> classs, Class<? extends Annotation> ann) { Set<Method> set = new HashSet<>(); for (Method method : getAllMethods(classs)) { if (method.isAnnotationPresent(ann)) { set.add(method); } } return set; } }
2,956
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; /** * Keep track of the cpu usage for threads in the jvm. */ public final class ThreadCpuStats { private static final Logger LOGGER = LoggerFactory.getLogger(ThreadCpuStats.class); private static final ThreadCpuStats INSTANCE = new ThreadCpuStats(); private static final long ONE_MINUTE_NANOS = TimeUnit.NANOSECONDS.convert(1, TimeUnit.MINUTES); private static final long FIVE_MINUTE_NANOS = 5 * ONE_MINUTE_NANOS; private static final long FIFTEEN_MINUTE_NANOS = 15 * ONE_MINUTE_NANOS; /** * Constant representing one minute. */ public static final String ONE_MIN = "one_min"; /** * Constant representing five minutes. */ public static final String FIVE_MIN = "five_min"; /** * Constant representing fifteen minutes. */ public static final String FIFTEEN_MIN = "fifteen_min"; /** * Constant representing the overall time. */ public static final String OVERALL = "overall"; /** * Current time in milliseconds. */ public static final String CURRENT_TIME = "time_ms"; /** * uptime in milliseconds. */ public static final String UPTIME_MS = "uptime_ms"; /** * JVM usage time in nanoseconds. */ public static final String JVM_USAGE_TIME = "jvm_usage_time_ns"; /** * JVM usage as a percentage. */ public static final String JVM_USAGE_PERCENT = "jvm_usage_percent"; /** * Thread ID. */ public static final String ID = "id"; /** * Thread name. */ public static final String NAME = "name"; /** * Threads. */ public static final String THREADS = "threads"; private volatile boolean running = false; private final CpuUsage jvmCpuUsage = new CpuUsage(-1, "jvm"); private final Map<Long, CpuUsage> threadCpuUsages = new ConcurrentHashMap<>(); /** * Return the singleton instance. */ public static ThreadCpuStats getInstance() { return INSTANCE; } /** * Creates a new instance. */ private ThreadCpuStats() { } /** * Returns true if cpu status are currently being collected. */ public boolean isRunning() { return false; } /** * Start collecting cpu stats for the threads. */ public synchronized void start() { if (!running) { running = true; Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector"); t.setDaemon(true); t.start(); } } /** * Stop collecting cpu stats for the threads. */ public void stop() { running = false; } /** * Overall usage for the jvm. */ public CpuUsage getOverallCpuUsage() { return jvmCpuUsage; } /** * List of cpu usages for each thread. */ public List<CpuUsage> getThreadCpuUsages() { return new ArrayList<>(threadCpuUsages.values()); } /** * Helper function for computing percentage. */ public static double toPercent(long value, long total) { return (total > 0) ? 100.0 * value / total : 0.0; } private static long append(StringBuilder buf, char label, long unit, long time) { if (time > unit) { long multiple = time / unit; buf.append(multiple).append(label); return time % unit; } else { return time; } } /** * Convert time in nanoseconds to a duration string. This is used to provide a more human * readable order of magnitude for the duration. We assume standard fixed size quantities for * all units. */ public static String toDuration(long inputTime) { final long second = 1000000000L; final long minute = 60 * second; final long hour = 60 * minute; final long day = 24 * hour; final long week = 7 * day; long time = inputTime; final StringBuilder buf = new StringBuilder(); buf.append('P'); time = append(buf, 'W', week, time); time = append(buf, 'D', day, time); buf.append('T'); time = append(buf, 'H', hour, time); time = append(buf, 'M', minute, time); append(buf, 'S', second, time); return buf.toString(); } /** * Utility function that dumps the cpu usages for the threads to stdout. Output will be sorted * based on the 1-minute usage from highest to lowest. */ public void printThreadCpuUsages() { printThreadCpuUsages(System.out, CpuUsageComparator.ONE_MINUTE); } private static PrintWriter getPrintWriter(OutputStream out) { try { return new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true); } catch (UnsupportedEncodingException e) { // should never happen throw Throwables.propagate(e); } } /** * Utility function that returns a Map containing cpu usages for threads. Output will be sorted * based on the {@link CpuUsageComparator} passed. * * @param cmp order to use for the results */ public Map<String, Object> getThreadCpuUsages(CpuUsageComparator cmp) { final CpuUsage overall = getOverallCpuUsage(); final List<CpuUsage> usages = getThreadCpuUsages(); final Map<String, Object> result = new HashMap<>(); Collections.sort(usages, cmp); final Date now = new Date(); result.put(CURRENT_TIME, now.getTime()); final long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime(); final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS); result.put(UPTIME_MS, uptimeMillis); final Map<String, Long> jvmUsageTime = new HashMap<>(); jvmUsageTime.put(ONE_MIN, overall.getOneMinute()); jvmUsageTime.put(FIVE_MIN, overall.getFiveMinute()); jvmUsageTime.put(FIFTEEN_MIN, overall.getFifteenMinute()); jvmUsageTime.put(OVERALL, overall.getOverall()); result.put(JVM_USAGE_TIME, jvmUsageTime); final Map<String, Double> jvmUsagePercent = new HashMap<>(); final int numProcs = Runtime.getRuntime().availableProcessors(); jvmUsagePercent.put(ONE_MIN, toPercent(overall.getOneMinute(), ONE_MINUTE_NANOS * numProcs)); jvmUsagePercent.put(FIVE_MIN, toPercent(overall.getFiveMinute(), FIVE_MINUTE_NANOS * numProcs)); jvmUsagePercent.put(FIFTEEN_MIN, toPercent(overall.getFifteenMinute(), FIFTEEN_MINUTE_NANOS * numProcs)); jvmUsagePercent.put(OVERALL, toPercent(overall.getOverall(), uptimeNanos * numProcs)); result.put(JVM_USAGE_PERCENT, jvmUsagePercent); List<Map<String, Object>> threads = new ArrayList<>(); for (CpuUsage usage : usages) { Map<String, Object> threadInfo = new HashMap<>(); threadInfo.put(ONE_MIN, toPercent(usage.getOneMinute(), overall.getOneMinute())); threadInfo.put(FIVE_MIN, toPercent(usage.getFiveMinute(), overall.getFiveMinute())); threadInfo.put(FIFTEEN_MIN, toPercent(usage.getFifteenMinute(), overall.getFifteenMinute())); threadInfo.put(OVERALL, toPercent(usage.getOverall(), overall.getOverall())); threadInfo.put(ID, usage.getThreadId()); threadInfo.put(NAME, usage.getName()); threads.add(threadInfo); } result.put(THREADS, threads); return result; } /** * Utility function that dumps the cpu usages for the threads to stdout. Output will be sorted * based on the 1-minute usage from highest to lowest. * * @param out stream where output will be written * @param cmp order to use for the results */ public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) { final PrintWriter writer = getPrintWriter(out); final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp); writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME))); final long uptimeMillis = (Long) threadCpuUsages.get(UPTIME_MS); final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS); writer.printf("Uptime: %s%n%n", toDuration(uptimeNanos)); @SuppressWarnings("unchecked") final Map<String, Long> jvmUsageTime = (Map<String, Long>) threadCpuUsages.get(JVM_USAGE_TIME); writer.println("JVM Usage Time: "); writer.printf("%11s %11s %11s %11s %7s %s%n", "1-min", "5-min", "15-min", "overall", "id", "name"); writer.printf("%11s %11s %11s %11s %7s %s%n", toDuration(jvmUsageTime.get(ONE_MIN)), toDuration(jvmUsageTime.get(FIVE_MIN)), toDuration(jvmUsageTime.get(FIFTEEN_MIN)), toDuration(jvmUsageTime.get(OVERALL)), "-", "jvm"); writer.println(); @SuppressWarnings("unchecked") final Map<String, Double> jvmUsagePerc = (Map<String, Double>) threadCpuUsages.get(JVM_USAGE_PERCENT); writer.println("JVM Usage Percent: "); writer.printf("%11s %11s %11s %11s %7s %s%n", "1-min", "5-min", "15-min", "overall", "id", "name"); writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n", jvmUsagePerc.get(ONE_MIN), jvmUsagePerc.get(FIVE_MIN), jvmUsagePerc.get(FIFTEEN_MIN), jvmUsagePerc.get(OVERALL), "-", "jvm"); writer.println(); writer.println("Breakdown by thread (100% = total cpu usage for jvm):"); writer.printf("%11s %11s %11s %11s %7s %s%n", "1-min", "5-min", "15-min", "overall", "id", "name"); @SuppressWarnings("unchecked") List<Map<String, Object>> threads = (List<Map<String, Object>>) threadCpuUsages.get(THREADS); for (Map<String, Object> thread : threads) { writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n", thread.get(ONE_MIN), thread.get(FIVE_MIN), thread.get(FIFTEEN_MIN), thread.get(OVERALL), thread.get(ID), thread.get(NAME)); } writer.println(); writer.flush(); } /** * Remove entries if the last update time is over this value. */ private static final long AGE_LIMIT = 15 * 60 * 1000; /** * Update the stats for all threads and the jvm. */ private void updateStats() { final ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (bean.isThreadCpuTimeEnabled()) { // Update stats for all current threads final long[] ids = bean.getAllThreadIds(); Arrays.sort(ids); long totalCpuTime = 0L; for (long id : ids) { long cpuTime = bean.getThreadCpuTime(id); if (cpuTime != -1) { totalCpuTime += cpuTime; CpuUsage usage = threadCpuUsages.get(id); if (usage == null) { final ThreadInfo info = bean.getThreadInfo(id); usage = new CpuUsage(id, info.getThreadName()); threadCpuUsages.put(id, usage); } usage.update(cpuTime); } } // Update jvm cpu usage, if possible we query the operating system mxbean so we get // an accurate total including any threads that may have been started and stopped // between sampling. As a fallback we use the sum of the cpu time for all threads found // in this interval. // // Total cpu time can be found in: // http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\ // com/sun/management/OperatingSystemMXBean.html // // We use reflection to avoid direct dependency on com.sun.* classes. final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); try { final Method m = osBean.getClass().getMethod("getProcessCpuTime"); final long jvmCpuTime = (Long) m.invoke(osBean); jvmCpuUsage.update((jvmCpuTime < 0) ? totalCpuTime : jvmCpuTime); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { jvmCpuUsage.update(totalCpuTime); } // Handle ids in the map that no longer exist: // * Remove old entries if the last update time is over AGE_LIMIT // * Otherwise, update usage so rolling window is correct final long now = System.currentTimeMillis(); final Iterator<Map.Entry<Long, CpuUsage>> iter = threadCpuUsages.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<Long, CpuUsage> entry = iter.next(); final long id = entry.getKey(); final CpuUsage usage = entry.getValue(); if (now - usage.getLastUpdateTime() > AGE_LIMIT) { iter.remove(); } else if (Arrays.binarySearch(ids, id) < 0) { usage.updateNoValue(); } } } else { LOGGER.debug("ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats"); } } /** * Update the stats for threads each minute. */ private class CpuStatRunnable implements Runnable { public void run() { final long step = 60000L; final long maxUpdateTime = step / 6; while (running) { try { long start = System.currentTimeMillis(); updateStats(); long elapsed = System.currentTimeMillis() - start; if (elapsed > maxUpdateTime) { LOGGER.warn("update stats is slow, took {} milliseconds", elapsed); } long delay = step - elapsed; Thread.sleep((delay < 1000L) ? step : delay); } catch (Exception e) { LOGGER.warn("failed to update thread stats", e); } } } } /** * Keeps track of the cpu usage for a single thread. */ public static final class CpuUsage { private static final int BUFFER_SIZE = 16; private final long id; private final String name; private final AtomicLong lastUpdateTime = new AtomicLong(0L); private final AtomicInteger nextPos = new AtomicInteger(0); /** * Cumulative cpu times for the different intervals. */ private final AtomicLongArray totals = new AtomicLongArray(BUFFER_SIZE); private CpuUsage(long id, String name) { this.id = id; this.name = name; } /** * The thread id that is being tracked. If the id is less than 0 it is for the jvm process * rather than a single thread. */ public long getThreadId() { return id; } /** * Name of the thread. */ public String getName() { return name; } /** * Last time the stats for this object were updated. */ public long getLastUpdateTime() { return lastUpdateTime.get(); } /** * Returns the overall usage for the lifetime of the thread. */ public long getOverall() { final int currentPos = toIndex(nextPos.get() - 1); return totals.get(currentPos); } /** * Returns the usage for the last one minute. */ public long getOneMinute() { return get(1); } /** * Returns the usage for the last five minutes. */ public long getFiveMinute() { return get(5); } /** * Returns the usage for the last fifteen minutes. */ public long getFifteenMinute() { return get(15); } private int toIndex(int v) { return ((v < 0) ? v + BUFFER_SIZE : v) % BUFFER_SIZE; } private long get(int n) { final int currentPos = toIndex(nextPos.get() - 1); final int startPos = toIndex(currentPos - n); final long currentValue = totals.get(currentPos); final long startValue = totals.get(startPos); final long diff = currentValue - startValue; return (diff < 0L) ? 0L : diff; } private void update(long threadTotal) { totals.set(toIndex(nextPos.getAndIncrement()), threadTotal); lastUpdateTime.set(System.currentTimeMillis()); } /** * Called if the thread no longer exists. The totals are cumulative so we copy the last * previously captured value. */ private void updateNoValue() { final int currentPos = toIndex(nextPos.get() - 1); totals.set(toIndex(nextPos.getAndIncrement()), totals.get(currentPos)); } } /** * Comparator for sorting cpu usage based on one of the columns. */ public enum CpuUsageComparator implements Comparator<CpuUsage> { /** * Sort based on 1-minute usage column. */ ONE_MINUTE(0), /** * Sort based on 5-minute usage column. */ FIVE_MINUTE(1), /** * Sort based on 15-minute usage column. */ FIFTEEN_MINUTE(2), /** * Sort based on overall usage column. */ OVERALL(3); private final int col; CpuUsageComparator(int col) { this.col = col; } /** * {@inheritDoc} */ public int compare(CpuUsage u1, CpuUsage u2) { long cmp; switch (col) { case 0: cmp = u2.getOneMinute() - u1.getOneMinute(); break; case 1: cmp = u2.getFiveMinute() - u1.getFiveMinute(); break; case 2: cmp = u2.getFifteenMinute() - u1.getFifteenMinute(); break; default: cmp = u2.getOverall() - u1.getOverall(); break; } return (cmp < 0) ? -1 : ((cmp > 0) ? 1 : 0); } } }
2,957
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/ThreadFactories.java
/* * Copyright 2014 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.servo.util; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * Simple utility class to create thread factories. */ public final class ThreadFactories { private ThreadFactories() { } private static final ThreadFactory BACKING_FACTORY = Executors.defaultThreadFactory(); /** * Create a new {@link ThreadFactory} that produces daemon threads with a given name format. * * @param fmt String format: for example foo-%d * @return a new {@link ThreadFactory} */ public static ThreadFactory withName(final String fmt) { return new ThreadFactory() { private final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(Runnable r) { final Thread t = BACKING_FACTORY.newThread(r); t.setDaemon(true); t.setName(String.format(fmt, count.getAndIncrement())); return t; } }; } }
2,958
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Strings.java
/* * Copyright 2014 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.servo.util; import java.util.Iterator; /** * Static helpers for {@code String} instances. */ public final class Strings { private Strings() { } /** * Returns true if the given string is null or is the empty string. */ public static boolean isNullOrEmpty(String string) { return string == null || string.isEmpty(); } /** * Join the string representation of each part separated by the given separator string. * * @param separator Separator string. For example "," * @param parts An iterator of the parts to join * @return The string formed by joining each part separated by the given separator. */ public static String join(String separator, Iterator<?> parts) { Preconditions.checkNotNull(separator, "separator"); Preconditions.checkNotNull(parts, "parts"); StringBuilder builder = new StringBuilder(); if (parts.hasNext()) { builder.append(parts.next().toString()); while (parts.hasNext()) { builder.append(separator); builder.append(parts.next().toString()); } } return builder.toString(); } }
2,959
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/VisibleForTesting.java
/* * Copyright 2014 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.servo.util; /** * Annotates a program element that exists, or is more widely visible than * otherwise necessary, only for use in test code. */ public @interface VisibleForTesting { }
2,960
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Throwables.java
/* * Copyright 2014 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.servo.util; /** * Utility class to deal with exceptions. Intended for internal use of servo only. */ public final class Throwables { private Throwables() { } /** * Propagates {@code throwable} as-is if it is an instance of * {@link RuntimeException} or {@link Error}, or else as a last resort, wraps * it in a {@code RuntimeException} then propagates. */ public static RuntimeException propagate(Throwable throwable) { final Throwable t = Preconditions.checkNotNull(throwable, "throwable"); if (t instanceof Error) { throw (Error) t; } if (t instanceof RuntimeException) { throw (RuntimeException) t; } throw new RuntimeException(t); } }
2,961
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/UnmodifiableSet.java
/* * Copyright 2014 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.servo.util; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Utility class to create unmodifiable sets. */ public final class UnmodifiableSet { private UnmodifiableSet() { } /** * Returns an unmodifiable view of the set created from the given elements. * * @param elements Array of elements * @param <E> type of the elements * @return an unmodifiable view of the set created from the given elements. */ @SafeVarargs public static <E> Set<E> of(E... elements) { Set<E> result = new HashSet<>(); Collections.addAll(result, elements); return Collections.unmodifiableSet(result); } /** * Returns an unmodifiable view of the set created from the given elements. * * @param elementsIterator iterator to get the elements of the set. * @param <E> type of the elements * @return an unmodifiable view of the set created from the given elements. */ public static <E> Set<E> copyOf(Iterator<? extends E> elementsIterator) { Set<E> result = new HashSet<>(); while (elementsIterator.hasNext()) { result.add(elementsIterator.next()); } return Collections.unmodifiableSet(result); } }
2,962
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/ManualClock.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; import java.util.concurrent.atomic.AtomicLong; /** * Mostly for testing, this clock must be explicitly set to a given value. Defaults to init. */ public class ManualClock implements Clock { private final AtomicLong time; /** * Construct a new clock setting the current time to {@code init}. * * @param init Number of milliseconds to use as the initial time. */ public ManualClock(long init) { time = new AtomicLong(init); } /** * Update the current time to {@code t}. * * @param t Number of milliseconds to use for the current time. */ public void set(long t) { time.set(t); } /** * {@inheritDoc} */ public long now() { return time.get(); } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ManualClock clock = (ManualClock) o; return now() == clock.now(); } /** * {@inheritDoc} */ @Override public int hashCode() { return Long.valueOf(now()).hashCode(); } }
2,963
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/ExpiringCache.java
/* * Copyright 2014 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.servo.util; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; /** * A semi-persistent mapping from keys to values. Values are automatically loaded * by the cache, and are stored in the cache until evicted. * * @param <K> The type of keys maintained * @param <V> The type of values maintained */ public class ExpiringCache<K, V> { private final ConcurrentHashMap<K, Entry<V>> map; private final long expireAfterMs; private final Function<K, Entry<V>> entryGetter; private final Clock clock; private static final class Entry<V> { private volatile long accessTime; private final V value; private final Clock clock; private Entry(V value, long accessTime, Clock clock) { this.value = value; this.accessTime = accessTime; this.clock = clock; } private V getValue() { accessTime = clock.now(); return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Entry entry = (Entry) o; return accessTime == entry.accessTime && value.equals(entry.value); } @Override public int hashCode() { int result = (int) (accessTime ^ (accessTime >>> 32)); result = 31 * result + value.hashCode(); return result; } @Override public String toString() { return "Entry{accessTime=" + accessTime + ", value=" + value + '}'; } } private static final ScheduledExecutorService SERVICE = Executors.newSingleThreadScheduledExecutor(ThreadFactories.withName("expiringMap-%d")); /** * Create a new ExpiringCache that will expire entries after a given number of milliseconds * computing the values as needed using the given getter. * * @param expireAfterMs Number of milliseconds after which entries will be evicted * @param getter Function that will be used to compute the values */ public ExpiringCache(final long expireAfterMs, final Function<K, V> getter) { this(expireAfterMs, getter, TimeUnit.MINUTES.toMillis(1), ClockWithOffset.INSTANCE); } /** * For unit tests. * Create a new ExpiringCache that will expire entries after a given number of milliseconds * computing the values as needed using the given getter. * * @param expireAfterMs Number of milliseconds after which entries will be evicted * @param getter Function that will be used to compute the values * @param expirationFreqMs Frequency at which to schedule the job that evicts entries * from the cache. */ public ExpiringCache(final long expireAfterMs, final Function<K, V> getter, final long expirationFreqMs, final Clock clock) { Preconditions.checkArgument(expireAfterMs > 0, "expireAfterMs must be positive."); Preconditions.checkArgument(expirationFreqMs > 0, "expirationFreqMs must be positive."); this.map = new ConcurrentHashMap<>(); this.expireAfterMs = expireAfterMs; this.entryGetter = toEntry(getter); this.clock = clock; final Runnable expirationJob = () -> { long tooOld = clock.now() - expireAfterMs; map.entrySet().stream().filter(entry -> entry.getValue().accessTime < tooOld) .forEach(entry -> map.remove(entry.getKey(), entry.getValue())); }; SERVICE.scheduleWithFixedDelay(expirationJob, 1, expirationFreqMs, TimeUnit.MILLISECONDS); } private Function<K, Entry<V>> toEntry(final Function<K, V> underlying) { return key -> new Entry<>(underlying.apply(key), 0L, clock); } /** * This method should be used instead of the * {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} call to minimize * thread contention. This method does not require locking for the common case * where the key exists, but potentially performs additional computation when * absent. */ private Entry<V> computeIfAbsent(K key) { Entry<V> v = map.get(key); if (v == null) { Entry<V> tmp = entryGetter.apply(key); v = map.putIfAbsent(key, tmp); if (v == null) { v = tmp; } } return v; } /** * Get the (possibly cached) value for a given key. */ public V get(final K key) { Entry<V> entry = computeIfAbsent(key); return entry.getValue(); } /** * Get the list of all values that are members of this cache. Does not * affect the access time used for eviction. */ public List<V> values() { final Collection<Entry<V>> values = map.values(); // Note below that e.value avoids updating the access time final List<V> res = values.stream().map(e -> e.value).collect(Collectors.toList()); return Collections.unmodifiableList(res); } /** * Return the number of entries in the cache. */ public int size() { return map.size(); } /** * {@inheritDoc} */ @Override public String toString() { return "ExpiringCache{" + "map=" + map + ", expireAfterMs=" + expireAfterMs + '}'; } }
2,964
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Clock.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.util; /** * A wrapper around the system clock to allow custom implementations to be used in unit tests * where we want to fake or control the clock behavior. */ public interface Clock { /** * A Clock instance that returns the current time in milliseconds since * the epoch using the system clock. */ Clock WALL = System::currentTimeMillis; /** * Returns the number of milliseconds since the epoch. */ long now(); }
2,965
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/util/Memoizer.java
/* * Copyright 2014 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.servo.util; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * A class that can cache the results of computations for a given amount of time. * * @param <T> Type of the value cached */ public final class Memoizer<T> { /** * Create a memoizer that caches the value produced by getter for a given duration. * * @param getter A {@link Callable} that returns a new value. This should not throw. * @param duration how long we should keep the cached value before refreshing it. * @param unit unit of time for {@code duration} * @param <T> type of the value produced by the {@code getter} * @return A thread safe memoizer. */ public static <T> Memoizer<T> create(Callable<T> getter, long duration, TimeUnit unit) { return new Memoizer<>(getter, duration, unit); } private volatile long whenItExpires = 0L; private volatile T value; private final Callable<T> getter; private final long durationNanos; private Memoizer(Callable<T> getter, long duration, TimeUnit unit) { this.durationNanos = unit.toNanos(duration); this.getter = getter; } /** * Get or refresh and return the latest value. */ public T get() { long expiration = whenItExpires; long now = System.nanoTime(); // if uninitialized or expired update value if (expiration == 0 || now >= expiration) { synchronized (this) { // ensure a different thread didn't update it if (whenItExpires == expiration) { whenItExpires = now + durationNanos; try { value = getter.call(); } catch (Exception e) { // shouldn't happen throw Throwables.propagate(e); } } } } return value; } }
2,966
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/ObjectNameBuilder.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Throwables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import java.util.regex.Pattern; /** * A helper class that assists in building * {@link ObjectName}s given monitor {@link Tag}s * or {@link TagList}. The builder also sanitizes * all values to avoid invalid input. Any characters that are * not alphanumeric, a period, or hypen are considered invalid * and are remapped to underscores. */ final class ObjectNameBuilder { private static final Pattern INVALID_CHARS = Pattern.compile("[^a-zA-Z0-9_\\-\\.]"); private static final Logger LOG = LoggerFactory.getLogger(ObjectNameBuilder.class); /** * Sanitizes a value by replacing any character that is not alphanumeric, * a period, or hyphen with an underscore. * * @param value the value to sanitize * @return the sanitized value */ public static String sanitizeValue(String value) { return INVALID_CHARS.matcher(value).replaceAll("_"); } /** * Creates an {@link ObjectNameBuilder} given the JMX domain. * * @param domain the JMX domain * @return The ObjectNameBuilder */ public static ObjectNameBuilder forDomain(String domain) { return new ObjectNameBuilder(domain); } private final StringBuilder nameStrBuilder; private ObjectNameBuilder(String domain) { nameStrBuilder = new StringBuilder(sanitizeValue(domain)); nameStrBuilder.append(":"); } /** * Adds the {@link TagList} as {@link ObjectName} properties. * * @param tagList the tag list to add * @return This builder */ public ObjectNameBuilder addProperties(TagList tagList) { for (Tag tag : tagList) { addProperty(tag); } return this; } /** * Adds the {@link Tag} as a {@link ObjectName} property. * * @param tag the tag to add * @return This builder */ public ObjectNameBuilder addProperty(Tag tag) { return addProperty(tag.getKey(), tag.getValue()); } /** * Adds the key/value as a {@link ObjectName} property. * * @param key the key to add * @param value the value to add * @return This builder */ public ObjectNameBuilder addProperty(String key, String value) { nameStrBuilder.append(sanitizeValue(key)) .append('=') .append(sanitizeValue(value)).append(","); return this; } /** * Builds the {@link ObjectName} given the configuration. * * @return The created ObjectName */ public ObjectName build() { final String name = nameStrBuilder.substring(0, nameStrBuilder.length() - 1); try { return new ObjectName(name); } catch (MalformedObjectNameException e) { LOG.warn("Invalid ObjectName provided: {}", name); throw Throwables.propagate(e); } } }
2,967
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/MonitorMBean.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.monitor.CompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.NumericMonitor; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.ObjectName; import javax.management.ReflectionException; import java.util.ArrayList; import java.util.List; /** * Exposes a {@link com.netflix.servo.monitor.Monitor} as an MBean that can be registered with JMX. */ class MonitorMBean implements DynamicMBean { /** * Create a set of MBeans for a {@link com.netflix.servo.monitor.Monitor}. This method will * recursively select all of the sub-monitors if a composite type is used. * * @param domain passed in to the object name created to identify the beans * @param monitor monitor to expose to jmx * @param mapper the mapper which maps the Monitor to ObjectName * @return flattened list of simple monitor mbeans */ public static List<MonitorMBean> createMBeans(String domain, Monitor<?> monitor, ObjectNameMapper mapper) { List<MonitorMBean> mbeans = new ArrayList<>(); createMBeans(mbeans, domain, monitor, mapper); return mbeans; } private static void createMBeans(List<MonitorMBean> mbeans, String domain, Monitor<?> monitor, ObjectNameMapper mapper) { if (monitor instanceof CompositeMonitor<?>) { for (Monitor<?> m : ((CompositeMonitor<?>) monitor).getMonitors()) { createMBeans(mbeans, domain, m, mapper); } } else { mbeans.add(new MonitorMBean(domain, monitor, mapper)); } } private final Monitor<?> monitor; private final ObjectName objectName; private final MBeanInfo beanInfo; /** * Create an MBean for a {@link com.netflix.servo.monitor.Monitor}. * * @param domain passed in to the object name created to identify the beans * @param monitor monitor to expose to jmx * @param mapper the mapper which maps the monitor to ObjectName */ MonitorMBean(String domain, Monitor<?> monitor, ObjectNameMapper mapper) { this.monitor = monitor; this.objectName = createObjectName(mapper, domain); this.beanInfo = createBeanInfo(); } /** * Returns the object name built from the {@link com.netflix.servo.monitor.MonitorConfig}. */ public ObjectName getObjectName() { return objectName; } /** * {@inheritDoc} */ @Override public Object getAttribute(String name) throws AttributeNotFoundException { return monitor.getValue(); } /** * {@inheritDoc} */ @Override public void setAttribute(Attribute attribute) throws InvalidAttributeValueException, MBeanException, AttributeNotFoundException { throw new UnsupportedOperationException("setAttribute is not implemented"); } /** * {@inheritDoc} */ @Override public AttributeList getAttributes(String[] names) { AttributeList list = new AttributeList(); for (String name : names) { list.add(new Attribute(name, monitor.getValue())); } return list; } /** * {@inheritDoc} */ @Override public AttributeList setAttributes(AttributeList list) { throw new UnsupportedOperationException("setAttributes is not implemented"); } /** * {@inheritDoc} */ @Override public Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException { throw new UnsupportedOperationException("invoke is not implemented"); } /** * {@inheritDoc} */ @Override public MBeanInfo getMBeanInfo() { return beanInfo; } private ObjectName createObjectName(ObjectNameMapper mapper, String domain) { return mapper.createObjectName(domain, monitor); } private MBeanInfo createBeanInfo() { MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[1]; attrs[0] = createAttributeInfo(monitor); return new MBeanInfo( this.getClass().getName(), "MonitorMBean", attrs, null, // constructors null, // operators null); // notifications } private MBeanAttributeInfo createAttributeInfo(Monitor<?> m) { final String type = (m instanceof NumericMonitor<?>) ? Number.class.getName() : String.class.getName(); return new MBeanAttributeInfo( "value", type, m.getConfig().toString(), true, // isReadable false, // isWritable false); // isIs } }
2,968
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/DefaultObjectNameMapper.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.monitor.Monitor; import javax.management.ObjectName; /** * The default {@link ObjectNameMapper} implementation that * is used by the {@link JmxMonitorRegistry}. This implementation * simply appends the monitor's name followed by the tags for the monitor. */ class DefaultObjectNameMapper implements ObjectNameMapper { @Override public ObjectName createObjectName(String domain, Monitor<?> monitor) { ObjectNameBuilder objNameBuilder = ObjectNameBuilder.forDomain(domain); objNameBuilder.addProperty("name", monitor.getConfig().getName()); objNameBuilder.addProperties(monitor.getConfig().getTags()); return objNameBuilder.build(); } }
2,969
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/JmxMonitorRegistry.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.MonitorRegistry; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.util.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.DynamicMBean; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Monitor registry backed by JMX. The monitor annotations on registered * objects will be used to export the data to JMX. For details about the * representation in JMX see {@link MonitorMBean}. The {@link ObjectName} * used for each monitor depends on the implementation of {@link ObjectNameMapper} * that is specified for the registry. See {@link ObjectNameMapper#DEFAULT} for * the default naming implementation. */ public final class JmxMonitorRegistry implements MonitorRegistry { private static final Logger LOG = LoggerFactory.getLogger(JmxMonitorRegistry.class); private final MBeanServer mBeanServer; private final ConcurrentMap<MonitorConfig, Monitor<?>> monitors; private final String name; private final ObjectNameMapper mapper; private final ConcurrentMap<ObjectName, Object> locks = new ConcurrentHashMap<>(); private final AtomicBoolean updatePending = new AtomicBoolean(false); private final AtomicReference<Collection<Monitor<?>>> monitorList = new AtomicReference<>(UnmodifiableList.<Monitor<?>>of()); /** * Creates a new instance that registers metrics with the local mbean * server using the default ObjectNameMapper {@link ObjectNameMapper#DEFAULT}. * * @param name the registry name */ public JmxMonitorRegistry(String name) { this(name, ObjectNameMapper.DEFAULT); } /** * Creates a new instance that registers metrics with the local mbean * server using the ObjectNameMapper provided. * * @param name the registry name * @param mapper the monitor to object name mapper */ public JmxMonitorRegistry(String name, ObjectNameMapper mapper) { this.name = name; this.mapper = mapper; mBeanServer = ManagementFactory.getPlatformMBeanServer(); monitors = new ConcurrentHashMap<>(); } private void register(ObjectName objectName, DynamicMBean mbean) throws Exception { synchronized (getLock(objectName)) { if (mBeanServer.isRegistered(objectName)) { mBeanServer.unregisterMBean(objectName); } mBeanServer.registerMBean(mbean, objectName); } } /** * The set of registered Monitor objects. */ @Override public Collection<Monitor<?>> getRegisteredMonitors() { if (updatePending.getAndSet(false)) { monitorList.set(UnmodifiableList.copyOf(monitors.values())); } return monitorList.get(); } /** * Register a new monitor in the registry. */ @Override public void register(Monitor<?> monitor) { try { List<MonitorMBean> beans = MonitorMBean.createMBeans(name, monitor, mapper); for (MonitorMBean bean : beans) { register(bean.getObjectName(), bean); } monitors.put(monitor.getConfig(), monitor); updatePending.set(true); } catch (Exception e) { LOG.warn("Unable to register Monitor:{}", monitor.getConfig(), e); } } /** * Unregister a Monitor from the registry. */ @Override public void unregister(Monitor<?> monitor) { try { List<MonitorMBean> beans = MonitorMBean.createMBeans(name, monitor, mapper); for (MonitorMBean bean : beans) { try { mBeanServer.unregisterMBean(bean.getObjectName()); locks.remove(bean.getObjectName()); } catch (InstanceNotFoundException ignored) { // ignore errors attempting to unregister a non-registered monitor // a common error is to unregister twice } } monitors.remove(monitor.getConfig()); updatePending.set(true); } catch (Exception e) { LOG.warn("Unable to un-register Monitor:{}", monitor.getConfig(), e); } } @Override public boolean isRegistered(Monitor<?> monitor) { try { List<MonitorMBean> beans = MonitorMBean.createMBeans(name, monitor, mapper); for (MonitorMBean bean : beans) { if (mBeanServer.isRegistered(bean.getObjectName())) { return true; } } } catch (Exception e) { return false; } return false; } private Object getLock(ObjectName objectName) { return locks.computeIfAbsent(objectName, k -> new Object()); } }
2,970
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/OrderedObjectNameMapper.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.monitor.Monitor; import javax.management.ObjectName; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * An {@link ObjectNameMapper} that allows the order of * tags to be specified when constructing the {@link ObjectName}. * The mapper will map the known ordered tag keys and then optionally * append the remaining tags. While an {@link ObjectName}'s properties * are meant to be unordered some visual tools such as VisualVM use the * given order to build a hierarchy. This ordering allows that hierarchy * to be manipulated. * <p/> * It is recommended to always append the remaining tags to avoid collisions * in the generated {@link ObjectName}. The mapper remaps any characters that * are not alphanumeric, a period, or hypen to an underscore. */ public final class OrderedObjectNameMapper implements ObjectNameMapper { private final List<String> keyOrder; private final boolean appendRemaining; private final boolean orderIncludesName; /** * Creates the mapper specifying the order of keys to use and whether * non-explicitly mentioned tag keys should then be appended or not to * the resulting {@link ObjectName}. * * @param appendRemaining whether to append the remaining tags * @param orderedKeys the keys in order that should be used */ public OrderedObjectNameMapper(boolean appendRemaining, String... orderedKeys) { this(appendRemaining, Arrays.asList(orderedKeys)); } /** * Creates the mapper specifying the order of keys to use and whether * non-explicitly mentioned tag keys should then be appended or not to * the resulting {@link ObjectName}. * * @param appendRemaining whether to append the remaining tags * @param orderedKeys the list of keys in the order that should be used */ public OrderedObjectNameMapper(boolean appendRemaining, List<String> orderedKeys) { this.keyOrder = new ArrayList<>(orderedKeys); this.appendRemaining = appendRemaining; this.orderIncludesName = keyOrder.contains("name"); } @Override public ObjectName createObjectName(String domain, Monitor<?> monitor) { ObjectNameBuilder objBuilder = ObjectNameBuilder.forDomain(domain); Map<String, String> tags = new TreeMap<>( monitor.getConfig().getTags().asMap()); // For the known ordered keys, try to add them if they're present in the monitor's tags for (String knownKey : keyOrder) { // Special case for name as it isn't a tag if ("name".equals(knownKey)) { addName(objBuilder, monitor); } else { String value = tags.remove(knownKey); if (value != null) { objBuilder.addProperty(knownKey, value); } } } // If appending, then add the name (if not already added) and remaining tags if (appendRemaining) { if (!orderIncludesName) { addName(objBuilder, monitor); } for (Map.Entry<String, String> additionalTag : tags.entrySet()) { objBuilder.addProperty(additionalTag.getKey(), additionalTag.getValue()); } } return objBuilder.build(); } private void addName(ObjectNameBuilder builder, Monitor<?> monitor) { builder.addProperty("name", monitor.getConfig().getName()); } }
2,971
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/ObjectNameMapper.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.jmx; import com.netflix.servo.monitor.Monitor; import javax.management.ObjectName; /** * Allows for different implementations when mapping a * monitor to a JMX {@link ObjectName}. The mapper can be * can be specified when using the {@link JmxMonitorRegistry}. * This interface also has a reference to the default mapping implementation. * Note that an {@link ObjectName}'s properties are meant to be unordered, * however, some tools such as VisualVM use the order to build a hierarchy * view where the default implementation may not be desirable. */ public interface ObjectNameMapper { /** * The default mapping implementation. This implementation simply * appends the monitor's name followed by all the tags as properties * of the {@link ObjectName}. The mapper remaps any characters that are * not alphanumeric, a period, or hypen to an underscore. */ ObjectNameMapper DEFAULT = new DefaultObjectNameMapper(); /** * Given the domain and monitor generates an {@link ObjectName} to use. * * @param domain the JMX domain * @param monitor the monitor * @return The created ObjectName */ ObjectName createObjectName(String domain, Monitor<?> monitor); }
2,972
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/jmx/package-info.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * <p/> * Monitor registry and helper classes to expose monitored attributes to * JMX. * <p/> * Monitor registry and helper classes to expose monitored attributes to * JMX. * <p/> * Monitor registry and helper classes to expose monitored attributes to * JMX. */ /** * Monitor registry and helper classes to expose monitored attributes to * JMX. */ package com.netflix.servo.jmx;
2,973
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/annotations/DataSourceLevel.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.annotations; import com.netflix.servo.tag.Tag; /** * Indicates a level for the monitor. This is meant to be similar to log levels to provide a * quick way to perform high-level filtering. */ public enum DataSourceLevel implements Tag { /** * Fine granularity monitors that provide a high amount of detail. */ DEBUG, /** * The default level for monitors. */ INFO, /** * Most important monitors for an application. */ CRITICAL; /** * Key name used for the data source level tag. */ public static final String KEY = "level"; /** * {@inheritDoc} */ public String getKey() { return KEY; } /** * {@inheritDoc} */ public String getValue() { return name(); } /** * {@inheritDoc} */ public String tagString() { return getKey() + "=" + getValue(); } }
2,974
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/annotations/MonitorTags.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Tags to associate with all metrics in an instance. The tags will be queried * when the instance is registered with the {@link * com.netflix.servo.MonitorRegistry} and used to provide a common base set of * tags for all attribute annotated with {@link Monitor}. Tags provided on the * {@link Monitor} annotation will override these tags if there is a common * key. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface MonitorTags { }
2,975
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/annotations/DataSourceType.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.annotations; import com.netflix.servo.tag.Tag; /** * Indicates the type of value that is annotated to determine how it will be * measured. */ public enum DataSourceType implements Tag { /** * A gauge is for numeric values that can be sampled without modification. * Examples of metrics that should be gauges are things like current * temperature, number of open connections, disk usage, etc. */ GAUGE, /** * A counter is for numeric values that get incremented when some event * occurs. Counters will be sampled and converted into a rate of change * per second. Counter values should be monotonically increasing, i.e., * the value should not decrease. */ COUNTER, /** * A rate is for numeric values that represent a rate per second. */ RATE, /** * A normalized rate per second. For counters that report values based on step * boundaries. */ NORMALIZED, /** * An informational attribute is for values that might be useful for * debugging, but will not be collected as metrics for monitoring purposes. * These values are made available in JMX. */ INFORMATIONAL; /** * Key name used for the data source type tag, configurable via * servo.datasourcetype.key system property. */ public static final String KEY = System.getProperty("servo.datasourcetype.key", "type"); /** * {@inheritDoc} */ public String getKey() { return KEY; } /** * {@inheritDoc} */ public String getValue() { return name(); } /** * {@inheritDoc} */ public String tagString() { return getKey() + "=" + getValue(); } }
2,976
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/annotations/Monitor.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation indicating a field or method should be collected for monitoring. * The attributes annotated should be thread-safe for access by a background * thread. If a method is annotated it should be inexpensive and avoid any * potentially costly operations such as IO and networking. Expect that the * fields will be polled frequently and cache values that require expensive * computation rather than computing them inline. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Monitor { /** * Name of the annotated attribute. */ String name() default ""; /** * Type of value that is annotated, for more information see * {@link DataSourceType}. */ DataSourceType type() default DataSourceType.INFORMATIONAL; /** * Level of the value that is annotated, for more information see * {@link DataSourceLevel}. */ DataSourceLevel level() default DataSourceLevel.INFO; /** * A human readable description of the annotated attribute. */ String description() default ""; }
2,977
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/annotations/package-info.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * <p/> * Annotations to easily expose metrics from a class. * <p/> * Annotations to easily expose metrics from a class. * <p/> * Annotations to easily expose metrics from a class. */ /** * Annotations to easily expose metrics from a class. */ package com.netflix.servo.annotations;
2,978
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/PrefixMetricFilter.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Strings; import java.util.Map; import java.util.NavigableMap; /** * Filter that checks for a prefix match on a given tag. This can be useful * providing rules associated with the canonical class name. */ public final class PrefixMetricFilter implements MetricFilter { private final String tagKey; private final MetricFilter root; private final NavigableMap<String, MetricFilter> filters; /** * Creates a new prefix filter. * * @param tagKey the tag to perform matching on, if null the name will be * checked * @param root filter used if there are no prefix matches * @param filters map of prefix to sub-filter. The filter associated with * the longest matching prefix will be used. */ public PrefixMetricFilter( String tagKey, MetricFilter root, NavigableMap<String, MetricFilter> filters) { this.tagKey = tagKey; this.root = root; this.filters = filters; } /** * {@inheritDoc} */ public boolean matches(MonitorConfig config) { String name = config.getName(); TagList tags = config.getTags(); String value; if (tagKey == null) { value = name; } else { Tag t = tags.getTag(tagKey); value = (t == null) ? null : t.getValue(); } if (Strings.isNullOrEmpty(value)) { return root.matches(config); } else { String start = value.substring(0, 1); NavigableMap<String, MetricFilter> candidates = filters.subMap(start, true, value, true).descendingMap(); if (candidates.isEmpty()) { return root.matches(config); } else { for (Map.Entry<String, MetricFilter> e : candidates.entrySet()) { if (value.startsWith(e.getKey())) { return e.getValue().matches(config); } } return root.matches(config); } } } }
2,979
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/MetricObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import java.util.List; /** * Observer that receives updates about metrics. */ public interface MetricObserver { /** * Invoked with the most recent values for a set of metrics. */ void update(List<Metric> metrics); /** * Name associated with an observer. Mostly used to make log messages more * informative. */ String getName(); }
2,980
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/MetricTransformObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.google.common.base.Function; import com.netflix.servo.Metric; import java.util.List; import java.util.stream.Collectors; /** * An observer that will transform the list of metrics using a given function. */ public class MetricTransformObserver implements MetricObserver { private final Function<Metric, Metric> transformer; private final MetricObserver observer; /** * Create a new MetricTransformObserver using the given transfomer function. * * @param transformer The function used to transform metrics. * @param observer The MetricObserver that will receive the transfomed metrics. */ public MetricTransformObserver(Function<Metric, Metric> transformer, MetricObserver observer) { this.transformer = transformer; this.observer = observer; } @Override public void update(List<Metric> metrics) { List<Metric> transformed = metrics.stream() .map(transformer::apply).collect(Collectors.toList()); observer.update(transformed); } @Override public String getName() { return "MetricTransformObserver"; } }
2,981
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/BaseMetricObserver.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.annotations.MonitorTags; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.StandardTagKeys; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.Throwables; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * Helper class for metric observers that keeps track of the number of calls * and number of failures. */ public abstract class BaseMetricObserver implements MetricObserver { @MonitorTags private final TagList tags; private final String name; /** * Total number of times update has been called. */ @Monitor(name = "updateCount", type = DataSourceType.COUNTER) private final AtomicInteger updateCount = new AtomicInteger(0); /** * Number of times update failed with an exception. */ @Monitor(name = "updateFailureCount", type = DataSourceType.COUNTER) private final AtomicInteger failedUpdateCount = new AtomicInteger(0); /** * Creates a new instance with a given name. */ public BaseMetricObserver(String name) { final Tag id = Tags.newTag(StandardTagKeys.MONITOR_ID.getKeyName(), name); this.name = Preconditions.checkNotNull(name, "name"); this.tags = BasicTagList.of(id); } /** * Update method that should be defined by sub-classes. This method will * get invoked and counts will be maintained in the base observer. */ public abstract void updateImpl(List<Metric> metrics); /** * {@inheritDoc} */ public final void update(List<Metric> metrics) { Preconditions.checkNotNull(metrics, "metrics"); try { updateImpl(metrics); } catch (Throwable t) { failedUpdateCount.incrementAndGet(); throw Throwables.propagate(t); } finally { updateCount.incrementAndGet(); } } /** * {@inheritDoc} */ public final String getName() { return name; } /** * Can be used by sub-classes to increment the failed count if they handle * exception internally. */ protected final void incrementFailedCount() { failedUpdateCount.incrementAndGet(); } /** * Returns the total number of times update has been called. */ public int getUpdateCount() { return updateCount.get(); } /** * Returns the number of times update failed with an exception. */ public int getFailedUpdateCount() { return failedUpdateCount.get(); } }
2,982
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/CounterToRateMetricTransform.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Converts counter metrics into a rate per second. The rate is calculated by * comparing two samples of given metric and looking at the delta. Since two * samples are needed to calculate the rate, no value will be sent to the * wrapped observer until a second sample arrives. If a given metric is not * updated within a given heartbeat interval, the previous cached value for the * counter will be dropped such that if a new sample comes in it will be * treated as the first sample for that metric. * <p/> * <p>Counters should be monotonically increasing values. If a counter value * decreases from one sample to the next, then we will assume the counter value * was reset and send a rate of 0. This is similar to the RRD concept of * type DERIVE with a min of 0. * <p/> * <p>This class is not thread safe and should generally be wrapped by an async * observer to prevent issues. */ public final class CounterToRateMetricTransform implements MetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(CounterToRateMetricTransform.class); private static final String COUNTER_VALUE = DataSourceType.COUNTER.name(); private static final Tag RATE_TAG = DataSourceType.RATE; private final MetricObserver observer; private final Map<MonitorConfig, CounterValue> cache; private final long intervalMillis; /** * Creates a new instance with the specified heartbeat interval. The * heartbeat should be some multiple of the sampling interval used when * collecting the metrics. */ public CounterToRateMetricTransform(MetricObserver observer, long heartbeat, TimeUnit unit) { this(observer, heartbeat, 0L, unit); } /** * Creates a new instance with the specified heartbeat interval. The * heartbeat should be some multiple of the sampling interval used when * collecting the metrics. * * @param observer downstream observer to forward values to after the rate has * been computed. * @param heartbeat how long to remember a previous value before dropping it and * treating new samples as the first report. * @param estPollingInterval estimated polling interval in to use for the first call. If set * to zero no values will be forwarded until the second sample for * a given counter. The delta for the first interval will be the * total value for the counter as it is assumed it started at 0 and * was first created since the last polling interval. If this * assumption is not true then this setting should be 0 so it waits * for the next sample to compute an accurate delta, otherwise * spikes will occur in the output. * @param unit unit for the heartbeat and estPollingInterval params. * @param clock Clock instance to use for getting the time. */ CounterToRateMetricTransform( MetricObserver observer, long heartbeat, long estPollingInterval, TimeUnit unit, final Clock clock) { this.observer = observer; this.intervalMillis = TimeUnit.MILLISECONDS.convert(estPollingInterval, unit); final long heartbeatMillis = TimeUnit.MILLISECONDS.convert(heartbeat, unit); this.cache = new LinkedHashMap<MonitorConfig, CounterValue>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<MonitorConfig, CounterValue> eldest) { final long now = clock.now(); final long lastMod = eldest.getValue().getTimestamp(); final boolean expired = (now - lastMod) > heartbeatMillis; if (expired) { LOGGER.debug("heartbeat interval exceeded, expiring {}", eldest.getKey()); } return expired; } }; } /** * Creates a new instance with the specified heartbeat interval. The * heartbeat should be some multiple of the sampling interval used when * collecting the metrics. * * @param observer downstream observer to forward values to after the rate has * been computed. * @param heartbeat how long to remember a previous value before dropping it and * treating new samples as the first report. * @param estPollingInterval estimated polling interval in to use for the first call. If set * to zero no values will be forwarded until the second sample for * a given counter. The delta for the first interval will be the * total value for the counter as it is assumed it started at 0 and * was first created since the last polling interval. If this * assumption is not true then this setting should be 0 so it waits * for the next sample to compute an accurate delta, otherwise * spikes will occur in the output. * @param unit unit for the heartbeat and estPollingInterval params. */ public CounterToRateMetricTransform( MetricObserver observer, long heartbeat, long estPollingInterval, TimeUnit unit) { this(observer, heartbeat, estPollingInterval, unit, ClockWithOffset.INSTANCE); } /** * {@inheritDoc} */ public String getName() { return observer.getName(); } /** * {@inheritDoc} */ public void update(List<Metric> metrics) { Preconditions.checkNotNull(metrics, "metrics"); LOGGER.debug("received {} metrics", metrics.size()); final List<Metric> newMetrics = new ArrayList<>(metrics.size()); for (Metric m : metrics) { if (isCounter(m)) { final MonitorConfig rateConfig = toRateConfig(m.getConfig()); final CounterValue prev = cache.get(rateConfig); if (prev != null) { final double rate = prev.computeRate(m); newMetrics.add(new Metric(rateConfig, m.getTimestamp(), rate)); } else { CounterValue current = new CounterValue(m); cache.put(rateConfig, current); if (intervalMillis > 0L) { final double delta = m.getNumberValue().doubleValue(); final double rate = current.computeRate(intervalMillis, delta); newMetrics.add(new Metric(rateConfig, m.getTimestamp(), rate)); } } } else { newMetrics.add(m); } } LOGGER.debug("writing {} metrics to downstream observer", newMetrics.size()); observer.update(newMetrics); } /** * Clear all cached state of previous counter values. */ public void reset() { cache.clear(); } /** * Convert a MonitorConfig for a counter to one that is explicit about * being a RATE. */ private MonitorConfig toRateConfig(MonitorConfig config) { return config.withAdditionalTag(RATE_TAG); } private boolean isCounter(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); return COUNTER_VALUE.equals(value); } private static class CounterValue { private long timestamp; private double value; CounterValue(long timestamp, double value) { this.timestamp = timestamp; this.value = value; } CounterValue(Metric m) { this(m.getTimestamp(), m.getNumberValue().doubleValue()); } public long getTimestamp() { return timestamp; } public double computeRate(Metric m) { final long currentTimestamp = m.getTimestamp(); final double currentValue = m.getNumberValue().doubleValue(); final long durationMillis = currentTimestamp - timestamp; final double delta = currentValue - value; timestamp = currentTimestamp; value = currentValue; return computeRate(durationMillis, delta); } public double computeRate(long durationMillis, double delta) { final double millisPerSecond = 1000.0; final double duration = durationMillis / millisPerSecond; return (duration <= 0.0 || delta <= 0.0) ? 0.0 : delta / duration; } } }
2,983
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/MemoryMetricObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Keeps the last N observations in-memory. */ public final class MemoryMetricObserver extends BaseMetricObserver { private static final int DEFAULT_N = 10; private final List<Metric>[] observations; private int next; /** * Creates a new instance that keeps 10 copies in memory. */ public MemoryMetricObserver() { this("unamed observer", DEFAULT_N); } /** * Creates a new instance that keeps {@code num} copies in memory. */ @SuppressWarnings("unchecked") public MemoryMetricObserver(String name, int num) { super(name); observations = (List<Metric>[]) new List[num]; next = 0; } /** * {@inheritDoc} */ public void updateImpl(List<Metric> metrics) { observations[next] = metrics; next = (next + 1) % observations.length; } /** * Returns the current set of observations. */ public List<List<Metric>> getObservations() { List<List<Metric>> builder = new ArrayList<>(); int pos = next; for (List<Metric> ignored : observations) { if (observations[pos] != null) { builder.add(observations[pos]); } pos = (pos + 1) % observations.length; } return Collections.unmodifiableList(builder); } }
2,984
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/AsyncMetricObserver.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; /** * Wraps another observer and asynchronously updates it in the background. The * update call will always return immediately. If the queue fills up newer * updates will overwrite older updates. * <p/> * If an exception is thrown when calling update on wrapped observer it will * be logged, but otherwise ignored. */ public final class AsyncMetricObserver extends BaseMetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncMetricObserver.class); private final MetricObserver wrappedObserver; private final long expireTime; private final BlockingQueue<TimestampedUpdate> updateQueue; private volatile boolean stopUpdateThread = false; private final Thread processingThread; /** * The number of updates that have been expired and dropped. */ private final Counter expiredUpdateCount = Monitors.newCounter("expiredUpdateCount"); /** * Creates a new instance. * * @param name name of this observer * @param observer a wrapped observer that will be updated asynchronously * @param queueSize maximum size of the update queue, if the queue fills * up older entries will be dropped * @param expireTime age in milliseconds before an update expires and will * not be passed on to the wrapped observer */ public AsyncMetricObserver( String name, MetricObserver observer, int queueSize, long expireTime) { super(name); this.expireTime = expireTime; wrappedObserver = Preconditions.checkNotNull(observer, "observer"); Preconditions.checkArgument(queueSize >= 1, String.format("invalid queueSize %d, size must be >= 1", queueSize)); updateQueue = new LinkedBlockingDeque<>(queueSize); String threadName = getClass().getSimpleName() + "-" + name; processingThread = new Thread(new UpdateProcessor(), threadName); processingThread.setDaemon(true); processingThread.start(); } /** * Creates a new instance with an unbounded queue and no expiration time. * * @param name name of this observer * @param observer a wrapped observer that will be updated asynchronously */ public AsyncMetricObserver(String name, MetricObserver observer) { this(name, observer, Integer.MAX_VALUE, Long.MAX_VALUE); } /** * Creates a new instance with no expiration time. * * @param name name of this observer * @param observer a wrapped observer that will be updated asynchronously * @param queueSize maximum size of the update queue, if the queue fills * up older entries will be dropped */ public AsyncMetricObserver(String name, MetricObserver observer, int queueSize) { this(name, observer, queueSize, Long.MAX_VALUE); } /** * {@inheritDoc} */ public void updateImpl(List<Metric> metrics) { long now = System.currentTimeMillis(); TimestampedUpdate update = new TimestampedUpdate(now, metrics); boolean result = updateQueue.offer(update); final int maxAttempts = 5; int attempts = 0; while (!result && attempts < maxAttempts) { updateQueue.remove(); result = updateQueue.offer(update); ++attempts; } if (!result) { incrementFailedCount(); } } /** * Stop the background thread that pushes updates to the wrapped observer. */ public void stop() { stopUpdateThread = true; processingThread.interrupt(); // in case it is blocked on an empty queue } private void processUpdate() { TimestampedUpdate update; try { update = updateQueue.take(); long cutoff = System.currentTimeMillis() - expireTime; if (update.getTimestamp() < cutoff) { expiredUpdateCount.increment(); return; } wrappedObserver.update(update.getMetrics()); } catch (InterruptedException ie) { LOGGER.warn("interrupted while adding to queue, update dropped"); incrementFailedCount(); } catch (Throwable t) { LOGGER.warn("update failed for downstream queue", t); incrementFailedCount(); } } private class UpdateProcessor implements Runnable { public void run() { while (!stopUpdateThread) { processUpdate(); } } } private static class TimestampedUpdate { private final long timestamp; private final List<Metric> metrics; TimestampedUpdate(long timestamp, List<Metric> metrics) { this.timestamp = timestamp; this.metrics = metrics; } long getTimestamp() { return timestamp; } List<Metric> getMetrics() { return metrics; } } }
2,985
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/BasicMetricFilter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.monitor.MonitorConfig; /** * Filter that always returns true or false. */ public final class BasicMetricFilter implements MetricFilter { /** * Filter that matches all metrics. */ public static final MetricFilter MATCH_ALL = new BasicMetricFilter(true); /** * Filter that does not match any metrics. */ public static final MetricFilter MATCH_NONE = new BasicMetricFilter(false); private final boolean match; /** * Creates a new instance with a boolean indicating whether it should * always match or always fail. * * @param match should this filter match? */ public BasicMetricFilter(boolean match) { this.match = match; } /** * {@inheritDoc} */ public boolean matches(MonitorConfig config) { return match; } }
2,986
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/CompositeMetricPoller.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.util.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Combines results from a list of metric pollers. This clas */ public class CompositeMetricPoller implements MetricPoller { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeMetricPoller.class); private static final List<Metric> EMPTY = UnmodifiableList.of(); private static final String POLLER_KEY = "PollerName"; private final Map<String, MetricPoller> pollers; private final ExecutorService executor; private final long timeout; /** * Creates a new instance for a set of pollers. * * @param pollers a set of pollers to collect data from, the map key for a * poller is used as a name identify a particular poller * for logging and error messages * @param executor an executor to use for executing the poll methods * @param timeout timeout in milliseconds used when getting the value * from the future */ public CompositeMetricPoller( Map<String, MetricPoller> pollers, ExecutorService executor, long timeout) { this.pollers = Collections.unmodifiableMap(pollers); this.executor = executor; this.timeout = timeout; } private void increment(Throwable t, String name) { //TagList tags = SortedTagList.builder().withTag(new BasicTag(POLLER_KEY, name)).build(); //Counters.increment(t.getClass().getSimpleName() + "Count", tags); } private List<Metric> getMetrics(String name, Future<List<Metric>> future) { List<Metric> metrics = EMPTY; try { metrics = future.get(timeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { increment(e, name); LOGGER.warn("uncaught exception from poll method for {}", name, e); } catch (TimeoutException e) { // The cancel is needed to prevent the slow task from using up all threads future.cancel(true); increment(e, name); LOGGER.warn("timeout executing poll method for {}", name, e); } catch (InterruptedException e) { increment(e, name); LOGGER.warn("interrupted while doing get for {}", name, e); } return metrics; } /** * {@inheritDoc} */ public final List<Metric> poll(MetricFilter filter) { return poll(filter, false); } /** * {@inheritDoc} */ public final List<Metric> poll(MetricFilter filter, boolean reset) { Map<String, Future<List<Metric>>> futures = new HashMap<>(); for (Map.Entry<String, MetricPoller> e : pollers.entrySet()) { PollCallable task = new PollCallable(e.getValue(), filter, reset); futures.put(e.getKey(), executor.submit(task)); } List<Metric> allMetrics = new ArrayList<>(); for (Map.Entry<String, Future<List<Metric>>> e : futures.entrySet()) { allMetrics.addAll(getMetrics(e.getKey(), e.getValue())); } return allMetrics; } }
2,987
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/MetricFilter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.monitor.MonitorConfig; /** * A filter to restrict the set of metrics that are polled. */ public interface MetricFilter { /** * Check if a metric with the provided configuration should be selected and * sent to observers. * * @param config config settings associated with the metric * @return true if the metric should be selected */ boolean matches(MonitorConfig config); }
2,988
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/PollCallable.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import java.util.List; import java.util.concurrent.Callable; /** * Callable implementation that invokes the {@link MetricPoller#poll} method. */ public final class PollCallable implements Callable<List<Metric>> { private final MetricPoller poller; private final MetricFilter filter; private final boolean reset; /** * Creates a new instance. * * @param poller poller to invoke * @param filter filter to pass into the poller */ public PollCallable(MetricPoller poller, MetricFilter filter) { this(poller, filter, false); } /** * Creates a new instance. * * @param poller poller to invoke * @param filter filter to pass into the poller * @param reset reset flag to pass into the poller */ public PollCallable(MetricPoller poller, MetricFilter filter, boolean reset) { this.poller = poller; this.filter = filter; this.reset = reset; } /** * {@inheritDoc} */ public List<Metric> call() { return poller.poll(filter, reset); } }
2,989
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/JvmMetricPoller.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ClassLoadingMXBean; import java.lang.management.CompilationMXBean; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Poller for standard JVM metrics. */ public class JvmMetricPoller implements MetricPoller { private static final String CLASS = "class"; private static final Thread.State[] VALID_STATES = Thread.State.values(); private static final MonitorConfig LOADED_CLASS_COUNT = MonitorConfig.builder("loadedClassCount") .withTag(CLASS, ClassLoadingMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig TOTAL_LOADED_CLASS_COUNT = MonitorConfig.builder("totalLoadedClassCount") .withTag(CLASS, ClassLoadingMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig UNLOADED_CLASS_COUNT = MonitorConfig.builder("unloadedClassCount") .withTag(CLASS, ClassLoadingMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig TOTAL_COMPILATION_TIME = MonitorConfig.builder("totalCompilationTime") .withTag(CLASS, CompilationMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig COLLECTION_COUNT = MonitorConfig.builder("collectionCount") .withTag(CLASS, GarbageCollectorMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig COLLECTION_TIME = MonitorConfig.builder("collectionTime") .withTag(CLASS, GarbageCollectorMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig COMMITTED_USAGE = MonitorConfig.builder("committedUsage") .withTag(CLASS, MemoryPoolMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig INIT_USAGE = MonitorConfig.builder("initUsage") .withTag(CLASS, MemoryPoolMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig MAX_USAGE = MonitorConfig.builder("maxUsage") .withTag(CLASS, MemoryPoolMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig ACTUAL_USAGE = MonitorConfig.builder("actualUsage") .withTag(CLASS, MemoryPoolMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig AVAILABLE_PROCESSORS = MonitorConfig.builder("availableProcessors") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig LOAD_AVERAGE = MonitorConfig.builder("systemLoadAverage") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig MAX_FILE_DESCRIPTOR_COUNT = MonitorConfig.builder("maxFileDescriptorCount") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig OPEN_FILE_DESCRIPTOR_COUNT = MonitorConfig.builder("openFileDescriptorCount") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig COMMITTED_VIRTUAL_MEMORY_SIZE = MonitorConfig.builder("committedVirtualMemorySize") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig TOTAL_PHYSICAL_MEMORY_SIZE = MonitorConfig.builder("totalPhysicalMemorySize") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig FREE_PHYSICAL_MEMORY_SIZE = MonitorConfig.builder("freePhysicalMemorySize") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig TOTAL_SWAP_SPACE_SIZE = MonitorConfig.builder("totalSwapSpaceSize") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig FREE_SWAP_SPACE_SIZE = MonitorConfig.builder("freeSwapSpaceSize") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig PROCESS_CPU_LOAD = MonitorConfig.builder("processCpuLoad") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig SYSTEM_CPU_LOAD = MonitorConfig.builder("systemCpuLoad") .withTag(CLASS, OperatingSystemMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig DAEMON_THREAD_COUNT = MonitorConfig.builder("daemonThreadCount") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.GAUGE) .build(); private static final MonitorConfig[] THREAD_COUNTS = new MonitorConfig[VALID_STATES.length]; private static final MonitorConfig TOTAL_STARTED_THREAD_COUNT = MonitorConfig.builder("totalStartedThreadCount") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig THREAD_BLOCKED_COUNT = MonitorConfig.builder("threadBlockedCount") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig THREAD_BLOCKED_TIME = MonitorConfig.builder("threadBlockedTime") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig THREAD_WAITED_COUNT = MonitorConfig.builder("threadWaitedCount") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final MonitorConfig THREAD_WAITED_TIME = MonitorConfig.builder("threadWaitedTime") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag(DataSourceType.COUNTER) .build(); private static final Logger LOGGER = LoggerFactory.getLogger(JvmMetricPoller.class); private static final int IDX_BLOCKED_COUNT = 0; private static final int IDX_BLOCKED_TIME = 1; private static final int IDX_WAITED_COUNT = 2; private static final int IDX_WAITED_TIME = 3; private static final long[] BASE_THREAD_COUNTS = new long[]{0L, 0L, 0L, 0L}; private static final Map<Thread.State, Integer> STATE_LOOKUP = new HashMap<>(); static { for (int i = 0; i < VALID_STATES.length; ++i) { Thread.State state = VALID_STATES[i]; STATE_LOOKUP.put(state, i); THREAD_COUNTS[i] = MonitorConfig.builder("threadCount") .withTag(CLASS, ThreadMXBean.class.getSimpleName()) .withTag("state", state.toString()) .withTag(DataSourceType.GAUGE) .build(); } } private ThreadInfo[] lastThreadInfos = new ThreadInfo[0]; /** * {@inheritDoc} */ @Override public final List<Metric> poll(MetricFilter filter) { return poll(filter, false); } /** * {@inheritDoc} */ @Override public final List<Metric> poll(MetricFilter filter, boolean reset) { long now = System.currentTimeMillis(); MetricList metrics = new MetricList(filter); addClassLoadingMetrics(now, metrics); addCompilationMetrics(now, metrics); addGarbageCollectorMetrics(now, metrics); addMemoryPoolMetrics(now, metrics); addOperatingSystemMetrics(now, metrics); addThreadMetrics(now, metrics); return metrics.getList(); } private void addClassLoadingMetrics(long timestamp, MetricList metrics) { ClassLoadingMXBean bean = ManagementFactory.getClassLoadingMXBean(); metrics.add(new Metric(LOADED_CLASS_COUNT, timestamp, bean.getLoadedClassCount())); metrics.add(new Metric(TOTAL_LOADED_CLASS_COUNT, timestamp, bean.getTotalLoadedClassCount())); metrics.add(new Metric(UNLOADED_CLASS_COUNT, timestamp, bean.getUnloadedClassCount())); } private void addCompilationMetrics(long timestamp, MetricList metrics) { CompilationMXBean bean = ManagementFactory.getCompilationMXBean(); metrics.add(new Metric(TOTAL_COMPILATION_TIME, timestamp, bean.getTotalCompilationTime())); } private void addGarbageCollectorMetrics(long timestamp, MetricList metrics) { final List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean bean : beans) { final Tag id = Tags.newTag("id", bean.getName()); metrics.add(new Metric(COLLECTION_COUNT.withAdditionalTag(id), timestamp, bean.getCollectionCount())); metrics.add(new Metric(COLLECTION_TIME.withAdditionalTag(id), timestamp, bean.getCollectionTime())); } } private void addMemoryPoolMetrics(long timestamp, MetricList metrics) { final List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean bean : beans) { final TagList tags = BasicTagList.of("id", bean.getName(), "memtype", bean.getType().name()); addMemoryUsageMetrics(tags, timestamp, bean.getUsage(), metrics); } } private void addMemoryUsageMetrics( TagList tags, long timestamp, MemoryUsage usage, MetricList metrics) { metrics.add(new Metric(COMMITTED_USAGE.withAdditionalTags(tags), timestamp, usage.getCommitted())); metrics.add(new Metric(INIT_USAGE.withAdditionalTags(tags), timestamp, usage.getInit())); metrics.add(new Metric(ACTUAL_USAGE.withAdditionalTags(tags), timestamp, usage.getUsed())); metrics.add(new Metric(MAX_USAGE.withAdditionalTags(tags), timestamp, usage.getMax())); } private void addOperatingSystemMetrics(long timestamp, MetricList metrics) { OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean(); metrics.add(new Metric(AVAILABLE_PROCESSORS, timestamp, bean.getAvailableProcessors())); metrics.add(new Metric(LOAD_AVERAGE, timestamp, bean.getSystemLoadAverage())); addOptionalMetric(MAX_FILE_DESCRIPTOR_COUNT, timestamp, bean, "getMaxFileDescriptorCount", metrics); addOptionalMetric(OPEN_FILE_DESCRIPTOR_COUNT, timestamp, bean, "getOpenFileDescriptorCount", metrics); addOptionalMetric(COMMITTED_VIRTUAL_MEMORY_SIZE, timestamp, bean, "getCommittedVirtualMemorySize", metrics); addOptionalMetric(TOTAL_PHYSICAL_MEMORY_SIZE, timestamp, bean, "getTotalPhysicalMemorySize", metrics); addOptionalMetric(FREE_PHYSICAL_MEMORY_SIZE, timestamp, bean, "getFreePhysicalMemorySize", metrics); addOptionalMetric(TOTAL_SWAP_SPACE_SIZE, timestamp, bean, "getTotalSwapSpaceSize", metrics); addOptionalMetric(FREE_SWAP_SPACE_SIZE, timestamp, bean, "getFreeSwapSpaceSize", metrics); addOptionalMetric(PROCESS_CPU_LOAD, timestamp, bean, "getProcessCpuLoad", metrics); addOptionalMetric(SYSTEM_CPU_LOAD, timestamp, bean, "getSystemCpuLoad", metrics); } private void addThreadMetrics(long timestamp, MetricList metrics) { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); metrics.add(new Metric(DAEMON_THREAD_COUNT, timestamp, bean.getDaemonThreadCount())); metrics.add(new Metric(TOTAL_STARTED_THREAD_COUNT, timestamp, bean.getTotalStartedThreadCount())); addDetailedThreadMetrics(timestamp, metrics); } private void addDetailedThreadMetrics(long timestamp, MetricList metrics) { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (!bean.isThreadContentionMonitoringSupported()) { return; } if (!bean.isThreadContentionMonitoringEnabled()) { bean.setThreadContentionMonitoringEnabled(true); } ThreadInfo[] threadInfo = bean.dumpAllThreads(false, false); Arrays.sort( threadInfo, (a, b) -> { long diff = b.getThreadId() - a.getThreadId(); return ((diff == 0L) ? 0 : (diff < 0L) ? -1 : 1); } ); long[] stateCounts = new long[VALID_STATES.length]; for (int i = 0; i < stateCounts.length; i++) { stateCounts[i] = 0L; } long blockedCount = 0L; long blockedTime = 0L; long waitedCount = 0L; long waitedTime = 0L; int l = lastThreadInfos.length - 1; for (int i = threadInfo.length - 1; i >= 0; i--) { long currId = threadInfo[i].getThreadId(); while (l >= 0 && lastThreadInfos[l].getThreadId() < currId) { --l; } if (l >= 0 && lastThreadInfos[l].getThreadId() > currId) { BASE_THREAD_COUNTS[IDX_BLOCKED_COUNT] += lastThreadInfos[l].getBlockedCount(); BASE_THREAD_COUNTS[IDX_BLOCKED_TIME] += lastThreadInfos[l].getBlockedTime(); BASE_THREAD_COUNTS[IDX_WAITED_COUNT] += lastThreadInfos[l].getWaitedCount(); BASE_THREAD_COUNTS[IDX_WAITED_TIME] += lastThreadInfos[l].getWaitedTime(); } stateCounts[STATE_LOOKUP.get(threadInfo[i].getThreadState())]++; blockedCount += threadInfo[i].getBlockedCount(); blockedTime += threadInfo[i].getBlockedTime(); waitedCount += threadInfo[i].getWaitedCount(); waitedTime += threadInfo[i].getWaitedTime(); } metrics.add(new Metric(THREAD_BLOCKED_COUNT, timestamp, blockedCount + BASE_THREAD_COUNTS[IDX_BLOCKED_COUNT])); metrics.add(new Metric(THREAD_BLOCKED_TIME, timestamp, (blockedTime + BASE_THREAD_COUNTS[IDX_BLOCKED_TIME]) / 1000)); metrics.add(new Metric(THREAD_WAITED_COUNT, timestamp, waitedCount + BASE_THREAD_COUNTS[IDX_WAITED_COUNT])); metrics.add(new Metric(THREAD_WAITED_TIME, timestamp, (waitedTime + BASE_THREAD_COUNTS[IDX_WAITED_TIME]) / 1000)); for (int i = 0; i < stateCounts.length; i++) { metrics.add(new Metric(THREAD_COUNTS[i], timestamp, stateCounts[i])); } lastThreadInfos = threadInfo; } private void addOptionalMetric( MonitorConfig config, long timestamp, Object obj, String methodName, MetricList metrics) { try { Method method = obj.getClass().getMethod(methodName); method.setAccessible(true); Number value = (Number) method.invoke(obj); metrics.add(new Metric(config, timestamp, value)); } catch (Exception e) { final String msg = String.format("failed to get value for %s.%s", obj.getClass().getName(), methodName); LOGGER.debug(msg, e); } } private static class MetricList { private final MetricFilter filter; private final List<Metric> list; MetricList(MetricFilter filter) { this.filter = filter; list = new ArrayList<>(); } public void add(Metric m) { if (filter.matches(m.getConfig())) { list.add(m); } } public List<Metric> getList() { return list; } } }
2,990
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/LocalJmxConnector.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import javax.management.MBeanServerConnection; import java.lang.management.ManagementFactory; /** * Retrieves a connection to the local mbean server running in the same JVM. */ public final class LocalJmxConnector implements JmxConnector { /** * {@inheritDoc} */ public MBeanServerConnection getConnection() { return ManagementFactory.getPlatformMBeanServer(); } }
2,991
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/NormalizationTransform.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Converts rate metrics into normalized values. See * <a href="http://www.vandenbogaerdt.nl/rrdtool/process.php">Rates, normalizing and * consolidating</a> for a * discussion on normalization of rates as done by rrdtool. */ public final class NormalizationTransform implements MetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(NormalizationTransform.class); private static final String DEFAULT_DSTYPE = DataSourceType.RATE.name(); static Counter newCounter(String name) { Counter c = Monitors.newCounter(name); DefaultMonitorRegistry.getInstance().register(c); return c; } @VisibleForTesting static final Counter HEARTBEAT_EXCEEDED = newCounter("servo.norm.heartbeatExceeded"); private final MetricObserver observer; private final long heartbeatMillis; private final long stepMillis; private final Map<MonitorConfig, NormalizedValue> cache; /** * Creates a new instance with the specified sampling and heartbeat interval using the default * clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval in milliseconds * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * (in milliseconds) * @deprecated Please use a constructor that specifies the the timeunit explicitly. */ @Deprecated public NormalizationTransform(MetricObserver observer, long step, long heartbeat) { this(observer, step, heartbeat, TimeUnit.MILLISECONDS, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the * specified clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval in milliseconds * @param heartbeat how long to keep values before dropping them and treating new samples as * first report (in milliseconds) * @param clock The {@link com.netflix.servo.util.Clock} to use for getting * the current time. * @deprecated Please use a constructor that specifies the the timeunit explicitly. */ @Deprecated public NormalizationTransform(MetricObserver observer, long step, final long heartbeat, final Clock clock) { this(observer, step, heartbeat, TimeUnit.MILLISECONDS, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the * specified clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * @param unit {@link java.util.concurrent.TimeUnit} in which step and heartbeat * are specified. */ public NormalizationTransform(MetricObserver observer, long step, long heartbeat, TimeUnit unit) { this(observer, step, heartbeat, unit, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the specified * clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * @param unit The {@link java.util.concurrent.TimeUnit} in which step * and heartbeat are specified. * @param clock The {@link com.netflix.servo.util.Clock} * to use for getting the current time. */ public NormalizationTransform(MetricObserver observer, long step, final long heartbeat, TimeUnit unit, final Clock clock) { this.observer = Preconditions.checkNotNull(observer, "observer"); Preconditions.checkArgument(step > 0, "step must be positive"); this.stepMillis = unit.toMillis(step); Preconditions.checkArgument(heartbeat > 0, "heartbeat must be positive"); this.heartbeatMillis = unit.toMillis(heartbeat); this.cache = new LinkedHashMap<MonitorConfig, NormalizedValue>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<MonitorConfig, NormalizedValue> eldest) { final long lastMod = eldest.getValue().lastUpdateTime; if (lastMod < 0) { return false; } final long now = clock.now(); final boolean expired = (now - lastMod) > heartbeatMillis; if (expired) { HEARTBEAT_EXCEEDED.increment(); LOGGER.debug("heartbeat interval exceeded, expiring {}", eldest.getKey()); } return expired; } }; } private static String getDataSourceType(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); if (value != null) { return value; } else { return DEFAULT_DSTYPE; } } private static boolean isGauge(String dsType) { return dsType.equals(DataSourceType.GAUGE.name()); } private static boolean isRate(String dsType) { return dsType.equals(DataSourceType.RATE.name()); } private static boolean isNormalized(String dsType) { return dsType.equals(DataSourceType.NORMALIZED.name()); } private static boolean isInformational(String dsType) { return dsType.equals(DataSourceType.INFORMATIONAL.name()); } private Metric normalize(Metric m, long stepBoundary) { NormalizedValue normalizedValue = cache.get(m.getConfig()); if (normalizedValue == null) { normalizedValue = new NormalizedValue(); cache.put(m.getConfig(), normalizedValue); } double value = normalizedValue.updateAndGet(m.getTimestamp(), m.getNumberValue().doubleValue()); return new Metric(m.getConfig(), stepBoundary, value); } /** * {@inheritDoc} */ @Override public void update(List<Metric> metrics) { Preconditions.checkNotNull(metrics, "metrics"); final List<Metric> newMetrics = new ArrayList<>(metrics.size()); for (Metric m : metrics) { long offset = m.getTimestamp() % stepMillis; long stepBoundary = m.getTimestamp() - offset; String dsType = getDataSourceType(m); if (isGauge(dsType) || isNormalized(dsType)) { Metric atStepBoundary = new Metric(m.getConfig(), stepBoundary, m.getValue()); newMetrics.add(atStepBoundary); // gauges are not normalized } else if (isRate(dsType)) { Metric normalized = normalize(m, stepBoundary); if (normalized != null) { newMetrics.add(normalized); } } else if (!isInformational(dsType)) { // unknown type - use a safe fallback newMetrics.add(m); // we cannot normalize this } } observer.update(newMetrics); } /** * {@inheritDoc} */ @Override public String getName() { return observer.getName(); } private static final long NO_PREVIOUS_UPDATE = -1L; private class NormalizedValue { private long lastUpdateTime = NO_PREVIOUS_UPDATE; private double lastValue = 0.0; private double weightedValue(long offset, double value) { double weight = (double) offset / stepMillis; return value * weight; } double updateAndGet(long timestamp, double value) { double result = Double.NaN; if (timestamp > lastUpdateTime) { if (lastUpdateTime > 0 && timestamp - lastUpdateTime > heartbeatMillis) { lastUpdateTime = NO_PREVIOUS_UPDATE; lastValue = 0.0; } long offset = timestamp % stepMillis; long stepBoundary = timestamp - offset; if (lastUpdateTime < stepBoundary) { if (lastUpdateTime != NO_PREVIOUS_UPDATE) { long intervalOffset = lastUpdateTime % stepMillis; lastValue += weightedValue(stepMillis - intervalOffset, value); result = lastValue; } else if (offset == 0) { result = value; } else { result = weightedValue(stepMillis - offset, value); } lastValue = weightedValue(offset, value); } else { // Didn't cross step boundary, so update is more frequent than step // and we just need to // add in the weighted value long intervalOffset = timestamp - lastUpdateTime; lastValue += weightedValue(intervalOffset, value); result = lastValue; } } lastUpdateTime = timestamp; return result; } } }
2,992
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/BaseMetricPoller.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Base class for simple pollers that do not benefit from filtering in advance. * Sub-classes implement {@link #pollImpl} to return a list and all filtering * will be taken care of by the provided implementation of {@link #poll}. */ public abstract class BaseMetricPoller implements MetricPoller { protected final Logger logger = LoggerFactory.getLogger(getClass()); /** * Return a list of all current metrics for this poller. */ public abstract List<Metric> pollImpl(boolean reset); /** * {@inheritDoc} */ public final List<Metric> poll(MetricFilter filter) { return poll(filter, false); } /** * {@inheritDoc} */ public final List<Metric> poll(MetricFilter filter, boolean reset) { Preconditions.checkNotNull(filter, "filter"); List<Metric> metrics = pollImpl(reset); List<Metric> retained = metrics.stream().filter(m -> filter.matches(m.getConfig())) .collect(Collectors.toList()); logger.debug("received {} metrics, retained {} metrics", metrics.size(), retained.size()); return Collections.unmodifiableList(retained); } }
2,993
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.Throwables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.zip.GZIPOutputStream; /** * Writes observations to a file. The format is a basic text file with tabs * separating the fields. */ public final class FileMetricObserver extends BaseMetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(FileMetricObserver.class); private static final String FILE_DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss_SSS"; private final File dir; private final boolean compress; private final Clock clock; private final SimpleDateFormat fileFormat; /** * Creates a new instance that stores files in {@code dir} with a prefix of * {@code name} and a suffix of a timestamp in the format * {@code yyyy_MM_dd_HH_mm_ss_SSS}. * * @param name name to use as a prefix on files * @param dir directory where observations will be stored */ public FileMetricObserver(String name, File dir) { this(name, dir, false); } /** * Creates a new instance that stores files in {@code dir} with a prefix of * {@code name} and a suffix of a timestamp in the format * {@code yyyy_MM_dd_HH_mm_ss_SSS}. * * @param name name to use as a prefix on files * @param dir directory where observations will be stored * @param compress whether to compress our output */ public FileMetricObserver(String name, File dir, boolean compress) { this(name, String.format("'%s'_%s", name, FILE_DATE_FORMAT) + (compress ? "'.log.gz'" : "'.log'"), dir, compress); } /** * Creates a new instance that stores files in {@code dir} with a name that * is created using {@code namePattern}. * * @param name name of the observer * @param namePattern date format pattern used to create the file names * @param dir directory where observations will be stored * @param compress whether to compress our output */ public FileMetricObserver(String name, String namePattern, File dir, boolean compress) { this(name, namePattern, dir, compress, ClockWithOffset.INSTANCE); } /** * Creates a new instance that stores files in {@code dir} with a name that * is created using {@code namePattern}. * * @param name name of the observer * @param namePattern date format pattern used to create the file names * @param dir directory where observations will be stored * @param compress whether to compress our output * @param clock clock instance to use for getting the time used in the filename */ public FileMetricObserver(String name, String namePattern, File dir, boolean compress, Clock clock) { super(name); this.dir = dir; this.compress = compress; this.clock = clock; fileFormat = new SimpleDateFormat(namePattern); fileFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * {@inheritDoc} */ public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics, "metrics"); File file = new File(dir, fileFormat.format(new Date(clock.now()))); Writer out = null; try { try { LOGGER.debug("writing {} metrics to file {}", metrics.size(), file); OutputStream fileOut = new FileOutputStream(file, true); if (compress) { fileOut = new GZIPOutputStream(fileOut); } out = new OutputStreamWriter(fileOut, "UTF-8"); for (Metric m : metrics) { out.append(m.getConfig().getName()).append('\t') .append(m.getConfig().getTags().toString()).append('\t') .append(m.getValue().toString()).append('\n'); } } catch (Throwable t) { if (out != null) { out.close(); out = null; } throw Throwables.propagate(t); } finally { if (out != null) { out.close(); } } } catch (IOException e) { incrementFailedCount(); LOGGER.error("failed to write update to file {}", file, e); } } }
2,994
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/RegexMetricFilter.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import java.util.regex.Pattern; /** * Filter that checks if a tag value matches a regular expression. */ public final class RegexMetricFilter implements MetricFilter { private final String tagKey; private final Pattern pattern; private final boolean matchIfMissingTag; private final boolean invert; /** * Creates a new regex filter. * * @param tagKey tag to check against the pattern * @param pattern pattern to check * @param matchIfMissingTag should metrics without the specified tag match? * @param invert should the match be inverted? */ public RegexMetricFilter( String tagKey, Pattern pattern, boolean matchIfMissingTag, boolean invert) { this.tagKey = tagKey; this.pattern = pattern; this.matchIfMissingTag = matchIfMissingTag; this.invert = invert; } /** * {@inheritDoc} */ public boolean matches(MonitorConfig config) { String name = config.getName(); TagList tags = config.getTags(); String value; if (tagKey == null) { value = name; } else { Tag t = tags.getTag(tagKey); value = (t == null) ? null : t.getValue(); } boolean match = matchIfMissingTag; if (value != null) { match = pattern.matcher(value).matches(); } return match ^ invert; } }
2,995
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/PollRunnable.java
/* * Copyright 2014 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.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; /** * Runnable that will send updates to a collection of observers. */ public class PollRunnable implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(PollRunnable.class); private final MetricPoller poller; private final MetricFilter filter; private final boolean reset; private final List<MetricObserver> observers; /** * Creates a new runnable instance that executes poll with the given filter * and sends the metrics to all of the given observers. */ public PollRunnable( MetricPoller poller, MetricFilter filter, Collection<MetricObserver> observers) { this(poller, filter, false, observers); } /** * Creates a new runnable instance that executes poll with the given filter * and sends the metrics to all of the given observers. */ public PollRunnable( MetricPoller poller, MetricFilter filter, boolean reset, Collection<MetricObserver> observers) { this.poller = Preconditions.checkNotNull(poller, "poller"); this.filter = Preconditions.checkNotNull(filter, "poller"); this.reset = reset; this.observers = UnmodifiableList.copyOf(observers); } /** * Creates a new runnable instance that executes poll with the given filter * and sends the metrics to all of the given observers. */ public PollRunnable( MetricPoller poller, MetricFilter filter, MetricObserver... observers) { this(poller, filter, false, UnmodifiableList.copyOf(observers)); } /** * {@inheritDoc} */ @Override public void run() { try { List<Metric> metrics = poller.poll(filter, reset); for (MetricObserver o : observers) { try { o.update(metrics); } catch (Throwable t) { LOGGER.warn("failed to send metrics to {}", o.getName(), t); } } } catch (Throwable t) { LOGGER.warn("failed to poll metrics", t); } } }
2,996
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/PollScheduler.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.util.ThreadFactories; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** * Basic scheduler for polling metrics and reporting them to observers. You * can add {@link PollRunnable} objects but not remove them individually. * If you stop the instance and then start it again all of the prior tasks * will be thrown away. */ public final class PollScheduler { private static final PollScheduler INSTANCE = new PollScheduler(); /** * Return the instance of this scheduler. */ public static PollScheduler getInstance() { return INSTANCE; } private PollScheduler() { } private final AtomicReference<ScheduledExecutorService> executor = new AtomicReference<>(); /** * Add a tasks to execute at a fixed rate based on the provided delay. */ public void addPoller(PollRunnable task, long delay, TimeUnit timeUnit) { ScheduledExecutorService service = executor.get(); if (service != null) { service.scheduleWithFixedDelay(task, 0, delay, timeUnit); } else { throw new IllegalStateException( "you must start the scheduler before tasks can be submitted"); } } /** * Start scheduling tasks with a default thread pool, sized based on the * number of available processors. */ public void start() { int numThreads = Runtime.getRuntime().availableProcessors(); ThreadFactory factory = ThreadFactories.withName("ServoPollScheduler-%d"); start(Executors.newScheduledThreadPool(numThreads, factory)); } /** * Start the poller with the given executor service. */ public void start(ScheduledExecutorService service) { if (!executor.compareAndSet(null, service)) { throw new IllegalStateException("cannot start scheduler again without stopping it"); } } /** * Stop the poller, shutting down the current executor service. */ public void stop() { ScheduledExecutorService service = executor.get(); if (service != null && executor.compareAndSet(service, null)) { service.shutdown(); } else { throw new IllegalStateException("scheduler must be started before you stop it"); } } /** * Returns true if this scheduler is currently started. */ public boolean isStarted() { return executor.get() != null; } }
2,997
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/JmxMetricPoller.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.SmallTagMap; import com.netflix.servo.tag.StandardTagKeys; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.Attribute; import javax.management.InstanceNotFoundException; import javax.management.JMException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Generic poller for fetching simple data from JMX. */ public final class JmxMetricPoller implements MetricPoller { private static final Logger LOGGER = LoggerFactory.getLogger(JmxMetricPoller.class); private static final Tag CLASS_TAG = Tags.newTag( StandardTagKeys.CLASS_NAME.getKeyName(), JmxMetricPoller.class.getCanonicalName()); private static final String DOMAIN_KEY = "JmxDomain"; private static final String COMPOSITE_PATH_KEY = "JmxCompositePath"; private static final String PROP_KEY_PREFIX = "Jmx"; private final JmxConnector connector; private final List<ObjectName> queries; private final MetricFilter counters; private final boolean onlyNumericMetrics; private final List<Tag> defaultTags; /** * Creates a new instance that polls mbeans matching the provided object * name pattern. * * @param connector used to get a connection to an MBeanServer * @param query object name pattern for selecting mbeans * @param counters metrics matching this filter will be treated as * counters, all others will be gauges */ public JmxMetricPoller( JmxConnector connector, ObjectName query, MetricFilter counters) { this(connector, Collections.singletonList(query), counters, true, null); } /** * Creates a new instance that polls mbeans matching the provided object * name patterns. * * @param connector used to get a connection to an MBeanServer * @param queries object name patterns for selecting mbeans * @param counters metrics matching this filter will be treated as * counters, all others will be gauges */ public JmxMetricPoller( JmxConnector connector, List<ObjectName> queries, MetricFilter counters) { this(connector, queries, counters, true, null); } /** * Creates a new instance that polls mbeans matching the provided object * name pattern. * * @param connector used to get a connection to an MBeanServer * @param queries object name patterns for selecting mbeans * @param counters metrics matching this filter will be treated as * counters, all others will be gauges * @param onlyNumericMetrics only produce metrics that can be converted to a Number * (filter out all strings, etc) * @param defaultTags a list of tags to attach to all metrics, usually * useful to identify all metrics from a given application or hostname */ public JmxMetricPoller( JmxConnector connector, List<ObjectName> queries, MetricFilter counters, boolean onlyNumericMetrics, List<Tag> defaultTags) { this.connector = connector; this.queries = queries; this.counters = counters; this.onlyNumericMetrics = onlyNumericMetrics; this.defaultTags = defaultTags; } /** * Creates a tag list from an object name. */ private TagList createTagList(ObjectName name) { Map<String, String> props = name.getKeyPropertyList(); SmallTagMap.Builder tagsBuilder = SmallTagMap.builder(); for (Map.Entry<String, String> e : props.entrySet()) { String key = PROP_KEY_PREFIX + "." + e.getKey(); tagsBuilder.add(Tags.newTag(key, e.getValue())); } tagsBuilder.add(Tags.newTag(DOMAIN_KEY, name.getDomain())); tagsBuilder.add(CLASS_TAG); if (defaultTags != null) { defaultTags.forEach(tagsBuilder::add); } return new BasicTagList(tagsBuilder.result()); } private static TagList getTagListWithAdditionalTag(TagList tags, Tag extra) { return new BasicTagList(SmallTagMap.builder().addAll(tags).add(extra).result()); } /** * Create a new metric object and add it to the list. */ private void addMetric( List<Metric> metrics, String name, TagList tags, Object value) { long now = System.currentTimeMillis(); if (onlyNumericMetrics) { value = asNumber(value); } if (value != null) { TagList newTags = counters.matches(MonitorConfig.builder(name).withTags(tags).build()) ? getTagListWithAdditionalTag(tags, DataSourceType.COUNTER) : getTagListWithAdditionalTag(tags, DataSourceType.GAUGE); Metric m = new Metric(name, newTags, now, value); metrics.add(m); } } /** * Recursively extracts simple numeric values from composite data objects. * The map {@code values} will be populated with a path to the value as * the key and the simple object as the value. */ private void extractValues(String path, Map<String, Object> values, CompositeData obj) { for (String key : obj.getCompositeType().keySet()) { String newPath = (path == null) ? key : path + "." + key; Object value = obj.get(key); if (value instanceof CompositeData) { extractValues(newPath, values, (CompositeData) value); } else if (value != null) { values.put(newPath, value); } } } /** * Query the mbean connection and add all metrics that satisfy the filter * to the list {@code metrics}. */ private void getMetrics( MBeanServerConnection con, MetricFilter filter, List<Metric> metrics, ObjectName name) throws JMException, IOException { // Create tags from the object name TagList tags = createTagList(name); MBeanInfo info = con.getMBeanInfo(name); MBeanAttributeInfo[] attrInfos = info.getAttributes(); // Restrict to attributes that match the filter List<String> matchingNames = new ArrayList<>(); for (MBeanAttributeInfo attrInfo : attrInfos) { String attrName = attrInfo.getName(); if (filter.matches(new MonitorConfig.Builder(attrName).withTags(tags).build())) { matchingNames.add(attrName); } } List<Attribute> attributeList = safelyLoadAttributes(con, name, matchingNames); for (Attribute attr : attributeList) { String attrName = attr.getName(); Object obj = attr.getValue(); if (obj instanceof TabularData) { ((TabularData) obj).values().stream() .filter(key -> key instanceof CompositeData) .forEach(key -> addTabularMetrics(filter, metrics, tags, attrName, (CompositeData) key)); } else if (obj instanceof CompositeData) { addCompositeMetrics(filter, metrics, tags, attrName, (CompositeData) obj); } else { addMetric(metrics, attrName, tags, obj); } } } private void addCompositeMetrics(MetricFilter filter, List<Metric> metrics, TagList tags, String attrName, CompositeData obj) { Map<String, Object> values = new HashMap<>(); extractValues(null, values, obj); for (Map.Entry<String, Object> e : values.entrySet()) { final Tag compositeTag = Tags.newTag(COMPOSITE_PATH_KEY, e.getKey()); final TagList newTags = getTagListWithAdditionalTag(tags, compositeTag); if (filter.matches(MonitorConfig.builder(attrName).withTags(newTags).build())) { addMetric(metrics, attrName, newTags, e.getValue()); } } } private void addTabularMetrics(MetricFilter filter, List<Metric> metrics, TagList tags, String attrName, CompositeData obj) { Map<String, Object> values = new HashMap<>(); // tabular composite data has a value called key and one called value values.put(obj.get("key").toString(), obj.get("value")); for (Map.Entry<String, Object> e : values.entrySet()) { final Tag compositeTag = Tags.newTag(COMPOSITE_PATH_KEY, e.getKey()); final TagList newTags = getTagListWithAdditionalTag(tags, compositeTag); if (filter.matches(MonitorConfig.builder(attrName).withTags(newTags).build())) { addMetric(metrics, attrName, newTags, e.getValue()); } } } /** * Try to convert an object into a number. Boolean values will return 1 if * true and 0 if false. If the value is null or an unknown data type null * will be returned. */ private static Number asNumber(Object value) { Number num = null; if (value == null) { num = null; } else if (value instanceof Number) { num = (Number) value; } else if (value instanceof Boolean) { num = ((Boolean) value) ? 1 : 0; } return num; } /** * {@inheritDoc} */ public List<Metric> poll(MetricFilter filter) { return poll(filter, false); } /** * {@inheritDoc} */ public List<Metric> poll(MetricFilter filter, boolean reset) { List<Metric> metrics = new ArrayList<>(); try { MBeanServerConnection con = connector.getConnection(); for (ObjectName query : queries) { Set<ObjectName> names = con.queryNames(query, null); if (names.isEmpty()) { LOGGER.warn("no mbeans matched query: {}", query); } else { for (ObjectName name : names) { try { getMetrics(con, filter, metrics, name); } catch (Exception e) { LOGGER.warn("failed to get metrics for: {}", name, e); } } } } } catch (Exception e) { LOGGER.warn("failed to collect jmx metrics.", e); } return metrics; } /** * There are issues loading some JMX attributes on some systems. This protects us from a * single bad attribute stopping us reading any metrics (or just a random sampling) out of * the system. */ private static List<Attribute> safelyLoadAttributes( MBeanServerConnection server, ObjectName objectName, List<String> matchingNames) { try { // first try batch loading all attributes as this is faster return batchLoadAttributes(server, objectName, matchingNames); } catch (Exception e) { // JBOSS ticket: https://issues.jboss.org/browse/AS7-4404 LOGGER.info("Error batch loading attributes for {} : {}", objectName, e.getMessage()); // some containers (jboss I am looking at you) fail the entire getAttributes request // if one is broken we can get the working attributes if we ask for them individually return individuallyLoadAttributes(server, objectName, matchingNames); } } private static List<Attribute> batchLoadAttributes( MBeanServerConnection server, ObjectName objectName, List<String> matchingNames) throws InstanceNotFoundException, ReflectionException, IOException { final String[] namesArray = matchingNames.toArray(new String[matchingNames.size()]); return server.getAttributes(objectName, namesArray).asList(); } private static List<Attribute> individuallyLoadAttributes( MBeanServerConnection server, ObjectName objectName, List<String> matchingNames) { List<Attribute> attributes = new ArrayList<>(); for (String attrName : matchingNames) { try { Object value = server.getAttribute(objectName, attrName); attributes.add(new Attribute(attrName, value)); } catch (Exception e) { LOGGER.info("Couldn't load attribute {} for {} : {}", new Object[]{attrName, objectName, e.getMessage()}, e); } } return attributes; } }
2,998
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/publish/MetricPoller.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish; import com.netflix.servo.Metric; import java.util.List; /** * A poller that can be used to fetch current values for a list of metrics on * demand. */ public interface MetricPoller { /** * Fetch the current values for a set of metrics that match the provided * filter. This method should be cheap, thread-safe, and interruptible so * that it can be called frequently to collect metrics at a regular * interval. * * @param filter retricts the set of metrics * @return list of current metric values */ List<Metric> poll(MetricFilter filter); /** * Fetch the current values for a set of metrics that match the provided * filter. This method should be cheap, thread-safe, and interruptible so * that it can be called frequently to collect metrics at a regular * interval. * * @param filter retricts the set of metrics * @param reset ignored. This is kept for backwards compatibility only. * @return list of current metric values */ List<Metric> poll(MetricFilter filter, boolean reset); }
2,999