index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ContextAwareMetric.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import com.codahale.metrics.Metric;
import org.apache.gobblin.metrics.metric.ProxyMetric;
/**
* An interface for a type of {@link com.codahale.metrics.Metric}s that are aware of their
* {@link MetricContext} and can have associated {@link Tag}s.
*
* @author Yinan Li
*/
public interface ContextAwareMetric extends Metric, ProxyMetric {
/**
* Get the name of the metric.
*
* @return the name of the metric
*/
public String getName();
/**
* Get the {@link MetricContext} the metric is registered in.
*/
public MetricContext getContext();
}
| 4,400 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerCounter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.lang.ref.WeakReference;
import com.codahale.metrics.Counter;
import com.google.common.base.Optional;
import org.apache.gobblin.metrics.metric.InnerMetric;
/**
* Implementation of {@link InnerMetric} for {@link Counter}.
*/
public class InnerCounter extends Counter implements InnerMetric {
protected final String name;
protected final Tagged tagged;
protected final Optional<ContextAwareCounter> parentCounter;
private final WeakReference<ContextAwareCounter> contextAwareCounter;
public InnerCounter(MetricContext context, String name, ContextAwareCounter counter) {
this.tagged = new Tagged();
this.name = name;
Optional<MetricContext> parentContext = context.getParent();
if (parentContext.isPresent()) {
this.parentCounter = Optional.fromNullable(parentContext.get().contextAwareCounter(name));
} else {
this.parentCounter = Optional.absent();
}
this.contextAwareCounter = new WeakReference<>(counter);
}
@Override
public void inc(long n) {
super.inc(n);
if (this.parentCounter.isPresent()) {
this.parentCounter.get().inc(n);
}
}
@Override
public void dec(long n) {
super.dec(n);
if (this.parentCounter.isPresent()) {
this.parentCounter.get().dec(n);
}
}
public String getName() {
return this.name;
}
@Override
public ContextAwareMetric getContextAwareMetric() {
return this.contextAwareCounter.get();
}
}
| 4,401 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/Tagged.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
/**
* A base implementation of {@link Taggable}.
*
* @author Yinan Li
*/
public class Tagged implements Taggable {
protected final Map<String, Object> tags;
public Tagged() {
this.tags = Maps.newLinkedHashMap();
}
public Tagged(Collection<Tag<?>> tags) {
this.tags = Maps.newLinkedHashMap();
addTags(tags);
}
@Override
public void addTag(Tag<?> tag) {
Preconditions.checkNotNull(tag, "Cannot add a null Tag");
Preconditions.checkNotNull(tag.getValue(), "Cannot add a Tag with a null value. Tag: " + tag);
this.tags.put(tag.getKey(), tag.getValue());
}
@Override
public void addTags(Collection<Tag<?>> tags) {
for (Tag<?> tag : tags) {
addTag(tag);
}
}
@Override
public List<Tag<?>> getTags() {
ImmutableList.Builder<Tag<?>> builder = ImmutableList.builder();
for (Map.Entry<String, Object> entry : this.tags.entrySet()) {
builder.add(new Tag<Object>(entry.getKey(), entry.getValue()));
}
return builder.build();
}
/**
* Return tags as a Map.
* @return map of tags.
*/
public Map<String, Object> getTagMap() {
return ImmutableMap.copyOf(this.tags);
}
/**
* Get a metric name constructed from the {@link Tag}s.
*/
@Override
public String metricNamePrefix(boolean includeTagKeys) {
return Joiner.on('.').join(includeTagKeys ? getTags() : this.tags.values());
}
}
| 4,402 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MetricContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import lombok.Getter;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.gobblin.metrics.context.NameConflictException;
import org.apache.gobblin.metrics.context.ReportableContext;
import org.apache.gobblin.metrics.notification.EventNotification;
import org.apache.gobblin.metrics.notification.Notification;
import org.apache.gobblin.util.ExecutorsUtils;
/**
* This class models a {@link MetricSet} that optionally has a list of {@link Tag}s
* and a set of {@link com.codahale.metrics.ScheduledReporter}s associated with it. The
* {@link Tag}s associated with a {@link MetricContext} are used to construct the
* common metric name prefix of registered {@link com.codahale.metrics.Metric}s.
*
* <p>
* {@link MetricContext}s can form a hierarchy and any {@link MetricContext} can create
* children {@link MetricContext}s. A child {@link MetricContext} inherit all the
* {@link Tag}s associated with its parent, in additional to the {@link Tag}s
* of itself. {@link Tag}s inherited from its parent will appear in front of those
* of itself when constructing the metric name prefix.
* </p>
*
* @author Yinan Li
*/
public class MetricContext extends MetricRegistry implements ReportableContext, Closeable {
protected final Closer closer;
public static final String METRIC_CONTEXT_ID_TAG_NAME = "metricContextID";
public static final String METRIC_CONTEXT_NAME_TAG_NAME = "metricContextName";
@Getter
private final InnerMetricContext innerMetricContext;
private static final Logger LOG = LoggerFactory.getLogger(MetricContext.class);
public static final String GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME = "gobblin.metrics.notifications.timer";
// Targets for notifications.
private final Map<UUID, Function<Notification, Void>> notificationTargets;
private final ContextAwareTimer notificationTimer;
private Optional<ExecutorService> executorServiceOptional;
// This set exists so that metrics that have no hard references in code don't get GCed while the MetricContext
// is alive.
private final Set<ContextAwareMetric> contextAwareMetricsSet;
protected MetricContext(String name, MetricContext parent, List<Tag<?>> tags, boolean isRoot) throws NameConflictException {
Preconditions.checkArgument(!Strings.isNullOrEmpty(name));
this.closer = Closer.create();
try {
this.innerMetricContext = this.closer.register(new InnerMetricContext(this, name, parent, tags));
} catch(ExecutionException ee) {
throw Throwables.propagate(ee);
}
this.contextAwareMetricsSet = Sets.newConcurrentHashSet();
this.notificationTargets = Maps.newConcurrentMap();
this.executorServiceOptional = Optional.absent();
this.notificationTimer = new ContextAwareTimer(this, GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME);
register(this.notificationTimer);
if (!isRoot) {
RootMetricContext.get().addMetricContext(this);
}
}
private synchronized ExecutorService getExecutorService() {
if(!this.executorServiceOptional.isPresent()) {
this.executorServiceOptional = Optional.of(MoreExecutors.getExitingExecutorService(
(ThreadPoolExecutor) Executors.newCachedThreadPool(ExecutorsUtils.newThreadFactory(Optional.of(LOG),
Optional.of("MetricContext-" + getName() + "-%d"))), 5,
TimeUnit.MINUTES));
}
return this.executorServiceOptional.get();
}
/**
* Get the name of this {@link MetricContext}.
*
* @return the name of this {@link MetricContext}
*/
public String getName() {
return this.innerMetricContext.getName();
}
/**
* Get the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}, which may be absent if it has not parent
* {@link MetricContext}.
*
* @return the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}
*/
public Optional<MetricContext> getParent() {
return this.innerMetricContext.getParent();
}
/**
* Get a view of the child {@link org.apache.gobblin.metrics.MetricContext}s as a {@link com.google.common.collect.ImmutableMap}.
* @return {@link com.google.common.collect.ImmutableMap} of
* child {@link org.apache.gobblin.metrics.MetricContext}s keyed by their names.
*/
public Map<String, MetricContext> getChildContextsAsMap() {
return this.innerMetricContext.getChildContextsAsMap();
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getNames()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedSet<String> getNames() {
return this.innerMetricContext.getNames();
}
/**
* Inject the tags of this {@link MetricContext} to the given {@link GobblinTrackingEvent}
*/
private void injectTagsToEvent(GobblinTrackingEvent event) {
Map<String, String> originalMetadata = event.getMetadata();
Map<String, Object> tags = getTagMap();
Map<String, String> newMetadata = Maps.newHashMap();
for(Map.Entry<String, Object> entry : tags.entrySet()) {
newMetadata.put(entry.getKey(), entry.getValue().toString());
}
newMetadata.putAll(originalMetadata);
event.setMetadata(newMetadata);
}
/**
* Submit {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to all notification listeners attached to this or any
* ancestor {@link org.apache.gobblin.metrics.MetricContext}s. The argument for this method is mutated by the method, so it
* should not be reused by the caller.
*
* @param nonReusableEvent {@link GobblinTrackingEvent} to submit. This object will be mutated by the method,
* so it should not be reused by the caller.
*/
public void submitEvent(GobblinTrackingEvent nonReusableEvent) {
nonReusableEvent.setTimestamp(System.currentTimeMillis());
injectTagsToEvent(nonReusableEvent);
EventNotification notification = new EventNotification(nonReusableEvent);
sendNotification(notification);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getMetrics()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public Map<String, Metric> getMetrics() {
return this.innerMetricContext.getMetrics();
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getGauges()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Gauge> getGauges() {
return this.innerMetricContext.getGauges(MetricFilter.ALL);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getGauges(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
return this.innerMetricContext.getGauges(filter);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getCounters()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Counter> getCounters() {
return this.innerMetricContext.getCounters(MetricFilter.ALL);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getCounters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Counter> getCounters(MetricFilter filter) {
return this.innerMetricContext.getCounters(filter);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getHistograms()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Histogram> getHistograms() {
return this.innerMetricContext.getHistograms(MetricFilter.ALL);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getHistograms(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
return this.innerMetricContext.getHistograms(filter);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getMeters()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Meter> getMeters() {
return this.innerMetricContext.getMeters(MetricFilter.ALL);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getMeters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return this.innerMetricContext.getMeters(filter);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getTimers()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Timer> getTimers() {
return this.innerMetricContext.getTimers(MetricFilter.ALL);
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getTimers(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Timer> getTimers(MetricFilter filter) {
return this.innerMetricContext.getTimers(filter);
}
/**
* This is equivalent to {@link #contextAwareCounter(String)}.
*/
@Override
public Counter counter(String name) {
return contextAwareCounter(name);
}
/**
* This is equivalent to {@link #contextAwareMeter(String)}.
*/
@Override
public Meter meter(String name) {
return contextAwareMeter(name);
}
/**
* This is equivalent to {@link #contextAwareHistogram(String)}.
*/
@Override
public Histogram histogram(String name) {
return contextAwareHistogram(name);
}
/**
* This is equivalent to {@link #contextAwareTimer(String)}.
*/
@Override
public ContextAwareTimer timer(String name) {
return contextAwareTimer(name);
}
/**
* Register a given metric under a given name.
*
* <p>
* This method does not support registering {@link com.codahale.metrics.MetricSet}s.
* See{@link #registerAll(com.codahale.metrics.MetricSet)}.
* </p>
*
* <p>
* This method will not register a metric with the same name in the parent context (if it exists).
* </p>
*/
@Override
public synchronized <T extends Metric> T register(String name, T metric)
throws IllegalArgumentException {
if(!(metric instanceof ContextAwareMetric)) {
throw new UnsupportedOperationException("Can only register ContextAwareMetrics.");
}
return this.innerMetricContext.register(name, metric);
}
/**
* Register a {@link org.apache.gobblin.metrics.ContextAwareMetric} under its own name.
*/
public <T extends ContextAwareMetric> T register(T metric) throws IllegalArgumentException {
return register(metric.getName(), metric);
}
/**
* Get a {@link ContextAwareCounter} with a given name.
*
* @param name name of the {@link ContextAwareCounter}
* @return the {@link ContextAwareCounter} with the given name
*/
public ContextAwareCounter contextAwareCounter(String name) {
return contextAwareCounter(name, ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_COUNTER_FACTORY);
}
/**
* Get a {@link ContextAwareCounter} with a given name.
*
* @param name name of the {@link ContextAwareCounter}
* @param factory a {@link ContextAwareMetricFactory} for building {@link ContextAwareCounter}s
* @return the {@link ContextAwareCounter} with the given name
*/
public ContextAwareCounter contextAwareCounter(String name, ContextAwareMetricFactory<ContextAwareCounter> factory) {
return this.innerMetricContext.getOrCreate(name, factory);
}
/**
* Get a {@link ContextAwareMeter} with a given name.
*
* @param name name of the {@link ContextAwareMeter}
* @return the {@link ContextAwareMeter} with the given name
*/
public ContextAwareMeter contextAwareMeter(String name) {
return contextAwareMeter(name, ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_METER_FACTORY);
}
/**
* Get a {@link ContextAwareMeter} with a given name.
*
* @param name name of the {@link ContextAwareMeter}
* @param factory a {@link ContextAwareMetricFactory} for building {@link ContextAwareMeter}s
* @return the {@link ContextAwareMeter} with the given name
*/
public ContextAwareMeter contextAwareMeter(String name, ContextAwareMetricFactory<ContextAwareMeter> factory) {
return this.innerMetricContext.getOrCreate(name, factory);
}
/**
* Get a {@link ContextAwareHistogram} with a given name.
*
* @param name name of the {@link ContextAwareHistogram}
* @return the {@link ContextAwareHistogram} with the given name
*/
public ContextAwareHistogram contextAwareHistogram(String name) {
return this.innerMetricContext.getOrCreate(name, ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_HISTOGRAM_FACTORY);
}
/**
* Get a {@link ContextAwareHistogram} with a given name and a customized {@link com.codahale.metrics.SlidingTimeWindowReservoir}
*
* @param name name of the {@link ContextAwareHistogram}
* @param windowSize normally the duration of the time window
* @param unit the unit of time
* @return the {@link ContextAwareHistogram} with the given name
*/
public ContextAwareHistogram contextAwareHistogram(String name, long windowSize, TimeUnit unit) {
ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs args = new ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs(
this.innerMetricContext.getMetricContext().get(), name, windowSize, unit);
return this.innerMetricContext.getOrCreate(ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_HISTOGRAM_FACTORY, args);
}
/**
* Get a {@link ContextAwareTimer} with a given name.
*
* @param name name of the {@link ContextAwareTimer}
* @return the {@link ContextAwareTimer} with the given name
*/
public ContextAwareTimer contextAwareTimer(String name) {
return this.innerMetricContext.getOrCreate(name, ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_TIMER_FACTORY);
}
/**
* Get a {@link ContextAwareTimer} with a given name and a customized {@link com.codahale.metrics.SlidingTimeWindowReservoir}
*
* @param name name of the {@link ContextAwareTimer}
* @param windowSize normally the duration of the time window
* @param unit the unit of time
* @return the {@link ContextAwareTimer} with the given name
*/
public ContextAwareTimer contextAwareTimer(String name, long windowSize, TimeUnit unit) {
ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs args = new ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs(
this.innerMetricContext.getMetricContext().get(), name, windowSize, unit);
return this.innerMetricContext.getOrCreate(ContextAwareMetricFactory.DEFAULT_CONTEXT_AWARE_TIMER_FACTORY, args);
}
/**
* Create a new {@link ContextAwareGauge} wrapping a given {@link com.codahale.metrics.Gauge}.
* Unlike other metrics, gauges are supposed to be registered by the caller.
*
* @param name name of the {@link ContextAwareGauge}
* @param gauge the {@link com.codahale.metrics.Gauge} to be wrapped by the {@link ContextAwareGauge}
* @param <T> the type of the {@link ContextAwareGauge}'s value
* @return a new {@link ContextAwareGauge}
*/
public <T> ContextAwareGauge<T> newContextAwareGauge(String name, Gauge<T> gauge) {
return new ContextAwareGauge<T>(this, name, gauge);
}
/**
* Remove a metric with a given name.
*
* <p>
* This method will remove the metric with the given name from this {@link MetricContext}
* as well as metrics with the same name from every child {@link MetricContext}s.
* </p>
*
* @param name name of the metric to be removed
* @return whether or not the metric has been removed
*/
@Override
public synchronized boolean remove(String name) {
return this.innerMetricContext.remove(name);
}
@Override
public void removeMatching(MetricFilter filter) {
this.innerMetricContext.removeMatching(filter);
}
public List<Tag<?>> getTags() {
return this.innerMetricContext.getTags();
}
public Map<String, Object> getTagMap() {
return this.innerMetricContext.getTagMap();
}
@Override
public void close() throws IOException {
this.closer.close();
}
/**
* Get a new {@link MetricContext.Builder} for building child {@link MetricContext}s.
*
* @param name name of the child {@link MetricContext} to be built
* @return a new {@link MetricContext.Builder} for building child {@link MetricContext}s
*/
public Builder childBuilder(String name) {
return builder(name).hasParent(this);
}
/**
* Get a new {@link MetricContext.Builder}.
*
* @param name name of the {@link MetricContext} to be built
* @return a new {@link MetricContext.Builder}
*/
public static Builder builder(String name) {
return new Builder(name);
}
/**
* Add a target for {@link org.apache.gobblin.metrics.notification.Notification}s.
* @param target A {@link com.google.common.base.Function} that will be run every time
* there is a new {@link org.apache.gobblin.metrics.notification.Notification} in this context.
* @return a key for this notification target. Can be used to remove the notification target later.
*/
public UUID addNotificationTarget(Function<Notification, Void> target) {
UUID uuid = UUID.randomUUID();
if(this.notificationTargets.containsKey(uuid)) {
throw new RuntimeException("Failed to create notification target.");
}
this.notificationTargets.put(uuid, target);
return uuid;
}
/**
* Remove notification target identified by the given key.
* @param key key for the notification target to remove.
*/
public void removeNotificationTarget(UUID key) {
this.notificationTargets.remove(key);
}
/**
* Send a notification to all targets of this context and to the parent of this context.
* @param notification {@link org.apache.gobblin.metrics.notification.Notification} to send.
*/
public void sendNotification(final Notification notification) {
ContextAwareTimer.Context timer = this.notificationTimer.time();
if(!this.notificationTargets.isEmpty()) {
for (final Map.Entry<UUID, Function<Notification, Void>> entry : this.notificationTargets.entrySet()) {
try {
entry.getValue().apply(notification);
} catch (RuntimeException exception) {
LOG.warn("RuntimeException when running notification target. Skipping.", exception);
}
}
}
if(getParent().isPresent()) {
getParent().get().sendNotification(notification);
}
timer.stop();
}
void addChildContext(String childContextName, MetricContext childContext) throws NameConflictException,
ExecutionException {
this.innerMetricContext.addChildContext(childContextName, childContext);
}
void addToMetrics(ContextAwareMetric metric) {
this.contextAwareMetricsSet.add(metric);
}
void removeFromMetrics(ContextAwareMetric metric) {
this.contextAwareMetricsSet.remove(metric);
}
@VisibleForTesting
void clearNotificationTargets() {
this.notificationTargets.clear();
}
/**
* A builder class for {@link MetricContext}.
*/
public static class Builder {
private String name;
private MetricContext parent = null;
private final List<Tag<?>> tags = Lists.newArrayList();
public Builder(String name) {
this.name = name;
}
/**
* Set the parent {@link MetricContext} of this {@link MetricContext} instance.
*
* <p>
* This method is intentionally made private and is only called in {@link MetricContext#childBuilder(String)}
* so users will not mistakenly call this method twice if they use {@link MetricContext#childBuilder(String)}.
* </p>
* @param parent the parent {@link MetricContext}
* @return {@code this}
*/
private Builder hasParent(MetricContext parent) {
this.parent = parent;
// Inherit parent context's tags
this.tags.addAll(parent.getTags());
return this;
}
/**
* Add a single {@link Tag}.
*
* @param tag the {@link Tag} to add
* @return {@code this}
*/
public Builder addTag(Tag<?> tag) {
this.tags.add(tag);
return this;
}
/**
* Add a collection of {@link Tag}s.
*
* @param tags the collection of {@link Tag}s to add
* @return {@code this}
*/
public Builder addTags(Collection<Tag<?>> tags) {
this.tags.addAll(tags);
return this;
}
/**
* Builder a new {@link MetricContext}.
*
* <p>
* See {@link Taggable#metricNamePrefix(boolean)} for the semantic of {@code includeTagKeys}.
* </p>
*
* <p>
* Note this builder may change the name of the built {@link MetricContext} if the parent context already has a child with
* that name. If this is unacceptable, use {@link #buildStrict} instead.
* </p>
*
* @return the newly built {@link MetricContext}
*/
public MetricContext build() {
try {
return buildStrict();
} catch (NameConflictException nce) {
String uuid = UUID.randomUUID().toString();
LOG.warn("MetricContext with specified name already exists, appending UUID to the given name: " + uuid);
this.name = this.name + "_" + uuid;
try {
return buildStrict();
} catch (NameConflictException nce2) {
throw Throwables.propagate(nce2);
}
}
}
/**
* Builder a new {@link MetricContext}.
*
* <p>
* See {@link Taggable#metricNamePrefix(boolean)} for the semantic of {@code includeTagKeys}.
* </p>
*
* @return the newly built {@link MetricContext}
* @throws NameConflictException if the parent {@link MetricContext} already has a child with this name.
*/
public MetricContext buildStrict() throws NameConflictException {
if(this.parent == null) {
hasParent(RootMetricContext.get());
}
return new MetricContext(this.name, this.parent, this.tags, false);
}
}
}
| 4,403 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/CustomReporterFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.io.IOException;
import java.util.Properties;
import org.apache.gobblin.metrics.reporter.ScheduledReporter;
/**
* BuilderFactory for custom {@link ScheduledReporter}. Implementations should have a parameter-less constructor.
*/
public interface CustomReporterFactory {
/**
* Builds and returns a new {@link com.codahale.metrics.ScheduledReporter}.
*
* @param properties {@link Properties} used to build the reporter.
* @return new {@link ScheduledReporter}.
*/
public ScheduledReporter newScheduledReporter(Properties properties) throws IOException;
}
| 4,404 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MultiReporterException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.io.IOException;
import java.util.List;
public class MultiReporterException extends IOException {
private List<MetricReporterException> exceptions;
public MultiReporterException(String message, List<MetricReporterException> exceptions) {
super(message);
this.exceptions = exceptions;
}
public List<MetricReporterException> getExceptions() {
return this.exceptions;
}
}
| 4,405 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/Taggable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.util.Collection;
import java.util.List;
/**
* An interface for classes with which {@link Tag}s can be associated.
*
* @author Yinan Li
*/
public interface Taggable {
/**
* Add a single {@link Tag}.
*
* <p>
* The order in which {@link Tag}s are added is important as this is the order
* the tag names appear in the metric name prefix.
* </p>
*
* @param tag the {@link Tag} to add
*/
public void addTag(Tag<?> tag);
/**
* Add a collection of {@link Tag}s.
*
* @param tags the collection of {@link Tag}s to add
*/
public void addTags(Collection<Tag<?>> tags);
/**
* Get all {@link Tag}s in a list.
*
* <p>
* This method guarantees no duplicated {@link Tag}s and the order of {@link Tag}s
* is the same as the one in which the {@link Tag}s were added.
* </p>
*
* @return all {@link Tag}s in a list
*/
public List<Tag<?>> getTags();
/**
* Construct a metric name prefix from the {@link Tag}s.
*
* <p>
* The prefix will include both the key and value of every {@link Tag} in the form of {@code key:value}
* if {@code includeTagKeys} is {@code true}, otherwise it only includes the value of every {@link Tag}.
* </p>
*
* @param includeTagKeys whether to include tag keys in the metric name prefix
* @return a metric name prefix constructed from the {@link Tag}s
*/
public String metricNamePrefix(boolean includeTagKeys);
}
| 4,406 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ContextAwareMeter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import com.codahale.metrics.Meter;
import org.apache.gobblin.metrics.metric.InnerMetric;
import lombok.experimental.Delegate;
/**
* A type of {@link com.codahale.metrics.Meter}s that are aware of their {@link org.apache.gobblin.metrics.MetricContext}
* and can have associated {@link Tag}s.
*
* <p>
* Any updates to a {@link ContextAwareMeter} will be applied automatically to the
* {@link ContextAwareMeter} of the same name in the parent {@link MetricContext}.
* </p>
*
* <p>
* This class wraps a {@link com.codahale.metrics.Meter} and delegates calls to public methods of
* {@link com.codahale.metrics.Meter} to the wrapped {@link com.codahale.metrics.Meter}.
* </p>
*
* @author Yinan Li
*/
public class ContextAwareMeter extends Meter implements ContextAwareMetric {
@Delegate
private final InnerMeter innerMeter;
private final MetricContext context;
ContextAwareMeter(MetricContext context, String name) {
this.innerMeter = new InnerMeter(context, name, this);
this.context = context;
}
@Override
public MetricContext getContext() {
return this.context;
}
@Override public InnerMetric getInnerMetric() {
return this.innerMeter;
}
}
| 4,407 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerGauge.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.lang.ref.WeakReference;
import com.codahale.metrics.Gauge;
import org.apache.gobblin.metrics.metric.InnerMetric;
/**
* Implementation of {@link InnerMetric} for {@link Gauge}.
*/
public class InnerGauge<T> implements InnerMetric, Gauge<T> {
private final String name;
private final Gauge<T> gauge;
private final WeakReference<ContextAwareGauge<T>> contextAwareGauge;
InnerGauge(MetricContext context, String name, Gauge<T> gauge, ContextAwareGauge<T> contextAwareGauge) {
this.name = name;
this.gauge = gauge;
this.contextAwareGauge = new WeakReference<>(contextAwareGauge);
}
@Override
public T getValue() {
return this.gauge.getValue();
}
public String getName() {
return this.name;
}
@Override
public ContextAwareMetric getContextAwareMetric() {
return this.contextAwareGauge.get();
}
}
| 4,408 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/Measurements.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
/**
* A enumeration of different measurements of metrics.
*
* @author Yinan Li
*/
public enum Measurements {
COUNT("count"),
MIN("min"),
MAX("max"),
MEDIAN("median"),
MEAN("mean"),
STDDEV("stddev"),
PERCENTILE_75TH("75thPercentile"),
PERCENTILE_95TH("95thPercentile"),
PERCENTILE_98TH("98thPercentile"),
PERCENTILE_99TH("99thPercentile"),
PERCENTILE_999TH("999thPercentile"),
RATE_1MIN("1MinuteRate"),
RATE_5MIN("5MinuteRate"),
RATE_15MIN("5MinuteRate"),
MEAN_RATE("meanRate");
private final String name;
Measurements(String name) {
this.name = name;
}
/**
* Get a succinct name of this {@link Measurements}.
*
* @return a succinct name of this {@link Measurements}
*/
public String getName() {
return this.name;
}
}
| 4,409 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ContextAwareTimer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.SlidingTimeWindowReservoir;
import com.codahale.metrics.Timer;
import org.apache.gobblin.metrics.metric.InnerMetric;
import lombok.experimental.Delegate;
/**
* A type of {@link com.codahale.metrics.Timer}s that are aware of their {@link org.apache.gobblin.metrics.MetricContext}
* and can have associated {@link Tag}s.
*
* <p>
* Any updates to a {@link ContextAwareTimer} will be applied automatically to the
* {@link ContextAwareTimer} of the same name in the parent {@link MetricContext}.
* </p>
*
* <p>
* This class wraps a {@link com.codahale.metrics.Timer} and delegates calls to public methods of
* {@link com.codahale.metrics.Timer} to the wrapped {@link com.codahale.metrics.Timer}.
* </p>
*
* @author Yinan Li
*/
public class ContextAwareTimer extends Timer implements ContextAwareMetric {
@Delegate
private final InnerTimer innerTimer;
private final MetricContext context;
ContextAwareTimer(MetricContext context, String name) {
this.innerTimer = new InnerTimer(context, name, this);
this.context = context;
}
ContextAwareTimer(MetricContext context, String name, long windowSize, TimeUnit unit) {
super(new SlidingTimeWindowReservoir(windowSize, unit));
this.innerTimer = new InnerTimer(context, name, this, windowSize, unit);
this.context = context;
}
@Override
public MetricContext getContext() {
return this.context;
}
@Override public InnerMetric getInnerMetric() {
return this.innerTimer;
}
}
| 4,410 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MetricReporterException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.io.IOException;
import lombok.Getter;
public class MetricReporterException extends IOException {
@Getter
private final ReporterType reporterType;
@Getter
private final ReporterSinkType sinkType;
public MetricReporterException(String message, ReporterType reporterType, ReporterSinkType sinkType) {
super(message);
this.reporterType = reporterType;
this.sinkType = sinkType;
}
public MetricReporterException(String message, Throwable t, ReporterType reporterType, ReporterSinkType sinkType) {
super(message, t);
this.reporterType = reporterType;
this.sinkType = sinkType;
}
}
| 4,411 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ReporterSinkType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
public enum ReporterSinkType {
JMX,
GRAPHITE,
FILE,
FILE_FAILURE,
KAFKA,
INFLUXDB,
CUSTOM
}
| 4,412 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerHistogram.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.ExponentiallyDecayingReservoir;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.SlidingTimeWindowReservoir;
import com.google.common.base.Optional;
import org.apache.gobblin.metrics.metric.InnerMetric;
/**
* Implementation of {@link InnerMetric} for {@link Histogram}.
*/
public class InnerHistogram extends Histogram implements InnerMetric {
private final String name;
private final Optional<ContextAwareHistogram> parentHistogram;
private final WeakReference<ContextAwareHistogram> contextAwareHistogram;
InnerHistogram(MetricContext context, String name, ContextAwareHistogram contextAwareHistogram) {
super(new ExponentiallyDecayingReservoir());
this.name = name;
Optional<MetricContext> parentContext = context.getParent();
if (parentContext.isPresent()) {
this.parentHistogram = Optional.fromNullable(parentContext.get().contextAwareHistogram(name));
} else {
this.parentHistogram = Optional.absent();
}
this.contextAwareHistogram = new WeakReference<>(contextAwareHistogram);
}
InnerHistogram(MetricContext context, String name, ContextAwareHistogram contextAwareHistogram, long windowSize, TimeUnit unit) {
super(new SlidingTimeWindowReservoir(windowSize, unit));
this.name = name;
Optional<MetricContext> parentContext = context.getParent();
if (parentContext.isPresent()) {
this.parentHistogram = Optional.fromNullable(parentContext.get().contextAwareHistogram(name, windowSize, unit));
} else {
this.parentHistogram = Optional.absent();
}
this.contextAwareHistogram = new WeakReference<>(contextAwareHistogram);
}
@Override
public void update(int value) {
update((long) value);
}
@Override
public void update(long value) {
super.update(value);
if (this.parentHistogram.isPresent()) {
this.parentHistogram.get().update(value);
}
}
public String getName() {
return this.name;
}
@Override
public ContextAwareMetric getContextAwareMetric() {
return this.contextAwareHistogram.get();
}
}
| 4,413 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MetricNames.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
/**
* Contains names for all metrics generated in gobblin-core.
*/
public class MetricNames {
/**
* Extractor metrics.
*/
public static class ExtractorMetrics {
public static final String RECORDS_READ_METER = "gobblin.extractor.records.read";
public static final String RECORDS_FAILED_METER = "gobblin.extractor.records.failed";
// Times extraction of records.
public static final String EXTRACT_TIMER = "gobblin.extractor.extract.time";
}
/**
* Converter metrics.
*/
public static class ConverterMetrics {
public static final String RECORDS_IN_METER = "gobblin.converter.records.in";
public static final String RECORDS_OUT_METER = "gobblin.converter.records.out";
// Records in which failed conversion.
public static final String RECORDS_FAILED_METER = "gobblin.converter.records.failed";
// Times the generation of the Iterable.
public static final String CONVERT_TIMER = "gobblin.converter.convert.time";
}
/**
* Fork Operator metrics
*/
public static class ForkOperatorMetrics {
public static final String RECORDS_IN_METER = "gobblin.fork.operator.records.in";
// Counts total number of forks generated (e.g. (true, true, false) adds 2).
public static final String FORKS_OUT_METER = "gobblin.fork.operator.forks.out";
// Times the computation of the fork list.
public static final String FORK_TIMER = "gobblin.fork.operator.fork.time";
}
/**
* Row level policy metrics.
*/
public static class RowLevelPolicyMetrics {
public static final String RECORDS_IN_METER = "gobblin.qualitychecker.records.in";
public static final String RECORDS_PASSED_METER = "gobblin.qualitychecker.records.passed";
public static final String RECORDS_FAILED_METER = "gobblin.qualitychecker.records.failed";
// Times the policy decision.
public static final String CHECK_TIMER = "gobblin.qualitychecker.check.time";
}
/**
* {@link org.apache.gobblin.writer.DataWriter} metrics.
*/
public static class DataWriterMetrics {
/**
* A {@link com.codahale.metrics.Meter} measuring the number of records
* given to a {@link org.apache.gobblin.writer.DataWriter}. This does not count retries.
*/
public static final String RECORDS_IN_METER = "gobblin.writer.records.in";
/**
* A {@link com.codahale.metrics.Meter} measuring the number of records attempted
* to be written by a {@link org.apache.gobblin.writer.DataWriter}. This includes retries.
*/
public static final String RECORDS_ATTEMPTED_METER = "gobblin.writer.records.attempted";
/**
* A {@link com.codahale.metrics.Meter} measuring the number of successful write operations performed by a
* {@link org.apache.gobblin.writer.DataWriter}.
*/
public static final String SUCCESSFUL_WRITES_METER = "gobblin.writer.successful.writes";
/**
* A {@link com.codahale.metrics.Meter} measuring the number of failed write operations performed by a
* {@link org.apache.gobblin.writer.DataWriter}.
*/
public static final String FAILED_WRITES_METER = "gobblin.writer.failed.writes";
/**
* A {@link com.codahale.metrics.Meter} measuring the number records written by a {@link org.apache.gobblin.writer.DataWriter}
* as reported by its {@link org.apache.gobblin.writer.DataWriter#recordsWritten()} method.
*/
public static final String RECORDS_WRITTEN_METER = "gobblin.writer.records.written";
/**
* A {@link com.codahale.metrics.Meter} measuring the number bytes written by a {@link org.apache.gobblin.writer.DataWriter} as
* reported by its {@link org.apache.gobblin.writer.DataWriter#bytesWritten()} method.
*/
public static final String BYTES_WRITTEN_METER = "gobblin.writer.bytes.written";
/**
* A {@link com.codahale.metrics.Timer} measuring the time taken for each write operation.
*/
public static final String WRITE_TIMER = "gobblin.writer.write.time";
}
}
| 4,414 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ConsoleReporterFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.io.IOException;
import java.util.Properties;
import org.apache.gobblin.metrics.reporter.OutputStreamReporter;
import org.apache.gobblin.metrics.reporter.ScheduledReporter;
/**
* A reporter factory to report metrics to console.
*
* <p>
* Set metrics.reporting.custom.builders=org.apache.gobblin.metrics.ConsoleReporterFactory to report event to console
* </p>
*/
public class ConsoleReporterFactory implements CustomReporterFactory {
@Override
public ScheduledReporter newScheduledReporter(Properties properties) throws IOException {
return OutputStreamReporter.Factory.newBuilder().build(properties);
}
}
| 4,415 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import java.io.Closeable;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Maps;
import com.google.common.io.Closer;
import lombok.Getter;
import org.apache.gobblin.metrics.context.ContextWeakReference;
import org.apache.gobblin.metrics.context.NameConflictException;
import org.apache.gobblin.metrics.context.ReportableContext;
import org.apache.gobblin.metrics.metric.InnerMetric;
/**
* Contains list of {@link Metric}s, {@link Tag}s, as well as references to parent and child {@link MetricContext} for
* a {@link MetricContext}. This object is only references by the corresponding {@link MetricContext} as well as the
* {@link RootMetricContext}, and it is used to report metrics one last time after the corresponding {@link MetricContext}
* has been GCed.
*/
public class InnerMetricContext extends MetricRegistry implements ReportableContext, Closeable {
private final Closer closer;
// Name of this context
private final String name;
// A map from simple names to context-aware metrics. All metrics registered with this context (using
// their simple names) are also registered with the MetricRegistry using their fully-qualified names.
private final ConcurrentMap<String, InnerMetric> contextAwareMetrics = Maps.newConcurrentMap();
// This is used to work on tags associated with this context
private final Tagged tagged;
// Reference to the parent context wrapped in an Optional as there may be no parent context
private final Optional<MetricContext> parent;
// A map from child context names to child contexts
private final Cache<String, MetricContext> children = CacheBuilder.newBuilder().weakValues().build();
@Getter
private final WeakReference<MetricContext> metricContext;
protected InnerMetricContext(MetricContext context, String name, MetricContext parent, List<Tag<?>> tags)
throws NameConflictException, ExecutionException {
this.name = name;
this.closer = Closer.create();
this.parent = Optional.fromNullable(parent);
if (this.parent.isPresent()) {
this.parent.get().addChildContext(this.name, context);
this.metricContext = new ContextWeakReference(context, this);
} else {
this.metricContext = new WeakReference<>(context);
}
this.tagged = new Tagged(tags);
this.tagged.addTag(new Tag<>(MetricContext.METRIC_CONTEXT_ID_TAG_NAME, UUID.randomUUID().toString()));
this.tagged.addTag(new Tag<>(MetricContext.METRIC_CONTEXT_NAME_TAG_NAME, name));
}
/**
* Get the name of this {@link MetricContext}.
*
* @return the name of this {@link MetricContext}
*/
@Override
public String getName() {
return this.name;
}
/**
* Get the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}, which may be absent if it has not parent
* {@link MetricContext}.
*
* @return the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}
*/
@Override
public Optional<MetricContext> getParent() {
return this.parent;
}
/**
* Add a {@link MetricContext} as a child of this {@link MetricContext} if it is not currently a child.
*
* @param childContextName the name of the child {@link MetricContext}
* @param childContext the child {@link MetricContext} to add
*/
public synchronized void addChildContext(String childContextName, final MetricContext childContext)
throws NameConflictException, ExecutionException {
if (this.children.get(childContextName, new Callable<MetricContext>() {
@Override
public MetricContext call() throws Exception {
return childContext;
}
}) != childContext) {
throw new NameConflictException("A child context with that name already exists.");
}
}
/**
* Get a view of the child {@link org.apache.gobblin.metrics.MetricContext}s as a {@link com.google.common.collect.ImmutableMap}.
* @return {@link com.google.common.collect.ImmutableMap} of
* child {@link org.apache.gobblin.metrics.MetricContext}s keyed by their names.
*/
@Override
public Map<String, MetricContext> getChildContextsAsMap() {
return ImmutableMap.copyOf(this.children.asMap());
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getNames()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedSet<String> getNames() {
return getSimpleNames();
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getMetrics()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public Map<String, com.codahale.metrics.Metric> getMetrics() {
return getSimplyNamedMetrics();
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getGauges(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
return getSimplyNamedMetrics(Gauge.class, Optional.of(filter));
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getCounters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Counter> getCounters(MetricFilter filter) {
return getSimplyNamedMetrics(Counter.class, Optional.of(filter));
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getHistograms(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
return getSimplyNamedMetrics(Histogram.class, Optional.of(filter));
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getMeters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return getSimplyNamedMetrics(Meter.class, Optional.of(filter));
}
/**
* See {@link com.codahale.metrics.MetricRegistry#getTimers(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
@Override
public SortedMap<String, Timer> getTimers(MetricFilter filter) {
return getSimplyNamedMetrics(Timer.class, Optional.of(filter));
}
/**
* Register a given metric under a given name.
*
* <p>
* This method does not support registering {@link com.codahale.metrics.MetricSet}s.
* See{@link #registerAll(com.codahale.metrics.MetricSet)}.
* </p>
*
* <p>
* This method will not register a metric with the same name in the parent context (if it exists).
* </p>
*/
@Override
public synchronized <T extends com.codahale.metrics.Metric> T register(String name, T metric)
throws IllegalArgumentException {
if (!(metric instanceof ContextAwareMetric)) {
throw new UnsupportedOperationException("Can only register ContextAwareMetrics");
}
if (this.contextAwareMetrics.putIfAbsent(name, ((ContextAwareMetric) metric).getInnerMetric()) != null) {
throw new IllegalArgumentException("A metric named " + name + " already exists");
}
MetricContext metricContext = this.metricContext.get();
if (metricContext != null) {
metricContext.addToMetrics((ContextAwareMetric) metric);
}
// Also register the metric with the MetricRegistry using its fully-qualified name
return metric;
}
/**
* Register a {@link org.apache.gobblin.metrics.ContextAwareMetric} under its own name.
*/
public <T extends ContextAwareMetric> T register(T metric) throws IllegalArgumentException {
return register(metric.getName(), metric);
}
@Override
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
throw new UnsupportedOperationException();
}
/**
* Remove a metric with a given name.
*
* <p>
* This method will remove the metric with the given name from this {@link MetricContext}
* as well as metrics with the same name from every child {@link MetricContext}s.
* </p>
*
* @param name name of the metric to be removed
* @return whether or not the metric has been removed
*/
@Override
public synchronized boolean remove(String name) {
MetricContext metricContext = this.metricContext.get();
if (metricContext != null && this.contextAwareMetrics.get(name) != null) {
metricContext.removeFromMetrics(this.contextAwareMetrics.get(name).getContextAwareMetric());
}
return this.contextAwareMetrics.remove(name) != null && removeChildrenMetrics(name);
}
@Override
public void removeMatching(MetricFilter filter) {
for (Map.Entry<String, InnerMetric> entry : this.contextAwareMetrics.entrySet()) {
if (filter.matches(entry.getKey(), entry.getValue().getContextAwareMetric())) {
remove(entry.getKey());
}
}
}
@Override
public List<Tag<?>> getTags() {
return this.tagged.getTags();
}
@Override
public Map<String, Object> getTagMap() {
return this.tagged.getTagMap();
}
@Override
public void close() throws IOException {
this.closer.close();
}
private SortedSet<String> getSimpleNames() {
return ImmutableSortedSet.copyOf(this.contextAwareMetrics.keySet());
}
private Map<String, com.codahale.metrics.Metric> getSimplyNamedMetrics() {
return ImmutableMap.<String, com.codahale.metrics.Metric> copyOf(this.contextAwareMetrics);
}
@SuppressWarnings("unchecked")
private <T extends com.codahale.metrics.Metric> SortedMap<String, T> getSimplyNamedMetrics(Class<T> mClass,
Optional<MetricFilter> filter) {
ImmutableSortedMap.Builder<String, T> builder = ImmutableSortedMap.naturalOrder();
for (Map.Entry<String, InnerMetric> entry : this.contextAwareMetrics.entrySet()) {
if (mClass.isInstance(entry.getValue())) {
if (filter.isPresent() && !filter.get().matches(entry.getKey(), entry.getValue().getContextAwareMetric())) {
continue;
}
builder.put(entry.getKey(), (T) entry.getValue());
}
}
return builder.build();
}
@SuppressWarnings("unchecked")
protected synchronized <T extends ContextAwareMetric> T getOrCreate(String name,
ContextAwareMetricFactory<T> factory) {
InnerMetric metric = this.contextAwareMetrics.get(name);
if (metric != null) {
if (factory.isInstance(metric)) {
return (T) metric.getContextAwareMetric();
}
throw new IllegalArgumentException(name + " is already used for a different type of metric");
}
T newMetric = factory.newMetric(this.metricContext.get(), name);
this.register(name, newMetric);
return newMetric;
}
@SuppressWarnings("unchecked")
protected synchronized <T extends ContextAwareMetric> T getOrCreate(
ContextAwareMetricFactory<T> factory, ContextAwareMetricFactoryArgs args) {
String name = args.getName();
InnerMetric metric = this.contextAwareMetrics.get(name);
if (metric != null) {
if (factory.isInstance(metric)) {
return (T) metric.getContextAwareMetric();
}
throw new IllegalArgumentException(name + " is already used for a different type of metric");
}
T newMetric = factory.newMetric(args);
this.register(name, newMetric);
return newMetric;
}
private boolean removeChildrenMetrics(String name) {
boolean removed = true;
for (MetricContext child : getChildContextsAsMap().values()) {
if (!child.remove(name)) {
removed = false;
}
}
return removed;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("InnerMetricContext Name: ");
stringBuilder.append(this.name);
if (this.getParent().isPresent()) {
stringBuilder.append(", Parent Name: ");
stringBuilder.append(this.getParent().get().getName());
} else {
stringBuilder.append(", No Parent Context");
}
stringBuilder.append(", Number of Children: ");
stringBuilder.append(this.getChildContextsAsMap().size());
stringBuilder.append(", Tags: ");
stringBuilder.append(Joiner.on(", ").withKeyValueSeparator(" : ").useForNull("NULL").join(this.getTagMap()));
return stringBuilder.toString();
}
}
| 4,416 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/ContextAwareMetricFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.Timer;
/**
* An interface for factory classes for {@link ContextAwareMetric}s.
*
* @author Yinan Li
*/
public interface ContextAwareMetricFactory<T extends ContextAwareMetric> {
public static final ContextAwareMetricFactory<ContextAwareCounter> DEFAULT_CONTEXT_AWARE_COUNTER_FACTORY =
new ContextAwareCounterFactory();
public static final ContextAwareMetricFactory<ContextAwareMeter> DEFAULT_CONTEXT_AWARE_METER_FACTORY =
new ContextAwareMeterFactory();
public static final ContextAwareMetricFactory<ContextAwareHistogram> DEFAULT_CONTEXT_AWARE_HISTOGRAM_FACTORY =
new ContextAwareHistogramFactory();
public static final ContextAwareMetricFactory<ContextAwareTimer> DEFAULT_CONTEXT_AWARE_TIMER_FACTORY =
new ContextAwareTimerFactory();
/**
* Create a new context-aware metric.
*
* @param context the {@link MetricContext} of the metric
* @param name metric name
* @return the newly created metric
*/
public T newMetric(MetricContext context, String name);
default public T newMetric(ContextAwareMetricFactoryArgs args) {
return null;
}
/**
* Check if a given metric is an instance of the type of context-aware metrics created by this
* {@link ContextAwareMetricFactory}.
*
* @param metric the given metric
* @return {@code true} if the given metric is an instance of the type of context-aware metrics
* created by this {@link ContextAwareMetricFactory}, {@code false} otherwise.
*/
public boolean isInstance(Metric metric);
/**
* A default implementation of {@link ContextAwareMetricFactory} for {@link ContextAwareCounter}s.
*/
public static class ContextAwareCounterFactory implements ContextAwareMetricFactory<ContextAwareCounter> {
@Override
public ContextAwareCounter newMetric(MetricContext context, String name) {
return new ContextAwareCounter(context, name);
}
@Override
public boolean isInstance(Metric metric) {
return Counter.class.isInstance(metric);
}
}
/**
* A default implementation of {@link ContextAwareMetricFactory} for {@link ContextAwareMeter}s.
*/
public static class ContextAwareMeterFactory implements ContextAwareMetricFactory<ContextAwareMeter> {
@Override
public ContextAwareMeter newMetric(MetricContext context, String name) {
return new ContextAwareMeter(context, name);
}
@Override
public boolean isInstance(Metric metric) {
return Meter.class.isInstance(metric);
}
}
/**
* A default implementation of {@link ContextAwareMetricFactory} for {@link ContextAwareHistogram}s.
*/
public static class ContextAwareHistogramFactory implements ContextAwareMetricFactory<ContextAwareHistogram> {
@Override
public ContextAwareHistogram newMetric(MetricContext context, String name) {
return new ContextAwareHistogram(context, name);
}
@Override
public ContextAwareHistogram newMetric(ContextAwareMetricFactoryArgs args) {
if (args instanceof ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs) {
ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs windowArgs = (ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs)args;
return new ContextAwareHistogram(windowArgs.getContext(), windowArgs.getName(), windowArgs.getWindowSize(), windowArgs.getUnit());
}
throw new UnsupportedOperationException("Unknown factory arguments to create ContextAwareHistogram");
}
@Override
public boolean isInstance(Metric metric) {
return Histogram.class.isInstance(metric);
}
}
/**
* A default implementation of {@link ContextAwareMetricFactory} for {@link ContextAwareTimer}s.
*/
public static class ContextAwareTimerFactory implements ContextAwareMetricFactory<ContextAwareTimer> {
@Override
public ContextAwareTimer newMetric(MetricContext context, String name) {
return new ContextAwareTimer(context, name);
}
@Override
public ContextAwareTimer newMetric(ContextAwareMetricFactoryArgs args) {
if (args instanceof ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs) {
ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs windowArgs = (ContextAwareMetricFactoryArgs.SlidingTimeWindowArgs)args;
return new ContextAwareTimer(windowArgs.getContext(), windowArgs.getName(), windowArgs.getWindowSize(), windowArgs.getUnit());
}
throw new UnsupportedOperationException("Unknown factory arguments to create ContextAwareTimer");
}
@Override
public boolean isInstance(Metric metric) {
return Timer.class.isInstance(metric);
}
}
}
| 4,417 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/broker/LineageInfoFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.broker;
import org.apache.gobblin.broker.EmptyKey;
import org.apache.gobblin.broker.ResourceInstance;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.ConfigView;
import org.apache.gobblin.broker.iface.NotConfiguredException;
import org.apache.gobblin.broker.iface.ScopedConfigView;
import org.apache.gobblin.broker.iface.SharedResourceFactory;
import org.apache.gobblin.broker.iface.SharedResourceFactoryResponse;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.metrics.event.lineage.LineageInfo;
/**
* A {@link SharedResourceFactory} to share a job level {@link LineageInfo} instance
*/
public class LineageInfoFactory implements SharedResourceFactory<LineageInfo, EmptyKey, GobblinScopeTypes> {
public static final String FACTORY_NAME = "lineageInfo";
@Override
public String getName() {
return FACTORY_NAME;
}
@Override
public SharedResourceFactoryResponse<LineageInfo> createResource(SharedResourcesBroker<GobblinScopeTypes> broker,
ScopedConfigView<GobblinScopeTypes, EmptyKey> config)
throws NotConfiguredException {
return new ResourceInstance<>(new LineageInfo(config.getConfig()));
}
@Override
public GobblinScopeTypes getAutoScope(SharedResourcesBroker<GobblinScopeTypes> broker, ConfigView<GobblinScopeTypes, EmptyKey> config) {
return GobblinScopeTypes.JOB;
}
}
| 4,418 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/broker/SubTaggedMetricContextKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.broker;
import com.google.common.collect.ImmutableMap;
/**
* A {@link org.apache.gobblin.broker.iface.SharedResourceKey} for {@link MetricContextFactory}. While {@link MetricContextKey}
* creates a {@link org.apache.gobblin.metrics.MetricContext} with keys extracted from the broker configuration, this factory creates
* a {@link org.apache.gobblin.metrics.MetricContext} which is a child of the former context, and which has tags and names specified
* in the key.
*
* This key is useful when a construct needs to acquire a variety of tagged {@link org.apache.gobblin.metrics.MetricContext} with
* different tags.
*/
public class SubTaggedMetricContextKey extends MetricContextKey {
private final String metricContextName;
private final ImmutableMap<String, String> tags;
@java.beans.ConstructorProperties({"metricContextName", "tags"})
public SubTaggedMetricContextKey(String metricContextName, ImmutableMap<String, String> tags) {
this.metricContextName = metricContextName;
this.tags = tags;
}
public String getMetricContextName() {
return this.metricContextName;
}
public ImmutableMap<String, String> getTags() {
return this.tags;
}
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
if (o == this) {
return true;
}
if (!(o instanceof SubTaggedMetricContextKey)) {
return false;
}
final SubTaggedMetricContextKey other = (SubTaggedMetricContextKey) o;
if (!other.canEqual((Object) this)) {
return false;
}
final Object this$metricContextName = this.getMetricContextName();
final Object other$metricContextName = other.getMetricContextName();
if (this$metricContextName == null ? other$metricContextName != null
: !this$metricContextName.equals(other$metricContextName)) {
return false;
}
final Object this$tags = this.getTags();
final Object other$tags = other.getTags();
if (this$tags == null ? other$tags != null : !this$tags.equals(other$tags)) {
return false;
}
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $metricContextName = this.getMetricContextName();
result = result * PRIME + ($metricContextName == null ? 43 : $metricContextName.hashCode());
final Object $tags = this.getTags();
result = result * PRIME + ($tags == null ? 43 : $tags.hashCode());
return result;
}
protected boolean canEqual(Object other) {
return other instanceof SubTaggedMetricContextKey;
}
public String toString() {
return "gobblin.metrics.broker.SubTaggedMetricContextKey(metricContextName=" + this.getMetricContextName()
+ ", tags=" + this.getTags() + ")";
}
}
| 4,419 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/broker/MetricContextKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.broker;
import org.apache.gobblin.broker.iface.SharedResourceKey;
import lombok.Data;
/**
* A {@link SharedResourceKey} used for {@link MetricContextFactory}.
*/
@Data
public class MetricContextKey implements SharedResourceKey {
@Override
public String toConfigurationKey() {
return null;
}
}
| 4,420 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/broker/MetricContextFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.broker;
import com.typesafe.config.ConfigValue;
import org.apache.gobblin.broker.ResourceInstance;
import org.apache.gobblin.broker.iface.ConfigView;
import org.apache.gobblin.broker.iface.NoSuchScopeException;
import org.apache.gobblin.broker.iface.NotConfiguredException;
import org.apache.gobblin.broker.iface.ScopeType;
import org.apache.gobblin.broker.iface.ScopedConfigView;
import org.apache.gobblin.broker.iface.SharedResourceFactory;
import org.apache.gobblin.broker.iface.SharedResourceFactoryResponse;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.RootMetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.util.ConfigUtils;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
/**
* A {@link SharedResourceFactory} to create {@link MetricContext}.
*
* The created {@link MetricContext} tree will mimic a sub-tree of the scopes DAG. If each scope has a unique parent,
* the metric contexts will have the corresponding parents. If a scope has multiple parents (which is not supported by
* {@link MetricContext}), the factory will chose the first parent of the scope.
*
* Tags can be injected using the configuration {@link Tag}.
*/
public class MetricContextFactory<S extends ScopeType<S>> implements SharedResourceFactory<MetricContext, MetricContextKey, S> {
public static final String NAME = "metricContext";
public static final String TAG_KEY = "tag";
@Override
public String getName() {
return NAME;
}
@Override
public SharedResourceFactoryResponse<MetricContext> createResource(SharedResourcesBroker<S> broker,
ScopedConfigView<S, MetricContextKey> config) throws NotConfiguredException {
try {
if (config.getKey() instanceof SubTaggedMetricContextKey) {
SubTaggedMetricContextKey key = (SubTaggedMetricContextKey) config.getKey();
MetricContext parent = broker.getSharedResource(this, new MetricContextKey());
MetricContext.Builder builder = parent.childBuilder(key.getMetricContextName());
for (Map.Entry<String, String> entry : key.getTags().entrySet()) {
builder.addTag(new Tag<>(entry.getKey(), entry.getValue()));
}
return new ResourceInstance<>(builder.build());
}
MetricContext parentMetricContext = RootMetricContext.get();
Collection<S> parents = config.getScope().parentScopes();
if (parents != null && !parents.isEmpty()) {
S parentScope = parents.iterator().next();
parentMetricContext = broker.getSharedResourceAtScope(this, config.getKey(), parentScope);
}
// If this is the root scope, append a UUID to the name. This allows having a separate root context per broker.
String metricContextName = parents == null ?
config.getScope().name() + "_" + UUID.randomUUID().toString() :
broker.selfScope().getScopeId();
MetricContext.Builder builder = parentMetricContext.childBuilder(metricContextName);
builder.addTag(new Tag<>(config.getScope().name(), broker.getScope(config.getScope()).getScopeId()));
for (Map.Entry<String, ConfigValue> entry : ConfigUtils.getConfigOrEmpty(config.getConfig(), TAG_KEY).entrySet()) {
builder.addTag(new Tag<>(entry.getKey(), entry.getValue().unwrapped()));
}
return new ResourceInstance<>(builder.build());
} catch (NoSuchScopeException nsse) {
throw new RuntimeException("Could not create MetricContext.", nsse);
}
}
@Override
public S getAutoScope(SharedResourcesBroker<S> broker, ConfigView<S, MetricContextKey> config) {
return broker.selfScope().getType();
}
}
| 4,421 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/NameConflictException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context;
import java.io.IOException;
/**
* Thrown when a {@link org.apache.gobblin.metrics.MetricContext} cannot be created as a child of a second
* {@link org.apache.gobblin.metrics.MetricContext} because the parent already has a {@link org.apache.gobblin.metrics.MetricContext} with
* that name.
*/
public class NameConflictException extends IOException {
private static final long serialVersionUID = 5569840033725693663L;
public NameConflictException(String message) {
super(message);
}
public NameConflictException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,422 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/ReportableContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.Timer;
import com.google.common.base.Optional;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
/**
* Interface for a context that can be reported (e.g. {@link org.apache.gobblin.metrics.InnerMetricContext},
* {@link org.apache.gobblin.metrics.MetricContext}).
*/
public interface ReportableContext {
/**
* Get the name of this {@link MetricContext}.
*
* @return the name of this {@link MetricContext}
*/
public String getName();
/**
* Get the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}, which may be absent if it has not parent
* {@link MetricContext}.
*
* @return the parent {@link MetricContext} of this {@link MetricContext} wrapped in an
* {@link com.google.common.base.Optional}
*/
public Optional<? extends ReportableContext> getParent();
/**
* Get a view of the child {@link org.apache.gobblin.metrics.MetricContext}s as a {@link com.google.common.collect.ImmutableMap}.
* @return {@link com.google.common.collect.ImmutableMap} of
* child {@link org.apache.gobblin.metrics.MetricContext}s keyed by their names.
*/
public Map<String, ? extends ReportableContext> getChildContextsAsMap();
/**
* See {@link com.codahale.metrics.MetricRegistry#getNames()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedSet<String> getNames();
/**
* See {@link com.codahale.metrics.MetricRegistry#getMetrics()}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public Map<String, com.codahale.metrics.Metric> getMetrics();
/**
* See {@link com.codahale.metrics.MetricRegistry#getGauges(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedMap<String, Gauge> getGauges(MetricFilter filter);
/**
* See {@link com.codahale.metrics.MetricRegistry#getCounters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedMap<String, Counter> getCounters(MetricFilter filter);
/**
* See {@link com.codahale.metrics.MetricRegistry#getHistograms(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedMap<String, Histogram> getHistograms(MetricFilter filter);
/**
* See {@link com.codahale.metrics.MetricRegistry#getMeters(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedMap<String, Meter> getMeters(MetricFilter filter);
/**
* See {@link com.codahale.metrics.MetricRegistry#getTimers(com.codahale.metrics.MetricFilter)}.
*
* <p>
* This method will return fully-qualified metric names if the {@link MetricContext} is configured
* to report fully-qualified metric names.
* </p>
*/
public SortedMap<String, Timer> getTimers(MetricFilter filter);
/**
* Get all {@link Tag}s in a list.
*
* <p>
* This method guarantees no duplicated {@link Tag}s and the order of {@link Tag}s
* is the same as the one in which the {@link Tag}s were added.
* </p>
*
* @return all {@link Tag}s in a list
*/
public List<Tag<?>> getTags();
/**
* @return all {@link Tag}s in a map.
*/
public Map<String, Object> getTagMap();
}
| 4,423 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/ContextWeakReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context;
import lombok.Getter;
import java.lang.ref.WeakReference;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.RootMetricContext;
/**
* {@link WeakReference} to a {@link MetricContext} used to notify the {@link RootMetricContext} of garbage collection
* of {@link MetricContext}s.
*/
@Getter
public class ContextWeakReference extends WeakReference<MetricContext> {
private final InnerMetricContext innerContext;
public ContextWeakReference(MetricContext referent, InnerMetricContext innerContext) {
super(referent, RootMetricContext.get().getReferenceQueue());
this.innerContext = innerContext;
}
}
| 4,424 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/filter/ContextFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context.filter;
import java.util.Set;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.MetricContext;
/**
* Filter for selecting {@link MetricContext}s to report by a {@link org.apache.gobblin.metrics.reporter.ContextAwareReporter}.
*/
public interface ContextFilter {
/**
* Get all {@link MetricContext}s in the {@link MetricContext} tree that should be reported.
* @return Set of {@link MetricContext}s that should be reported.
*/
public Set<MetricContext> getMatchingContexts();
/**
* Whether the input {@link MetricContext} should be reported.
* @param metricContext {@link MetricContext} to check.
* @return true if the input {@link MetricContext} should be reported.
*/
public boolean matches(MetricContext metricContext);
/**
* This method is called by a {@link org.apache.gobblin.metrics.reporter.ContextAwareReporter} when a {@link MetricContext}
* that it used to report is cleaned. Every cleaned {@link MetricContext} is a leaf of the tree. In some circumstances,
* after removing the {@link MetricContext} it is necessary to start reporting the parent (for example, if we
* are reporting leaves, and the parent is a new leaf). This method is called to determine if the
* {@link org.apache.gobblin.metrics.reporter.ContextAwareReporter} should start reporting the parent of the input
* {@link InnerMetricContext}.
*
* @param removedMetricContext {@link InnerMetricContext} backing up the newly removed {@link MetricContext}.
* @return true if the parent of the removed {@link MetricContext} should be reported.
*/
public boolean shouldReplaceByParent(InnerMetricContext removedMetricContext);
}
| 4,425 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/filter/AllContextFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context.filter;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.RootMetricContext;
/**
* Accepts all {@link MetricContext} in the tree.
*/
public class AllContextFilter implements ContextFilter {
@Override public Set<MetricContext> getMatchingContexts() {
ImmutableSet.Builder<MetricContext> builder = ImmutableSet.builder();
addContextsRecursively(builder, RootMetricContext.get());
return builder.build();
}
@Override public boolean matches(MetricContext metricContext) {
return true;
}
@Override public boolean shouldReplaceByParent(InnerMetricContext removedMetricContext) {
return false;
}
private void addContextsRecursively(ImmutableSet.Builder<MetricContext> builder, MetricContext metricContext) {
builder.add(metricContext);
for(MetricContext context : metricContext.getChildContextsAsMap().values()) {
addContextsRecursively(builder, context);
}
}
}
| 4,426 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/context/filter/ContextFilterFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.context.filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValueFactory;
/**
* Factory for {@link ContextFilter}s.
*/
@Slf4j
public class ContextFilterFactory {
public static final String CONTEXT_FILTER_CLASS = "context.filter.class";
/**
* Modify the configuration to set the {@link ContextFilter} class.
* @param config Input {@link Config}.
* @param klazz Class of desired {@link ContextFilter}.
* @return Modified {@link Config}.
*/
public static Config setContextFilterClass(Config config, Class<? extends ContextFilter> klazz) {
return config.withValue(CONTEXT_FILTER_CLASS, ConfigValueFactory.fromAnyRef(klazz.getCanonicalName()));
}
/**
* Create a {@link ContextFilter} from a {@link Config}.
* @param config {@link Config} used for creating new {@link ContextFilter}.
* @return a new {@link ContextFilter}.
*/
public static ContextFilter createContextFilter(Config config) {
// For now always return an accept-all context filter.
if (config.hasPath(CONTEXT_FILTER_CLASS)) {
try {
return ContextFilter.class.cast(
ConstructorUtils.invokeConstructor(Class.forName(config.getString(CONTEXT_FILTER_CLASS)), config));
} catch (ReflectiveOperationException rfe) {
log.error("Failed to instantiate context filter with class " + config.getString(CONTEXT_FILTER_CLASS), rfe);
}
}
return new AllContextFilter();
}
}
| 4,427 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/test/TestConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.test;
/**
* A central place for constants used in tests for gobblin-metrics.
*
* @author Yinan Li
*/
public class TestConstants {
public static final String METRIC_PREFIX = "com.linkedin.example";
public static final String GAUGE = "gauge";
public static final String COUNTER = "counter";
public static final String METER = "meter";
public static final String HISTOGRAM = "histogram";
public static final String TIMER = "timer";
public static final String CONTEXT_NAME = "TestContext";
public static final String RECORDS_PROCESSED = "recordsProcessed";
public static final String RECORD_PROCESS_RATE = "recordProcessRate";
public static final String RECORD_SIZE_DISTRIBUTION = "recordSizeDistribution";
public static final String TOTAL_DURATION = "totalDuration";
public static final String QUEUE_SIZE = "queueSize";
}
| 4,428 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/test/MetricsAssert.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.test;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import javax.annotation.Nonnull;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.notification.EventNotification;
import org.apache.gobblin.metrics.notification.Notification;
/**
* A class to help with testing metrics. It provides asserts on a {@link MetricContext}
*/
public class MetricsAssert implements Function<Notification, Void> {
private final MetricContext _metricContext;
private final LinkedBlockingQueue<GobblinTrackingEvent> _events = new LinkedBlockingQueue<>();
public MetricsAssert(MetricContext metricContext) {
_metricContext = metricContext;
_metricContext.addNotificationTarget(this);
}
/** {@inheritDoc} */
@Override public Void apply(Notification input) {
if (input instanceof EventNotification) {
_events.offer(((EventNotification)input).getEvent());
}
return null;
}
public MetricContext getMetricContext() {
return _metricContext;
}
public void assertEvent(Predicate<GobblinTrackingEvent> predicate, long timeout,
TimeUnit timeUnit) throws TimeoutException, InterruptedException {
GobblinTrackingEvent gte = timeout > 0 ? _events.poll(timeout, timeUnit) : _events.take();
if (null == gte) {
throw new TimeoutException();
}
if (!predicate.apply(gte)) {
throw new AssertionError("Event predicate mismatch: " + gte);
}
}
public void assertEvent(Predicate<GobblinTrackingEvent> predicate) throws InterruptedException {
try {
assertEvent(predicate, 0, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new Error("This should never happen");
}
}
public static Predicate<GobblinTrackingEvent> eqEventName(final String expectedName) {
return new Predicate<GobblinTrackingEvent>() {
@Override public boolean apply(@Nonnull GobblinTrackingEvent input) {
return input.getName().equals(expectedName);
}
};
}
public static Predicate<GobblinTrackingEvent> eqEventNamespace(final String expectedNamespace) {
return new Predicate<GobblinTrackingEvent>() {
@Override public boolean apply(@Nonnull GobblinTrackingEvent input) {
return input.getNamespace().equals(expectedNamespace);
}
};
}
public static Predicate<GobblinTrackingEvent> eqEventMetdata(final String metadataKey,
final String metadataValue) {
return new Predicate<GobblinTrackingEvent>() {
@Override public boolean apply(@Nonnull GobblinTrackingEvent input) {
return input.getMetadata().get(metadataKey).equals(metadataValue);
}
};
}
public static Predicate<GobblinTrackingEvent> hasEventMetdata(final String metadataKey) {
return new Predicate<GobblinTrackingEvent>() {
@Override public boolean apply(@Nonnull GobblinTrackingEvent input) {
return input.getMetadata().containsKey(metadataKey);
}
};
}
public ImmutableList<GobblinTrackingEvent> getEvents() {
return ImmutableList.copyOf(_events);
}
}
| 4,429 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/test/ContextStoreReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.typesafe.config.Config;
import org.apache.gobblin.metrics.context.ReportableContext;
import org.apache.gobblin.metrics.reporter.ScheduledReporter;
import lombok.Getter;
/**
* Stores {@link ReportableContext} that is should report in a list.
*/
public class ContextStoreReporter extends ScheduledReporter {
@Getter
private final List<ReportableContext> reportedContexts;
public ContextStoreReporter(String name, Config config) {
super(name, config);
this.reportedContexts = Lists.newArrayList();
}
@Override
protected void report(ReportableContext context, boolean isFinal) {
this.reportedContexts.add(context);
}
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, Object> tags) {
// Noop
}
public Set<ReportableContext> getContextsToReport() {
return Sets.newHashSet(this.getMetricContextsToReport());
}
}
| 4,430 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/test/TimestampedValue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.test;
/**
*
* @author Yinan Li
*
*/
public class TimestampedValue {
private final long timestamp;
private final String value;
public TimestampedValue(long timestamp, String value) {
this.timestamp = timestamp;
this.value = value;
}
public long getTimestamp() {
return this.timestamp;
}
public String getValue() {
return this.value;
}
}
| 4,431 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/MetricReportReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Counting;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metered;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.typesafe.config.Config;
import org.apache.gobblin.metrics.Measurements;
import org.apache.gobblin.metrics.Metric;
import org.apache.gobblin.metrics.MetricReport;
/**
* Scheduled reporter based on {@link org.apache.gobblin.metrics.MetricReport}.
*
* <p>
* This class will generate a metric report, and call {@link #emitReport} to actually emit the metrics.
* </p>
*/
public abstract class MetricReportReporter extends ConfiguredScheduledReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricReportReporter.class);
public MetricReportReporter(Builder<?> builder, Config config) {
super(builder, config);
}
/**
* Builder for {@link MetricReportReporter}. Defaults to no filter, reporting rates in seconds and times in
* milliseconds.
*/
public static abstract class Builder<T extends ConfiguredScheduledReporter.Builder<T>> extends
ConfiguredScheduledReporter.Builder<T> {
protected MetricFilter filter;
protected Builder() {
super();
this.name = "MetricReportReporter";
this.filter = MetricFilter.ALL;
}
/**
* Only report metrics which match the given filter.
*
* @param filter a {@link MetricFilter}
* @return {@code this}
*/
public T filter(MetricFilter filter) {
this.filter = filter;
return self();
}
}
/**
* Serializes metrics and pushes the byte arrays to Kafka. Uses the serialize* methods in {@link MetricReportReporter}.
*
* @param gauges map of {@link com.codahale.metrics.Gauge} to report and their name.
* @param counters map of {@link com.codahale.metrics.Counter} to report and their name.
* @param histograms map of {@link com.codahale.metrics.Histogram} to report and their name.
* @param meters map of {@link com.codahale.metrics.Meter} to report and their name.
* @param timers map of {@link com.codahale.metrics.Timer} to report and their name.
*/
@Override
protected void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, Object> tags) {
List<Metric> metrics = Lists.newArrayList();
for (Map.Entry<String, Gauge> gauge : gauges.entrySet()) {
metrics.addAll(serializeGauge(gauge.getKey(), gauge.getValue()));
}
for (Map.Entry<String, Counter> counter : counters.entrySet()) {
metrics.addAll(serializeCounter(counter.getKey(), counter.getValue()));
}
for (Map.Entry<String, Histogram> histogram : histograms.entrySet()) {
metrics.addAll(serializeSnapshot(histogram.getKey(), histogram.getValue().getSnapshot()));
metrics.addAll(serializeCounter(histogram.getKey(), histogram.getValue()));
}
for (Map.Entry<String, Meter> meter : meters.entrySet()) {
metrics.addAll(serializeMetered(meter.getKey(), meter.getValue()));
}
for (Map.Entry<String, Timer> timer : timers.entrySet()) {
metrics.addAll(serializeSnapshot(timer.getKey(), timer.getValue().getSnapshot()));
metrics.addAll(serializeMetered(timer.getKey(), timer.getValue()));
}
Map<String, Object> allTags = Maps.newHashMap();
allTags.putAll(tags);
allTags.putAll(this.tags);
Map<String, String> allTagsString = Maps.transformValues(allTags, new Function<Object, String>() {
@Nullable
@Override
public String apply(Object input) {
return input.toString();
}
});
MetricReport report = new MetricReport(allTagsString, System.currentTimeMillis(), metrics);
emitReport(report);
}
/**
* Emit the {@link org.apache.gobblin.metrics.MetricReport} to the metrics sink.
*
* @param report metric report to emit.
*/
protected abstract void emitReport(MetricReport report);
/**
* Extracts metrics from {@link com.codahale.metrics.Gauge}.
*
* @param name name of the {@link com.codahale.metrics.Gauge}.
* @param gauge instance of {@link com.codahale.metrics.Gauge} to serialize.
* @return a list of {@link org.apache.gobblin.metrics.Metric}.
*/
protected List<Metric> serializeGauge(String name, Gauge gauge) {
List<Metric> metrics = Lists.newArrayList();
try {
metrics.add(new Metric(name, Double.parseDouble(gauge.getValue().toString())));
} catch(NumberFormatException exception) {
LOGGER.info("Failed to serialize gauge metric. Not compatible with double value.", exception);
}
return metrics;
}
/**
* Extracts metrics from {@link com.codahale.metrics.Counter}.
*
* @param name name of the {@link com.codahale.metrics.Counter}.
* @param counter instance of {@link com.codahale.metrics.Counter} to serialize.
* @return a list of {@link org.apache.gobblin.metrics.Metric}.
*/
protected List<Metric> serializeCounter(String name, Counting counter) {
return Lists.newArrayList(
serializeValue(name, counter.getCount(), Measurements.COUNT.name())
);
}
/**
* Extracts metrics from {@link com.codahale.metrics.Metered}.
*
* @param name name of the {@link com.codahale.metrics.Metered}.
* @param meter instance of {@link com.codahale.metrics.Metered} to serialize.
* @return a list of {@link org.apache.gobblin.metrics.Metric}.
*/
protected List<Metric> serializeMetered(String name, Metered meter) {
return Lists.newArrayList(
serializeValue(name, meter.getCount(), Measurements.COUNT.name()),
serializeValue(name, meter.getMeanRate(), Measurements.MEAN_RATE.name()),
serializeValue(name, meter.getOneMinuteRate(), Measurements.RATE_1MIN.name()),
serializeValue(name, meter.getFiveMinuteRate(), Measurements.RATE_5MIN.name()),
serializeValue(name, meter.getFifteenMinuteRate(), Measurements.RATE_15MIN.name())
);
}
/**
* Extracts metrics from {@link com.codahale.metrics.Snapshot}.
*
* @param name name of the {@link com.codahale.metrics.Snapshot}.
* @param snapshot instance of {@link com.codahale.metrics.Snapshot} to serialize.
* @return a list of {@link org.apache.gobblin.metrics.Metric}.
*/
protected List<Metric> serializeSnapshot(String name, Snapshot snapshot) {
return Lists.newArrayList(
serializeValue(name, snapshot.getMean(), Measurements.MEAN.name()),
serializeValue(name, snapshot.getMin(), Measurements.MIN.name()),
serializeValue(name, snapshot.getMax(), Measurements.MAX.name()),
serializeValue(name, snapshot.getMedian(), Measurements.MEDIAN.name()),
serializeValue(name, snapshot.get75thPercentile(), Measurements.PERCENTILE_75TH.name()),
serializeValue(name, snapshot.get95thPercentile(), Measurements.PERCENTILE_95TH.name()),
serializeValue(name, snapshot.get99thPercentile(), Measurements.PERCENTILE_99TH.name()),
serializeValue(name, snapshot.get999thPercentile(), Measurements.PERCENTILE_999TH.name())
);
}
/**
* Convert single value into list of {@link org.apache.gobblin.metrics.Metric}.
*
* @param name name of the metric.
* @param value value of the metric.
* @param path suffixes to more precisely identify the meaning of the reported value
* @return a Singleton list of {@link org.apache.gobblin.metrics.Metric}.
*/
protected List<Metric> serializeSingleValue(String name, Number value, String... path) {
return Lists.newArrayList(
serializeValue(name, value, path)
);
}
/**
* Converts a single key-value pair into a metric.
*
* @param name name of the metric
* @param value value of the metric to report
* @param path additional suffixes to further identify the meaning of the reported value
* @return a {@link org.apache.gobblin.metrics.Metric}.
*/
protected Metric serializeValue(String name, Number value, String... path) {
return new Metric(MetricRegistry.name(name, path), value.doubleValue());
}
} | 4,432 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/ContextAwareScheduledReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Timer;
import com.google.common.base.Optional;
import org.apache.gobblin.metrics.MetricContext;
/**
* A custom {@link com.codahale.metrics.ScheduledReporter} that is aware of the
* {@link org.apache.gobblin.metrics.MetricContext} it is associated to.
*
* @author Yinan Li
*/
public abstract class ContextAwareScheduledReporter extends ScheduledReporter {
private final MetricContext context;
private final Optional<MetricFilter> filter;
protected ContextAwareScheduledReporter(MetricContext context, String name, MetricFilter filter,
TimeUnit rateUnit, TimeUnit durationUnit) {
super(context, name, filter, rateUnit, durationUnit);
this.context = context;
this.filter = Optional.fromNullable(filter);
}
@Override
public void report() {
if (this.filter.isPresent()) {
report(this.context.getGauges(this.filter.get()),
this.context.getCounters(this.filter.get()),
this.context.getHistograms(this.filter.get()),
this.context.getMeters(this.filter.get()),
this.context.getTimers(this.filter.get()));
} else {
report(this.context.getGauges(),
this.context.getCounters(),
this.context.getHistograms(),
this.context.getMeters(),
this.context.getTimers());
}
}
@Override
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers) {
reportInContext(this.context, gauges, counters, histograms, meters, timers);
}
/**
* Report all the given metrics in the {@link MetricContext}.
*
* <p>
* Called periodically by the polling thread. Subclasses should report all the given metrics.
* </p>
*
* <p>
* The metric names (the keys in the given {@link SortedMap}s) may or may not include the
* {@link org.apache.gobblin.metrics.Tag}s of the {@link MetricContext} depending on if the {@link MetricContext} is
* configured to report fully-qualified metric names or not using the method
* {@link MetricContext.Builder#reportFullyQualifiedNames(boolean)}. It is up to the
* implementation of this method to decide on whether to include the name of the
* {@link MetricContext} (given by {@link MetricContext#getName()}) and the {@link org.apache.gobblin.metrics.Tag}s
* of individual {@link org.apache.gobblin.metrics.ContextAwareMetric}s when reporting them.
* </p>
*
* @param gauges all of the gauges in the {@link MetricContext}
* @param counters all of the counters in the {@link MetricContext}
* @param histograms all of the histograms in the {@link MetricContext}
* @param meters all of the meters in the {@link MetricContext}
* @param timers all of the timers in the {@link MetricContext}
*/
protected abstract void reportInContext(MetricContext context,
SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers);
/**
* A builder class for {@link ContextAwareScheduledReporter}.
*
* @param <R> type of a subclass of {@link ContextAwareScheduledReporter}
* @param <B> type of a subclass of {@link Builder}
*/
@SuppressWarnings("unchecked")
public abstract static class Builder<R extends ContextAwareScheduledReporter, B extends Builder> {
protected final String name;
protected MetricFilter filter = MetricFilter.ALL;
protected TimeUnit rateUnit = TimeUnit.SECONDS;
protected TimeUnit durationUnit = TimeUnit.MILLISECONDS;
public Builder(String name) {
this.name = name;
}
/**
* Get the name of the {@link ContextAwareScheduledReporter} that is going to be built by this
* {@link ContextAwareScheduledReporter.Builder}.
*
* @return name of the {@link ContextAwareScheduledReporter} that is going to be built
*/
public String getName() {
return this.name;
}
/**
* Build a new {@link ContextAwareScheduledReporter}.
*
* @param context the {@link MetricContext} of this {@link ContextAwareScheduledReporter}
* @return the newly built {@link ContextAwareScheduledReporter}
*/
public abstract R build(MetricContext context);
/**
* Only report metrics which match the given filter.
*
* @param filter a {@link MetricFilter}
* @return {@code this}
*/
public B filter(MetricFilter filter) {
this.filter = filter;
return (B) this;
}
/**
* Convert rates to the given time unit.
*
* @param rateUnit a unit of time
* @return {@code this}
*/
public B convertRatesTo(TimeUnit rateUnit) {
this.rateUnit = rateUnit;
return (B) this;
}
/**
* Convert durations to the given time unit.
*
* @param durationUnit a unit of time
* @return {@code this}
*/
public B convertDurationsTo(TimeUnit durationUnit) {
this.durationUnit = durationUnit;
return (B) this;
}
}
}
| 4,433 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/ConfiguredScheduledReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.io.Closer;
import com.typesafe.config.Config;
import lombok.Getter;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
/**
* Scheduled reporter with metrics reporting configuration.
*
* <p>
* Concrete reporters need to subclass this class and implement {@link ScheduledReporter#report(SortedMap , SortedMap, SortedMap, SortedMap, SortedMap, Map)}
* that emits the metrics in the desired (textual/serialized) form.
* </p>
*
* @author Lorand Bendig
*
*/
public abstract class ConfiguredScheduledReporter extends ScheduledReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfiguredScheduledReporter.class);
private static final String FINAL_TAG_KEY = "finalReport";
@Getter
private final TimeUnit rateUnit;
@Getter
private final TimeUnit durationUnit;
private final double rateFactor;
private final double durationFactor;
protected final ImmutableMap<String, String> tags;
protected final Closer closer;
protected final String metricContextName;
protected final String metricsPrefix;
protected static final Joiner JOINER = Joiner.on('.').skipNulls();
public ConfiguredScheduledReporter(Builder<?> builder, Config config) {
super(builder.name, config);
this.rateUnit = builder.rateUnit;
this.durationUnit = builder.durationUnit;
this.rateFactor = builder.rateUnit.toSeconds(1);
this.durationFactor = 1.0 / builder.durationUnit.toNanos(1);
this.tags = ImmutableMap.copyOf(builder.tags);
this.closer = Closer.create();
this.metricContextName = builder.metricContextName;
this.metricsPrefix = builder.metricsPrefix;
}
/**
* Builder for {@link ConfiguredScheduledReporter}. Defaults to no filter, reporting rates in seconds and times in
* milliseconds.
*/
public static abstract class Builder<T extends Builder<T>> {
protected String name;
protected TimeUnit rateUnit;
protected TimeUnit durationUnit;
protected Map<String, String> tags;
protected String metricContextName;
protected String metricsPrefix;
protected Builder() {
this.name = "ConfiguredScheduledReporter";
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.tags = Maps.newHashMap();
}
protected abstract T self();
/**
* Set the name of the reporter
*
* @param name name of the metric reporter
* @return {@code this}
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* Convert rates to the given time unit.
*
* @param rateUnit a unit of time
* @return {@code this}
*/
public T convertRatesTo(TimeUnit rateUnit) {
this.rateUnit = rateUnit;
return self();
}
/**
* Convert durations to the given time unit.
*
* @param durationUnit a unit of time
* @return {@code this}
*/
public T convertDurationsTo(TimeUnit durationUnit) {
this.durationUnit = durationUnit;
return self();
}
/**
* Add tags
* @param tags additional {@link org.apache.gobblin.metrics.Tag}s for the reporter.
* @return {@code this}
*/
public T withTags(Map<String, String> tags) {
this.tags.putAll(tags);
return self();
}
/**
* Add tags.
* @param tags List of {@link org.apache.gobblin.metrics.Tag}
* @return {@code this}
*/
public T withTags(List<Tag<?>> tags) {
for(Tag<?> tag : tags) {
this.tags.put(tag.getKey(), tag.getValue().toString());
}
return self();
}
/**
* Add tag.
* @param key tag key
* @param value tag value
* @return {@code this}
*/
public T withTag(String key, String value) {
this.tags.put(key, value);
return self();
}
/**
* Sets metrics prefix independent from the context (useful for grouping metrics in Graphite or other metric-store)
* @param metricsPrefix
* @return
*/
public T withMetricsPrefix(String metricsPrefix) {
this.metricsPrefix = metricsPrefix;
return self();
}
/**
* Add the name of the base metrics context as prefix to the metric keys
*
* @param metricContextName name of the metrics context
* @return {@code this}
*/
public T withMetricContextName(String metricContextName) {
this.metricContextName = metricContextName;
return self();
}
}
@Override
protected void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, Object> tags, boolean isFinal) {
if (isFinal) {
report(gauges, counters, histograms, meters, timers,
ImmutableMap.<String, Object>builder().putAll(tags).put(FINAL_TAG_KEY, Boolean.TRUE).build());
} else {
report(gauges, counters, histograms, meters, timers, tags);
}
}
protected double convertDuration(double duration) {
return duration * this.durationFactor;
}
protected double convertRate(double rate) {
return rate * this.rateFactor;
}
/**
* Constructs the prefix of metric key to be emitted.
* Enriches {@link ConfiguredScheduledReporter#metricContextName} with the current task id and fork id to
* be able to identify the emitted metric by its origin
*
* @param tags
* @return Prefix of the metric key
*/
protected String getMetricNamePrefix(Map<String, Object> tags){
String currentContextName = (String) tags.get(MetricContext.METRIC_CONTEXT_NAME_TAG_NAME);
if (metricContextName == null || (currentContextName.indexOf(metricContextName) > -1)) {
return currentContextName;
}
return JOINER.join(Strings.emptyToNull(metricsPrefix),
metricContextName, tags.get("taskId"), tags.get("forkBranchName"), tags.get("class"));
}
@Override
public void close() throws IOException {
try {
this.closer.close();
} catch(Exception e) {
LOGGER.warn("Exception when closing ConfiguredScheduledReporter", e);
} finally {
super.close();
}
}
}
| 4,434 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/RecursiveScheduledReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Timer;
import org.apache.gobblin.metrics.MetricContext;
/**
* Reports a Metric context and all of its descendants recursively.
*/
public abstract class RecursiveScheduledReporter extends ScheduledReporter {
protected final MetricRegistry registry;
public RecursiveScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit,
TimeUnit durationUnit) {
super(registry, name, filter, rateUnit, durationUnit);
this.registry = registry;
}
@Override
public final void report() {
reportContextTree(this.registry);
}
/**
* Report a {@link com.codahale.metrics.MetricRegistry}. If the input is a {@link org.apache.gobblin.metrics.MetricContext}
* it will also report all of its children recursively.
* @param registry MetricRegistry to report.
*/
public void reportContextTree(MetricRegistry registry) {
reportRegistry(registry);
if (registry instanceof MetricContext) {
for (MetricContext context : ((MetricContext) registry).getChildContextsAsMap().values()) {
reportContextTree(context);
}
}
}
public abstract void reportRegistry(MetricRegistry registry);
/**
* This is an abstract method of {@link com.codahale.metrics.ScheduledReporter} which is no longer used.
* Implement as a NOOP.
*/
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
}
}
| 4,435 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/ScheduledReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValueFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.context.ReportableContext;
import org.apache.gobblin.metrics.metric.filter.MetricFilters;
import org.apache.gobblin.metrics.metric.filter.MetricNameRegexFilter;
import org.apache.gobblin.metrics.metric.filter.MetricTypeFilter;
import org.apache.gobblin.util.ExecutorsUtils;
/**
* A {@link ContextAwareReporter} that reports on a schedule.
*/
@Slf4j
public abstract class ScheduledReporter extends ContextAwareReporter {
/**
* Interval at which metrics are reported. Format: hours, minutes, seconds. Examples: 1h, 1m, 10s, 1h30m, 2m30s, ...
*/
public static final String REPORTING_INTERVAL =
ConfigurationKeys.METRICS_CONFIGURATIONS_PREFIX + "reporting.interval";
public static final String DEFAULT_REPORTING_INTERVAL_PERIOD = "1M";
public static final PeriodFormatter PERIOD_FORMATTER = new PeriodFormatterBuilder().
appendHours().appendSuffix("H").
appendMinutes().appendSuffix("M").
appendSeconds().appendSuffix("S").toFormatter();
private static final String METRIC_FILTER_NAME_REGEX = "metric.filter.name.regex";
private static final String METRIC_FILTER_TYPE_LIST = "metric.filter.type.list";
@VisibleForTesting
static int parsePeriodToSeconds(String periodStr) {
try {
return Period.parse(periodStr.toUpperCase(), PERIOD_FORMATTER).toStandardSeconds().getSeconds();
} catch(ArithmeticException ae) {
throw new RuntimeException(String.format("Reporting interval is too long. Max: %d seconds.", Integer.MAX_VALUE));
}
}
public static void setReportingInterval(Properties props, long reportingInterval, TimeUnit reportingIntervalUnit) {
long seconds = TimeUnit.SECONDS.convert(reportingInterval, reportingIntervalUnit);
if (seconds > Integer.MAX_VALUE) {
throw new RuntimeException(String.format("Reporting interval is too long. Max: %d seconds.", Integer.MAX_VALUE));
}
props.setProperty(REPORTING_INTERVAL, Long.toString(seconds) + "S");
}
public static Config setReportingInterval(Config config, long reportingInterval, TimeUnit reportingIntervalUnit) {
long seconds = TimeUnit.SECONDS.convert(reportingInterval, reportingIntervalUnit);
if (seconds > Integer.MAX_VALUE) {
throw new RuntimeException(String.format("Reporting interval is too long. Max: %d seconds.", Integer.MAX_VALUE));
}
return config.withValue(REPORTING_INTERVAL, ConfigValueFactory.fromAnyRef(seconds + "S"));
}
private ScheduledExecutorService executor;
private MetricFilter metricFilter;
private Optional<ScheduledFuture> scheduledTask;
private int reportingPeriodSeconds;
public ScheduledReporter(String name, Config config) {
super(name, config);
ensureMetricFilterIsInitialized(config);
}
private synchronized void ensureMetricFilterIsInitialized(Config config) {
if (this.metricFilter == null) {
this.metricFilter = createMetricFilter(config);
}
}
private MetricFilter createMetricFilter(Config config) {
if (config.hasPath(METRIC_FILTER_NAME_REGEX) && config.hasPath(METRIC_FILTER_TYPE_LIST)) {
return MetricFilters.and(new MetricNameRegexFilter(config.getString(METRIC_FILTER_NAME_REGEX)),
new MetricTypeFilter(config.getString(METRIC_FILTER_TYPE_LIST)));
}
if (config.hasPath(METRIC_FILTER_NAME_REGEX)) {
return new MetricNameRegexFilter(config.getString(METRIC_FILTER_NAME_REGEX));
}
if (config.hasPath(METRIC_FILTER_TYPE_LIST)) {
return new MetricTypeFilter(config.getString(METRIC_FILTER_TYPE_LIST));
}
return MetricFilter.ALL;
}
@Override
public void startImpl() {
this.executor = Executors.newSingleThreadScheduledExecutor(
ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of("metrics-" + name + "-scheduler")));
this.reportingPeriodSeconds = parsePeriodToSeconds(
config.hasPath(REPORTING_INTERVAL) ? config.getString(REPORTING_INTERVAL) : DEFAULT_REPORTING_INTERVAL_PERIOD);
ensureMetricFilterIsInitialized(config);
this.scheduledTask = Optional.<ScheduledFuture>of(this.executor.scheduleAtFixedRate(new Runnable() {
@Override public void run() {
report();
}
}, 0, this.reportingPeriodSeconds, TimeUnit.SECONDS));
}
@Override
public void stopImpl() {
if (this.scheduledTask.isPresent()) {
this.scheduledTask.get().cancel(false);
}
this.scheduledTask = Optional.absent();
ExecutorsUtils.shutdownExecutorService(this.executor, Optional.of(log), 10, TimeUnit.SECONDS);
// Report metrics one last time - this ensures any metrics values updated between intervals are reported
report(true);
}
@Override
public void close() throws IOException {
super.close();
}
@Override
protected void removedMetricContext(InnerMetricContext context) {
if (shouldReportInnerMetricContext(context)) {
report(context, true);
}
super.removedMetricContext(context);
}
/**
* Trigger emission of a report.
*/
public void report() {
report(false);
}
/***
* @param isFinal true if this is the final time report will be called for this reporter, false otherwise
* @see #report()
*/
protected void report(boolean isFinal) {
for (ReportableContext metricContext : getMetricContextsToReport()) {
report(metricContext, isFinal);
}
}
/**
* Report as {@link InnerMetricContext}.
*
* <p>
* This method is marked as final because it is not directly invoked from the framework, so this method should not
* be overloaded. Overload {@link #report(ReportableContext, boolean)} instead.
* </p>
*
* @param context {@link InnerMetricContext} to report.
* @see #report(ReportableContext, boolean)
*/
protected final void report(ReportableContext context) {
report(context, false);
}
/**
* @param context {@link InnerMetricContext} to report.
* @param isFinal true if this is the final time report will be called for the given context, false otherwise
* @see #report(ReportableContext)
*/
protected void report(ReportableContext context, boolean isFinal) {
report(context.getGauges(this.metricFilter), context.getCounters(this.metricFilter),
context.getHistograms(this.metricFilter), context.getMeters(this.metricFilter),
context.getTimers(this.metricFilter), context.getTagMap(), isFinal);
}
/**
* Report the input metrics. The input tags apply to all input metrics.
*
* <p>
* The default implementation of this method is to ignore the value of isFinal. Sub-classes that are interested in
* using the value of isFinal should override this method as well as
* {@link #report(SortedMap, SortedMap, SortedMap, SortedMap, SortedMap, Map)}. If they are not interested in the
* value of isFinal, they should just override
* {@link #report(SortedMap, SortedMap, SortedMap, SortedMap, SortedMap, Map)}.
* </p>
*
* @param isFinal true if this is the final time report will be called, false otherwise
*/
protected void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, Object> tags, boolean isFinal) {
report(gauges, counters, histograms, meters, timers, tags);
}
/**
* @see #report(SortedMap, SortedMap, SortedMap, SortedMap, SortedMap, Map)
*/
protected abstract void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, Object> tags);
}
| 4,436 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/FileFailureEventReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Queue;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.event.FailureEventBuilder;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;
/**
* An {@link OutputStreamEventReporter} reports only failure event build by {@link FailureEventBuilder}. It won't create
* the failure log file until a failure event is processed
*/
@Slf4j
public class FileFailureEventReporter extends OutputStreamEventReporter {
private final FileSystem fs;
private final Path failureLogFile;
private volatile boolean hasSetupOutputStream;
public FileFailureEventReporter(MetricContext context, FileSystem fs, Path failureLogFile)
throws IOException {
super(OutputStreamEventReporter.forContext(context));
this.fs = fs;
this.failureLogFile = failureLogFile;
hasSetupOutputStream = false;
}
@Override
public void addEventToReportingQueue(GobblinTrackingEvent event) {
if (FailureEventBuilder.isFailureEvent(event)) {
super.addEventToReportingQueue(event);
}
}
@Override
public void reportEventQueue(Queue<GobblinTrackingEvent> queue) {
if (queue.size() > 0) {
setupOutputStream();
super.reportEventQueue(queue);
}
}
/**
* Set up the {@link OutputStream} to the {@link #failureLogFile} only once
*/
private void setupOutputStream() {
synchronized (failureLogFile) {
// Setup is done by some thread
if (hasSetupOutputStream) {
return;
}
try {
boolean append = false;
if (fs.exists(failureLogFile)) {
log.info("Failure log file %s already exists, appending to it", failureLogFile);
append = true;
}
OutputStream outputStream = append ? fs.append(failureLogFile) : fs.create(failureLogFile);
output = this.closer.register(new PrintStream(outputStream, false, Charsets.UTF_8.toString()));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
hasSetupOutputStream = true;
}
}
}
}
| 4,437 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/RecursiveScheduledMetricReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.apache.gobblin.metrics.MetricContext;
/**
* Reports the metrics of a {@link org.apache.gobblin.metrics.MetricContext} following a schedule.
*/
public abstract class RecursiveScheduledMetricReporter extends RecursiveScheduledReporter {
private MetricFilter filter;
public RecursiveScheduledMetricReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit,
TimeUnit durationUnit) {
super(registry, name, filter, rateUnit, durationUnit);
this.filter = filter;
}
public void reportRegistry(MetricRegistry registry) {
Map<String, String> tags = Maps.newHashMap();
if (registry instanceof MetricContext) {
tags = Maps.transformValues(((MetricContext) registry).getTagMap(), new Function<Object, String>() {
@Override
public String apply(Object input) {
return input.toString();
}
});
}
report(registry.getGauges(this.filter), registry.getCounters(this.filter), registry.getHistograms(this.filter),
registry.getMeters(this.filter), registry.getTimers(this.filter), tags);
}
/**
* Report the input metrics. The input tags apply to all input metrics.
*/
public abstract void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers,
Map<String, String> tags);
}
| 4,438 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/ContextAwareReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.Closeable;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import com.codahale.metrics.Reporter;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.typesafe.config.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.RootMetricContext;
import org.apache.gobblin.metrics.context.ReportableContext;
import org.apache.gobblin.metrics.context.filter.ContextFilter;
import org.apache.gobblin.metrics.context.filter.ContextFilterFactory;
import org.apache.gobblin.metrics.notification.MetricContextCleanupNotification;
import org.apache.gobblin.metrics.notification.NewMetricContextNotification;
import org.apache.gobblin.metrics.notification.Notification;
/**
* Base {@link Reporter} for gobblin metrics. Automatically handles {@link MetricContext} selection,
* {@link org.apache.gobblin.metrics.Metric} filtering, and changes to reporting on {@link MetricContext} life cycle.
*
* <p>
* The lifecycle of a {@link ContextAwareReporter} fully managed by the {@link RootMetricContext} is:
* {@code construct -> start -> stop -> close}. However, {@link ContextAwareReporter}s created manually by the user
* can have a different life cycle (for example multiple calls to start / stop).
* </p>
*/
@Slf4j
public class ContextAwareReporter implements Reporter, Closeable {
private boolean started;
private final UUID notificationTargetUUID;
private final Set<InnerMetricContext> contextsToReport;
private final ContextFilter contextFilter;
protected final String name;
protected final Config config;
public ContextAwareReporter(String name, Config config) {
this.name = name;
this.config = config;
this.started = false;
RootMetricContext.get().addNewReporter(this);
this.notificationTargetUUID = RootMetricContext.get().addNotificationTarget(new Function<Notification, Void>() {
@Nullable @Override public Void apply(Notification input) {
notificationCallback(input);
return null;
}
});
this.contextFilter = ContextFilterFactory.createContextFilter(config);
this.contextsToReport = Sets.newConcurrentHashSet();
for (MetricContext context : this.contextFilter.getMatchingContexts()) {
this.contextsToReport.add(context.getInnerMetricContext());
}
}
public boolean isStarted() {
return this.started;
}
/**
* Starts the {@link ContextAwareReporter}. If the {@link ContextAwareReporter} has been started
* (and not stopped since), this is a no-op.
*/
public final void start() {
if (this.started) {
log.warn(String.format("Reporter %s has already been started.", this.name));
return;
}
try {
startImpl();
this.started = true;
} catch (Exception exception) {
log.warn(String.format("Reporter %s did not start correctly.", this.name), exception);
}
}
/**
* Actual logic for starting the {@link ContextAwareReporter}. This is a separate method from {@link #start()} to
* allow {@link ContextAwareReporter} to handle the started / non-started state.
*/
protected void startImpl() {
}
/**
* Stops the {@link ContextAwareReporter}. If the {@link ContextAwareReporter} has not been started, or if it has been
* stopped already, and not started since, this is a no-op.
*/
public final void stop() {
if (!this.started) {
log.warn(String.format("Reporter %s has already been stopped.", this.name));
return;
}
try {
stopImpl();
this.started = false;
} catch (Exception exception) {
log.warn(String.format("Reporter %s did not stop correctly.", this.name), exception);
}
}
/**
* Actual logic for stopping the {@link ContextAwareReporter}. This is a separate method from {@link #stop()} to
* allow {@link ContextAwareReporter} to handle the started / non-started state.
*/
protected void stopImpl() {
}
/**
* Removes {@link ContextAwareReporter} records from the {@link RootMetricContext}.
* This method should be considered irreversible and destructive to the {@link ContextAwareReporter}.
* @throws IOException
*/
@Override
public void close() throws IOException {
RootMetricContext.get().removeNotificationTarget(this.notificationTargetUUID);
RootMetricContext.get().removeReporter(this);
}
/**
* Callback used to receive notifications from the {@link RootMetricContext}.
*/
private void notificationCallback(Notification notification) {
if (notification instanceof MetricContextCleanupNotification) {
removedMetricContext(((MetricContextCleanupNotification) notification).getMetricContext());
}
if (notification instanceof NewMetricContextNotification) {
newMetricContext(((NewMetricContextNotification) notification).getMetricContext());
}
}
/**
* Called when any {@link MetricContext} is removed from the tree.
*
* @param context {@link InnerMetricContext} backing the removed {@link MetricContext}.
*/
protected void removedMetricContext(InnerMetricContext context) {
this.contextsToReport.remove(context);
if (context.getParent().isPresent() && this.contextFilter.shouldReplaceByParent(context)) {
this.contextsToReport.add(context.getParent().get().getInnerMetricContext());
}
}
/**
* Called whenever a new {@link MetricContext} is added to the tree.
*
* @param context new {@link MetricContext} added.
*/
protected void newMetricContext(MetricContext context) {
if (this.contextFilter.matches(context)) {
this.contextsToReport.add(context.getInnerMetricContext());
}
}
/**
* Whether a {@link InnerMetricContext} should be reported. Called when a {@link MetricContext} has been removed and
* just before the corresponding {@link InnerMetricContext} is removed.
*/
protected boolean shouldReportInnerMetricContext(InnerMetricContext context) {
return this.contextsToReport.contains(context);
}
/**
* @return an {@link Iterable} of all {@link MetricContext}s to report.
*/
protected Iterable<ReportableContext> getMetricContextsToReport() {
return ImmutableSet.<ReportableContext>copyOf(this.contextsToReport);
}
}
| 4,439 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/OutputStreamReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TimeZone;
import com.typesafe.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Clock;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import com.google.common.collect.Maps;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.io.Closer;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.util.ConfigUtils;
public class OutputStreamReporter extends ConfiguredScheduledReporter {
private static final String TAGS_SECTION = "-- Tags";
private static final String GAUGES_SECTION = "-- Gauges";
private static final String COUNTERS_SECTION = "-- Counters";
private static final String HISTOGRAMS_SECTION = "-- Histograms";
private static final String METERS_SECTION = "-- Meters";
private static final String TIMERS_SECTION = "-- Times";
private static final Logger LOGGER = LoggerFactory.getLogger(OutputStreamReporter.class);
public static class Factory {
public static BuilderImpl newBuilder() {
return new BuilderImpl();
}
}
public static class BuilderImpl extends Builder<BuilderImpl> {
@Override
protected BuilderImpl self() {
return this;
}
}
/**
* A builder for {@link OutputStreamReporter} instances. Defaults to using the default locale and time zone, writing
* to {@code System.out}, converting rates to events/second, converting durations to milliseconds, and not filtering
* metrics.
*/
public static abstract class Builder<T extends ConfiguredScheduledReporter.Builder<T>>
extends ConfiguredScheduledReporter.Builder<T> {
protected PrintStream output;
protected Locale locale;
protected Clock clock;
protected TimeZone timeZone;
protected Builder() {
this.name = "OutputStreamReporter";
this.output = System.out;
this.locale = Locale.getDefault();
this.clock = Clock.defaultClock();
this.timeZone = TimeZone.getDefault();
}
protected abstract T self();
/**
* Write to the given {@link PrintStream}.
*
* @param output a {@link PrintStream} instance.
* @return {@code this}
*/
public T outputTo(PrintStream output) {
this.output = output;
return self();
}
/**
* Write to the given {@link java.io.OutputStream}.
*
* @param stream 2 {@link java.io.OutputStream} instance
* @return {@code this}
*/
public T outputTo(OutputStream stream) {
try {
this.output = new PrintStream(stream, false, Charsets.UTF_8.toString());
} catch(UnsupportedEncodingException exception) {
LOGGER.error("Unsupported encoding in OutputStreamReporter. This is an error with the code itself.", exception);
throw new RuntimeException(exception);
}
return self();
}
/**
* Format numbers for the given {@link Locale}.
*
* @param locale a {@link Locale}
* @return {@code this}
*/
public T formattedFor(Locale locale) {
this.locale = locale;
return self();
}
/**
* Use the given {@link Clock} instance for the time.
*
* @param clock a {@link Clock} instance
* @return {@code this}
*/
public T withClock(Clock clock) {
this.clock = clock;
return self();
}
/**
* Use the given {@link TimeZone} for the time.
*
* @param timeZone a {@link TimeZone}
* @return {@code this}
*/
public T formattedFor(TimeZone timeZone) {
this.timeZone = timeZone;
return self();
}
/**
* Builds a {@link OutputStreamReporter} with the given properties.
*
* @return a {@link OutputStreamReporter}
*/
public OutputStreamReporter build(Properties props) {
return new OutputStreamReporter(this, ConfigUtils.propertiesToConfig(props,
Optional.of(ConfigurationKeys.METRICS_CONFIGURATIONS_PREFIX)));
}
}
private static final int CONSOLE_WIDTH = 80;
private final PrintStream output;
private final Locale locale;
private final Clock clock;
private final DateFormat dateFormat;
private final ByteArrayOutputStream outputBuffer;
private final PrintStream outputBufferPrintStream;
private final Closer closer;
private OutputStreamReporter(Builder<?> builder, Config config) {
super(builder, config);
this.closer = Closer.create();
this.output = this.closer.register(builder.output);
this.locale = builder.locale;
this.clock = builder.clock;
this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
this.dateFormat.setTimeZone(builder.timeZone);
this.outputBuffer = new ByteArrayOutputStream();
try {
this.outputBufferPrintStream =
this.closer.register(new PrintStream(this.outputBuffer, false, Charsets.UTF_8.toString()));
} catch (UnsupportedEncodingException re) {
throw new RuntimeException("This should never happen.", re);
}
}
@Override
public void close() throws IOException {
try {
this.closer.close();
} catch (IOException exception) {
LOGGER.warn("Failed to close output streams.");
} finally {
super.close();
}
}
@SuppressWarnings("rawtypes")
@Override
protected synchronized void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers,
Map<String, Object> tags) {
this.outputBuffer.reset();
final String dateTime = dateFormat.format(new Date(clock.getTime()));
printWithBanner(dateTime, '=');
this.outputBufferPrintStream.println();
Map<String, Object> allTags = Maps.newHashMap();
allTags.putAll(tags);
allTags.putAll(this.tags);
if (!allTags.isEmpty()) {
printWithBanner(TAGS_SECTION, '-');
for (Map.Entry<String, Object> entry : allTags.entrySet()) {
this.outputBufferPrintStream.println(String.format("%s=%s", entry.getKey(), entry.getValue()));
}
this.outputBufferPrintStream.println();
}
if (!gauges.isEmpty()) {
printWithBanner(GAUGES_SECTION, '-');
for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
this.outputBufferPrintStream.println(entry.getKey());
printGauge(entry);
}
this.outputBufferPrintStream.println();
}
if (!counters.isEmpty()) {
printWithBanner(COUNTERS_SECTION, '-');
for (Map.Entry<String, Counter> entry : counters.entrySet()) {
this.outputBufferPrintStream.println(entry.getKey());
printCounter(entry);
}
this.outputBufferPrintStream.println();
}
if (!histograms.isEmpty()) {
printWithBanner(HISTOGRAMS_SECTION, '-');
for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
this.outputBufferPrintStream.println(entry.getKey());
printHistogram(entry.getValue());
}
this.outputBufferPrintStream.println();
}
if (!meters.isEmpty()) {
printWithBanner(METERS_SECTION, '-');
for (Map.Entry<String, Meter> entry : meters.entrySet()) {
this.outputBufferPrintStream.println(entry.getKey());
printMeter(entry.getValue());
}
this.outputBufferPrintStream.println();
}
if (!timers.isEmpty()) {
printWithBanner(TIMERS_SECTION, '-');
for (Map.Entry<String, Timer> entry : timers.entrySet()) {
this.outputBufferPrintStream.println(entry.getKey());
printTimer(entry.getValue());
}
this.outputBufferPrintStream.println();
}
this.outputBufferPrintStream.println();
this.outputBufferPrintStream.flush();
try {
this.outputBuffer.writeTo(this.output);
} catch (IOException exception) {
LOGGER.warn("Failed to write metric report to output stream.");
}
}
private void printMeter(Meter meter) {
this.outputBufferPrintStream.printf(locale, " count = %d%n", meter.getCount());
this.outputBufferPrintStream.printf(locale, " mean rate = %2.2f events/%s%n", convertRate(meter.getMeanRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 1-minute rate = %2.2f events/%s%n", convertRate(meter.getOneMinuteRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 5-minute rate = %2.2f events/%s%n", convertRate(meter.getFiveMinuteRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 15-minute rate = %2.2f events/%s%n", convertRate(meter.getFifteenMinuteRate()), getRateUnit());
}
private void printCounter(Map.Entry<String, Counter> entry) {
this.outputBufferPrintStream.printf(locale, " count = %d%n", entry.getValue().getCount());
}
private void printGauge(Map.Entry<String, Gauge> entry) {
this.outputBufferPrintStream.printf(locale, " value = %s%n", entry.getValue().getValue());
}
private void printHistogram(Histogram histogram) {
this.outputBufferPrintStream.printf(locale, " count = %d%n", histogram.getCount());
Snapshot snapshot = histogram.getSnapshot();
this.outputBufferPrintStream.printf(locale, " min = %d%n", snapshot.getMin());
this.outputBufferPrintStream.printf(locale, " max = %d%n", snapshot.getMax());
this.outputBufferPrintStream.printf(locale, " mean = %2.2f%n", snapshot.getMean());
this.outputBufferPrintStream.printf(locale, " stddev = %2.2f%n", snapshot.getStdDev());
this.outputBufferPrintStream.printf(locale, " median = %2.2f%n", snapshot.getMedian());
this.outputBufferPrintStream.printf(locale, " 75%% <= %2.2f%n", snapshot.get75thPercentile());
this.outputBufferPrintStream.printf(locale, " 95%% <= %2.2f%n", snapshot.get95thPercentile());
this.outputBufferPrintStream.printf(locale, " 98%% <= %2.2f%n", snapshot.get98thPercentile());
this.outputBufferPrintStream.printf(locale, " 99%% <= %2.2f%n", snapshot.get99thPercentile());
this.outputBufferPrintStream.printf(locale, " 99.9%% <= %2.2f%n", snapshot.get999thPercentile());
}
private void printTimer(Timer timer) {
final Snapshot snapshot = timer.getSnapshot();
this.outputBufferPrintStream.printf(locale, " count = %d%n", timer.getCount());
this.outputBufferPrintStream.printf(locale, " mean rate = %2.2f calls/%s%n", convertRate(timer.getMeanRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 1-minute rate = %2.2f calls/%s%n", convertRate(timer.getOneMinuteRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 5-minute rate = %2.2f calls/%s%n", convertRate(timer.getFiveMinuteRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " 15-minute rate = %2.2f calls/%s%n", convertRate(timer.getFifteenMinuteRate()), getRateUnit());
this.outputBufferPrintStream.printf(locale, " min = %2.2f %s%n", convertDuration(snapshot.getMin()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " max = %2.2f %s%n", convertDuration(snapshot.getMax()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " mean = %2.2f %s%n", convertDuration(snapshot.getMean()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " stddev = %2.2f %s%n", convertDuration(snapshot.getStdDev()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " median = %2.2f %s%n", convertDuration(snapshot.getMedian()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " 75%% <= %2.2f %s%n", convertDuration(snapshot.get75thPercentile()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " 95%% <= %2.2f %s%n", convertDuration(snapshot.get95thPercentile()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " 98%% <= %2.2f %s%n", convertDuration(snapshot.get98thPercentile()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " 99%% <= %2.2f %s%n", convertDuration(snapshot.get99thPercentile()), getDurationUnit());
this.outputBufferPrintStream.printf(locale, " 99.9%% <= %2.2f %s%n", convertDuration(snapshot.get999thPercentile()), getDurationUnit());
}
private void printWithBanner(String s, char c) {
this.outputBufferPrintStream.print(s);
this.outputBufferPrintStream.print(' ');
for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) {
this.outputBufferPrintStream.print(c);
}
this.outputBufferPrintStream.println();
}
}
| 4,440 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/EventReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.Closeable;
import java.util.Map;
import java.util.Queue;
import java.util.SortedMap;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Timer;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import com.google.common.io.Closer;
import com.google.common.util.concurrent.MoreExecutors;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.notification.EventNotification;
import org.apache.gobblin.metrics.notification.Notification;
import org.apache.gobblin.util.ExecutorsUtils;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_ID;
import static org.apache.gobblin.metrics.event.TaskEvent.METADATA_TASK_ID;
/**
* Abstract class for reporting {@link org.apache.gobblin.metrics.GobblinTrackingEvent}s at a fixed schedule.
*
* <p>
* Subclasses should implement {@link #reportEventQueue} to emit the events to the sink. Events will only be
* reported once, and then removed from the event queue.
* </p>
*/
@Slf4j
public abstract class EventReporter extends ScheduledReporter implements Closeable {
protected static final Joiner JOINER = Joiner.on('.').skipNulls();
protected static final String METRIC_KEY_PREFIX = "gobblin.metrics";
protected static final String EVENTS_QUALIFIER = "events";
public static final int DEFAULT_QUEUE_CAPACITY = 100;
public static final String QUEUE_CAPACITY_KEY = ConfigurationKeys.METRICS_REPORTING_EVENTS_CONFIGURATIONS_PREFIX + ".queue.capacity";
public static final int DEFAULT_QUEUE_OFFER_TIMEOUT_SECS = 10;
public static final String QUEUE_OFFER_TIMOUT_SECS_KEY = ConfigurationKeys.METRICS_REPORTING_EVENTS_CONFIGURATIONS_PREFIX + ".queue.offer.timeout.secs";
private static final String NULL_STRING = "null";
public static final int REPORT_TIMEOUT_SECS = 60;
private final MetricContext metricContext;
private final BlockingQueue<GobblinTrackingEvent> reportingQueue;
@Getter
private final int queueCapacity;
@Getter
private final int queueOfferTimeoutSecs;
private final ExecutorService immediateReportExecutor;
private final UUID notificationTargetKey;
protected final Closer closer;
protected final Config config;
private static final Config FALLBACK = ConfigFactory.parseMap(
ImmutableMap.<String, Object>builder()
.put(QUEUE_CAPACITY_KEY, DEFAULT_QUEUE_CAPACITY)
.put(QUEUE_OFFER_TIMOUT_SECS_KEY, DEFAULT_QUEUE_OFFER_TIMEOUT_SECS)
.build());
public EventReporter(Builder builder) {
super(builder.context, builder.name, builder.filter, builder.rateUnit, builder.durationUnit);
this.closer = Closer.create();
this.immediateReportExecutor = MoreExecutors.getExitingExecutorService(
(ThreadPoolExecutor) Executors.newFixedThreadPool(1,
ExecutorsUtils.newThreadFactory(Optional.of(log), Optional.of("EventReporter-" + builder.name + "-%d"))),
5, TimeUnit.MINUTES);
this.metricContext = builder.context;
this.notificationTargetKey = builder.context.addNotificationTarget(new Function<Notification, Void>() {
@Nullable
@Override
public Void apply(Notification notification) {
notificationCallback(notification);
return null;
}
});
this.config = builder.config.withFallback(FALLBACK);
this.queueCapacity = this.config.getInt(QUEUE_CAPACITY_KEY);
this.queueOfferTimeoutSecs = this.config.getInt(QUEUE_OFFER_TIMOUT_SECS_KEY);
this.reportingQueue = Queues.newLinkedBlockingQueue(this.queueCapacity);
}
/**
* Callback used by the {@link org.apache.gobblin.metrics.MetricContext} to notify the object of a new
* {@link org.apache.gobblin.metrics.GobblinTrackingEvent}.
* @param notification {@link org.apache.gobblin.metrics.notification.Notification} to process.
*/
public void notificationCallback(Notification notification) {
if (notification instanceof EventNotification) {
addEventToReportingQueue(((EventNotification) notification).getEvent());
}
}
/**
* Add {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the events queue.
* @param event {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to add to queue.
*/
public void addEventToReportingQueue(GobblinTrackingEvent event) {
if (this.reportingQueue.size() > this.queueCapacity * 2 / 3) {
log.debug("Trigger immediate run to report the event since queue is almost full");
immediatelyScheduleReport();
}
try {
log.debug(String.format("Offering one event to the metrics queue with event name: %s", event.getName()));
if (!this.reportingQueue.offer(sanitizeEvent(event), this.queueOfferTimeoutSecs, TimeUnit.SECONDS)) {
log.error("Enqueuing of event {} at reporter with class {} timed out. Sending of events is probably stuck.",
event, this.getClass().getCanonicalName());
}
} catch (InterruptedException ie) {
log.warn("Enqueuing of event {} at reporter with class {} was interrupted.", event,
this.getClass().getCanonicalName(), ie);
}
}
/**
* Report all {@link org.apache.gobblin.metrics.GobblinTrackingEvent}s in the queue.
*/
@Override
public void report() {
reportEventQueue(this.reportingQueue);
}
/**
* Emit all {@link org.apache.gobblin.metrics.GobblinTrackingEvent} in queue.
* @param queue {@link java.util.Queue} containing {@link org.apache.gobblin.metrics.GobblinTrackingEvent}s that should be emitted.
*/
public abstract void reportEventQueue(Queue<GobblinTrackingEvent> queue);
/**
* NOOP because {@link com.codahale.metrics.ScheduledReporter} requires this method implemented.
*/
@Override
public final void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
//NOOP
}
/**
* Constructs the metric key to be emitted.
* The actual event name is enriched with the current job and task id to be able to keep track of its origin
*
* @param metadata metadata of the actual {@link GobblinTrackingEvent}
* @param eventName name of the actual {@link GobblinTrackingEvent}
* @return prefix of the metric key
*/
protected String getMetricName(Map<String, String> metadata, String eventName) {
return JOINER.join(METRIC_KEY_PREFIX, metadata.get(METADATA_JOB_ID), metadata.get(METADATA_TASK_ID),
EVENTS_QUALIFIER, eventName);
}
private void immediatelyScheduleReport() {
this.immediateReportExecutor.submit(new Runnable() {
@Override
public void run() {
report();
}
});
}
/**
* Builder for {@link EventReporter}.
* Defaults to no filter, reporting rates in seconds and times in milliseconds.
*/
public static abstract class Builder<T extends Builder<T>> {
protected MetricContext context;
protected String name;
protected MetricFilter filter;
protected TimeUnit rateUnit;
protected TimeUnit durationUnit;
protected Config config;
protected Builder(MetricContext context) {
this.context = context;
this.name = "MetricReportReporter";
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
this.config = ConfigFactory.empty();
}
public T withConfig(Config config) {
this.config = (config == null) ? ConfigFactory.empty() : config;
return self();
}
protected abstract T self();
}
@Override
public void close() {
try {
log.info(String.format("Closing event reporter %s", this.getClass().getCanonicalName()));
this.metricContext.removeNotificationTarget(this.notificationTargetKey);
this.immediateReportExecutor.awaitTermination(REPORT_TIMEOUT_SECS, TimeUnit.SECONDS);
log.info(String.format("Flush out %s events before closing the reporter", this.reportingQueue.size()));
report();
this.closer.close();
} catch (Exception e) {
log.warn("Exception when closing EventReporter", e);
} finally {
super.close();
}
}
private static GobblinTrackingEvent sanitizeEvent(GobblinTrackingEvent event) {
Map<String, String> newMetadata = Maps.newHashMap();
for (Map.Entry<String, String> metadata : event.getMetadata().entrySet()) {
newMetadata.put(metadata.getKey() == null ? NULL_STRING : metadata.getKey(),
metadata.getValue() == null ? NULL_STRING : metadata.getValue());
}
event.setMetadata(newMetadata);
return event;
}
}
| 4,441 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/OutputStreamEventReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.reporter.util.AvroJsonSerializer;
import org.apache.gobblin.metrics.reporter.util.AvroSerializer;
import org.apache.gobblin.metrics.reporter.util.NoopSchemaVersionWriter;
/**
* {@link org.apache.gobblin.metrics.reporter.EventReporter} that writes {@link org.apache.gobblin.metrics.GobblinTrackingEvent}s to an
* {@link java.io.OutputStream}.
*/
public class OutputStreamEventReporter extends EventReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(OutputStreamEventReporter.class);
private static final int CONSOLE_WIDTH = 80;
protected PrintStream output;
protected final AvroSerializer<GobblinTrackingEvent> serializer;
private final ByteArrayOutputStream outputBuffer;
private final PrintStream outputBufferPrintStream;
private final DateFormat dateFormat;
public OutputStreamEventReporter(Builder builder) throws IOException {
super(builder);
this.serializer = this.closer.register(
new AvroJsonSerializer<GobblinTrackingEvent>(GobblinTrackingEvent.SCHEMA$, new NoopSchemaVersionWriter()));
this.output = builder.output;
this.outputBuffer = new ByteArrayOutputStream();
this.outputBufferPrintStream = this.closer.register(new PrintStream(this.outputBuffer, false, Charsets.UTF_8.toString()));
this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.getDefault());
}
@Override
public void reportEventQueue(Queue<GobblinTrackingEvent> queue) {
if(queue.size() <= 0) {
return;
}
this.outputBuffer.reset();
GobblinTrackingEvent nextEvent;
final String dateTime = dateFormat.format(new Date());
printWithBanner(dateTime, '=');
this.outputBufferPrintStream.println();
printWithBanner("-- Events", '-');
while(null != (nextEvent = queue.poll())) {
this.outputBufferPrintStream.println(new String(this.serializer.serializeRecord(nextEvent), Charsets.UTF_8));
}
this.outputBufferPrintStream.println();
try {
this.outputBuffer.writeTo(this.output);
} catch(IOException exception) {
LOGGER.warn("Failed to write events to output stream.");
}
}
private void printWithBanner(String s, char c) {
this.outputBufferPrintStream.print(s);
this.outputBufferPrintStream.print(' ');
for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) {
this.outputBufferPrintStream.print(c);
}
this.outputBufferPrintStream.println();
}
/**
* Returns a new {@link org.apache.gobblin.metrics.kafka.KafkaEventReporter.Builder} for {@link org.apache.gobblin.metrics.kafka.KafkaEventReporter}.
* Will automatically add all Context tags to the reporter.
*
* @param context the {@link org.apache.gobblin.metrics.MetricContext} to report
* @return KafkaReporter builder
*/
public static Builder<? extends Builder> forContext(MetricContext context) {
return new BuilderImpl(context);
}
private static class BuilderImpl extends Builder<BuilderImpl> {
public BuilderImpl(MetricContext context) {
super(context);
}
@Override
protected BuilderImpl self() {
return this;
}
}
public static abstract class Builder<T extends Builder<T>> extends EventReporter.Builder<T> {
protected PrintStream output;
public Builder(MetricContext context) {
super(context);
this.output = System.out;
}
/**
* Write to the given {@link java.io.PrintStream}.
*
* @param output a {@link java.io.PrintStream} instance.
* @return {@code this}
*/
public T outputTo(PrintStream output) {
this.output = output;
return self();
}
/**
* Write to the given {@link java.io.OutputStream}.
* @param stream a {@link java.io.OutputStream} instance
* @return {@code this}
*/
public T outputTo(OutputStream stream) {
try {
this.output = new PrintStream(stream, false, Charsets.UTF_8.toString());
} catch(UnsupportedEncodingException exception) {
LOGGER.error("Unsupported encoding in OutputStreamReporter. This is an error with the code itself.", exception);
throw new RuntimeException(exception);
}
return self();
}
public OutputStreamEventReporter build() throws IOException {
return new OutputStreamEventReporter(this);
}
}
}
| 4,442 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/AvroJsonSerializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.avro.Schema;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificRecord;
/**
* {@link org.apache.gobblin.metrics.reporter.util.AvroSerializer} that serializes into JSON.
*/
public class AvroJsonSerializer<T extends SpecificRecord> extends AvroSerializer<T> {
public AvroJsonSerializer(Schema schema, SchemaVersionWriter schemaVersionWriter)
throws IOException {
super(schema, schemaVersionWriter);
}
@Override
protected Encoder getEncoder(Schema schema, OutputStream outputStream) throws IOException {
return EncoderFactory.get().jsonEncoder(schema, outputStream);
}
}
| 4,443 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/SchemaVersionWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.avro.Schema;
/**
* Writes schema information to an {@link java.io.DataOutputStream}.
*
* <p>
* This class is used for prefixing serialized Avro {@link org.apache.avro.generic.GenericData.Record} with
* schema information that may help downstream services to parse the record.
* </p>
*
* @param <S> the type of the schema version that can be recovered from {@link java.io.InputStream}s,
* i.e. the return type of {@link #readSchemaVersioningInformation(DataInputStream)}
*/
public interface SchemaVersionWriter<S> {
/**
* Write schema information to {@link java.io.DataOutputStream}.
* @param schema Avro {@link org.apache.avro.Schema} of the data that will be serialized into outputStream.
* @param outputStream {@link java.io.DataOutputStream} where record will be serialized.
* @throws IOException
*/
public void writeSchemaVersioningInformation(Schema schema, DataOutputStream outputStream) throws IOException;
/**
* Parse schema information from {@link java.io.DataInputStream}, and advance inputStream to the location
* where actual record starts.
* @param inputStream {@link java.io.DataInputStream} containing schema information and serialized record.
* @return Schema information.
* @throws IOException
*/
public S readSchemaVersioningInformation(DataInputStream inputStream) throws IOException;
/**
* Advance inputStream to the location where actual record starts, but ignore the schema information.
* @param inputStream {@link java.io.DataInputStream} containing schema information and serialized record.
* @throws IOException
*/
public void advanceInputStreamToRecord(DataInputStream inputStream) throws IOException;
}
| 4,444 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/AvroSerializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.avro.Schema;
import org.apache.avro.io.Encoder;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.specific.SpecificRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Closer;
/**
* Class used for serializing Avro {@link org.apache.avro.specific.SpecificRecord} for metrics reporting.
*
* @param <T> Type of avro records that will be serialized.
*/
public abstract class AvroSerializer<T extends SpecificRecord> implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(AvroSerializer.class);
private final Closer closer;
private final Encoder encoder;
private final ByteArrayOutputStream byteArrayOutputStream;
private final DataOutputStream out;
private final SpecificDatumWriter<T> writer;
private SchemaVersionWriter schemaVersionWriter;
public AvroSerializer(Schema schema, SchemaVersionWriter schemaVersionWriter) throws IOException {
this.closer = Closer.create();
this.byteArrayOutputStream = new ByteArrayOutputStream();
this.out = this.closer.register(new DataOutputStream(this.byteArrayOutputStream));
this.encoder = getEncoder(schema, this.out);
this.schemaVersionWriter = schemaVersionWriter;
this.writer = new SpecificDatumWriter<>(schema);
}
/**
* Change the {@link org.apache.gobblin.metrics.reporter.util.SchemaVersionWriter} used by this serializer.
* @param schemaVersionWriter new {@link org.apache.gobblin.metrics.reporter.util.SchemaVersionWriter} to use.
*/
public synchronized void setSchemaVersionWriter(SchemaVersionWriter schemaVersionWriter) {
this.schemaVersionWriter = schemaVersionWriter;
}
/**
* Get {@link org.apache.avro.io.Encoder} for serializing Avro records.
* @param schema {@link org.apache.avro.Schema} that will be written to outputStream.
* @param outputStream {@link java.io.OutputStream} where records should be written.
* @return Encoder.
*/
protected abstract Encoder getEncoder(Schema schema, OutputStream outputStream) throws IOException;
/**
* Converts a {@link org.apache.gobblin.metrics.MetricReport} to bytes to send through Kafka.
*
* <p>
* Actual serialized record will be prepended with a schema version generated by {@link #schemaVersionWriter}.
* </p>
*
* @param record MetricReport to serialize.
* @return Serialized bytes.
*/
public synchronized byte[] serializeRecord(T record) {
try {
this.byteArrayOutputStream.reset();
// Write schema versioning information.
this.schemaVersionWriter.writeSchemaVersioningInformation(record.getSchema(), this.out);
// Now write the record itself.
this.writer.write(record, this.encoder);
this.encoder.flush();
return this.byteArrayOutputStream.toByteArray();
} catch (IOException exception) {
LOGGER.warn("Could not serialize Avro record for Kafka Metrics.", exception);
return null;
}
}
@Override
public void close() throws IOException {
this.closer.close();
}
}
| 4,445 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/FixedSchemaVersionWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.gobblin.annotation.Alias;
/**
* Write a fixed integer ({@link #SCHEMA_VERSION}) as schema version into the {@link java.io.DataOutputStream}.
*/
@Alias(value = "FIXED_VERSION")
public class FixedSchemaVersionWriter implements SchemaVersionWriter<Integer> {
public static final int SCHEMA_VERSION = 1;
@Override
public void writeSchemaVersioningInformation(Schema schema, DataOutputStream outputStream) throws IOException {
outputStream.writeInt(SCHEMA_VERSION);
}
@Override
public Integer readSchemaVersioningInformation(DataInputStream inputStream)
throws IOException {
return inputStream.readInt();
}
@Override
public void advanceInputStreamToRecord(DataInputStream inputStream) throws IOException {
inputStream.readInt();
}
}
| 4,446 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/EventUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import com.google.common.base.Optional;
import com.google.common.io.Closer;
import javax.annotation.Nullable;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* Utilities for {@link org.apache.gobblin.metrics.MetricReport}.
*/
public class EventUtils {
public static final int SCHEMA_VERSION = 1;
private static Optional<SpecificDatumReader<GobblinTrackingEvent>> reader = Optional.absent();
/**
* Parses a {@link org.apache.gobblin.metrics.MetricReport} from a byte array representing a json input.
* @param reuse MetricReport to reuse.
* @param bytes Input bytes.
* @return MetricReport.
* @throws java.io.IOException
*/
public synchronized static GobblinTrackingEvent deserializeReportFromJson(GobblinTrackingEvent reuse, byte[] bytes) throws IOException {
if (!reader.isPresent()) {
reader = Optional.of(new SpecificDatumReader<>(GobblinTrackingEvent.class));
}
Closer closer = Closer.create();
try {
DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));
// Check version byte
int versionNumber = inputStream.readInt();
if (versionNumber != SCHEMA_VERSION) {
throw new IOException(String
.format("MetricReport schema version not recognized. Found version %d, expected %d.", versionNumber,
SCHEMA_VERSION));
}
// Decode the rest
Decoder decoder = DecoderFactory.get().jsonDecoder(GobblinTrackingEvent.SCHEMA$, inputStream);
return reader.get().read(reuse, decoder);
} catch(Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
/**
* Parses a {@link org.apache.gobblin.metrics.GobblinTrackingEvent} from a byte array Avro serialization.
* @param reuse GobblinTrackingEvent to reuse.
* @param bytes Input bytes.
* @return GobblinTrackingEvent.
* @throws java.io.IOException
*/
public synchronized static GobblinTrackingEvent deserializeEventFromAvroSerialization(GobblinTrackingEvent reuse, byte[] bytes)
throws IOException {
return deserializeEventFromAvroSerialization(reuse, bytes, null);
}
/**
* Parses a {@link org.apache.gobblin.metrics.GobblinTrackingEvent} from a byte array Avro serialization.
* @param reuse GobblinTrackingEvent to reuse.
* @param bytes Input bytes.
* @param schemaId Expected schemaId.
* @return GobblinTrackingEvent.
* @throws java.io.IOException
*/
public synchronized static GobblinTrackingEvent deserializeEventFromAvroSerialization(GobblinTrackingEvent reuse, byte[] bytes, @Nullable String schemaId)
throws IOException {
if (!reader.isPresent()) {
reader = Optional.of(new SpecificDatumReader<>(GobblinTrackingEvent.class));
}
Closer closer = Closer.create();
try {
DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));
if (schemaId != null) {
MetricReportUtils.readAndVerifySchemaId(inputStream, schemaId);
} else {
MetricReportUtils.readAndVerifySchemaVersion(inputStream);
}
// Decode the rest
Decoder decoder = DecoderFactory.get().binaryDecoder(inputStream, null);
return reader.get().read(reuse, decoder);
} catch(Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
}
| 4,447 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/NoopSchemaVersionWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.gobblin.annotation.Alias;
/**
* Implementation of {@link org.apache.gobblin.metrics.reporter.util.SchemaVersionWriter} that does not write anything to
* {@link java.io.DataOutputStream}.
*/
@Alias(value = "NOOP")
public class NoopSchemaVersionWriter implements SchemaVersionWriter<Void> {
@Override
public void writeSchemaVersioningInformation(Schema schema, DataOutputStream outputStream)
throws IOException {
}
@Override
public Void readSchemaVersioningInformation(DataInputStream inputStream)
throws IOException {
return null;
}
@Override
public void advanceInputStreamToRecord(DataInputStream inputStream) throws IOException {
}
}
| 4,448 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/MetricReportUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import com.google.common.base.Optional;
import com.google.common.io.Closer;
import javax.annotation.Nullable;
import org.apache.gobblin.metrics.MetricReport;
import org.apache.gobblin.metrics.MetricReporterException;
import org.apache.gobblin.metrics.MultiReporterException;
import org.apache.gobblin.metrics.ReporterType;
/**
* Utilities for {@link org.apache.gobblin.metrics.MetricReport}.
*/
public class MetricReportUtils {
public static final int SCHEMA_VERSION = 1;
private static Optional<SpecificDatumReader<MetricReport>> READER = Optional.absent();
/**
* Parses a {@link org.apache.gobblin.metrics.MetricReport} from a byte array representing a json input.
* @param reuse MetricReport to reuse.
* @param bytes Input bytes.
* @return MetricReport.
* @throws java.io.IOException
*/
public synchronized static MetricReport deserializeReportFromJson(MetricReport reuse, byte[] bytes)
throws IOException {
if (!READER.isPresent()) {
READER = Optional.of(new SpecificDatumReader<>(MetricReport.class));
}
Closer closer = Closer.create();
try {
DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));
// Check version byte
int versionNumber = inputStream.readInt();
if (versionNumber != SCHEMA_VERSION) {
throw new IOException(String
.format("MetricReport schema version not recognized. Found version %d, expected %d.", versionNumber,
SCHEMA_VERSION));
}
// Decode the rest
Decoder decoder = DecoderFactory.get().jsonDecoder(MetricReport.SCHEMA$, inputStream);
return READER.get().read(reuse, decoder);
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
/**
* Parses a {@link org.apache.gobblin.metrics.MetricReport} from a byte array Avro serialization.
* @param reuse MetricReport to reuse.
* @param bytes Input bytes.
* @return MetricReport.
* @throws java.io.IOException
*/
public synchronized static MetricReport deserializeReportFromAvroSerialization(MetricReport reuse, byte[] bytes)
throws IOException {
return deserializeReportFromAvroSerialization(reuse, bytes, null);
}
/**
* Parses a {@link org.apache.gobblin.metrics.MetricReport} from a byte array Avro serialization.
* @param reuse MetricReport to reuse.
* @param bytes Input bytes.
* @param schemaId Expected schemaId.
* @return MetricReport.
* @throws java.io.IOException
*/
public synchronized static MetricReport deserializeReportFromAvroSerialization(MetricReport reuse, byte[] bytes,
@Nullable String schemaId)
throws IOException {
if (!READER.isPresent()) {
READER = Optional.of(new SpecificDatumReader<>(MetricReport.class));
}
Closer closer = Closer.create();
try {
DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));
if (schemaId != null) {
readAndVerifySchemaId(inputStream, schemaId);
} else {
readAndVerifySchemaVersion(inputStream);
}
// Decode the rest
Decoder decoder = DecoderFactory.get().binaryDecoder(inputStream, null);
return READER.get().read(reuse, decoder);
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
public static void readAndVerifySchemaId(DataInputStream inputStream, String schemaId)
throws IOException {
//Read the magic byte
inputStream.readByte();
int schemaIdLengthBytes = schemaId.length() / 2;
byte[] readId = new byte[schemaIdLengthBytes];
int numBytesRead = inputStream.read(readId, 0, schemaIdLengthBytes);
String readSchemaId = Hex.encodeHexString(readId);
if (numBytesRead != schemaIdLengthBytes || !schemaId.equals(readSchemaId)) {
throw new IOException(String
.format("Schema version not recognized. Found version %s, expected %s.", readSchemaId,
schemaId));
}
}
public static void readAndVerifySchemaVersion(DataInputStream inputStream)
throws IOException {
// Check version byte
int versionNumber = inputStream.readInt();
if (versionNumber != SCHEMA_VERSION) {
throw new IOException(String
.format("Schema version not recognized. Found version %d, expected %d.", versionNumber,
SCHEMA_VERSION));
}
}
public static boolean shouldThrowException(Logger log, MultiReporterException ex, boolean isMetricReportingFailureFatal, boolean isEventReportingFailureFatal) {
boolean shouldThrow = false;
for (MetricReporterException e: ex.getExceptions()) {
if ((isMetricReportingFailureFatal && ReporterType.isReporterTypeMetric(e.getReporterType())) || (
isEventReportingFailureFatal && ReporterType.isReporterTypeEvent(e.getReporterType()))) {
shouldThrow = true;
}
log.error("Failed to start {} {} reporter", e.getSinkType().name(), e.getReporterType().name(), e);
}
return shouldThrow;
}
}
| 4,449 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/util/AvroBinarySerializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.reporter.util;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.avro.Schema;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificRecord;
/**
* {@link org.apache.gobblin.metrics.reporter.util.AvroSerializer} that serializes into binary.
*/
public class AvroBinarySerializer<T extends SpecificRecord> extends AvroSerializer<T> {
public AvroBinarySerializer(Schema schema, SchemaVersionWriter schemaVersionWriter) throws IOException {
super(schema, schemaVersionWriter);
}
@Override
protected Encoder getEncoder(Schema schema, OutputStream outputStream) {
return EncoderFactory.get().binaryEncoder(outputStream, null);
}
}
| 4,450 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/notification/NewMetricContextNotification.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.notification;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.gobblin.metrics.InnerMetricContext;
import org.apache.gobblin.metrics.MetricContext;
/**
* {@link Notification} that a new {@link org.apache.gobblin.metrics.MetricContext} has been created. Contains the
* new {@link MetricContext}.
*/
@AllArgsConstructor
@Getter
public class NewMetricContextNotification implements Notification {
private final MetricContext metricContext;
private final InnerMetricContext innerMetricContext;
}
| 4,451 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/notification/Notification.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.notification;
/**
* Generic interface for notifications.
* See for example {@link org.apache.gobblin.metrics.MetricContext#sendNotification}.
*/
public interface Notification {
}
| 4,452 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/notification/MetricContextCleanupNotification.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.notification;
import lombok.Data;
import org.apache.gobblin.metrics.InnerMetricContext;
/**
* {@link Notification} that a {@link org.apache.gobblin.metrics.MetricContext} has been garbage collected. Contains the
* {@link InnerMetricContext} associated which still includes {@link org.apache.gobblin.metrics.Metric}s and
* {@link org.apache.gobblin.metrics.Tag}s.
*/
@Data
public class MetricContextCleanupNotification implements Notification {
private final InnerMetricContext metricContext;
}
| 4,453 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/notification/EventNotification.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.notification;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* Notification wrapping a {@link org.apache.gobblin.metrics.GobblinTrackingEvent}.
*/
public class EventNotification implements Notification {
private final GobblinTrackingEvent event;
public EventNotification(GobblinTrackingEvent event) {
this.event = event;
}
public GobblinTrackingEvent getEvent() {
return this.event;
}
}
| 4,454 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/example/ReporterExampleBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.example;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import org.apache.gobblin.metrics.event.JobEvent;
import org.apache.gobblin.metrics.reporter.ContextAwareScheduledReporter;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
/**
* A base class for those that exemplifies the usage of {@link MetricContext} and a given
* {@link ContextAwareScheduledReporter}.
*
* <p>
* This class simulating a record processing job that spawns a configurable number of tasks
* running in a thread pool for processing incoming data records in parallel. Each task will
* simulate processing the same configurable number of records. The job creates a job-level
* {@link MetricContext}, from which a child {@link MetricContext} for each task is created.
* Each task uses four metrics in its {@link MetricContext} to keep track of the total number
* of records processed, record processing rate, record size distribution, and record processing
* times. Since the job-level {@link MetricContext} is the parent of the {@link MetricContext}s
* of the tasks, updates to a metric of a task will be automatically applied to the metric with
* the same name in the job-level {@link MetricContext}. The job and task {@link MetricContext}s
* use the same given {@link ContextAwareScheduledReporter} to report metrics.
* </p>
*
* @author Yinan Li
*/
public class ReporterExampleBase {
private static final Logger LOGGER = LoggerFactory.getLogger(ReporterExampleBase.class);
private static final String JOB_NAME = "ExampleJob";
private static final String TASK_ID_KEY = "task.id";
private static final String TASK_ID_PREFIX = "ExampleTask_";
private static final String TOTAL_RECORDS = "totalRecords";
private static final String RECORD_PROCESS_RATE = "recordProcessRate";
private static final String RECORD_PROCESS_TIME = "recordProcessTime";
private static final String RECORD_SIZES = "recordSizes";
private final ExecutorService executor;
private final MetricContext context;
private final ContextAwareScheduledReporter.Builder reporterBuilder;
private final int tasks;
private final long totalRecords;
public ReporterExampleBase(ContextAwareScheduledReporter.Builder reporterBuilder, int tasks, long totalRecords) {
this.executor = Executors.newFixedThreadPool(10);
this.context = MetricContext.builder("Job")
.addTag(new Tag<String>(JobEvent.METADATA_JOB_NAME, "ExampleJob"))
.addTag(new Tag<String>(JobEvent.METADATA_JOB_ID, JOB_NAME + "_" + System.currentTimeMillis()))
.build();
this.reporterBuilder = reporterBuilder;
this.tasks = tasks;
this.totalRecords = totalRecords;
}
/**
* Run the example.
*/
public void run() throws Exception {
try {
CountDownLatch countDownLatch = new CountDownLatch(this.tasks);
for (int i = 0; i < this.tasks; i++) {
addTask(i, countDownLatch);
}
// Wait for the tasks to finish
countDownLatch.await();
} finally {
try {
// Calling close() will stop metric reporting
this.context.close();
} finally {
this.executor.shutdownNow();
}
}
}
private void addTask(int taskIndex, CountDownLatch countDownLatch) {
// Build the context of this task, which is a child of the job's context.
// Tags of the job (parent) context will be inherited automatically.
MetricContext taskContext = this.context.childBuilder("Task" + taskIndex)
.addTag(new Tag<String>(TASK_ID_KEY, TASK_ID_PREFIX + taskIndex))
.build();
Task task = new Task(taskContext, taskIndex, this.totalRecords, countDownLatch);
this.executor.execute(task);
}
private static class Task implements Runnable {
private final MetricContext context;
private final int taskIndex;
private final long totalRecords;
private final CountDownLatch countDownLatch;
private final Random rand = new Random();
public Task(MetricContext context, int taskIndex, long totalRecords, CountDownLatch countDownLatch) {
this.context = context;
this.taskIndex = taskIndex;
this.totalRecords = totalRecords;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
Counter totalRecordsCounter = this.context.contextAwareCounter(TOTAL_RECORDS);
Meter recordProcessRateMeter = this.context.contextAwareMeter(RECORD_PROCESS_RATE);
Timer recordProcessTimeTimer = this.context.contextAwareTimer(RECORD_PROCESS_TIME);
Histogram recordSizesHistogram = this.context.contextAwareHistogram(RECORD_SIZES);
try {
for (int i = 0; i < this.totalRecords; i++) {
totalRecordsCounter.inc();
recordProcessRateMeter.mark();
recordSizesHistogram.update((this.rand.nextLong() & Long.MAX_VALUE) % 5000l);
if (i % 100 == 0) {
LOGGER.info(String.format("Task %d has processed %d records so far", this.taskIndex, i));
}
long processTime = (this.rand.nextLong() & Long.MAX_VALUE) % 10;
// Simulate record processing by sleeping for a random amount of time
try {
Thread.sleep(processTime);
} catch (InterruptedException ie) {
LOGGER.warn(String.format("Task %d has been interrupted", this.taskIndex));
Thread.currentThread().interrupt();
return;
}
recordProcessTimeTimer.update(processTime, TimeUnit.MILLISECONDS);
}
LOGGER.info(String.format("Task %d has processed all %d records", this.taskIndex, this.totalRecords));
} finally{
try {
this.context.close();
} catch (IOException ioe) {
LOGGER.error("Failed to close context: " + this.context.getName(), ioe);
} finally {
this.countDownLatch.countDown();
}
}
}
}
}
| 4,455 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/InnerMetric.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric;
import com.codahale.metrics.Metric;
import org.apache.gobblin.metrics.ContextAwareMetric;
/**
* Inner {@link Metric} used for reporting metrics one last time even after the user-facing wrapper has been
* garbage collected.
*/
public interface InnerMetric extends Metric {
/**
* @return the associated {@link ContextAwareMetric}.
*/
public ContextAwareMetric getContextAwareMetric();
}
| 4,456 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/ProxyMetric.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric;
import com.codahale.metrics.Metric;
/**
* Interface for {@link Metric}s that proxy a {@link InnerMetric}.
*/
public interface ProxyMetric extends Metric {
/**
* @return associated {@link InnerMetric}.
*/
public InnerMetric getInnerMetric();
}
| 4,457 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/Metrics.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.Timer;
import lombok.Getter;
/**
* An {@link Enum} of all {@link com.codahale.metrics.Metric}s.
*/
public enum Metrics {
COUNTER(Counter.class),
GAUGE(Gauge.class),
HISTOGRAM(Histogram.class),
METER(Meter.class),
TIMER(Timer.class);
@Getter
private final Class<? extends Metric> metricClass;
Metrics(Class<? extends Metric> metricClass) {
this.metricClass = metricClass;
}
}
| 4,458 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/filter/MetricTypeFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric.filter;
import java.util.List;
import javax.annotation.Nullable;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.gobblin.metrics.metric.Metrics;
/**
* Implementation of {@link MetricFilter} that takes in a {@link String} containing a comma separated list of
* {@link Metrics}. This {@link MetricFilter} {@link #matches(String, Metric)} a {@link Metric} if the given
* {@link Metric} has a type in the given list of allowed {@link Metrics}.
*/
public class MetricTypeFilter implements MetricFilter {
private List<Metrics> allowedMetrics;
public MetricTypeFilter(String allowedMetrics) {
if (Strings.isNullOrEmpty(allowedMetrics)) {
this.allowedMetrics = Lists.newArrayList(Metrics.values());
} else {
List<String> allowedMetricsList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(allowedMetrics);
this.allowedMetrics = Lists.transform(allowedMetricsList, new Function<String, Metrics>() {
@Nullable @Override public Metrics apply(String input) {
return input == null ? null : Metrics.valueOf(input);
}
});
}
}
@Override
public boolean matches(String name, Metric metric) {
final Class<? extends Metric> metricClass = metric.getClass();
return Iterables.any(this.allowedMetrics, new Predicate<Metrics>() {
@Override public boolean apply(@Nullable Metrics input) {
return input != null && input.getMetricClass().isAssignableFrom(metricClass);
}
});
}
}
| 4,459 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/filter/MetricFilters.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric.filter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
/**
* A utility class for working with {@link MetricFilter}s.
*
* @see MetricFilter
*/
public class MetricFilters {
public static MetricFilter and(final MetricFilter metricFilter1, final MetricFilter metricFilter2) {
return new MetricFilter() {
@Override public boolean matches(String name, Metric metric) {
return metricFilter1.matches(name, metric) && metricFilter2.matches(name, metric);
}
};
}
}
| 4,460 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/metric/filter/MetricNameRegexFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.metric.filter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
/**
* Implementation of {@link MetricFilter} that takes in a regex, and {@link #matches(String, Metric)} a {@link Metric}
* if the name of the {@link Metric} matches the regex.
*/
public class MetricNameRegexFilter implements MetricFilter {
private final Pattern regex;
private final Matcher matcher;
public MetricNameRegexFilter(String regex) {
this.regex = Pattern.compile(regex);
this.matcher = this.regex.matcher("");
}
@Override
public boolean matches(String name, Metric metric) {
return this.matcher.reset(name).matches();
}
}
| 4,461 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/MultiPartEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import static org.apache.gobblin.metrics.event.JobEvent.JOB_STATE;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_COMPLETED_TASKS;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_END_TIME;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_LAUNCHED_TASKS;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_START_TIME;
import static org.apache.gobblin.metrics.event.JobEvent.METADATA_JOB_STATE;
import static org.apache.gobblin.metrics.event.TaskEvent.METADATA_TASK_END_TIME;
import static org.apache.gobblin.metrics.event.TaskEvent.METADATA_TASK_START_TIME;
import static org.apache.gobblin.metrics.event.TaskEvent.METADATA_TASK_WORKING_STATE;
import static org.apache.gobblin.metrics.event.TaskEvent.TASK_STATE;
import static org.apache.gobblin.metrics.event.TimingEvent.METADATA_DURATION;
import static org.apache.gobblin.metrics.event.TimingEvent.METADATA_END_TIME;
import static org.apache.gobblin.metrics.event.TimingEvent.METADATA_START_TIME;
import static org.apache.gobblin.metrics.event.TimingEvent.METADATA_TIMING_EVENT;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
/**
* Each of the metadata fields of a MultiPartEvent is reported separately
*
* @author Lorand Bendig
*
*/
public enum MultiPartEvent {
TIMING_EVENT(
METADATA_TIMING_EVENT,
METADATA_START_TIME,
METADATA_END_TIME,
METADATA_DURATION),
JOBSTATE_EVENT(
JOB_STATE,
METADATA_JOB_START_TIME,
METADATA_JOB_END_TIME,
METADATA_JOB_LAUNCHED_TASKS,
METADATA_JOB_COMPLETED_TASKS,
METADATA_JOB_STATE),
TASKSTATE_EVENT(
TASK_STATE,
METADATA_TASK_START_TIME,
METADATA_TASK_END_TIME,
METADATA_TASK_WORKING_STATE);
private String eventName;
private String[] metadataFields;
private static final Map<String, MultiPartEvent> lookup;
static {
ImmutableMap.Builder<String, MultiPartEvent> builder = new ImmutableMap.Builder<String, MultiPartEvent>();
for (MultiPartEvent event : MultiPartEvent.values()) {
builder.put(event.eventName, event);
}
lookup = builder.build();
}
private MultiPartEvent(String eventName, String... metadataFields) {
this.eventName = eventName;
this.metadataFields = metadataFields;
}
public static MultiPartEvent getEvent(String eventName) {
return lookup.get(eventName);
}
public String getEventName() {
return eventName;
}
public String[] getMetadataFields() {
return metadataFields;
}
}
| 4,462 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TaskEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* Task-related event types and their metadata, stored in {@link GobblinTrackingEvent#metadata}
*
* @author Lorand Bendig
*
*/
public class TaskEvent {
public static final String TASK_STATE = "TaskStateEvent";
public static final String TASK_FAILED = "TaskFailed";
public static final String TASK_COMMITTED_EVENT_NAME = "taskCommitted";
public static final String METADATA_TASK_ID = "taskId";
public static final String METADATA_TASK_ATTEMPT_ID = "taskAttemptId";
public static final String METADATA_TASK_START_TIME = "taskStartTime";
public static final String METADATA_TASK_END_TIME = "taskEndTime";
public static final String METADATA_TASK_WORKING_STATE = "taskWorkingState";
public static final String METADATA_TASK_FAILURE_CONTEXT = "taskFailureContext";
}
| 4,463 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/EntityMissingEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import lombok.Getter;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* An event reporting missing any kind of entity, e.g. WorkUnit, Record, kafka topic
*/
public class EntityMissingEventBuilder extends GobblinEventBuilder {
private static final String ENTITY_MISSING_EVENT_TYPE = "EntityMissingEvent";
private static final String INSTANCE_KEY = "entityInstance";
/**
* The missing instance of this entity, e.g record id, topic name
*/
@Getter
private final String instance;
public EntityMissingEventBuilder(String name, String instance) {
this(name, null, instance);
}
public EntityMissingEventBuilder(String name, String namespace, String instance) {
super(name, namespace);
this.instance = instance;
this.metadata.put(EVENT_TYPE, ENTITY_MISSING_EVENT_TYPE);
}
@Override
public GobblinTrackingEvent build() {
if (instance != null) {
this.metadata.put(INSTANCE_KEY, instance);
}
return super.build();
}
public static boolean isEntityMissingEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(ENTITY_MISSING_EVENT_TYPE);
}
public static EntityMissingEventBuilder fromEvent(GobblinTrackingEvent event) {
if(!isEntityMissingEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
String instance = metadata.get(INSTANCE_KEY);
EntityMissingEventBuilder eventBuilder = new EntityMissingEventBuilder(
event.getName(), event.getNamespace(), instance);
metadata.forEach((key, value) -> {
switch (key) {
case INSTANCE_KEY:
break;
default:
eventBuilder.addMetadata(key, value);
break;
}
});
return eventBuilder;
}
}
| 4,464 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/JobStateEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* An event reporting job state. It can be used to report the overall Gobblin job state or
* the state of an internal job, e.g MR job
*/
public class JobStateEventBuilder extends GobblinEventBuilder {
private static final String JOB_STATE_EVENT_TYPE = "JobStateEvent";
private static final String STATUS_KEY = "jobState";
private static final String JOB_URL_KEY = "jobTrackingURL";
public enum Status {
SUCCEEDED,
FAILED
}
public Status status;
public String jobTrackingURL;
public JobStateEventBuilder(String name) {
this(name, null);
}
public JobStateEventBuilder(String name, String namespace) {
super(name, namespace);
this.metadata.put(EVENT_TYPE, JOB_STATE_EVENT_TYPE);
}
@Override
public GobblinTrackingEvent build() {
if (status != null) {
this.metadata.put(STATUS_KEY, status.name());
}
this.metadata.put(JOB_URL_KEY, jobTrackingURL);
return super.build();
}
public static boolean isJobStateEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(JOB_STATE_EVENT_TYPE);
}
public static JobStateEventBuilder fromEvent(GobblinTrackingEvent event) {
if(!isJobStateEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
JobStateEventBuilder eventBuilder = new JobStateEventBuilder(event.getName(), event.getNamespace());
metadata.forEach((key, value) -> {
switch (key) {
case STATUS_KEY:
eventBuilder.status = Status.valueOf(value);
break;
case JOB_URL_KEY:
eventBuilder.jobTrackingURL = value;
break;
default:
eventBuilder.addMetadata(key, value);
break;
}
});
return eventBuilder;
}
public static final class MRJobState {
public static final String MR_JOB_STATE = "MRJobState";
}
}
| 4,465 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/TimingEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.io.Closeable;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.Maps;
import lombok.Getter;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* Event to time actions in the program. Automatically reports start time, end time, and duration from the time
* the {@link org.apache.gobblin.metrics.event.TimingEvent} was created to the time {@link #stop} is called.
*/
public class TimingEvent extends GobblinEventBuilder implements Closeable {
public static class LauncherTimings {
public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer";
public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer";
public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer";
public static final String JOB_PENDING = "JobPending";
public static final String JOB_PENDING_RESUME = "JobPendingResume";
public static final String JOB_ORCHESTRATED = "JobOrchestrated";
public static final String JOB_PREPARE = "JobPrepareTimer";
public static final String JOB_START = "JobStartTimer";
public static final String JOB_RUN = "JobRunTimer";
public static final String JOB_COMMIT = "JobCommitTimer";
public static final String JOB_SUMMARY = "JobSummaryTimer";
public static final String JOB_CLEANUP = "JobCleanupTimer";
public static final String JOB_CANCEL = "JobCancelTimer";
public static final String JOB_COMPLETE = "JobCompleteTimer";
public static final String JOB_FAILED = "JobFailedTimer";
public static final String JOB_SUCCEEDED = "JobSucceededTimer";
}
public static class RunJobTimings {
public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer";
public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer";
public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer";
public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer";
public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer";
public static final String MR_JOB_SETUP = "JobMrSetupTimer";
public static final String MR_JOB_RUN = "JobMrRunTimer";
public static final String HELIX_JOB_SUBMISSION = "JobHelixSubmissionTimer";
public static final String HELIX_JOB_RUN = "JobHelixRunTimer";
}
public static class FlowTimings {
public static final String FLOW_COMPILED = "FlowCompiled";
public static final String FLOW_COMPILE_FAILED = "FlowCompileFailed";
public static final String FLOW_SUCCEEDED = "FlowSucceeded";
public static final String FLOW_FAILED = "FlowFailed";
public static final String FLOW_RUNNING = "FlowRunning";
public static final String FLOW_CANCELLED = "FlowCancelled";
public static final String FLOW_RUN_DEADLINE_EXCEEDED = "FlowRunDeadlineExceeded";
public static final String FLOW_START_DEADLINE_EXCEEDED = "FlowStartDeadlineExceeded";
public static final String FLOW_PENDING_RESUME = "FlowPendingResume";
}
public static class FlowEventConstants {
public static final String FLOW_NAME_FIELD = "flowName";
public static final String FLOW_GROUP_FIELD = "flowGroup";
public static final String FLOW_EXECUTION_ID_FIELD = "flowExecutionId";
public static final String FLOW_EDGE_FIELD = "flowEdge";
public static final String FLOW_MODIFICATION_TIME_FIELD = "flowModificationTime";
public static final String JOB_NAME_FIELD = "jobName";
public static final String JOB_GROUP_FIELD = "jobGroup";
public static final String JOB_TAG_FIELD = "jobTag";
public static final String JOB_EXECUTION_ID_FIELD = "jobExecutionId";
public static final String SPEC_EXECUTOR_FIELD = "specExecutor";
public static final String LOW_WATERMARK_FIELD = "lowWatermark";
public static final String HIGH_WATERMARK_FIELD = "highWatermark";
public static final String PROCESSED_COUNT_FIELD = "processedCount";
public static final String MAX_ATTEMPTS_FIELD = "maxAttempts";
public static final String CURRENT_ATTEMPTS_FIELD = "currentAttempts";
//This state should always move forward, more details can be found in method {@link KafkaJobStatusMonitor.addJobStatusToStateStore}
public static final String CURRENT_GENERATION_FIELD = "currentGeneration";
public static final String SHOULD_RETRY_FIELD = "shouldRetry";
public static final String DOES_CANCELED_FLOW_MERIT_RETRY = "doesCancelledFlowMeritRetry";
}
public static final String METADATA_START_TIME = "startTime";
public static final String METADATA_END_TIME = "endTime";
public static final String METADATA_DURATION = "durationMillis";
public static final String METADATA_TIMING_EVENT = "timingEvent";
public static final String METADATA_MESSAGE = "message";
public static final String JOB_ORCHESTRATED_TIME = "jobOrchestratedTime";
public static final String JOB_START_TIME = "jobStartTime";
public static final String JOB_SKIPPED_TIME = "jobSkippedTime";
public static final String WORKUNIT_PLAN_START_TIME = "workunitPlanStartTime";
public static final String WORKUNIT_PLAN_END_TIME = "workunitPlanEndTime";
public static final String JOB_END_TIME = "jobEndTime";
public static final String JOB_LAST_PROGRESS_EVENT_TIME = "jobLastProgressEventTime";
public static final String JOB_COMPLETION_PERCENTAGE = "jobCompletionPercentage";
public static final String DATASET_TASK_SUMMARIES = "datasetTaskSummaries";
@Getter
private Long startTime;
@Getter
private Long endTime;
@Getter
private Long duration;
private final EventSubmitter submitter;
private boolean stopped;
public TimingEvent(EventSubmitter submitter, String name) {
super(name);
this.stopped = false;
this.submitter = submitter;
this.startTime = System.currentTimeMillis();
}
/**
* Stop the timer and submit the event. If the timer was already stopped before, this is a no-op.
*/
public void stop() {
stop(Maps.<String, String>newHashMap());
}
/**
* Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped
* before, this is a no-op.
*
* @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event
* @deprecated Use {@link #close()}
*/
@Deprecated
public void stop(Map<String, String> additionalMetadata) {
if (this.stopped) {
return;
}
this.metadata.putAll(additionalMetadata);
doStop();
this.submitter.submit(name, this.metadata);
}
public void doStop() {
if (this.stopped) {
return;
}
this.stopped = true;
this.endTime = System.currentTimeMillis();
this.duration = this.endTime - this.startTime;
this.metadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT);
this.metadata.put(METADATA_START_TIME, Long.toString(this.startTime));
this.metadata.put(METADATA_END_TIME, Long.toString(this.endTime));
this.metadata.put(METADATA_DURATION, Long.toString(this.duration));
}
@Override
public void close() {
doStop();
submitter.submit(this);
}
/**
* Check if the given {@link GobblinTrackingEvent} is a {@link TimingEvent}
*/
public static boolean isTimingEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(METADATA_TIMING_EVENT);
}
/**
* Create a {@link TimingEvent} from a {@link GobblinTrackingEvent}. An inverse function
* to {@link TimingEvent#build()}
*/
public static TimingEvent fromEvent(GobblinTrackingEvent event) {
if(!isTimingEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
TimingEvent timingEvent = new TimingEvent(null, event.getName());
metadata.forEach((key, value) -> {
switch (key) {
case METADATA_START_TIME:
timingEvent.startTime = Long.parseLong(value);
break;
case METADATA_END_TIME:
timingEvent.endTime = Long.parseLong(value);
break;
case METADATA_DURATION:
timingEvent.duration = Long.parseLong(value);
break;
default:
timingEvent.addMetadata(key, value);
break;
}
});
return timingEvent;
}
}
| 4,466 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/EventName.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.HashMap;
import java.util.Map;
/**
* Enum for event names
*/
public enum EventName {
FULL_JOB_EXECUTION("FullJobExecutionTimer"),
WORK_UNITS_CREATION("WorkUnitsCreationTimer"),
WORK_UNITS_PREPARATION("WorkUnitsPreparationTimer"),
JOB_PREPARE("JobPrepareTimer"),
JOB_START("JobStartTimer"),
JOB_RUN("JobRunTimer"),
JOB_COMMIT("JobCommitTimer"),
JOB_CLEANUP("JobCleanupTimer"),
JOB_CANCEL("JobCancelTimer"),
JOB_COMPLETE("JobCompleteTimer"),
JOB_SUCCEEDED("JobSucceededTimer"),
JOB_FAILED("JobFailedTimer"),
MR_STAGING_DATA_CLEAN("JobMrStagingDataCleanTimer"),
UNKNOWN("Unknown");
// for mapping event id to enum object
private static final Map<String,EventName> idMap;
static {
idMap = new HashMap<String, EventName>();
for (EventName value : EventName.values()) {
idMap.put(value.eventId, value);
}
}
private String eventId;
EventName(String eventId) {
this.eventId = eventId;
}
public String getEventId() {
return eventId;
}
public static EventName getEnumFromEventId(String eventId) {
EventName eventNameEnum = idMap.get(eventId);
return eventNameEnum == null ? UNKNOWN : eventNameEnum;
}
}
| 4,467 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/MultiTimingEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
/**
* Submits an event with timings for various stages of a process. The usage is as follows:
*
* MultiTimingEvent multiTimer = new MultiTimingEvent(eventSubmitter, "myMultiTimer", false);
* multiTimer.nextStage("setup");
* ... // setup
* multiTimer.nextStage("run");
* ... // run
* multiTimer.submit();
*
* A call to {@link #nextStage(String)} computes the time spent in the previous stage and
* starts a new timer for the new stage. A stage can be ended and timed without starting a new stage by calling
* {@link #endStage()}.
* When calling {@link #submit()}, the current stage will be ended, and a single event will be send containing the timing
* for each stage. Calling {@link #close()} will also submit the event.
* Calling {@link #submit()} or {@link #close()} when the event has already been called will throw an exception.
*
* Note: {@link MultiTimingEvent} is not thread-safe, and it should be only used from a single thread.
*
*/
public class MultiTimingEvent implements Closeable {
public static final String MULTI_TIMING_EVENT = "multiTimingEvent";
private final String name;
private final EventSubmitter submitter;
private final List<Stage> timings;
private boolean submitted;
private final boolean reportAsMetrics;
private String currentStage;
private long currentStageStart;
@Data
private static class Stage {
private final String name;
private final long duration;
}
/**
* @param submitter {@link EventSubmitter} used to send the event.
* @param name Name of the event to be submitted.
* @param reportAsMetrics if true, will also report the timing of each stage to a timer with name <namespace>.<name>.<stage>
*/
public MultiTimingEvent(EventSubmitter submitter, String name, boolean reportAsMetrics) {
this.name = name;
this.submitter = submitter;
this.timings = Lists.newArrayList();
this.submitted = false;
this.reportAsMetrics = reportAsMetrics;
}
/**
* End the previous stage, record the time spent in that stage, and start the timer for a new stage.
* @param name name of the new stage.
* @throws IOException
*/
public void nextStage(String name) throws IOException {
endStage();
this.currentStage = name;
this.currentStageStart = System.currentTimeMillis();
}
/**
* End the previous stage and record the time spent in that stage.
*/
public void endStage() {
if (this.currentStage != null) {
long time = System.currentTimeMillis() - this.currentStageStart;
this.timings.add(new Stage(this.currentStage, time));
if (reportAsMetrics && submitter.getMetricContext().isPresent()) {
String timerName = submitter.getNamespace() + "." + name + "." + this.currentStage;
submitter.getMetricContext().get().timer(timerName).update(time, TimeUnit.MILLISECONDS);
}
}
this.currentStage = null;
}
/**
* See {@link #submit(Map)}. Sends no additional metadata.
* @throws IOException
*/
public void submit() throws IOException {
submit(Maps.<String, String>newHashMap());
}
/**
* Ends the current stage and submits the event containing the timings of each event.
* @param additionalMetadata additional metadata to include in the event.
* @throws IOException
*/
public void submit(Map<String, String> additionalMetadata) throws IOException {
if (this.submitted) {
throw new IOException("MultiTimingEvent has already been submitted.");
}
this.submitted = true;
endStage();
Map<String, String> finalMetadata = Maps.newHashMap();
finalMetadata.putAll(additionalMetadata);
finalMetadata.put(EventSubmitter.EVENT_TYPE, MULTI_TIMING_EVENT);
for (Stage timing : this.timings) {
finalMetadata.put(timing.getName(), Long.toString(timing.getDuration()));
}
this.submitter.submit(this.name, finalMetadata);
}
/**
* Same as {@link #submit()}
* @throws IOException
*/
@Override
public void close()
throws IOException {
submit();
}
}
| 4,468 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/FailureEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import lombok.Getter;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* The builder builds builds a specific {@link GobblinTrackingEvent} whose metadata has
* {@value GobblinEventBuilder#EVENT_TYPE} to be {@value #FAILURE_EVENT_TYPE}
*
* <p>
* Note: A {@link FailureEventBuilder} instance is not reusable
*/
public class FailureEventBuilder extends GobblinEventBuilder {
private static final String FAILURE_EVENT_TYPE = "FailureEvent";
private static final String ROOT_CAUSE = "rootException";
@Getter
private String rootCause;
public FailureEventBuilder(String name) {
this(name, NAMESPACE);
}
public FailureEventBuilder(String name, String namespace) {
super(name, namespace);
metadata.put(EVENT_TYPE, FAILURE_EVENT_TYPE);
}
/**
* Given an throwable, get its root cause and set as a metadata
*/
public void setRootCause(Throwable t) {
Throwable rootCause = getRootCause(t);
if(rootCause != null) {
this.rootCause = ExceptionUtils.getStackTrace(rootCause);
}
}
/**
* Build as {@link GobblinTrackingEvent}
*/
public GobblinTrackingEvent build() {
if (this.rootCause != null) {
metadata.put(ROOT_CAUSE, this.rootCause);
}
return new GobblinTrackingEvent(0L, namespace, name, metadata);
}
/**
* Check if the given {@link GobblinTrackingEvent} is a failure event
*/
public static boolean isFailureEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(FAILURE_EVENT_TYPE);
}
private static Throwable getRootCause(Throwable t) {
Throwable rootCause = ExceptionUtils.getRootCause(t);
if (rootCause == null) {
rootCause = t;
}
return rootCause;
}
/**
* Create a {@link FailureEventBuilder} from a {@link GobblinTrackingEvent}. An inverse function
* to {@link FailureEventBuilder#build()}
*/
public static FailureEventBuilder fromEvent(GobblinTrackingEvent event) {
if(!isFailureEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
FailureEventBuilder failureEvent = new FailureEventBuilder(event.getName(), event.getNamespace());
metadata.forEach((key, value) -> {
switch (key) {
case ROOT_CAUSE:
failureEvent.rootCause = value;
break;
default:
failureEvent.addMetadata(key, value);
break;
}
});
return failureEvent;
}
}
| 4,469 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/GobblinEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
/**
* This class is to support semi-typed Gobblin event. Instead of all events represented as
* instances of {@link GobblinTrackingEvent}. Different types of events can be defined from {@link GobblinEventBuilder},
* where each can define its own attributes. In this way, one can inspect a Gobblin event with the corresponding event
* builder instead of looking into the metadata maps, whose keys could be changed without control
*
* Note: a {@link GobblinEventBuilder} instance is not reusable
*/
@ToString
public class GobblinEventBuilder {
public static final String NAMESPACE = "gobblin.event";
public static final String EVENT_TYPE = "eventType";
@Getter
protected final String name;
@Getter
@Setter
protected String namespace;
protected final Map<String, String> metadata;
public GobblinEventBuilder(String name) {
this(name, null);
}
public GobblinEventBuilder(String name, String namespace) {
this.name = name;
this.namespace = namespace;
metadata = Maps.newHashMap();
}
public ImmutableMap<String, String> getMetadata() {
return new ImmutableMap.Builder<String, String>().putAll(metadata).build();
}
/**
* Add a metadata pair
*/
public void addMetadata(String key, String value) {
metadata.put(key, value);
}
/**
* Add additional metadata
*/
public void addAdditionalMetadata(Map<String, String> additionalMetadata) {
metadata.putAll(additionalMetadata);
}
/**
* Build as {@link GobblinTrackingEvent}
*/
public GobblinTrackingEvent build() {
return new GobblinTrackingEvent(0L, namespace, name, metadata);
}
/**
* Submit the event
* @deprecated Use {@link EventSubmitter#submit(MetricContext, GobblinEventBuilder)}
*/
@Deprecated
public void submit(MetricContext context) {
if(namespace == null) {
namespace = NAMESPACE;
}
context.submitEvent(build());
}
}
| 4,470 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/CountEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import lombok.Getter;
import lombok.Setter;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* The builder builds builds a specific {@link GobblinTrackingEvent} whose metadata has
* {@value GobblinEventBuilder#EVENT_TYPE} to be {@value #COUNT_EVENT_TYPE}
*
* <p>
* Note: A {@link CountEventBuilder} instance is not reusable
*/
public class CountEventBuilder extends GobblinEventBuilder {
public static final String COUNT_EVENT_TYPE = "CountEvent";
public static final String COUNT_KEY = "count";
@Setter
@Getter
private long count;
public CountEventBuilder(String name, long count) {
this(name, null, count);
}
public CountEventBuilder(String name, String namespace, long count) {
super(name, namespace);
this.metadata.put(EVENT_TYPE, COUNT_EVENT_TYPE);
this.count = count;
}
/**
*
* @return {@link GobblinTrackingEvent}
*/
@Override
public GobblinTrackingEvent build() {
this.metadata.put(COUNT_KEY, Long.toString(count));
return super.build();
}
/**
* Check if the given {@link GobblinTrackingEvent} is a {@link CountEventBuilder}
*/
public static boolean isCountEvent(GobblinTrackingEvent event) {
String eventType = (event.getMetadata() == null) ? "" : event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(COUNT_EVENT_TYPE);
}
/**
* Create a {@link CountEventBuilder} from a {@link GobblinTrackingEvent}. An inverse function
* to {@link CountEventBuilder#build()}
*/
public static CountEventBuilder fromEvent(GobblinTrackingEvent event) {
if(!isCountEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
long count = Long.parseLong(metadata.getOrDefault(COUNT_KEY, "0"));
CountEventBuilder countEventBuilder = new CountEventBuilder(event.getName(), event.getNamespace(), count);
metadata.forEach((key, value) -> {
switch (key) {
case COUNT_KEY:
break;
default:
countEventBuilder.addMetadata(key, value);
break;
}
});
return countEventBuilder;
}
}
| 4,471 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/EventSubmitter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import java.util.Map;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import lombok.Getter;
/**
* Wrapper around Avro {@link org.apache.gobblin.metrics.GobblinTrackingEvent.Builder} simplifying handling {@link org.apache.gobblin.metrics.GobblinTrackingEvent}s.
*
* <p>
* Instances of this class are immutable. Calling set* methods returns a copy of the calling instance.
* </p>
*
*/
public class EventSubmitter {
public static final String EVENT_TYPE = "eventType";
private final Map<String, String> metadata;
@Getter
private final String namespace;
@Getter
private final Optional<MetricContext> metricContext;
public static class Builder {
private final Optional<MetricContext> metricContext;
private final Map<String, String> metadata;
private final String namespace;
public Builder(MetricContext metricContext, String namespace) {
this(Optional.fromNullable(metricContext), namespace);
}
public Builder(Optional<MetricContext> metricContext, String namespace) {
this.metricContext = metricContext;
this.namespace = namespace;
this.metadata = Maps.newHashMap();
}
public Builder addMetadata(String key, String value) {
this.metadata.put(key, value);
return this;
}
public Builder addMetadata(Map<? extends String, ? extends String> additionalMetadata) {
this.metadata.putAll(additionalMetadata);
return this;
}
public EventSubmitter build() {
return new EventSubmitter(this);
}
}
/**
* GobblinEventBuilder namespace trumps over the namespace of the EventSubmitter unless it's null
*
* @param eventBuilder
*/
public void submit(GobblinEventBuilder eventBuilder) {
eventBuilder.addAdditionalMetadata(this.metadata);
if(eventBuilder.namespace == null) {
eventBuilder.setNamespace(this.namespace);
}
if (metricContext.isPresent()) {
this.metricContext.get().submitEvent(eventBuilder.build());
}
}
/**
* This is a convenient way to submit an Event without using an EventSubmitter
* namespace should never be null and is defaulted to {@link GobblinEventBuilder#NAMESPACE}
* @param context
* @param builder
*/
public static void submit(MetricContext context, GobblinEventBuilder builder) {
if(builder.namespace == null) {
builder.setNamespace(GobblinEventBuilder.NAMESPACE);
}
context.submitEvent(builder.build());
}
private EventSubmitter(Builder builder) {
this.metadata = builder.metadata;
this.namespace = builder.namespace;
this.metricContext = builder.metricContext;
}
/**
* Submits the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the {@link org.apache.gobblin.metrics.MetricContext}.
* @param name Name of the event.
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public void submit(String name) {
submit(name, ImmutableMap.<String, String>of());
}
/**
* Calls submit on submitter if present.timing
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public static void submit(Optional<EventSubmitter> submitter, String name) {
if (submitter.isPresent()) {
submitter.get().submit(name);
}
}
/**
* Submits the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the {@link org.apache.gobblin.metrics.MetricContext}.
* @param name Name of the event.
* @param metadataEls List of keys and values for metadata of the form key1, value2, key2, value2, ...
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public void submit(String name, String... metadataEls) {
if(metadataEls.length % 2 != 0) {
throw new IllegalArgumentException("Unmatched keys in metadata elements.");
}
Map<String, String> metadata = Maps.newHashMap();
for(int i = 0; i < metadataEls.length/2; i++) {
metadata.put(metadataEls[2 * i], metadataEls[2 * i + 1]);
}
submit(name, metadata);
}
/**
* Calls submit on submitter if present.
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public static void submit(Optional<EventSubmitter> submitter, String name, String... metadataEls) {
if (submitter.isPresent()) {
submitter.get().submit(name, metadataEls);
}
}
/**
* Submits the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the {@link org.apache.gobblin.metrics.MetricContext}.
* @param name Name of the event.
* @param additionalMetadata Additional metadata to be added to the event.
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public void submit(String name, Map<String, String> additionalMetadata) {
if(this.metricContext.isPresent()) {
Map<String, String> finalMetadata = Maps.newHashMap(this.metadata);
if(!additionalMetadata.isEmpty()) {
finalMetadata.putAll(additionalMetadata);
}
// Timestamp is set by metric context.
this.metricContext.get().submitEvent(new GobblinTrackingEvent(0l, this.namespace, name, finalMetadata));
}
}
/**
* Calls submit on submitter if present.
* @deprecated Use {{@link #submit(GobblinEventBuilder)}}
*/
@Deprecated
public static void submit(Optional<EventSubmitter> submitter, String name, Map<String, String> additionalMetadata) {
if (submitter.isPresent()) {
submitter.get().submit(name, additionalMetadata);
}
}
/**
* Get a {@link org.apache.gobblin.metrics.event.TimingEvent} attached to this {@link org.apache.gobblin.metrics.event.EventSubmitter}.
* @param name Name of the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} that will be generated.
* @return a {@link org.apache.gobblin.metrics.event.TimingEvent}.
* @deprecated Use {{@link TimingEvent)}}
*/
@Deprecated
public TimingEvent getTimingEvent(String name) {
return new TimingEvent(this, name);
}
}
| 4,472 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/JobEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
/**
* Job-related event types and their metadata, stored in {@link GobblinTrackingEvent#metadata}
*
* @author Lorand Bendig
*
*/
public class JobEvent {
public static final String JOB_STATE = "JobStateEvent"; // TODO: Migrate to JobStateEventBuilder
public static final String LOCK_IN_USE = "LockInUse";
public static final String WORK_UNITS_MISSING = "WorkUnitsMissing";
public static final String WORK_UNITS_EMPTY = "WorkUnitsEmpty";
public static final String WORK_UNITS_CREATED = "WorkUnitsCreated";
public static final String TASKS_SUBMITTED = "TasksSubmitted";
public static final String METADATA_JOB_ID = "jobId";
public static final String METADATA_JOB_NAME = "jobName";
public static final String METADATA_JOB_START_TIME = "jobBeginTime";
public static final String METADATA_JOB_END_TIME = "jobEndTime";
public static final String METADATA_JOB_STATE = "jobState";
public static final String METADATA_JOB_LAUNCHED_TASKS = "jobLaunchedTasks";
public static final String METADATA_JOB_COMPLETED_TASKS = "jobCompletedTasks";
public static final String METADATA_JOB_LAUNCHER_TYPE = "jobLauncherType";
public static final String METADATA_JOB_TRACKING_URL = "jobTrackingURL";
}
| 4,473 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/lineage/LineageInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event.lineage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import javax.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.broker.EmptyKey;
import org.apache.gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import org.apache.gobblin.broker.iface.NotConfiguredException;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.dataset.DatasetDescriptor;
import org.apache.gobblin.dataset.DatasetResolver;
import org.apache.gobblin.dataset.DatasetResolverFactory;
import org.apache.gobblin.dataset.Descriptor;
import org.apache.gobblin.dataset.DescriptorResolver;
import org.apache.gobblin.dataset.NoopDatasetResolver;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.broker.LineageInfoFactory;
import org.apache.gobblin.metrics.event.EventSubmitter;
import org.apache.gobblin.util.ConfigUtils;
/**
* The lineage coordinator in a Gobblin job with single source and multiple destinations
*
* <p>
* In Gobblin, a work unit processes records from only one dataset. It writes output to one or more destinations,
* depending on the number of branches configured in the job. One destination means an output as another dataset.
* </p>
*
* <p>
* Lineage info is jointly collected from the source, represented by {@link org.apache.gobblin.source.Source} or
* {@link org.apache.gobblin.source.extractor.Extractor}, and destination,
* represented by {@link org.apache.gobblin.writer.DataWriter} or {@link org.apache.gobblin.publisher.DataPublisher}
* </p>
*
* <p>
* The general flow is:
* <ol>
* <li> get a {@link LineageInfo} instance with {@link LineageInfo#getLineageInfo(SharedResourcesBroker)}</li>
* <li> source sets its {@link DatasetDescriptor} to each work unit </li>
* <li> destination puts its {@link DatasetDescriptor} to the work unit </li>
* <li> load and send all lineage events from all states </li>
* <li> purge lineage info from all states </li>
* </ol>
* </p>
*/
@Slf4j
public final class LineageInfo {
private static final String DATASET_RESOLVER_FACTORY = "datasetResolverFactory";
private static final String DATASET_RESOLVER_CONFIG_NAMESPACE = "datasetResolver";
private static final String BRANCH = "branch";
private static final String NAME_KEY = "name";
private static final Config FALLBACK =
ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
.put(DATASET_RESOLVER_FACTORY, NoopDatasetResolver.FACTORY)
.build());
private final DescriptorResolver resolver;
public LineageInfo(Config config) {
resolver = getResolver(config.withFallback(FALLBACK));
}
/**
* Set source {@link DatasetDescriptor} of a lineage event
*
* <p>
* Only the {@link org.apache.gobblin.source.Source} or its {@link org.apache.gobblin.source.extractor.Extractor}
* is supposed to set the source for a work unit of a dataset
* </p>
*
* @param state state about a {@link org.apache.gobblin.source.workunit.WorkUnit}
*
*/
public void setSource(Descriptor source, State state) {
Descriptor descriptor = resolver.resolve(source, state);
if (descriptor == null) {
return;
}
state.setProp(getKey(NAME_KEY), descriptor.getName());
state.setProp(getKey(LineageEventBuilder.SOURCE), Descriptor.toJson(descriptor));
}
/**
* Put a {@link DatasetDescriptor} of a destination dataset to a state
*
* <p>
* Only the {@link org.apache.gobblin.writer.DataWriter} or {@link org.apache.gobblin.publisher.DataPublisher}
* is supposed to put the destination dataset information. Since different branches may concurrently put,
* the method is implemented to be threadsafe
* </p>
*
* @deprecated Use {@link #putDestination(List, int, State)}
*/
@Deprecated
public void putDestination(Descriptor destination, int branchId, State state) {
putDestination(Lists.newArrayList(destination), branchId, state);
}
/**
* Put data {@link Descriptor}s of a destination dataset to a state
*
* @param descriptors It can be a single item list which just has the dataset descriptor or a list
* of dataset partition descriptors
*/
public void putDestination(List<Descriptor> descriptors, int branchId, State state) {
if (!hasLineageInfo(state)) {
log.warn("State has no lineage info but branch " + branchId + " puts {} descriptors", descriptors.size());
return;
}
log.debug(String.format("Put destination %s for branch %d", Descriptor.toJson(descriptors), branchId));
synchronized (state.getProp(getKey(NAME_KEY))) {
List<Descriptor> resolvedDescriptors = new ArrayList<>();
for (Descriptor descriptor : descriptors) {
Descriptor resolvedDescriptor = resolver.resolve(descriptor, state);
if (resolvedDescriptor == null) {
continue;
}
resolvedDescriptors.add(resolvedDescriptor);
}
String destinationKey = getDestinationKey(branchId);
String currentDestinations = state.getProp(destinationKey);
List<Descriptor> allDescriptors = Lists.newArrayList();
if (StringUtils.isNotEmpty(currentDestinations)) {
allDescriptors = Descriptor.fromJsonList(currentDestinations);
}
allDescriptors.addAll(resolvedDescriptors);
state.setProp(destinationKey, Descriptor.toJson(allDescriptors));
}
}
/**
* Load all lineage information from {@link State}s of a dataset
*
* @param states All states which belong to the same dataset
* @return A collection of {@link LineageEventBuilder}s put in the state
*/
public static Collection<LineageEventBuilder> load(Collection<? extends State> states) {
Preconditions.checkArgument(states != null && !states.isEmpty());
Set<LineageEventBuilder> allEvents = Sets.newHashSet();
for (State state : states) {
Map<String, Set<LineageEventBuilder>> branchedEvents = load(state);
branchedEvents.values().forEach(allEvents::addAll);
}
return allEvents;
}
/**
* Load all lineage info from a {@link State}
*
* @return A map from branch to its lineage info. If there is no destination info, return an empty map
*/
static Map<String, Set<LineageEventBuilder>> load(State state) {
String name = state.getProp(getKey(NAME_KEY));
Descriptor source = Descriptor.fromJson(state.getProp(getKey(LineageEventBuilder.SOURCE)));
String branchedPrefix = getKey(BRANCH, "");
Map<String, Set<LineageEventBuilder>> events = Maps.newHashMap();
if (source == null) {
return events;
}
for (Map.Entry<Object, Object> entry : state.getProperties().entrySet()) {
String key = entry.getKey().toString();
if (!key.startsWith(branchedPrefix)) {
continue;
}
String[] parts = key.substring(branchedPrefix.length()).split("\\.");
assert parts.length == 2;
String branchId = parts[0];
Set<LineageEventBuilder> branchEvents = events.computeIfAbsent(branchId, k -> new HashSet<>());
switch (parts[1]) {
case LineageEventBuilder.DESTINATION:
List<Descriptor> descriptors = Descriptor.fromJsonList(entry.getValue().toString());
for (Descriptor descriptor : descriptors) {
LineageEventBuilder event = new LineageEventBuilder(name);
event.setSource(source);
event.setDestination(descriptor);
branchEvents.add(event);
}
break;
default:
throw new RuntimeException("Unsupported lineage key: " + key);
}
}
return events;
}
/**
* Remove all lineage related properties from a state
*/
public static void purgeLineageInfo(State state) {
state.removePropsWithPrefix(LineageEventBuilder.LIENAGE_EVENT_NAMESPACE);
}
/**
* Check if the given state has lineage info
*/
public static boolean hasLineageInfo(State state) {
return state.contains(getKey(NAME_KEY));
}
/**
* Get the full lineage event name from a state
*/
public static String getFullEventName(State state) {
return Joiner.on('.').join(LineageEventBuilder.LIENAGE_EVENT_NAMESPACE, state.getProp(getKey(NAME_KEY)));
}
/**
* Try to get a {@link LineageInfo} instance from the given {@link SharedResourcesBroker}
*/
public static Optional<LineageInfo> getLineageInfo(@Nullable SharedResourcesBroker<GobblinScopeTypes> broker) {
if (broker == null) {
log.warn("Null broker. Will not track data lineage");
return Optional.absent();
}
try {
LineageInfo lineageInfo = broker.getSharedResource(new LineageInfoFactory(), EmptyKey.INSTANCE);
return Optional.of(lineageInfo);
} catch (NotConfiguredException e) {
log.warn("Fail to get LineageInfo instance from broker. Will not track data lineage", e);
return Optional.absent();
}
}
/**
* Get the configured {@link DatasetResolver} from {@link State}
*/
public static DatasetResolver getResolver(Config config) {
// ConfigException.Missing will throw if DATASET_RESOLVER_FACTORY is absent
String resolverFactory = config.getString(DATASET_RESOLVER_FACTORY);
if (resolverFactory.toUpperCase().equals(NoopDatasetResolver.FACTORY)) {
return NoopDatasetResolver.INSTANCE;
}
DatasetResolver resolver = NoopDatasetResolver.INSTANCE;
try {
DatasetResolverFactory factory = (DatasetResolverFactory) Class.forName(resolverFactory).newInstance();
resolver = factory.createResolver(ConfigUtils.getConfigOrEmpty(config, DATASET_RESOLVER_CONFIG_NAMESPACE));
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
log.error(String.format("Fail to create a DatasetResolver with factory class %s", resolverFactory));
}
return resolver;
}
/**
* Prefix all keys with {@link LineageEventBuilder#LIENAGE_EVENT_NAMESPACE}
*/
private static String getKey(Object... objects) {
Object[] args = new Object[objects.length + 1];
args[0] = LineageEventBuilder.LIENAGE_EVENT_NAMESPACE;
System.arraycopy(objects, 0, args, 1, objects.length);
return LineageEventBuilder.getKey(args);
}
private static String getDestinationKey(int branchId) {
return getKey(BRANCH, branchId, LineageEventBuilder.DESTINATION);
}
/**
* Remove the destination property from the state object. Used in streaming mode, where we want to selectively purge
* lineage information from the state.
* @param state
* @param branchId
*/
public static void removeDestinationProp(State state, int branchId) {
String destinationKey = getDestinationKey(branchId);
if (state.contains(destinationKey)) {
state.removeProp(destinationKey);
}
}
/**
* Group states by lineage event name (i.e the dataset name). Used for de-duping LineageEvents for a given dataset.
* @param states
* @return a map of {@link WorkUnitState}s keyed by dataset name.
*/
public static Map<String, Collection<WorkUnitState>> aggregateByLineageEvent(Collection<? extends WorkUnitState> states) {
Map<String, Collection<WorkUnitState>> statesByEvents = Maps.newHashMap();
for (WorkUnitState state : states) {
String eventName = LineageInfo.getFullEventName(state);
Collection<WorkUnitState> statesForEvent = statesByEvents.computeIfAbsent(eventName, k -> Lists.newArrayList());
statesForEvent.add(state);
}
return statesByEvents;
}
/**
* Emit lineage events for a given dataset. This method de-dupes the LineageEvents before submitting to the Lineage
* Event reporter
* @param dataset dataset name
* @param states a set of {@link WorkUnitState}s associated with the dataset
* @param metricContext {@link MetricContext} to submit the events to, which then notifies the Lineage EventReporter.
*/
public static void submitLineageEvent(String dataset, Collection<? extends WorkUnitState> states, MetricContext metricContext) {
Collection<LineageEventBuilder> events = LineageInfo.load(states);
// Send events
events.forEach(event -> EventSubmitter.submit(metricContext, event));
log.info(String.format("Submitted %d lineage events for dataset %s", events.size(), dataset));
}
}
| 4,474 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/lineage/LineageEventBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event.lineage;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.dataset.Descriptor;
import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.event.GobblinEventBuilder;
/**
* The builder builds a specific {@link GobblinTrackingEvent} whose metadata has {@value GobblinEventBuilder#EVENT_TYPE}
* to be {@value LineageEventBuilder#LINEAGE_EVENT_TYPE}
*
* Note: A {@link LineageEventBuilder} instance is not reusable
*/
@Slf4j
public final class LineageEventBuilder extends GobblinEventBuilder {
static final String LIENAGE_EVENT_NAMESPACE = getKey(NAMESPACE, "lineage");
static final String SOURCE = "source";
static final String DESTINATION = "destination";
static final String LINEAGE_EVENT_TYPE = "LineageEvent";
private static final Gson GSON = new Gson();
@Getter @Setter
private Descriptor source;
@Getter @Setter
private Descriptor destination;
public LineageEventBuilder(String name) {
super(name, LIENAGE_EVENT_NAMESPACE);
addMetadata(EVENT_TYPE, LINEAGE_EVENT_TYPE);
}
@Override
public GobblinTrackingEvent build() {
Map<String, String> dataMap = Maps.newHashMap(metadata);
dataMap.put(SOURCE, Descriptor.toJson(source));
dataMap.put(DESTINATION, Descriptor.toJson(destination));
return new GobblinTrackingEvent(0L, namespace, name, dataMap);
}
@Override
public String toString() {
return GSON.toJson(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LineageEventBuilder event = (LineageEventBuilder) o;
if (!namespace.equals(event.namespace) || !name.equals(event.name) || !metadata.equals(event.metadata)) {
return false;
}
if (source != null ? !source.equals(event.source) : event.source != null) {
return false;
}
return destination != null ? destination.equals(event.destination) : event.destination == null;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + namespace.hashCode();
result = 31 * result + metadata.hashCode();
result = 31 * result + (source != null ? source.hashCode() : 0);
result = 31 * result + (destination != null ? destination.hashCode() : 0);
return result;
}
/**
* Check if the given {@link GobblinTrackingEvent} is a lineage event
*/
public static boolean isLineageEvent(GobblinTrackingEvent event) {
String eventType = event.getMetadata().get(EVENT_TYPE);
return StringUtils.isNotEmpty(eventType) && eventType.equals(LINEAGE_EVENT_TYPE);
}
/**
* Create a {@link LineageEventBuilder} from a {@link GobblinEventBuilder}. An inverse function
* to {@link LineageEventBuilder#build()}
*/
public static LineageEventBuilder fromEvent(GobblinTrackingEvent event) {
if(!isLineageEvent(event)) {
return null;
}
Map<String, String> metadata = event.getMetadata();
LineageEventBuilder lineageEvent = new LineageEventBuilder(event.getName());
metadata.forEach((key, value) -> {
switch (key) {
case SOURCE:
lineageEvent.setSource(Descriptor.fromJson(value));
break;
case DESTINATION:
lineageEvent.setDestination(Descriptor.fromJson(value));
break;
default:
lineageEvent.addMetadata(key, value);
break;
}
});
return lineageEvent;
}
static String getKey(Object ... parts) {
return Joiner.on(".").join(parts);
}
}
| 4,475 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/sla/SlaEventSubmitter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event.sla;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Singular;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.metrics.event.EventSubmitter;
/**
* A wrapper around the {@link EventSubmitter} which can submit SLA Events.
*/
@Builder
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class SlaEventSubmitter {
private EventSubmitter eventSubmitter;
private String eventName;
private String datasetUrn;
private String partition;
private String originTimestamp;
private String upstreamTimestamp;
private String recordCount;
private String previousPublishTimestamp;
private String dedupeStatus;
private String completenessPercentage;
private String isFirstPublish;
private String sourceCluster;
private String destinationCluster;
private String azkabanExecutionUrl;
@Singular("additionalMetadata") private Map<String, String> additionalMetadata;
/**
* Construct an {@link SlaEventSubmitter} by extracting Sla event metadata from the properties. See
* {@link SlaEventKeys} for keys to set in properties
* <p>
* The <code>props</code> MUST have required property {@link SlaEventKeys#DATASET_URN_KEY} set.<br>
* All properties with prefix {@link SlaEventKeys#EVENT_ADDITIONAL_METADATA_PREFIX} will be automatically added as
* event metadata
* </p>
* <p>
* Use {@link SlaEventSubmitter#builder()} to build an {@link SlaEventSubmitter} directly with event metadata.
* </p>
*
* @param submitter used to submit the event
* @param name of the event
* @param props reference that contains event metadata
*/
public SlaEventSubmitter(EventSubmitter submitter, String name , Properties props) {
this.eventName = name;
this.eventSubmitter = submitter;
this.datasetUrn = props.getProperty(SlaEventKeys.DATASET_URN_KEY);
if (props.containsKey(SlaEventKeys.DATASET_URN_KEY)) {
this.datasetUrn = props.getProperty(SlaEventKeys.DATASET_URN_KEY);
} else {
this.datasetUrn = props.getProperty(ConfigurationKeys.DATASET_URN_KEY);
}
this.partition = props.getProperty(SlaEventKeys.PARTITION_KEY);
this.originTimestamp = props.getProperty(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY);
this.upstreamTimestamp = props.getProperty(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY);
this.completenessPercentage = props.getProperty(SlaEventKeys.COMPLETENESS_PERCENTAGE_KEY);
this.recordCount = props.getProperty(SlaEventKeys.RECORD_COUNT_KEY);
this.previousPublishTimestamp = props.getProperty(SlaEventKeys.PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY);
this.dedupeStatus = props.getProperty(SlaEventKeys.DEDUPE_STATUS_KEY);
this.isFirstPublish = props.getProperty(SlaEventKeys.IS_FIRST_PUBLISH);
this.additionalMetadata = Maps.newHashMap();
for (Entry<Object, Object> entry : props.entrySet()) {
if (StringUtils.startsWith(entry.getKey().toString(), SlaEventKeys.EVENT_ADDITIONAL_METADATA_PREFIX)) {
this.additionalMetadata.put(StringUtils.removeStart(entry.getKey().toString(),
SlaEventKeys.EVENT_ADDITIONAL_METADATA_PREFIX), entry.getValue().toString());
}
}
}
/**
* Submit the sla event by calling {@link SlaEventSubmitter#EventSubmitter#submit()}. If
* {@link SlaEventSubmitter#eventName}, {@link SlaEventSubmitter#eventSubmitter}, {@link SlaEventSubmitter#datasetUrn}
* are not available the method is a no-op.
*/
public void submit() {
try {
Preconditions.checkArgument(Predicates.notNull().apply(eventSubmitter), "EventSubmitter needs to be set");
Preconditions.checkArgument(NOT_NULL_OR_EMPTY_PREDICATE.apply(eventName), "Eventname is required");
Preconditions.checkArgument(NOT_NULL_OR_EMPTY_PREDICATE.apply(datasetUrn), "DatasetUrn is required");
eventSubmitter.submit(eventName, buildEventMap());
} catch (IllegalArgumentException e) {
log.info("Required arguments to submit an SLA event is not available. No Sla event will be submitted. " + e.toString());
}
}
/**
* Builds an EventMetadata {@link Map} from the {@link #SlaEventSubmitter}. The method filters out metadata by
* applying {@link #NOT_NULL_OR_EMPTY_PREDICATE}
*
*/
private Map<String, String> buildEventMap() {
Map<String, String> eventMetadataMap = Maps.newHashMap();
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.DATASET_URN_KEY), datasetUrn);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.PARTITION_KEY), partition);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY), originTimestamp);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY), upstreamTimestamp);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.COMPLETENESS_PERCENTAGE_KEY), completenessPercentage);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.RECORD_COUNT_KEY), recordCount);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY), previousPublishTimestamp);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.DEDUPE_STATUS_KEY), dedupeStatus);
eventMetadataMap.put(withoutPropertiesPrefix(SlaEventKeys.IS_FIRST_PUBLISH), isFirstPublish);
if (additionalMetadata != null) {
eventMetadataMap.putAll(additionalMetadata);
}
return Maps.newHashMap(Maps.filterValues(eventMetadataMap, NOT_NULL_OR_EMPTY_PREDICATE));
}
/**
* {@link SlaEventKeys} have a prefix of {@link SlaEventKeys#EVENT_GOBBLIN_STATE_PREFIX} to keep properties organized
* in state. This method removes the prefix before submitting an Sla event.
*/
private String withoutPropertiesPrefix(String key) {
return StringUtils.removeStart(key, SlaEventKeys.EVENT_GOBBLIN_STATE_PREFIX);
}
/**
* Predicate that returns false if a string is null or empty. Calls {@link Strings#isNullOrEmpty(String)} internally.
*/
private static final Predicate<String> NOT_NULL_OR_EMPTY_PREDICATE = new Predicate<String>() {
@Override
public boolean apply(String input) {
return !Strings.isNullOrEmpty(input);
}
};
}
| 4,476 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/sla/SlaEventKeys.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.metrics.event.sla;
public class SlaEventKeys {
static final String EVENT_GOBBLIN_STATE_PREFIX = "event.sla.";
public static final String DATASET_URN_KEY = EVENT_GOBBLIN_STATE_PREFIX + "datasetUrn";
public static final String PARTITION_KEY = EVENT_GOBBLIN_STATE_PREFIX + "partition";
public static final String ORIGIN_TS_IN_MILLI_SECS_KEY = EVENT_GOBBLIN_STATE_PREFIX + "originTimestamp";
public static final String UPSTREAM_TS_IN_MILLI_SECS_KEY = EVENT_GOBBLIN_STATE_PREFIX + "upstreamTimestamp";
public static final String COMPLETENESS_PERCENTAGE_KEY = EVENT_GOBBLIN_STATE_PREFIX + "completenessPercentage";
public static final String DEDUPE_STATUS_KEY = EVENT_GOBBLIN_STATE_PREFIX + "dedupeStatus";
public static final String RECORD_COUNT_KEY = EVENT_GOBBLIN_STATE_PREFIX + "recordCount";
public static final String PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY = EVENT_GOBBLIN_STATE_PREFIX + "previousPublishTs";
public static final String IS_FIRST_PUBLISH = EVENT_GOBBLIN_STATE_PREFIX + "isFirstPublish";
public static final String EVENT_ADDITIONAL_METADATA_PREFIX = EVENT_GOBBLIN_STATE_PREFIX + "additionalMetadata.";
public static final String SOURCE_URI = "sourceCluster";
public static final String DESTINATION_URI = "destinationCluster";
public static final String DATASET_OUTPUT_PATH = "datasetOutputPath";
}
| 4,477 |
0 | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/filesystem/MetricsFileSystemInstrumentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.filesystem;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.util.Progressable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Timer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closer;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.broker.iface.ConfigView;
import org.apache.gobblin.broker.iface.ScopeType;
import org.apache.gobblin.broker.iface.SharedResourcesBroker;
import org.apache.gobblin.metrics.ContextAwareTimer;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.util.filesystem.FileSystemInstrumentation;
import org.apache.gobblin.util.filesystem.FileSystemInstrumentationFactory;
import org.apache.gobblin.util.filesystem.FileSystemKey;
/**
* A {@link org.apache.hadoop.fs.FileSystem} that extends HDFS and allows instrumentation of certain calls (for example,
* counting the number of calls to a certain method or measuring latency). For now it is just a skeleton.
*
* Using the scheme "instrumented-hdfs" will automatically use this {@link org.apache.hadoop.fs.FileSystem} and work
* transparently as any other HDFS file system.
*
* When modifying this class, tests must be run manually (see InstrumentedHDFSFileSystemTest).
*/
@Slf4j
public class MetricsFileSystemInstrumentation extends FileSystemInstrumentation {
public static class Factory<S extends ScopeType<S>> extends FileSystemInstrumentationFactory<S> {
@Override
public FileSystem instrumentFileSystem(FileSystem fs, SharedResourcesBroker<S> broker,
ConfigView<S, FileSystemKey> config) {
return new MetricsFileSystemInstrumentation(fs);
}
}
private MetricContext metricContext;
protected final Closer closer;
// Below are HDFS metrics
@VisibleForTesting
protected final ContextAwareTimer listStatusTimer;
@VisibleForTesting
protected final ContextAwareTimer listFilesTimer;
@VisibleForTesting
protected final ContextAwareTimer globStatusTimer;
@VisibleForTesting
protected final ContextAwareTimer mkdirTimer;
@VisibleForTesting
protected final ContextAwareTimer deleteTimer;
@VisibleForTesting
protected final ContextAwareTimer renameTimer;
@VisibleForTesting
protected final ContextAwareTimer createTimer;
@VisibleForTesting
protected final ContextAwareTimer openTimer;
@VisibleForTesting
protected final ContextAwareTimer setOwnerTimer;
@VisibleForTesting
protected final ContextAwareTimer getFileStatusTimer;
@VisibleForTesting
protected final ContextAwareTimer setPermissionTimer;
@VisibleForTesting
protected final ContextAwareTimer setTimesTimer;
@VisibleForTesting
protected final ContextAwareTimer appendTimer;
@VisibleForTesting
protected final ContextAwareTimer concatTimer;
private final List<ContextAwareTimer> allTimers;
private static class TimerContextWithLog implements Closeable {
Timer.Context context;
String operation;
List<Object> parameters;
long startTick;
Object result;
private static final Logger LOG = LoggerFactory.getLogger(TimerContextWithLog.class);
public TimerContextWithLog (Timer.Context context, String operation, Object... values) {
this.context = context;
this.startTick = System.nanoTime();
this.operation = operation;
this.parameters = new ArrayList<>(Arrays.asList(values));
this.result = null;
}
public void setResult(Object rst) {
this.result = rst;
}
public void close() {
long duration = System.nanoTime() - startTick;
if (result instanceof FileStatus[]) {
LOG.debug ("HDFS operation {} with {} takes {} nanoseconds and returns {} files", operation, parameters, duration, ((FileStatus[])result).length);
} else {
LOG.debug ("HDFS operation {} with {} takes {} nanoseconds", operation, parameters, duration);
}
this.context.close();
}
}
public MetricsFileSystemInstrumentation(FileSystem underlying) {
super(underlying);
this.closer = Closer.create();
this.metricContext = new MetricContext.Builder(underlying.getUri() + "_metrics").build();
this.metricContext = this.closer.register(metricContext);
this.listStatusTimer = this.metricContext.timer("listStatus");
this.listFilesTimer = this.metricContext.timer("listFiles");
this.globStatusTimer = this.metricContext.timer("globStatus");
this.mkdirTimer = this.metricContext.timer("mkdirs");
this.renameTimer = this.metricContext.timer("rename");
this.deleteTimer = this.metricContext.timer("delete");
this.createTimer = this.metricContext.timer("create");
this.openTimer = this.metricContext.timer("open");
this.setOwnerTimer = this.metricContext.timer("setOwner");
this.getFileStatusTimer = this.metricContext.timer("getFileStatus");
this.setPermissionTimer = this.metricContext.timer("setPermission");
this.setTimesTimer = this.metricContext.timer("setTimes");
this.appendTimer = this.metricContext.timer ("append");
this.concatTimer = this.metricContext.timer ("concat");
this.allTimers = ImmutableList.<ContextAwareTimer>builder().add(
this.listStatusTimer, this.listFilesTimer, this.globStatusTimer, this.mkdirTimer, this.renameTimer,
this.deleteTimer, this.createTimer, this.openTimer, this.setOwnerTimer, this.getFileStatusTimer, this.setPermissionTimer,
this.setTimesTimer, this.appendTimer, this.concatTimer
).build();
}
@Override
protected void onClose() {
StringBuilder message = new StringBuilder();
message.append("========================").append("\n");
message.append("Statistics for FileSystem: ").append(getUri()).append("\n");
message.append("------------------------").append("\n");
message.append("method\tcalls\tmean time(ns)\t99 percentile(ns)").append("\n");
for (ContextAwareTimer timer : this.allTimers) {
if (timer.getCount() > 0) {
message.append(timer.getName()).append("\t").append(timer.getCount()).append("\t").
append(timer.getSnapshot().getMean()).append("\t").append(timer.getSnapshot().get99thPercentile()).append("\n");
}
}
message.append("------------------------").append("\n");
log.info(message.toString());
super.onClose();
}
@Override
public void close()
throws IOException {
super.close();
// Should print out statistics here
}
/**
* Add timer metrics to {@link DistributedFileSystem#mkdirs(Path, FsPermission)}
*/
public boolean mkdirs(Path f, FsPermission permission) throws IOException {
try (Closeable context = new TimerContextWithLog(mkdirTimer.time(), "mkdirs", f, permission)) {
return super.mkdirs (f, permission);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#rename(Path, Path)}
*/
public boolean rename (Path src, Path dst) throws IOException {
try (Closeable context = new TimerContextWithLog(renameTimer.time(), "rename", src, dst)) {
return super.rename(src, dst);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#delete(Path, boolean)}
*/
public boolean delete (Path f, boolean recursive) throws IOException {
try (Closeable context = new TimerContextWithLog(deleteTimer.time(), "delete", f, recursive)) {
return super.delete (f, recursive);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#listStatus(Path)}
*/
public FileStatus[] listStatus(Path path) throws IOException {
try (TimerContextWithLog context = new TimerContextWithLog(listStatusTimer.time(), "listStatus", path)) {
FileStatus[] statuses = super.listStatus(path);
context.setResult(statuses);
return statuses;
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#globStatus(Path)}
*/
public FileStatus[] globStatus(Path pathPattern) throws IOException {
try (TimerContextWithLog context = new TimerContextWithLog(globStatusTimer.time(), "globStatus", pathPattern)) {
FileStatus[] statuses = super.globStatus(pathPattern);
context.setResult(statuses);
return statuses;
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#globStatus(Path, PathFilter)}
*/
public FileStatus[] globStatus(Path pathPattern, PathFilter filter) throws IOException {
try (TimerContextWithLog context = new TimerContextWithLog(globStatusTimer.time(), "globStatus", pathPattern, filter)) {
FileStatus[] statuses = super.globStatus(pathPattern, filter);
context.setResult(statuses);
return statuses;
}
}
/**
* Add timer metrics to {@link FileSystem#listFiles(Path, boolean)}
*/
public RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive) throws FileNotFoundException, IOException {
try (Closeable context = new TimerContextWithLog(this.listFilesTimer.time(), "listFiles", f, recursive)) {
return super.listFiles(f, recursive);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#create(Path, FsPermission, boolean, int, short, long, Progressable)}
*/
public FSDataOutputStream create(Path f,
FsPermission permission,
boolean overwrite,
int bufferSize,
short replication,
long blockSize,
Progressable progress) throws IOException {
try (Closeable context = new TimerContextWithLog(this.createTimer.time(), "create", f, permission, overwrite, bufferSize, replication, blockSize, progress)) {
return super.create(f, permission, overwrite, bufferSize, replication, blockSize, progress);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#open(Path, int)}
*/
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
try (Closeable context = new TimerContextWithLog(this.openTimer.time(), "open", f, bufferSize)) {
return super.open(f, bufferSize);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#setOwner(Path, String, String)}
*/
public void setOwner(Path f, String user, String group) throws IOException {
try (Closeable context = new TimerContextWithLog(this.setOwnerTimer.time(), "setOwner", f, user, group)) {
super.setOwner(f, user, group);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#getFileStatus(Path)}
*/
public FileStatus getFileStatus (Path f) throws IOException {
try (Closeable context = new TimerContextWithLog(this.getFileStatusTimer.time(), "getFileStatus", f)) {
return super.getFileStatus(f);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#setPermission(Path, FsPermission)}
*/
public void setPermission (Path f, final FsPermission permission) throws IOException {
try (Closeable context = new TimerContextWithLog(this.setPermissionTimer.time(), "setPermission", f, permission)) {
super.setPermission(f, permission);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#setTimes(Path, long, long)}
*/
public void setTimes (Path f, long t, long a) throws IOException {
try (Closeable context = new TimerContextWithLog(this.setTimesTimer.time(), "setTimes", f, t, a)) {
super.setTimes(f, t, a);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#append(Path, int, Progressable)}
*/
public FSDataOutputStream append (Path p, final int bufferSize, Progressable progress) throws IOException {
try (Closeable context = new TimerContextWithLog(this.appendTimer.time(), "append", p)) {
return super.append(p, bufferSize, progress);
}
}
/**
* Add timer metrics to {@link DistributedFileSystem#concat(Path, Path[])}
*/
public void concat (Path trg, Path [] psrcs) throws IOException {
try (Closeable context = new TimerContextWithLog(this.concatTimer.time(), "concat", trg, psrcs)) {
super.concat(trg, psrcs);
}
}
}
| 4,478 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented/fork/InstrumentedForkOperatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented.fork;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.MetricsHelper;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.fork.ForkOperator;
import org.apache.gobblin.metrics.MetricNames;
public class InstrumentedForkOperatorTest {
public class TestInstrumentedForkOperator extends InstrumentedForkOperator<String, String> {
@Override
public List<Boolean> forkDataRecordImpl(WorkUnitState workUnitState, String input) {
List<Boolean> output = new ArrayList<>();
output.add(true);
output.add(false);
output.add(true);
return output;
}
@Override
public int getBranches(WorkUnitState workUnitState) {
return 0;
}
@Override
public List<Boolean> forkSchema(WorkUnitState workUnitState, String input) {
return null;
}
@Override
public void close() throws IOException {
}
}
public class TestForkOperator implements ForkOperator<String, String> {
@Override
public List<Boolean> forkDataRecord(WorkUnitState workUnitState, String input) {
List<Boolean> output = new ArrayList<>();
output.add(true);
output.add(false);
output.add(true);
return output;
}
@Override
public void init(WorkUnitState workUnitState) throws Exception {}
@Override
public int getBranches(WorkUnitState workUnitState) {
return 0;
}
@Override
public List<Boolean> forkSchema(WorkUnitState workUnitState, String input) {
return null;
}
@Override
public void close() throws IOException {
}
}
@Test
public void test() throws Exception {
TestInstrumentedForkOperator fork = new TestInstrumentedForkOperator();
testBase(fork);
}
@Test
public void testDecorated() throws Exception {
InstrumentedForkOperatorBase instrumentedFork =
new InstrumentedForkOperatorDecorator(new TestInstrumentedForkOperator());
testBase(instrumentedFork);
InstrumentedForkOperatorBase notInstrumentedFork = new InstrumentedForkOperatorDecorator(new TestForkOperator());
testBase(notInstrumentedFork);
}
public void testBase(InstrumentedForkOperatorBase<String, String> fork) throws Exception {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
fork.init(state);
fork.forkDataRecord(new WorkUnitState(), "in");
Map<String, Long> metrics = MetricsHelper.dumpMetrics(fork.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.ForkOperatorMetrics.RECORDS_IN_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.ForkOperatorMetrics.FORKS_OUT_METER), Long.valueOf(2));
Assert.assertEquals(metrics.get(MetricNames.ForkOperatorMetrics.FORK_TIMER), Long.valueOf(1));
Assert.assertEquals(MetricsHelper.dumpTags(fork.getMetricContext()).get("construct"),
Constructs.FORK_OPERATOR.toString());
}
}
| 4,479 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented/qualitychecker/InstrumentedRowLevelPolicyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented.qualitychecker;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.MetricsHelper;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metrics.MetricNames;
import org.apache.gobblin.qualitychecker.row.RowLevelPolicy;
public class InstrumentedRowLevelPolicyTest {
public class TestInstrumentedRowLevelPolicy extends InstrumentedRowLevelPolicy {
public TestInstrumentedRowLevelPolicy(State state, Type type) {
super(state, type);
}
@Override
public Result executePolicyImpl(Object record) {
return Result.PASSED;
}
}
@Test
public void test() {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
TestInstrumentedRowLevelPolicy policy = new TestInstrumentedRowLevelPolicy(state, null);
testBase(policy);
}
@Test
public void testDecorated() {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
InstrumentedRowLevelPolicyBase instrumentedPolicy = new InstrumentedRowLevelPolicyDecorator(
new TestInstrumentedRowLevelPolicy(state, null)
);
testBase(instrumentedPolicy);
InstrumentedRowLevelPolicyBase notInstrumentedPolicy = new InstrumentedRowLevelPolicyDecorator(
new RowLevelPolicy(state, null) {
@Override
public Result executePolicy(Object record) {
return Result.PASSED;
}
});
testBase(notInstrumentedPolicy);
}
public void testBase(InstrumentedRowLevelPolicyBase policy) {
policy.executePolicy("test");
Map<String, Long> metrics = MetricsHelper.dumpMetrics(policy.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.RowLevelPolicyMetrics.RECORDS_IN_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.RowLevelPolicyMetrics.RECORDS_PASSED_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.RowLevelPolicyMetrics.RECORDS_FAILED_METER), Long.valueOf(0));
Assert.assertEquals(metrics.get(MetricNames.RowLevelPolicyMetrics.CHECK_TIMER), Long.valueOf(1));
Assert.assertEquals(MetricsHelper.dumpTags(policy.getMetricContext()).get("construct"),
Constructs.ROW_QUALITY_CHECKER.toString());
}
}
| 4,480 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented/converter/InstrumentedConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented.converter;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.MetricsHelper;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.converter.DataConversionException;
import org.apache.gobblin.converter.IdentityConverter;
import org.apache.gobblin.converter.SchemaConversionException;
import org.apache.gobblin.converter.SingleRecordIterable;
import org.apache.gobblin.metrics.MetricNames;
public class InstrumentedConverterTest {
public class TestInstrumentedConverter extends InstrumentedConverter<String, String, String, String> {
@Override
public Iterable<String> convertRecordImpl(String outputSchema, String inputRecord, WorkUnitState workUnit)
throws DataConversionException {
return new SingleRecordIterable<>(inputRecord);
}
@Override
public String convertSchema(String inputSchema, WorkUnitState workUnit)
throws SchemaConversionException {
return null;
}
}
@Test
public void testInstrumented() throws DataConversionException{
TestInstrumentedConverter converter = new TestInstrumentedConverter();
testBase(converter);
}
@Test
public void testDecorator() throws DataConversionException{
InstrumentedConverterBase instrumentedConverter = new InstrumentedConverterDecorator(
new TestInstrumentedConverter()
);
testBase(instrumentedConverter);
InstrumentedConverterBase nonInstrumentedConverter = new InstrumentedConverterDecorator(
new IdentityConverter()
);
testBase(nonInstrumentedConverter);
}
public void testBase(InstrumentedConverterBase<String, String, String, String> converter)
throws DataConversionException {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
converter.init(state);
Iterable<String> iterable = converter.convertRecord("schema", "record", new WorkUnitState());
Map<String, Long> metrics = MetricsHelper.dumpMetrics(converter.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.ConverterMetrics.RECORDS_IN_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.ConverterMetrics.RECORDS_OUT_METER), Long.valueOf(0));
Assert.assertEquals(metrics.get(MetricNames.ConverterMetrics.CONVERT_TIMER), Long.valueOf(1));
iterable.iterator().next();
metrics = MetricsHelper.dumpMetrics(converter.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.ConverterMetrics.RECORDS_IN_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.ConverterMetrics.RECORDS_OUT_METER), Long.valueOf(1));
Assert.assertEquals(MetricsHelper.dumpTags(converter.getMetricContext()).get("construct"),
Constructs.CONVERTER.toString());
}
}
| 4,481 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented/extractor/InstrumentedExtractorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented.extractor;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.MetricsHelper;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.metrics.MetricNames;
import org.apache.gobblin.records.RecordStreamWithMetadata;
import org.apache.gobblin.source.extractor.DataRecordException;
import org.apache.gobblin.source.extractor.Extractor;
import org.apache.gobblin.stream.RecordEnvelope;
public class InstrumentedExtractorTest {
public class TestInstrumentedExtractor extends InstrumentedExtractor<String, String> {
public TestInstrumentedExtractor(WorkUnitState workUnitState) {
super(workUnitState);
}
@Override
public String readRecordImpl(String reuse)
throws DataRecordException, IOException {
return "test";
}
@Override
public String getSchema() {
return null;
}
@Override
public long getExpectedRecordCount() {
return 0;
}
@Override
public long getHighWatermark() {
return 0;
}
}
public class TestExtractor implements Extractor<String, String> {
@Override
public String readRecord(String reuse)
throws DataRecordException, IOException {
return "test";
}
@Override
public String getSchema() {
return null;
}
@Override
public long getExpectedRecordCount() {
return 0;
}
@Override
public long getHighWatermark() {
return 0;
}
@Override
public void close()
throws IOException {
}
}
@Test
public void test() throws DataRecordException, IOException {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
TestInstrumentedExtractor extractor = new TestInstrumentedExtractor(state);
testBase(extractor);
}
@Test
public void testDecorated() throws DataRecordException, IOException {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
InstrumentedExtractorBase instrumentedExtractor = new InstrumentedExtractorDecorator(state,
new TestInstrumentedExtractor(state)
);
testBase(instrumentedExtractor);
InstrumentedExtractorBase nonInstrumentedExtractor = new InstrumentedExtractorDecorator(state,
new TestExtractor());
testBase(nonInstrumentedExtractor);
}
public void testBase(InstrumentedExtractorBase<String, String> extractor)
throws DataRecordException, IOException {
RecordStreamWithMetadata<String, String> stream = extractor.recordStream(new AtomicBoolean(false));
RecordEnvelope<String> r = (RecordEnvelope<String>) stream.getRecordStream().firstOrError().blockingGet();
Map<String, Long> metrics = MetricsHelper.dumpMetrics(extractor.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.ExtractorMetrics.RECORDS_READ_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.ExtractorMetrics.RECORDS_FAILED_METER), Long.valueOf(0));
Assert.assertEquals(metrics.get(MetricNames.ExtractorMetrics.EXTRACT_TIMER), Long.valueOf(1));
Assert.assertEquals(MetricsHelper.dumpTags(extractor.getMetricContext()).get("construct"),
Constructs.EXTRACTOR.toString());
}
}
| 4,482 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/instrumented/writer/InstrumentedDataWriterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented.writer;
import java.io.IOException;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.MetricsHelper;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metrics.MetricNames;
import org.apache.gobblin.stream.RecordEnvelope;
import org.apache.gobblin.writer.DataWriter;
public class InstrumentedDataWriterTest {
public class TestInstrumentedDataWriter extends InstrumentedDataWriter<String> {
public TestInstrumentedDataWriter(State state) {
super(state);
}
@Override
public void writeImpl(String record)
throws IOException {
}
@Override
public void commit()
throws IOException {
}
@Override
public void cleanup()
throws IOException {
}
@Override
public long recordsWritten() {
return 0;
}
@Override
public long bytesWritten()
throws IOException {
return 0;
}
}
public class TestDataWriter implements DataWriter<String> {
@Override
public void close()
throws IOException {
}
@Override
public void write(String record)
throws IOException {
}
@Override
public void commit()
throws IOException {
}
@Override
public void cleanup()
throws IOException {
}
@Override
public long recordsWritten() {
return 0;
}
@Override
public long bytesWritten()
throws IOException {
return 0;
}
}
@Test
public void test() throws IOException {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
TestInstrumentedDataWriter writer = new TestInstrumentedDataWriter(state);
testBase(writer);
}
@Test
public void testDecorated() throws IOException {
WorkUnitState state = new WorkUnitState();
state.setProp(ConfigurationKeys.METRICS_ENABLED_KEY, Boolean.toString(true));
InstrumentedDataWriterBase instrumentedWriter = new InstrumentedDataWriterDecorator(
new TestInstrumentedDataWriter(state), state
);
testBase(instrumentedWriter);
InstrumentedDataWriterBase notInstrumentedWriter = new InstrumentedDataWriterDecorator(
new TestDataWriter(), state);
testBase(notInstrumentedWriter);
}
public void testBase(InstrumentedDataWriterBase<String> writer) throws IOException {
writer.writeEnvelope(new RecordEnvelope<String>("test"));
Map<String, Long> metrics = MetricsHelper.dumpMetrics(writer.getMetricContext());
Assert.assertEquals(metrics.get(MetricNames.DataWriterMetrics.RECORDS_IN_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.DataWriterMetrics.SUCCESSFUL_WRITES_METER), Long.valueOf(1));
Assert.assertEquals(metrics.get(MetricNames.DataWriterMetrics.FAILED_WRITES_METER), Long.valueOf(0));
Assert.assertEquals(metrics.get(MetricNames.DataWriterMetrics.WRITE_TIMER), Long.valueOf(1));
Assert.assertEquals(MetricsHelper.dumpTags(writer.getMetricContext()).get("construct"),
Constructs.WRITER.toString());
}
}
| 4,483 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/crypto/EncryptionConfigParserTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.crypto;
import java.util.Map;
import java.util.Properties;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
public class EncryptionConfigParserTest {
private EncryptionConfigParser parser;
@BeforeTest
public void initParser() {
parser = new EncryptionConfigParser();
}
@Test
public void testValidConfigOneBranch() {
testWithWriterPrefix(1, 0);
}
@Test
public void testValidConfigSeparateBranch() {
testWithWriterPrefix(3, 1);
}
@Test
public void testAlgorithmNotPresent() {
Properties properties = new Properties();
properties
.put(EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY,
"/tmp/foobar");
properties.put(
EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY,
"abracadabra");
State s = new State(properties);
Map<String, Object> parsedProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.WRITER, s, 1, 0);
Assert.assertNull(parsedProperties, "Expected encryption be empty if no algorithm specified");
}
@Test
public void testProperPrefix() {
Properties properties = new Properties();
properties.put(EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY,
"any");
properties
.put(EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY,
"/tmp/foobar");
properties.put(
EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY,
"abracadabra");
properties.put(EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "abc.def", "foobar");
State s = new State(properties);
Map<String, Object> parsedProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.WRITER, s, 1, 0);
Assert.assertNotNull(parsedProperties, "Expected parser to only return one record");
Assert.assertEquals(parsedProperties.size(), 3, "Did not expect abc.def to be picked up in config");
}
@Test
public void testConverter() {
WorkUnitState wuState = new WorkUnitState();
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY, "any");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY,
"/tmp/foobar");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY,
"abracadabra");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEY_NAME,
"keyname");
wuState.setProp(EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "abc.def", "foobar");
Map<String, Object> parsedProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.CONVERTER_ENCRYPT, wuState);
Assert.assertNotNull(parsedProperties, "Expected parser to only return one record");
Assert.assertEquals(parsedProperties.size(), 4, "Did not expect abc.def to be picked up in config");
Map<String, Object> parsedWriterProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.WRITER, wuState);
Assert.assertNull(parsedWriterProperties, "Did not expect to find writer properties");
}
@Test
public void testConverterWithEntityPrefix() {
final String entityName = "MyConverter";
WorkUnitState wuState = new WorkUnitState();
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY, "any");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + entityName + "." + EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY, "aes_rotating");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY,
"/tmp/foobar");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY,
"abracadabra");
wuState.getJobState().setProp(
EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEY_NAME,
"keyname");
wuState.setProp(EncryptionConfigParser.CONVERTER_ENCRYPT_PREFIX + "abc.def", "foobar");
Map<String, Object> parsedProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.CONVERTER_ENCRYPT, entityName, wuState);
Assert.assertNotNull(parsedProperties, "Expected parser to only return one record");
Assert.assertEquals(parsedProperties.size(), 4, "Did not expect abc.def to be picked up in config");
Assert.assertEquals(EncryptionConfigParser.getEncryptionType(parsedProperties), "aes_rotating");
Map<String, Object> parsedWriterProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.WRITER, wuState);
Assert.assertNull(parsedWriterProperties, "Did not expect to find writer properties");
}
private void testWithWriterPrefix(int numBranches, int branch) {
String branchString = "";
if (numBranches > 1) {
branchString = String.format(".%d", branch);
}
Properties properties = new Properties();
properties.put(EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_ALGORITHM_KEY
+ branchString, "any");
properties.put(
EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PATH_KEY
+ branchString, "/tmp/foobar");
properties.put(
EncryptionConfigParser.WRITER_ENCRYPT_PREFIX + "." + EncryptionConfigParser.ENCRYPTION_KEYSTORE_PASSWORD_KEY
+ branchString, "abracadabra");
State s = new State(properties);
Map<String, Object> parsedProperties = EncryptionConfigParser.getConfigForBranch(EncryptionConfigParser.EntityType.WRITER, s, numBranches, branch);
Assert.assertNotNull(parsedProperties, "Expected parser to only return one record");
Assert.assertEquals(EncryptionConfigParser.getEncryptionType(parsedProperties), "any");
Assert.assertEquals(EncryptionConfigParser.getKeystorePath(parsedProperties), "/tmp/foobar");
Assert.assertEquals(EncryptionConfigParser.getKeystorePassword(parsedProperties), "abracadabra");
}
}
| 4,484 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/types/AvroGenericRecordTypeMapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.types;
import org.apache.avro.generic.GenericRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.test.TestUtils;
public class AvroGenericRecordTypeMapperTest {
@Test
public void test()
throws FieldMappingException {
GenericRecord record = TestUtils.generateRandomAvroRecord();
AvroGenericRecordTypeMapper typeMapper = new AvroGenericRecordTypeMapper();
Object field = typeMapper.getField(record, "field1");
Assert.assertEquals(field.getClass(), String.class);
}
}
| 4,485 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/SamplingConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.configuration.WorkUnitState;
@Test
public class SamplingConverterTest {
private void assertNear(int actual, int expected, int threshold, String context) {
boolean near = (Math.abs(actual - expected) <= Math.abs(threshold));
Assert.assertTrue(near, context + ": Failed nearness test between "
+ actual + " and " + expected + " with threshold " + threshold);
}
public void testSampling()
throws DataConversionException {
int numIterations = 100;
Random random = new Random();
for (int j = 0; j < numIterations; ++j) {
SamplingConverter sampler = new SamplingConverter();
Properties props = new Properties();
float randomSampling = random.nextFloat();
props.setProperty(SamplingConverter.SAMPLE_RATIO_KEY, "" + randomSampling);
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.addAll(props);
sampler.init(workUnitState);
int numRecords = 10000; // need at least 10k samples
int sampledRecords = 0;
for (int i = 0; i < numRecords; ++i) {
Object o = new Object();
Iterator<Object> recordIter = sampler.convertRecord(null, o, workUnitState).iterator();
if (recordIter.hasNext()) {
++sampledRecords;
// make sure we got back the same record
Assert.assertEquals(recordIter.next(), o, "Sampler should return the same record");
Assert.assertFalse(recordIter.hasNext(), "There should only be 1 record returned");
}
}
int threshold = (int) (0.02 * (double) numRecords); // 2 %
assertNear(sampledRecords, (int) (randomSampling * (float) numRecords), threshold, "SampleRatio: " + randomSampling);
}
}
}
| 4,486 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/AsyncConverter1to1Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metadata.GlobalMetadata;
import org.apache.gobblin.records.RecordStreamWithMetadata;
import org.apache.gobblin.stream.RecordEnvelope;
import org.apache.gobblin.util.ExponentialBackoff;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
public class AsyncConverter1to1Test {
@Test
public void test1to1() throws Exception {
MyAsyncConverter1to1 converter = new MyAsyncConverter1to1();
List<Throwable> errors = Lists.newArrayList();
AtomicBoolean done = new AtomicBoolean(false);
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.setProp(AsyncConverter1to1.MAX_CONCURRENT_ASYNC_CONVERSIONS_KEY, 3);
RecordStreamWithMetadata<String, String> stream =
new RecordStreamWithMetadata<>(Flowable.range(0, 5).map(i -> i.toString()).map(RecordEnvelope::new),
GlobalMetadata.<String>builder().schema("schema").build());
Set<String> outputRecords = Sets.newConcurrentHashSet();
converter.processStream(stream, workUnitState).getRecordStream().subscribeOn(Schedulers.newThread())
.subscribe(r -> outputRecords.add(((RecordEnvelope<String>)r).getRecord()), errors::add, () -> done.set(true));
// Release record 0
Assert.assertTrue(
ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> converter.completeFutureIfPresent("0")).await());
Assert.assertTrue(ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> outputRecords.contains("0")).await());
Assert.assertEquals(outputRecords.size(), 1);
// Record 4 should not be in the queue yet (max concurrent conversions is 3).
Assert.assertFalse(
ExponentialBackoff.awaitCondition().maxWait(200L).callable(() -> converter.completeFutureIfPresent("4")).await());
// Release record 3 (out of order)
Assert.assertTrue(
ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> converter.completeFutureIfPresent("3")).await());
Assert.assertTrue(ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> outputRecords.contains("3")).await());
// only two records have been released
Assert.assertEquals(outputRecords.size(), 2);
// Release record 4 (now in queue)
Assert.assertTrue(
ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> converter.completeFutureIfPresent("4")).await());
Assert.assertTrue(ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> outputRecords.contains("4")).await());
Assert.assertEquals(outputRecords.size(), 3);
// Release records 1 and 2
Assert.assertTrue(
ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> converter.completeFutureIfPresent("1")).await());
Assert.assertTrue(
ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> converter.completeFutureIfPresent("2")).await());
Assert.assertTrue(ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> outputRecords.size() == 5).await());
Assert.assertEquals(outputRecords, Sets.newHashSet("0", "1", "2", "3", "4"));
Assert.assertTrue(errors.isEmpty());
Assert.assertTrue(done.get());
}
@Test
public void testFailedConversion() throws Exception {
MyAsyncConverter1to1 converter = new MyAsyncConverter1to1();
List<Throwable> errors = Lists.newArrayList();
AtomicBoolean done = new AtomicBoolean(false);
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.setProp(AsyncConverter1to1.MAX_CONCURRENT_ASYNC_CONVERSIONS_KEY, 3);
RecordStreamWithMetadata<String, String> stream =
new RecordStreamWithMetadata<>(Flowable.just("0", MyAsyncConverter1to1.FAIL, "1").map(RecordEnvelope::new),
GlobalMetadata.<String>builder().schema("schema").build());
Set<String> outputRecords = Sets.newConcurrentHashSet();
converter.processStream(stream, workUnitState).getRecordStream().subscribeOn(Schedulers.newThread())
.subscribe(r -> outputRecords.add(((RecordEnvelope<String>)r).getRecord()), errors::add, () -> done.set(true));
Assert.assertTrue(ExponentialBackoff.awaitCondition().maxWait(100L).callable(() -> errors.size() > 0).await());
Assert.assertEquals(errors.size(), 1);
Assert.assertEquals(errors.get(0).getCause().getMessage(), "injected failure");
}
public static class MyAsyncConverter1to1 extends AsyncConverter1to1<String, String, String, String> {
public static final String FAIL = "fail";
Map<String, CompletableFuture<String>> futures = Maps.newConcurrentMap();
@Override
public String convertSchema(String inputSchema, WorkUnitState workUnit) throws SchemaConversionException {
return inputSchema;
}
@Override
protected CompletableFuture<String> convertRecordAsync(String outputSchema, String inputRecord, WorkUnitState workUnit)
throws DataConversionException {
CompletableFuture<String> future = new CompletableFuture<>();
if (inputRecord.equals(FAIL)) {
future.completeExceptionally(new DataConversionException("injected failure"));
} else {
this.futures.put(inputRecord, future);
}
return future;
}
public boolean completeFutureIfPresent(String record) {
if (this.futures.containsKey(record)) {
this.futures.get(record).complete(record);
this.futures.remove(record);
return true;
}
return false;
}
}
}
| 4,487 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/SingleRecordIterableTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter;
import java.util.Iterator;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Unit tests for {@link SingleRecordIterable}.
*
* @author Yinan Li
*/
@Test(groups = {"gobblin.converter"})
public class SingleRecordIterableTest {
@Test
public void testIterator() {
String str = "foo";
SingleRecordIterable<String> singleRecordIterable = new SingleRecordIterable<String>(str);
Iterator<String> iterator = singleRecordIterable.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(iterator.next(), str);
Assert.assertFalse(iterator.hasNext());
}
}
| 4,488 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/filter/AvroSchemaFieldRemoverTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter.filter;
import java.io.IOException;
import java.io.InputStream;
import org.apache.avro.Schema;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.io.Closer;
/**
* Tests for {@link AvroSchemaFieldRemover}
*/
@Test(groups = { "gobblin.converter.filter" })
public class AvroSchemaFieldRemoverTest {
@Test
public void testRemoveFields() throws IllegalArgumentException, IOException {
Schema convertedSchema1 = convertSchema("/converter/recursive_schema_1.avsc", "YwchQiH.OjuzrLOtmqLW");
Schema expectedSchema1 = parseSchema("/converter/recursive_schema_1_converted.avsc");
Assert.assertEquals(convertedSchema1.toString(), expectedSchema1.toString());
Schema convertedSchema2 =
convertSchema("/converter/recursive_schema_2.avsc", "FBuKC.wIINqII.lvaerUEKxBQUWg,eFQjDj.TzuYZajb");
Schema expectedSchema2 = parseSchema("/converter/recursive_schema_2_converted.avsc");
Assert.assertEquals(convertedSchema2.toString(), expectedSchema2.toString());
Schema convertedSchema3 = convertSchema("/converter/recursive_schema_2.avsc", "field.that.does.not.exist");
Schema expectedSchema3 = parseSchema("/converter/recursive_schema_2_not_converted.avsc");
Assert.assertEquals(convertedSchema3.toString(), expectedSchema3.toString());
}
private Schema parseSchema(String schemaFile) throws IOException {
Closer closer = Closer.create();
try {
InputStream in = closer.register(getClass().getResourceAsStream(schemaFile));
return new Schema.Parser().parse(in);
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
private Schema convertSchema(String schemaFile, String fieldsToRemove) throws IllegalArgumentException, IOException {
Schema originalSchema = parseSchema(schemaFile);
return new AvroSchemaFieldRemover(fieldsToRemove).removeFields(originalSchema);
}
}
| 4,489 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/filter/GobblinTrackingEventFlattenFilterConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter.filter;
import java.io.IOException;
import java.util.Properties;
import org.apache.avro.Schema;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.converter.SchemaConversionException;
/**
* Test for {@link GobblinTrackingEventFlattenFilterConverter}.
*/
public class GobblinTrackingEventFlattenFilterConverterTest {
@Test
public void testSchemaConversion()
throws SchemaConversionException, IOException {
GobblinTrackingEventFlattenFilterConverter converter = new GobblinTrackingEventFlattenFilterConverter();
Properties props = new Properties();
props.put(GobblinTrackingEventFlattenFilterConverter.class.getSimpleName() + "."
+ GobblinTrackingEventFlattenFilterConverter.FIELDS_TO_FLATTEN, "field1,field2");
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.addAll(props);
converter.init(workUnitState);
Schema output = converter.convertSchema(
new Schema.Parser().parse(getClass().getClassLoader().getResourceAsStream("GobblinTrackingEvent.avsc")),
workUnitState);
Schema parsedSchema = new Schema.Parser().parse(
"{\"type\":\"record\",\"name\":\"GobblinTrackingEvent\",\"namespace\":\"org.apache.gobblin.metrics\",\"fields\":"
+ "[{\"name\":\"timestamp\",\"type\":\"long\",\"doc\":\"Time at which event was created.\",\"default\":0},"
+ "{\"name\":\"namespace\",\"type\":[\"string\",\"null\"],\"doc\":\"Namespace used for filtering of events.\"},"
+ "{\"name\":\"name\",\"type\":\"string\",\"doc\":\"Event name.\"},{\"name\":\"field1\",\"type\":\"string\",\"doc\":\"\"},"
+ "{\"name\":\"field2\",\"type\":\"string\",\"doc\":\"\"}]}");
Assert.assertEquals(output.toString(), parsedSchema.toString());
props.put(GobblinTrackingEventFlattenFilterConverter.class.getSimpleName() + "."
+ GobblinTrackingEventFlattenFilterConverter.FIELDS_RENAME_MAP, "name:eventName,field1:field3");
WorkUnitState workUnitState2 = new WorkUnitState();
workUnitState2.addAll(props);
converter.init(workUnitState2);
Schema output2 = converter.convertSchema(
new Schema.Parser().parse(getClass().getClassLoader().getResourceAsStream("GobblinTrackingEvent.avsc")),
workUnitState2);
parsedSchema = new Schema.Parser().parse(
"{\"type\":\"record\",\"name\":\"GobblinTrackingEvent\",\"namespace\":\"org.apache.gobblin.metrics\",\"fields\":"
+ "[{\"name\":\"timestamp\",\"type\":\"long\",\"doc\":\"Time at which event was created.\",\"default\":0},"
+ "{\"name\":\"namespace\",\"type\":[\"string\",\"null\"],\"doc\":\"Namespace used for filtering of events.\"},"
+ "{\"name\":\"eventName\",\"type\":\"string\",\"doc\":\"Event name.\"},{\"name\":\"field3\",\"type\":\"string\",\"doc\":\"\"},"
+ "{\"name\":\"field2\",\"type\":\"string\",\"doc\":\"\"}]}");
Assert.assertEquals(output2.toString(), parsedSchema.toString());
}
}
| 4,490 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/converter/filter/AvroProjectionConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.converter.filter;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.util.test.TestIOUtils;
public class AvroProjectionConverterTest {
@Test
public void testRemoveWithNamespace()
throws Exception {
WorkUnitState wus = new WorkUnitState();
wus.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, "db1");
wus.setProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, "table1");
wus.setProp(AvroProjectionConverter.USE_NAMESPACE, true);
GenericRecord inputRecord = TestIOUtils.readAllRecords(
getClass().getResource("/avroProjectionConverter/simpleRecord.json").getPath(),
getClass().getResource("/avroProjectionConverter/simpleRecord.avsc").getPath()).get(0);
Schema inputSchema = inputRecord.getSchema();
AvroProjectionConverter converter = new AvroProjectionConverter();
// Test no field removed with table1.remove.fields
wus.setProp("table1.remove.fields", "id");
converter.init(wus);
Schema outputSchema = converter.convertSchema(inputSchema, wus);
Assert.assertEquals(outputSchema.getFields().size(), 2);
// Field successfully removed
wus.setProp("db1.table1.remove.fields", "id");
converter.init(wus);
outputSchema = converter.convertSchema(inputSchema, wus);
Assert.assertEquals(outputSchema.getFields().size(), 1);
GenericRecord outputRecord = converter.convertRecord(outputSchema, inputRecord, wus).iterator().next();
Assert.assertEquals(outputRecord.toString(), "{\"created\": 20170906185911}");
}
}
| 4,491 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/source/extractor | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/source/extractor/extract/AbstractSourceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.source.extractor.extract;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.configuration.WorkUnitState.WorkingState;
import org.apache.gobblin.source.extractor.Extractor;
import org.apache.gobblin.source.workunit.WorkUnit;
@Test(groups = { "gobblin.source.extractor.extract" })
public class AbstractSourceTest {
private TestSource<String, String> testSource;
private List<WorkUnitState> previousWorkUnitStates;
private List<WorkUnitState> expectedPreviousWorkUnitStates;
@BeforeClass
public void setUpBeforeClass() {
this.testSource = new TestSource<>();
WorkUnitState committedWorkUnitState = new WorkUnitState();
committedWorkUnitState.setWorkingState(WorkingState.COMMITTED);
WorkUnitState successfulWorkUnitState = new WorkUnitState();
successfulWorkUnitState.setWorkingState(WorkingState.SUCCESSFUL);
WorkUnitState failedWorkUnitState = new WorkUnitState();
failedWorkUnitState.setWorkingState(WorkingState.FAILED);
this.previousWorkUnitStates =
Lists.newArrayList(committedWorkUnitState, successfulWorkUnitState, failedWorkUnitState);
this.expectedPreviousWorkUnitStates = Lists.newArrayList(successfulWorkUnitState, failedWorkUnitState);
}
/**
* Test the never-retry policy.
*/
@Test
public void testGetPreviousWorkUnitStatesNeverRetry() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "never");
Assert.assertEquals(this.testSource.getPreviousWorkUnitStatesForRetry(sourceState), Collections.EMPTY_LIST);
}
/**
* Test when work unit retry disabled.
*/
@Test
public void testGetPreviousWorkUnitStatesDisabledRetry() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_ENABLED_KEY, Boolean.FALSE);
Assert.assertEquals(this.testSource.getPreviousWorkUnitStatesForRetry(sourceState), Collections.EMPTY_LIST);
}
/**
* Test when work unit retry policy is on partial, but the job commit policy is "full".
*/
@Test
public void testGetPreviousWorkUnitStatesOnPartialRetryFullCommit() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "onpartial");
sourceState.setProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "full");
Assert.assertEquals(this.testSource.getPreviousWorkUnitStatesForRetry(sourceState), Collections.EMPTY_LIST);
}
/**
* Test when work unit retry policy is on full, but the job commit policy is "partial".
*/
@Test
public void testGetPreviousWorkUnitStatesOnFullRetryPartialCommit() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "onfull");
sourceState.setProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "partial");
Assert.assertEquals(this.testSource.getPreviousWorkUnitStatesForRetry(sourceState), Collections.EMPTY_LIST);
}
/**
* Test when work unit retry policy is on full, and the job commit policy is "full".
*/
@Test
public void testGetPreviousWorkUnitStatesOnFullRetryFullCommit() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "onfull");
sourceState.setProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "full");
List<WorkUnitState> returnedWorkUnitStates = this.testSource.getPreviousWorkUnitStatesForRetry(sourceState);
Assert.assertEquals(returnedWorkUnitStates, this.expectedPreviousWorkUnitStates);
}
/**
* Test when work unit retry policy is on partial, and the job commit policy is "partial".
*/
@Test
public void testGetPreviousWorkUnitStatesOnPartialRetryPartialCommit() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "onpartial");
sourceState.setProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "partial");
List<WorkUnitState> returnedWorkUnitStates = this.testSource.getPreviousWorkUnitStatesForRetry(sourceState);
Assert.assertEquals(returnedWorkUnitStates, this.expectedPreviousWorkUnitStates);
}
/**
* Test the always-retry policy, with WORK_UNIT_RETRY_ENABLED_KEY enabled.
*/
@Test
public void testGetPreviousWorkUnitStatesEnabledRetry() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_ENABLED_KEY, Boolean.TRUE);
List<WorkUnitState> returnedWorkUnitStates = this.testSource.getPreviousWorkUnitStatesForRetry(sourceState);
Assert.assertEquals(returnedWorkUnitStates, this.expectedPreviousWorkUnitStates);
}
/**
* Test under always-retry policy, the overwrite_configs_in_statestore enabled.
* The previous workUnitState should be reset with the config in the current source.
*/
@Test
public void testGetPreviousWorkUnitStatesWithConfigOverWrittenEnabled() {
for (WorkUnitState workUnitState : this.previousWorkUnitStates) {
workUnitState.setProp("a", "3");
workUnitState.setProp("b", "4");
}
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "always");
sourceState.setProp(ConfigurationKeys.OVERWRITE_CONFIGS_IN_STATESTORE, Boolean.TRUE);
// random properties for test
sourceState.setProp("a", "1");
sourceState.setProp("b", "2");
List<WorkUnitState> returnedWorkUnitStates = this.testSource.getPreviousWorkUnitStatesForRetry(sourceState);
for (WorkUnitState workUnitState : returnedWorkUnitStates) {
Assert.assertEquals(workUnitState.getProp("a"), "1");
Assert.assertEquals(workUnitState.getProp("b"), "2");
}
}
/**
* Test under always-retry policy, the overwrite_configs_in_statestore disabled (default).
* The previous workUnitState would not be reset with the config in the current source.
*/
@Test
public void testGetPreviousWorkUnitStatesWithConfigOverWrittenDisabled() {
SourceState sourceState = new SourceState(new State(), this.previousWorkUnitStates);
sourceState.setProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY, "always");
// random properties for test
sourceState.setProp("a", "1");
sourceState.setProp("b", "2");
List<WorkUnitState> returnedWorkUnitStates = this.testSource.getPreviousWorkUnitStatesForRetry(sourceState);
Assert.assertEquals(returnedWorkUnitStates, this.expectedPreviousWorkUnitStates);
for (WorkUnitState workUnitState : returnedWorkUnitStates) {
Assert.assertEquals(workUnitState.contains("a"), false);
Assert.assertEquals(workUnitState.contains("b"), false);
}
}
// Class for test AbstractSource
public class TestSource<S, D> extends AbstractSource<S, D> {
@Override
public List<WorkUnit> getWorkunits(SourceState state) {
return null;
}
@Override
public Extractor<S, D> getExtractor(WorkUnitState state) throws IOException {
return null;
}
@Override
public void shutdown(SourceState state) {
}
}
}
| 4,492 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/writer/FineGrainedWatermarkTrackerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.writer;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.source.extractor.CheckpointableWatermark;
import org.apache.gobblin.source.extractor.DefaultCheckpointableWatermark;
import org.apache.gobblin.source.extractor.extract.LongWatermark;
import org.apache.gobblin.util.ExecutorsUtils;
@Slf4j
@Test
public class FineGrainedWatermarkTrackerTest {
/**
* Single threaded test that creates attempts, acknowledges a few at random
* then checks if the getCommitables method is returning the right values.
* Runs a few iterations.
*/
@Test
public static void testWatermarkTracker() {
Random random = new Random();
Config config = ConfigFactory.empty();
for (int j =0; j < 100; ++j) {
FineGrainedWatermarkTracker tracker = new FineGrainedWatermarkTracker(config);
int numWatermarks = 1 + random.nextInt(1000);
AcknowledgableWatermark[] acknowledgableWatermarks = new AcknowledgableWatermark[numWatermarks];
for (int i = 0; i < numWatermarks; ++i) {
CheckpointableWatermark checkpointableWatermark = new DefaultCheckpointableWatermark("default", new LongWatermark(i));
AcknowledgableWatermark ackable = new AcknowledgableWatermark(checkpointableWatermark);
acknowledgableWatermarks[i] = ackable;
tracker.track(ackable);
}
// Create some random holes. Don't fire acknowledgements for these messages.
int numMissingAcks = random.nextInt(numWatermarks);
SortedSet<Integer> holes = new TreeSet<>();
for (int i = 0; i < numMissingAcks; ++i) {
holes.add(random.nextInt(numWatermarks));
}
for (int i = 0; i < numWatermarks; ++i) {
if (!holes.contains(i)) {
acknowledgableWatermarks[i].ack();
}
}
verifyCommitables(tracker, holes, numWatermarks-1);
// verify that sweeping doesn't have any side effects on correctness
tracker.sweep();
verifyCommitables(tracker, holes, numWatermarks-1);
}
}
private static void verifyCommitables(FineGrainedWatermarkTracker tracker, SortedSet<Integer> holes, long maxWatermark) {
// commitable should be the first hole -1
// uncommitable should be the first hole
Map<String, CheckpointableWatermark> uncommitted = tracker.getUnacknowledgedWatermarks();
if (holes.isEmpty()) {
Assert.assertEquals(uncommitted.size(), 0);
} else {
Assert.assertEquals(uncommitted.size(), 1);
CheckpointableWatermark uncommitable = uncommitted.get("default");
Assert.assertEquals(((LongWatermark) uncommitable.getWatermark()).getValue(), (long) holes.first());
}
Map<String, CheckpointableWatermark> commitables = tracker.getCommittableWatermarks();
if (holes.contains(0)) {
// if the first record didn't get an ack
Assert.assertEquals(commitables.size(), 0);
} else {
Assert.assertEquals(commitables.size(), 1);
CheckpointableWatermark commitable = commitables.get("default");
if (holes.isEmpty()) {
Assert.assertEquals(((LongWatermark) commitable.getWatermark()).getValue(), maxWatermark);
} else {
Assert.assertEquals(((LongWatermark) commitable.getWatermark()).getValue(), holes.first() - 1);
}
}
}
/**
* Tests that sweep is sweeping the correct number of entries.
*/
@Test
public static void testSweep() {
Random random = new Random();
for (int j =0; j < 1000; ++j) {
FineGrainedWatermarkTracker tracker = new FineGrainedWatermarkTracker(ConfigFactory.empty());
tracker.setAutoStart(false);
int numWatermarks = 1+random.nextInt(1000);
AcknowledgableWatermark[] acknowledgableWatermarks = new AcknowledgableWatermark[numWatermarks];
for (int i = 0; i < numWatermarks; ++i) {
CheckpointableWatermark checkpointableWatermark = new DefaultCheckpointableWatermark("default", new LongWatermark(i));
AcknowledgableWatermark ackable = new AcknowledgableWatermark(checkpointableWatermark);
acknowledgableWatermarks[i] = ackable;
tracker.track(ackable);
}
int numMissingAcks = random.nextInt(numWatermarks);
SortedSet<Integer> holes = new TreeSet<>();
for (int i = 0; i < numMissingAcks; ++i) {
holes.add(random.nextInt(numWatermarks));
}
for (int i = 0; i < numWatermarks; ++i) {
if (!holes.contains(i)) {
acknowledgableWatermarks[i].ack();
}
}
verifyCommitables(tracker, holes, numWatermarks - 1);
int swept = tracker.sweep();
if (holes.isEmpty()) {
Assert.assertEquals(swept, numWatermarks -1);
} else {
if (holes.contains(0)) {
Assert.assertEquals(swept, 0);
} else {
Assert.assertEquals(swept, holes.first() - 1);
}
}
verifyCommitables(tracker, holes, numWatermarks - 1);
}
}
/**
* A concurrent test, attempts fired in a single thread, but acks come in from multiple threads,
* out of order.
*
*/
@Test
public static void testConcurrentWatermarkTracker()
throws IOException, InterruptedException {
Random random = new Random();
ScheduledExecutorService ackingService = new ScheduledThreadPoolExecutor(100, ExecutorsUtils.defaultThreadFactory());
for (int j =0; j < 100; ++j) {
FineGrainedWatermarkTracker tracker = new FineGrainedWatermarkTracker(ConfigFactory.empty());
tracker.start();
int numWatermarks = 1 + random.nextInt(1000);
AcknowledgableWatermark[] acknowledgableWatermarks = new AcknowledgableWatermark[numWatermarks];
SortedSet<Integer> holes = new TreeSet<>();
final AtomicInteger numAcks = new AtomicInteger(0);
for (int i = 0; i < numWatermarks; ++i) {
CheckpointableWatermark checkpointableWatermark = new DefaultCheckpointableWatermark("default", new LongWatermark(i));
final AcknowledgableWatermark ackable = new AcknowledgableWatermark(checkpointableWatermark);
tracker.track(ackable);
acknowledgableWatermarks[i] = ackable;
// ack or not
boolean ack = random.nextBoolean();
if (ack) {
numAcks.incrementAndGet();
long sleepTime = random.nextInt(100);
ackingService.schedule(new Callable<Object>() {
@Override
public Object call()
throws Exception {
ackable.ack();
numAcks.decrementAndGet();
return null;
}
}, sleepTime, TimeUnit.MILLISECONDS);
} else {
holes.add(i);
}
}
while (numAcks.get() != 0) {
log.info("Waiting for " + numAcks.get() + " acks");
Thread.sleep(100);
}
verifyCommitables(tracker, holes, numWatermarks-1);
tracker.close();
}
}
}
| 4,493 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/writer/WatermarkTrackerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.writer;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.gobblin.source.extractor.DefaultCheckpointableWatermark;
import org.apache.gobblin.source.extractor.extract.LongWatermark;
@Test
public class WatermarkTrackerTest {
private void commits(WatermarkTracker watermarkTracker, String source, int... commit)
{
for (int oneCommit: commit) {
watermarkTracker.committedWatermark(new DefaultCheckpointableWatermark(source, new LongWatermark(oneCommit)));
}
}
@Test
public void testSingleSource() {
MultiWriterWatermarkTracker watermarkTracker = new MultiWriterWatermarkTracker();
commits(watermarkTracker, "default", 0, 4, 5, 6);
Assert.assertEquals(watermarkTracker.getCommittableWatermark("default").get().getSource(), "default");
Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("default")
.get().getWatermark()).getValue(), 6L);
}
@Test
public void testMultiSource() {
MultiWriterWatermarkTracker watermarkTracker = new MultiWriterWatermarkTracker();
commits(watermarkTracker, "default", 0, 4, 5, 6);
commits(watermarkTracker, "other", 1, 3, 5, 7);
Assert.assertEquals(watermarkTracker.getCommittableWatermark("default").get().getSource(), "default");
Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("default")
.get().getWatermark()).getValue(), 6L);
Assert.assertEquals(watermarkTracker.getCommittableWatermark("other").get().getSource(), "other");
Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("other")
.get().getWatermark()).getValue(), 7L);
}
}
| 4,494 |
0 | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/test/java/org/apache/gobblin/writer/AsyncWriterManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.writer;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.avro.generic.GenericRecord;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.base.Throwables;
import com.typesafe.config.ConfigFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.metrics.RootMetricContext;
import org.apache.gobblin.metrics.reporter.OutputStreamReporter;
import org.apache.gobblin.test.ConstantTimingType;
import org.apache.gobblin.test.ErrorManager;
import org.apache.gobblin.test.NthTimingType;
import org.apache.gobblin.test.TestUtils;
import org.apache.gobblin.test.TimingManager;
import org.apache.gobblin.test.TimingResult;
import org.apache.gobblin.test.TimingType;
@Slf4j
public class AsyncWriterManagerTest {
class FakeTimedAsyncWriter implements AsyncDataWriter {
TimingManager timingManager;
public FakeTimedAsyncWriter(TimingManager timingManager) {
this.timingManager = timingManager;
}
@Override
public Future<WriteResponse> write(final Object record, final WriteCallback callback) {
final TimingResult result = this.timingManager.nextTime();
log.debug("sync: " + result.isSync + " time : " + result.timeValueMillis);
final FutureWrappedWriteCallback futureCallback = new FutureWrappedWriteCallback(callback);
if (result.isSync) {
try {
Thread.sleep(result.timeValueMillis);
} catch (InterruptedException e) {
}
futureCallback.onSuccess(new GenericWriteResponse(record));
} else {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
log.debug("Sleeping for ms: " + result.timeValueMillis);
Thread.sleep(result.timeValueMillis);
} catch (InterruptedException e) {
}
futureCallback.onSuccess(new GenericWriteResponse(record));
}
});
t.setDaemon(true);
t.start();
}
return futureCallback;
}
@Override
public void flush()
throws IOException {
}
@Override
public void close()
throws IOException {
}
}
@Test (enabled=false)
public void testSlowWriters()
throws Exception {
// Every call incurs 1s latency, commit timeout is 40s
testAsyncWrites(new ConstantTimingType(1000), 40000, 0, true);
// Every call incurs 10s latency, commit timeout is 4s
testAsyncWrites(new ConstantTimingType(10000), 4000, 0, false);
// Every 7th call incurs 10s latency, every other call incurs 1s latency
testAsyncWrites(new NthTimingType(7, 1000, 10000), 4000, 0, false);
// Every 7th call incurs 10s latency, every other call incurs 1s latency, failures allowed < 11%
testAsyncWrites(new NthTimingType(7, 1000, 10000), 4000, 11, true);
}
private void testAsyncWrites(TimingType timingType, long commitTimeoutInMillis, double failurePercentage,
boolean success) {
TimingManager timingManager = new TimingManager(false, timingType);
AsyncDataWriter fakeTimedAsyncWriter = new FakeTimedAsyncWriter(timingManager);
AsyncWriterManager asyncWriter = AsyncWriterManager.builder().config(ConfigFactory.empty())
.commitTimeoutMillis(commitTimeoutInMillis).failureAllowanceRatio(failurePercentage / 100.0)
.asyncDataWriter(fakeTimedAsyncWriter).build();
try {
for (int i = 0; i < 10; i++) {
asyncWriter.write(TestUtils.generateRandomBytes());
}
} catch (Exception e) {
Assert.fail("Should not throw any Exception");
}
try {
asyncWriter.commit();
if (!success) {
Assert.fail("Commit should not succeed");
}
} catch (IOException e) {
if (success) {
Assert.fail("Commit should not throw IOException");
}
} catch (Exception e) {
Assert.fail("Should not throw any exception other than IOException");
}
try {
asyncWriter.close();
} catch (Exception e) {
Assert.fail("Should not throw any exception on close");
}
}
public class FlakyAsyncWriter<D> implements AsyncDataWriter<D> {
private final ErrorManager errorManager;
public FlakyAsyncWriter(ErrorManager errorManager) {
this.errorManager = errorManager;
}
@Override
public Future<WriteResponse> write(final D record, WriteCallback callback) {
final boolean error = this.errorManager.nextError(record);
final FutureWrappedWriteCallback futureWrappedWriteCallback = new FutureWrappedWriteCallback(callback);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
if (error) {
final Exception e = new Exception();
futureWrappedWriteCallback.onFailure(e);
} else {
futureWrappedWriteCallback.onSuccess(new GenericWriteResponse(record));
}
}
});
t.setDaemon(true);
t.start();
return futureWrappedWriteCallback;
}
@Override
public void flush()
throws IOException {
}
@Override
public void close()
throws IOException {
}
}
@Test (enabled=false)
public void testCompleteFailureMode()
throws Exception {
FlakyAsyncWriter flakyAsyncWriter = new FlakyAsyncWriter(
org.apache.gobblin.test.ErrorManager.builder().errorType(org.apache.gobblin.test.ErrorManager.ErrorType.ALL).build());
AsyncWriterManager asyncWriterManager =
AsyncWriterManager.builder().asyncDataWriter(flakyAsyncWriter).retriesEnabled(true).numRetries(5).build();
byte[] messageBytes = TestUtils.generateRandomBytes();
asyncWriterManager.write(messageBytes);
try {
asyncWriterManager.commit();
} catch (IOException e) {
// ok for commit to throw exception
} finally {
asyncWriterManager.close();
}
Assert.assertEquals(asyncWriterManager.recordsIn.getCount(), 1);
Assert.assertEquals(asyncWriterManager.recordsAttempted.getCount(), 6);
Assert.assertEquals(asyncWriterManager.recordsSuccess.getCount(), 0);
Assert.assertEquals(asyncWriterManager.recordsWritten(), 0);
Assert.assertEquals(asyncWriterManager.recordsFailed.getCount(), 1);
}
@Test (enabled=false)
public void testFlakyWritersWithRetries()
throws Exception {
FlakyAsyncWriter flakyAsyncWriter = new FlakyAsyncWriter(
org.apache.gobblin.test.ErrorManager.builder().errorType(ErrorManager.ErrorType.NTH).errorEvery(4).build());
AsyncWriterManager asyncWriterManager =
AsyncWriterManager.builder().asyncDataWriter(flakyAsyncWriter).retriesEnabled(true).numRetries(5).build();
for (int i = 0; i < 100; ++i) {
byte[] messageBytes = TestUtils.generateRandomBytes();
asyncWriterManager.write(messageBytes);
}
try {
asyncWriterManager.commit();
} catch (IOException e) {
// ok for commit to throw exception
} finally {
asyncWriterManager.close();
}
log.info(asyncWriterManager.recordsAttempted.getCount() + "");
Assert.assertEquals(asyncWriterManager.recordsIn.getCount(), 100);
Assert.assertTrue(asyncWriterManager.recordsAttempted.getCount() > 100);
Assert.assertEquals(asyncWriterManager.recordsSuccess.getCount(), 100);
Assert.assertEquals(asyncWriterManager.recordsFailed.getCount(), 0);
}
/**
* In the presence of lots of failures, the manager should slow down
* and not overwhelm the system.
*/
@Test (enabled=false)
public void testFlowControlWithWriteFailures()
throws Exception {
FlakyAsyncWriter flakyAsyncWriter =
new FlakyAsyncWriter(org.apache.gobblin.test.ErrorManager.builder().errorType(ErrorManager.ErrorType.ALL).build());
int maxOutstandingWrites = 2000;
final AsyncWriterManager asyncWriterManager =
AsyncWriterManager.builder().asyncDataWriter(flakyAsyncWriter).retriesEnabled(true).numRetries(5)
.maxOutstandingWrites(maxOutstandingWrites).failureAllowanceRatio(1.0) // ok to fail all the time
.build();
boolean verbose = false;
if (verbose) {
// Create a reporter for metrics. This reporter will write metrics to STDOUT.
OutputStreamReporter.Factory.newBuilder().build(new Properties());
// Start all metric reporters.
RootMetricContext.get().startReporting();
}
final int load = 10000; // 10k records per sec
final long tickDiffInNanos = (1000 * 1000 * 1000) / load;
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
GenericRecord record = TestUtils.generateRandomAvroRecord();
try {
asyncWriterManager.write(record);
} catch (IOException e) {
log.error("Failure during write", e);
Throwables.propagate(e);
}
}
}, 0, tickDiffInNanos, TimeUnit.NANOSECONDS);
LinkedBlockingQueue retryQueue = (LinkedBlockingQueue) asyncWriterManager.retryQueue.get();
int sleepTime = 100;
int totalTime = 10000;
for (int i = 0; i < (totalTime / sleepTime); ++i) {
Thread.sleep(sleepTime);
int retryQueueSize = retryQueue.size();
Assert.assertTrue(retryQueueSize <= (maxOutstandingWrites + 1),
"Retry queue should never exceed the " + "maxOutstandingWrites. Found " + retryQueueSize);
log.debug("Retry queue size = {}", retryQueue.size());
}
scheduler.shutdown();
asyncWriterManager.commit();
long recordsIn = asyncWriterManager.recordsIn.getCount();
long recordsAttempted = asyncWriterManager.recordsAttempted.getCount();
String msg = String.format("recordsIn = %d, recordsAttempted = %d.", recordsIn, recordsAttempted);
log.info(msg);
Assert.assertTrue(recordsAttempted > recordsIn, "There must have been a bunch of failures");
Assert.assertTrue(retryQueue.size() == 0, "Retry queue should be empty");
}
}
| 4,495 |
0 | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/StandardMetricsBridge.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.gobblin.metrics.ContextAwareMetric;
/**
* This interface indicates a class will expose its metrics to some external systems.
*/
public interface StandardMetricsBridge {
/**
* Get multiple standard metrics.
*/
default Collection<StandardMetrics> getStandardMetricsCollection() {
return ImmutableList.of();
}
class StandardMetrics implements MetricSet {
protected final List<ContextAwareMetric> contextAwareMetrics;
protected final Map<String, Metric> rawMetrics;
public StandardMetrics() {
this.contextAwareMetrics = Lists.newArrayList();
this.rawMetrics = Maps.newHashMap();
}
public String getName() {
return this.getClass().getName();
}
public Collection<ContextAwareMetric> getContextAwareMetrics() {
return contextAwareMetrics;
}
public Map<String, Metric> getMetrics() {
return rawMetrics;
}
}
}
| 4,496 |
0 | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/GobblinMetricsKeys.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented;
import org.apache.gobblin.Constructs;
/**
* Shared constants related to gobblin metrics
*/
public class GobblinMetricsKeys {
/** The FQN of the class that emitted a tracking event */
public static final String CLASS_META = "class";
/** The gobblin construct that emitted the event
* @see Constructs */
public static final String CONSTRUCT_META = "construct";
// JobSpec related keys
/** The JobSpec URI for which the tracking event is */
public static final String JOB_SPEC_URI_META = "jobSpecURI";
/** The version of the JobSpec for which the tracking event is */
public static final String JOB_SPEC_VERSION_META = "jobSpecVersion";
// Generic keys
public static final String OPERATION_TYPE_META = "operationType";
// FlowSpec related keys
/** The FlowSpec URI for which the tracking event is */
public static final String SPEC_URI_META = "flowSpecURI";
/** The version of the FlowSpec for which the tracking event is */
public static final String SPEC_VERSION_META = "flowSpecVersion";
}
| 4,497 |
0 | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/Instrumentable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
/**
* Interface for classes instrumenting their execution into a {@link org.apache.gobblin.metrics.MetricContext}.
*/
public interface Instrumentable {
/**
* Get {@link org.apache.gobblin.metrics.MetricContext} containing metrics related to this Instrumentable.
* @return an instance of {@link org.apache.gobblin.metrics.MetricContext}.
*/
@Nonnull
public MetricContext getMetricContext();
/**
* Returns true if instrumentation is activated.
* @return true if instrumentation is enabled, false otherwise.
*/
public boolean isInstrumentationEnabled();
/**
* Generate tags that should be added to the {@link org.apache.gobblin.metrics.MetricContext}.
* @return List of tags to add to {@link org.apache.gobblin.metrics.MetricContext}.
*/
public List<Tag<?>> generateTags(State state);
/**
* Generate a new {@link org.apache.gobblin.metrics.MetricContext} replacing old {@link org.apache.gobblin.metrics.Tag} with input
* {@link org.apache.gobblin.metrics.Tag} (only tags with the same keys will be replaced),
* and recreate all metrics in this new context.
*
* <p>
* This method is useful when the state of the {@link org.apache.gobblin.instrumented.Instrumentable} changes and the user
* wants that state change to be reflected in the tags of the instrumentation.
* </p>
*
* <p>
* Notice that this method creates a brand new {@link org.apache.gobblin.metrics.MetricContext} and {@link org.apache.gobblin.metrics.Metric}
* every time it is called,
* with the associated processing and memory overhead. Use sparingly only for state changes that must be visible in
* emitted metrics.
* </p>
*
* @param tags additional {@link org.apache.gobblin.metrics.Tag}.
*/
public void switchMetricContext(List<Tag<?>> tags);
/**
* Switches the existing {@link org.apache.gobblin.metrics.MetricContext} with the supplied metric context and regenerates
* {@link org.apache.gobblin.metrics.Metric}.
*
* <p>
* This method is useful when the state of the {@link org.apache.gobblin.instrumented.Instrumentable} changes and the user
* wants that state change to be reflected in the set of {@link org.apache.gobblin.metrics.Tag} of the instrumentation.
* </p>
*
* <p>
* This method is an alternative to {@link #switchMetricContext(List)} when metric context switching is done
* often between a small set of contexts. The subclass should keep a list of previously generated contexts as a cache,
* and call this method to simply switch between the different contexts,
* avoiding the overhead of generating a brand new context every time a metric context switch is required.
* </p>
*
* @param context new {@link org.apache.gobblin.metrics.MetricContext}.
*/
public void switchMetricContext(MetricContext context);
}
| 4,498 |
0 | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/Instrumented.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.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 org.apache.gobblin.instrumented;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Closer;
import org.apache.gobblin.Constructs;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.converter.Converter;
import org.apache.gobblin.fork.ForkOperator;
import org.apache.gobblin.metrics.GobblinMetrics;
import org.apache.gobblin.metrics.GobblinMetricsRegistry;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.Tag;
import org.apache.gobblin.qualitychecker.row.RowLevelPolicy;
import org.apache.gobblin.source.extractor.Extractor;
import org.apache.gobblin.util.DecoratorUtils;
import org.apache.gobblin.writer.DataWriter;
/**
* Provides simple instrumentation for gobblin-core components.
*
* <p>
* Creates {@link org.apache.gobblin.metrics.MetricContext}. Tries to read the name of the parent context
* from key "metrics.context.name" at state, and tries to get the parent context by name from
* the {@link org.apache.gobblin.metrics.MetricContext} registry (the parent context must be registered).
* </p>
*
* <p>
* Automatically adds two tags to the inner context:
* <ul>
* <li> component: attempts to determine which component type within gobblin-api generated this instance. </li>
* <li> class: the specific class of the object that generated this instance of Instrumented </li>
* </ul>
* </p>
*
*/
public class Instrumented implements Instrumentable, Closeable {
public static final String METRIC_CONTEXT_NAME_KEY = ConfigurationKeys.METRIC_CONTEXT_NAME_KEY;
public static final Random RAND = new Random();
private final boolean instrumentationEnabled;
protected MetricContext metricContext;
protected final Closer closer;
/**
* Gets metric context with no additional tags.
* See {@link #getMetricContext(State, Class, List)}
*/
public static MetricContext getMetricContext(State state, Class<?> klazz) {
return getMetricContext(state, klazz, new ArrayList<Tag<?>>());
}
/**
* Get a {@link org.apache.gobblin.metrics.MetricContext} to be used by an object needing instrumentation.
*
* <p>
* This method will read the property "metrics.context.name" from the input State, and will attempt
* to find a MetricContext with that name in the global instance of {@link org.apache.gobblin.metrics.GobblinMetricsRegistry}.
* If it succeeds, the generated MetricContext will be a child of the retrieved Context, otherwise it will
* be a parent-less context.
* </p>
* <p>
* The method will automatically add two tags to the context:
* <ul>
* <li> construct will contain the name of the {@link org.apache.gobblin.Constructs} that klazz represents. </li>
* <li> class will contain the canonical name of the input class. </li>
* </ul>
* </p>
*
* @param state {@link org.apache.gobblin.configuration.State} used to find the parent MetricContext.
* @param klazz Class of the object needing instrumentation.
* @param tags Additional tags to add to the returned context.
* @return A {@link org.apache.gobblin.metrics.MetricContext} with the appropriate tags and parent.
*/
public static MetricContext getMetricContext(State state, Class<?> klazz, List<Tag<?>> tags) {
int randomId = RAND.nextInt(Integer.MAX_VALUE);
List<Tag<?>> generatedTags = Lists.newArrayList();
Constructs construct = null;
if (Converter.class.isAssignableFrom(klazz)) {
construct = Constructs.CONVERTER;
} else if (ForkOperator.class.isAssignableFrom(klazz)) {
construct = Constructs.FORK_OPERATOR;
} else if (RowLevelPolicy.class.isAssignableFrom(klazz)) {
construct = Constructs.ROW_QUALITY_CHECKER;
} else if (Extractor.class.isAssignableFrom(klazz)) {
construct = Constructs.EXTRACTOR;
} else if (DataWriter.class.isAssignableFrom(klazz)) {
construct = Constructs.WRITER;
}
if (construct != null) {
generatedTags.add(new Tag<>(GobblinMetricsKeys.CONSTRUCT_META, construct.toString()));
}
if (!klazz.isAnonymousClass()) {
generatedTags.add(new Tag<>(GobblinMetricsKeys.CLASS_META, klazz.getCanonicalName()));
}
Optional<GobblinMetrics> gobblinMetrics = state.contains(METRIC_CONTEXT_NAME_KEY)
? GobblinMetricsRegistry.getInstance().get(state.getProp(METRIC_CONTEXT_NAME_KEY))
: Optional.<GobblinMetrics> absent();
MetricContext.Builder builder = gobblinMetrics.isPresent()
? gobblinMetrics.get().getMetricContext().childBuilder(klazz.getCanonicalName() + "." + randomId)
: MetricContext.builder(klazz.getCanonicalName() + "." + randomId);
return builder.addTags(generatedTags).addTags(tags).build();
}
/**
* Generates a new {@link org.apache.gobblin.metrics.MetricContext} with the parent and tags taken from the reference context.
* Allows replacing {@link org.apache.gobblin.metrics.Tag} with new input tags.
* This method will not copy any {@link org.apache.gobblin.metrics.Metric} contained in the reference {@link org.apache.gobblin.metrics.MetricContext}.
*
* @param context Reference {@link org.apache.gobblin.metrics.MetricContext}.
* @param newTags New {@link org.apache.gobblin.metrics.Tag} to apply to context. Repeated keys will override old tags.
* @param name Name of the new {@link org.apache.gobblin.metrics.MetricContext}.
* If absent or empty, will modify old name by adding a random integer at the end.
* @return Generated {@link org.apache.gobblin.metrics.MetricContext}.
*/
public static MetricContext newContextFromReferenceContext(MetricContext context, List<Tag<?>> newTags,
Optional<String> name) {
String newName = name.orNull();
if (Strings.isNullOrEmpty(newName)) {
UUID uuid = UUID.randomUUID();
String randomIdPrefix = "uuid:";
String oldName = context.getName();
List<String> splitName = Strings.isNullOrEmpty(oldName) ? Lists.<String> newArrayList()
: Lists.newArrayList(Splitter.on(".").splitToList(oldName));
if (splitName.size() > 0 && StringUtils.startsWith(Iterables.getLast(splitName), randomIdPrefix)) {
splitName.set(splitName.size() - 1, String.format("%s%s", randomIdPrefix, uuid.toString()));
} else {
splitName.add(String.format("%s%s", randomIdPrefix, uuid.toString()));
}
newName = Joiner.on(".").join(splitName);
}
MetricContext.Builder builder = context.getParent().isPresent() ? context.getParent().get().childBuilder(newName)
: MetricContext.builder(newName);
return builder.addTags(context.getTags()).addTags(newTags).build();
}
/**
* Determines whether an object or, if it is a {@link org.apache.gobblin.util.Decorator}, any object on its lineage,
* is of class {@link org.apache.gobblin.instrumented.Instrumentable}.
* @param obj Object to analyze.
* @return Whether the lineage is instrumented.
*/
public static boolean isLineageInstrumented(Object obj) {
List<Object> lineage = DecoratorUtils.getDecoratorLineage(obj);
for (Object node : lineage) {
if (node instanceof Instrumentable) {
return true;
}
}
return false;
}
/**
* Returns a {@link com.codahale.metrics.Timer.Context} only if {@link org.apache.gobblin.metrics.MetricContext} is defined.
* @param context an Optional<{@link org.apache.gobblin.metrics.MetricContext}$gt;
* @param name name of the timer.
* @return an Optional<{@link com.codahale.metrics.Timer.Context}$gt;
*/
public static Optional<Timer.Context> timerContext(Optional<MetricContext> context, final String name) {
return context.transform(new Function<MetricContext, Timer.Context>() {
@Override
public Timer.Context apply(@Nonnull MetricContext input) {
return input.timer(name).time();
}
});
}
/**
* Ends a {@link com.codahale.metrics.Timer.Context} only if it exists.
* @param timer an Optional<{@link com.codahale.metrics.Timer.Context}$gt;
*/
public static void endTimer(Optional<Timer.Context> timer) {
timer.transform(new Function<Timer.Context, Timer.Context>() {
@Override
public Timer.Context apply(@Nonnull Timer.Context input) {
input.close();
return input;
}
});
}
/**
* Updates a timer only if it is defined.
* @param timer an Optional<{@link com.codahale.metrics.Timer}>
* @param duration
* @param unit
*/
public static void updateTimer(Optional<Timer> timer, final long duration, final TimeUnit unit) {
timer.transform(new Function<Timer, Timer>() {
@Override
public Timer apply(@Nonnull Timer input) {
input.update(duration, unit);
return input;
}
});
}
/**
* Marks a meter only if it is defined.
* @param meter an Optional<{@link com.codahale.metrics.Meter}>
*/
public static void markMeter(Optional<Meter> meter) {
markMeter(meter, 1);
}
/**
* Marks a meter only if it is defined.
* @param meter an Optional<{@link com.codahale.metrics.Meter}>
* @param value value to mark
*/
public static void markMeter(Optional<Meter> meter, final long value) {
meter.transform(new Function<Meter, Meter>() {
@Override
public Meter apply(@Nonnull Meter input) {
input.mark(value);
return input;
}
});
}
/**
* Sets the key {@link #METRIC_CONTEXT_NAME_KEY} to the specified name, in the given {@link State}.
*/
public static void setMetricContextName(State state, String name) {
state.setProp(Instrumented.METRIC_CONTEXT_NAME_KEY, name);
}
public Instrumented(State state, Class<?> klazz) {
this(state, klazz, ImmutableList.<Tag<?>> of());
}
public Instrumented(State state, Class<?> klazz, List<Tag<?>> tags) {
this.closer = Closer.create();
this.instrumentationEnabled = GobblinMetrics.isEnabled(state);
this.metricContext = this.closer.register(getMetricContext(state, klazz, tags));
}
/** Default with no additional tags */
@Override
public List<Tag<?>> generateTags(State state) {
return Lists.newArrayList();
}
@Override
public boolean isInstrumentationEnabled() {
return this.instrumentationEnabled;
}
@Override
public MetricContext getMetricContext() {
return this.metricContext;
}
@Override
public void switchMetricContext(List<Tag<?>> tags) {
this.metricContext = this.closer
.register(Instrumented.newContextFromReferenceContext(this.metricContext, tags, Optional.<String> absent()));
}
@Override
public void switchMetricContext(MetricContext context) {
this.metricContext = context;
}
@Override
public void close() throws IOException {
this.closer.close();
}
}
| 4,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.