From f05bd397ac919948e25a5c75d15b47359f8a0781 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 18:59:12 +0000 Subject: [PATCH 01/26] add toString()s to Metrics classes - MetricKey - MetricName - MetricQueryResults - MetricsContainerStepMap --- .../core/construction/metrics/MetricKey.java | 5 +++ .../core/metrics/MetricsContainerStepMap.java | 5 +++ .../apache/beam/sdk/metrics/MetricName.java | 5 +++ .../beam/sdk/metrics/MetricQueryResults.java | 44 +++++++++++++++++++ 4 files changed, 59 insertions(+) diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java index f4d1e9d4acb6..4bfabe0c125e 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java @@ -34,6 +34,11 @@ public abstract class MetricKey implements Serializable { /** The name of the metric. */ public abstract MetricName metricName(); + @Override + public String toString() { + return String.format("%s:%s", stepName(), metricName()); + } + public static MetricKey create(String stepName, MetricName metricName) { return new AutoValue_MetricKey(stepName, metricName); } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index f2c6f03da738..6a73e679aa05 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -212,6 +212,11 @@ private Function, AttemptedAndCommitted> committedCount }; } + @Override + public String toString() { + return queryMetrics(null).toString(); + } + @Override public MetricQueryResults queryMetrics(@Nullable MetricsFilter filter) { return new QueryResults(filter); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java index 3ffea6ec80a5..ae23ff0c23bd 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java @@ -50,6 +50,11 @@ public String namespace() { /** The name of this metric. */ public abstract String getName(); + @Override + public String toString() { + return String.format("%s:%s", getNamespace(), getName()); + } + /** * The name of this metric. * diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java index baae446174eb..be313e1ffe66 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java @@ -18,8 +18,12 @@ package org.apache.beam.sdk.metrics; import com.google.auto.value.AutoValue; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.List; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; +import org.apache.beam.vendor.grpc.v1p13p1.com.google.common.collect.ImmutableList; /** * The results of a query for metrics. Allows accessing all of the metrics that matched the filter. @@ -36,6 +40,46 @@ public abstract class MetricQueryResults { /** Return the metric results for the getGauges that matched the filter. */ public abstract Iterable> getGauges(); + static void printMetrics(String type, Iterable> metrics, PrintStream ps) { + List> metricsList = ImmutableList.copyOf(metrics); + if (!metricsList.isEmpty()) { + ps.print(type + "("); + // ps.println(metricsList.size() + " " + type + ":"); + boolean first = true; + for (MetricResult metricResult : metricsList) { + if (first) { + first = false; + } else { + ps.print(", "); + } + MetricName name = metricResult.getName(); + ps.print(metricResult.getStep() + ":" + name.getNamespace() + ":" + name.getName()); + ps.print(": "); + ps.print(metricResult.getAttempted()); + try { + T committed = metricResult.getCommitted(); + ps.print(", "); + ps.print(committed); + } catch (UnsupportedOperationException ignored) { + } + } + ps.print(")"); + } + } + + @Override + public String toString() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + ps.print("MetricQueryResults("); + printMetrics("Counters", getCounters(), ps); + printMetrics("Distributions", getDistributions(), ps); + printMetrics("Gauges", getGauges(), ps); + ps.print(")"); + ps.close(); + return baos.toString(); + } + public static MetricQueryResults create( Iterable> counters, Iterable> distributions, From ef44fa2fb9c75a95296dc943f685ef0beb318aa4 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 19:02:37 +0000 Subject: [PATCH 02/26] add MetricResult.result wrapper around committed || attempted --- sdks/python/apache_beam/examples/wordcount.py | 4 ++-- sdks/python/apache_beam/metrics/execution.py | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/sdks/python/apache_beam/examples/wordcount.py b/sdks/python/apache_beam/examples/wordcount.py index e23f46ccbfbd..0945985fa8c7 100644 --- a/sdks/python/apache_beam/examples/wordcount.py +++ b/sdks/python/apache_beam/examples/wordcount.py @@ -122,13 +122,13 @@ def format_result(word_count): query_result = result.metrics().query(empty_lines_filter) if query_result['counters']: empty_lines_counter = query_result['counters'][0] - logging.info('number of empty lines: %d', empty_lines_counter.committed) + logging.info('number of empty lines: %d', empty_lines_counter.result) word_lengths_filter = MetricsFilter().with_name('word_len_dist') query_result = result.metrics().query(word_lengths_filter) if query_result['distributions']: word_lengths_dist = query_result['distributions'][0] - logging.info('average word length: %d', word_lengths_dist.committed.mean) + logging.info('average word length: %d', word_lengths_dist.result.mean) if __name__ == '__main__': diff --git a/sdks/python/apache_beam/metrics/execution.py b/sdks/python/apache_beam/metrics/execution.py index 77e0a884b74b..ba190ff981e9 100644 --- a/sdks/python/apache_beam/metrics/execution.py +++ b/sdks/python/apache_beam/metrics/execution.py @@ -122,6 +122,13 @@ def __repr__(self): return 'MetricResult(key={}, committed={}, attempted={})'.format( self.key, str(self.committed), str(self.attempted)) + @property + def result(self): + """Short-hand for falling back to attempted metrics if it seems that + committed was not populated (e.g. due to not being supported on a given + runner""" + return self.committed if self.committed else self.attempted + class _MetricsEnvironment(object): """Holds the MetricsContainer for every thread and other metric information. From b4b549530730d9e0283ad0cdb203d384a107dfbf Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Mon, 28 Jan 2019 04:02:24 +0000 Subject: [PATCH 03/26] fix MetricQueryResults comments --- .../org/apache/beam/sdk/metrics/MetricQueryResults.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java index be313e1ffe66..639f19d474d8 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricQueryResults.java @@ -31,13 +31,13 @@ @AutoValue @Experimental(Kind.METRICS) public abstract class MetricQueryResults { - /** Return the metric results for the getCounters that matched the filter. */ + /** Return the metric results for the counters that matched the filter. */ public abstract Iterable> getCounters(); - /** Return the metric results for the getDistributions that matched the filter. */ + /** Return the metric results for the distributions that matched the filter. */ public abstract Iterable> getDistributions(); - /** Return the metric results for the getGauges that matched the filter. */ + /** Return the metric results for the gauges that matched the filter. */ public abstract Iterable> getGauges(); static void printMetrics(String type, Iterable> metrics, PrintStream ps) { From ea14497a108836a9167168f3904da0c9a6e2616d Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 18 Jan 2019 16:05:57 -0800 Subject: [PATCH 04/26] Some initial code --- .../core/metrics/MetricsContainerStepMap.java | 14 +++++ .../harness/control/ProcessBundleHandler.java | 53 +++++++++---------- .../data/PTransformFunctionRegistry.java | 23 ++++++-- 3 files changed, 59 insertions(+), 31 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index f2c6f03da738..a136ff8f25e4 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -18,6 +18,7 @@ package org.apache.beam.runners.core.metrics; import java.io.Serializable; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -106,6 +107,19 @@ public static MetricResults asMetricResults( attemptedMetricsContainers, committedMetricsContainers); } + /** Return the cumulative values for any metrics in this container as MonitoringInfos. */ + public Iterable getMonitoringInfos() { + // Extract user metrics and store as MonitoringInfos. + ArrayList monitoringInfos = new ArrayList(); + for (MetricsContainerImpl container : metricsContainers.values()) { + for (MonitoringInfo mi : container.getMonitoringInfos()) { + monitoringInfos.add(mi); + } + } + return monitoringInfos; + } + + /** * Returns {@link MetricResults} based on given {@link MetricsContainerStepMap} of attempted * metrics. diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java index 26f30a898e06..3072e3fbcae6 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java @@ -53,7 +53,9 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; import org.apache.beam.model.pipeline.v1.RunnerApi.WindowingStrategy; import org.apache.beam.runners.core.construction.PTransformTranslation; -import org.apache.beam.runners.core.metrics.MetricsContainerImpl; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; +import org.apache.beam.runners.dataflow.worker.MetricsContainerRegistry; +import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.options.PipelineOptions; @@ -227,8 +229,11 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction PCollectionConsumerRegistry pCollectionConsumerRegistry = new PCollectionConsumerRegistry(); HashSet processedPTransformIds = new HashSet<>(); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry( + metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry( + metricsContainerRegistry); // Build a multimap of PCollection ids to PTransform ids which consume said PCollections for (Map.Entry entry : @@ -293,34 +298,26 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction splitListener); } - // TODO(ajamato): A MetricsContainerImpl should be created and used for each PTransform - // or the metric should be registered in some other way with the ptransform name context, - // not for the instruction. This fails to associate each user counter with an appropriate - // ptransform. - MetricsContainerImpl metricsContainer = new MetricsContainerImpl(request.getInstructionId()); - try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { - - // Already in reverse topological order so we don't need to do anything. - for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { - LOG.debug("Starting function {}", startFunction); - startFunction.run(); - } + // Already in reverse topological order so we don't need to do anything. + for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { + LOG.debug("Starting function {}", startFunction); + startFunction.run(); + } - queueingClient.drainAndBlock(); + queueingClient.drainAndBlock(); - // Need to reverse this since we want to call finish in topological order. - for (ThrowingRunnable finishFunction : - Lists.reverse(finishFunctionRegistry.getFunctions())) { - LOG.debug("Finishing function {}", finishFunction); - finishFunction.run(); - } - if (!allResiduals.isEmpty()) { - response.addAllResidualRoots(allResiduals.values()); - } + // Need to reverse this since we want to call finish in topological order. + for (ThrowingRunnable finishFunction : + Lists.reverse(finishFunctionRegistry.getFunctions())) { + LOG.debug("Finishing function {}", finishFunction); + finishFunction.run(); + } + if (!allResiduals.isEmpty()) { + response.addAllResidualRoots(allResiduals.values()); + } - for (MonitoringInfo mi : metricsContainer.getMonitoringInfos()) { - response.addMonitoringInfos(mi); - } + for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { + response.addMonitoringInfos(mi); } } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java index 6d1e950f3fd6..e32d6249002e 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java @@ -17,9 +17,13 @@ */ package org.apache.beam.fn.harness.data; +import java.io.Closeable; import java.util.ArrayList; import java.util.List; +import org.apache.beam.runners.core.metrics.MetricsContainerImpl; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingRunnable; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,6 +55,16 @@ public class PTransformFunctionRegistry { private static final Logger LOG = LoggerFactory.getLogger(PTransformFunctionRegistry.class); private List runnables = new ArrayList<>(); + private MetricsContainerStepMap metricsContainerRegistry; + + /** + * + * @param metricsContainerRegistry Used to get the appropriate metrics container for the + * pTransform in order to set its context before invoking the pTransform specific function. + */ + public PTransformFunctionRegistry(MetricsContainerStepMap metricsContainerRegistry) { + this.metricsContainerRegistry = metricsContainerRegistry; + } /** * Register the runnable to process the specific pTransformId. @@ -61,9 +75,12 @@ public class PTransformFunctionRegistry { public void register(String pTransformId, ThrowingRunnable runnable) { ThrowingRunnable wrapped = () -> { - // TODO(ajamato): Setup the proper pTransform context for Metrics to use. - // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. - runnable.run(); + MetricsContainerImpl baseContainer = metricsContainerRegistry.getContainer(pTransformId); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { + // TODO(ajamato): Setup the proper pTransform context for Metrics to use. + // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. + runnable.run(); + } }; runnables.add(wrapped); } From 80491198cbd043dac5d057340d2bd9965dc233be Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 18 Jan 2019 16:21:03 -0800 Subject: [PATCH 05/26] got start and finish metrics working --- .../core/metrics/MetricsContainerStepMap.java | 2 + .../control/RemoteExecutionTest.java | 64 +++++++++++++------ .../harness/control/ProcessBundleHandler.java | 1 - .../data/PTransformFunctionRegistry.java | 4 +- 4 files changed, 47 insertions(+), 24 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index a136ff8f25e4..06710e3eebdf 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -23,6 +23,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.runners.core.construction.metrics.MetricFiltering; import org.apache.beam.runners.core.construction.metrics.MetricKey; import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; @@ -60,6 +61,7 @@ public MetricsContainerImpl getContainer(String stepName) { /** * Update this {@link MetricsContainerStepMap} with all values from given {@link * MetricsContainerStepMap}. + * */ public void updateAll(MetricsContainerStepMap other) { for (Map.Entry container : other.metricsContainers.entrySet()) { diff --git a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java index 80e5a566bdf2..283f040be9ab 100644 --- a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java +++ b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java @@ -491,29 +491,43 @@ public Coder resultCoder() { @Test public void testMetrics() throws Exception { - final String counterMetricName = "counterMetric"; + final String processUserCounterName = "processUserCounter"; + final String startUserCounterName = "startUserCounter"; + final String finishUserCounterName = "finishUserCounter"; Pipeline p = Pipeline.create(); PCollection input = p.apply("impulse", Impulse.create()) .apply( "create", - ParDo.of( - new DoFn() { - private boolean emitted = false; + ParDo.of(new DoFn() { + private boolean emitted = false; - @ProcessElement - public void process(ProcessContext ctxt) { - // TODO(BEAM-6467): Impulse is producing two elements instead of one. - // So add this check to only emit these three elemenets. - if (!emitted) { - ctxt.output("zero"); - ctxt.output("one"); - ctxt.output("two"); - Metrics.counter(RemoteExecutionTest.class, counterMetricName).inc(); - } - emitted = true; - } - })) + @StartBundle + public void startBundle() throws InterruptedException { + //Thread.sleep(2000); // TODO smarter test without sleeps??? + Metrics.counter(RemoteExecutionTest.class, startUserCounterName).inc(10); + } + + @SuppressWarnings("unused") + @ProcessElement + public void processElement(ProcessContext ctxt) { + // TODO(BEAM-6467): Impulse is producing two elements instead of one. + // So add this check to only emit these three elemenets. + if (!emitted) { + ctxt.output("zero"); + ctxt.output("one"); + ctxt.output("two"); + Metrics.counter(RemoteExecutionTest.class, processUserCounterName).inc(); + } + emitted = true; + } + + @DoFn.FinishBundle + public void finishBundle() throws InterruptedException { + //Thread.sleep(2000); // TODO smarter test without sleeps??? + Metrics.counter(RemoteExecutionTest.class, finishUserCounterName).inc(100); + } + })) .setCoder(StringUtf8Coder.of()); SingleOutput pardo = @@ -608,12 +622,20 @@ public void onCompleted(ProcessBundleResponse response) { // element 4 = 2 x 2 elements. List expected = new ArrayList(); - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), counterMetricName); // TODO(ajamato): Add test having a user counter with the same name, in two // separate ptransforms, should be labelled differnetly. Currently this does not work // because the MetricContainer is not being seeded properly with the step name. - builder.setInt64Value(1); // Count just the one inc() in create(); + SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); + builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), processUserCounterName); + builder.setInt64Value(2); + expected.add(builder.build()); + + builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), startUserCounterName); + builder.setInt64Value(10); + expected.add(builder.build()); + + builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), finishUserCounterName); + builder.setInt64Value(100); expected.add(builder.build()); // The element counter should be counted only once for the pcollection. @@ -643,7 +665,7 @@ public void onCompleted(ProcessBundleResponse response) { builder.setInt64Value(6); expected.add(builder.build()); - assertEquals(5, result.size()); + assertEquals(7, result.size()); assertThat(result, containsInAnyOrder(expected.toArray())); } }; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java index 3072e3fbcae6..aaf459ea4e77 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java @@ -54,7 +54,6 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.WindowingStrategy; import org.apache.beam.runners.core.construction.PTransformTranslation; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; -import org.apache.beam.runners.dataflow.worker.MetricsContainerRegistry; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java index e32d6249002e..90b96aff422b 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java @@ -75,8 +75,8 @@ public PTransformFunctionRegistry(MetricsContainerStepMap metricsContainerRegist public void register(String pTransformId, ThrowingRunnable runnable) { ThrowingRunnable wrapped = () -> { - MetricsContainerImpl baseContainer = metricsContainerRegistry.getContainer(pTransformId); - try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { + MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) { // TODO(ajamato): Setup the proper pTransform context for Metrics to use. // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. runnable.run(); From 875ce2fa868c2f35dc8482289e93f06d44c05aad Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Thu, 24 Jan 2019 18:10:21 -0800 Subject: [PATCH 06/26] Fixup after merge and make process work with user metrics as well --- .../core/metrics/MetricsContainerImpl.java | 1 + .../core/metrics/MetricsContainerStepMap.java | 4 +- .../control/RemoteExecutionTest.java | 72 +++++++++++-------- .../fn/harness/BeamFnDataWriteRunner.java | 1 + .../beam/fn/harness/BoundedSourceRunner.java | 2 +- .../beam/fn/harness/CombineRunners.java | 3 +- .../harness/DoFnPTransformRunnerFactory.java | 2 + .../apache/beam/fn/harness/FlattenRunner.java | 3 +- .../apache/beam/fn/harness/MapFnRunners.java | 1 + .../harness/control/ProcessBundleHandler.java | 59 +++++++++------ .../data/ElementCountFnDataReceiver.java | 8 +++ .../data/PCollectionConsumerRegistry.java | 29 ++++++-- .../data/PTransformFunctionRegistry.java | 6 +- .../fn/harness/AssignWindowsRunnerTest.java | 7 +- .../fn/harness/BeamFnDataReadRunnerTest.java | 18 +++-- .../fn/harness/BeamFnDataWriteRunnerTest.java | 11 ++- .../fn/harness/BoundedSourceRunnerTest.java | 15 ++-- .../beam/fn/harness/CombineRunnersTest.java | 45 ++++++++---- .../beam/fn/harness/FlattenRunnerTest.java | 11 ++- .../beam/fn/harness/FnApiDoFnRunnerTest.java | 59 +++++++++++---- .../beam/fn/harness/MapFnRunnersTest.java | 39 ++++++---- .../data/PCollectionConsumerRegistryTest.java | 21 +++--- .../data/PTransformFunctionRegistryTest.java | 5 +- 23 files changed, 287 insertions(+), 135 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index fa2b83453041..de6a24374862 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -158,6 +158,7 @@ private MonitoringInfo counterUpdateToMonitoringInfo(MetricUpdate metricUp builder.setUrnForUserMetric( metricUpdate.getKey().metricName().getNamespace(), metricUpdate.getKey().metricName().getName()); + builder.setPTransformLabel(metricUpdate.getKey().stepName()); } builder.setInt64Value(metricUpdate.getUpdate()); builder.setTimestampToNow(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 06710e3eebdf..37ebb8ed3994 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -61,7 +61,6 @@ public MetricsContainerImpl getContainer(String stepName) { /** * Update this {@link MetricsContainerStepMap} with all values from given {@link * MetricsContainerStepMap}. - * */ public void updateAll(MetricsContainerStepMap other) { for (Map.Entry container : other.metricsContainers.entrySet()) { @@ -114,14 +113,13 @@ public Iterable getMonitoringInfos() { // Extract user metrics and store as MonitoringInfos. ArrayList monitoringInfos = new ArrayList(); for (MetricsContainerImpl container : metricsContainers.values()) { - for (MonitoringInfo mi : container.getMonitoringInfos()) { + for (MonitoringInfo mi : container.getMonitoringInfos()) { monitoringInfos.add(mi); } } return monitoringInfos; } - /** * Returns {@link MetricResults} based on given {@link MetricsContainerStepMap} of attempted * metrics. diff --git a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java index 283f040be9ab..0a3eca3138e5 100644 --- a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java +++ b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java @@ -17,7 +17,6 @@ */ package org.apache.beam.runners.fnexecution.control; -import static junit.framework.TestCase.assertEquals; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkState; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; @@ -80,6 +79,7 @@ import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.fn.stream.OutboundObserverFactory; import org.apache.beam.sdk.fn.test.InProcessManagedChannelFactory; +import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.state.BagState; @@ -489,6 +489,7 @@ public Coder resultCoder() { } } + // TODO(ajamato): Test creating the metric in the ctor/object field. @Test public void testMetrics() throws Exception { final String processUserCounterName = "processUserCounter"; @@ -499,35 +500,37 @@ public void testMetrics() throws Exception { p.apply("impulse", Impulse.create()) .apply( "create", - ParDo.of(new DoFn() { - private boolean emitted = false; + ParDo.of( + new DoFn() { + private boolean emitted = false; + Counter startCounter = + Metrics.counter(RemoteExecutionTest.class, startUserCounterName); - @StartBundle - public void startBundle() throws InterruptedException { - //Thread.sleep(2000); // TODO smarter test without sleeps??? - Metrics.counter(RemoteExecutionTest.class, startUserCounterName).inc(10); - } + @StartBundle + public void startBundle() throws InterruptedException { + startCounter.inc(10); + } - @SuppressWarnings("unused") - @ProcessElement - public void processElement(ProcessContext ctxt) { - // TODO(BEAM-6467): Impulse is producing two elements instead of one. - // So add this check to only emit these three elemenets. - if (!emitted) { - ctxt.output("zero"); - ctxt.output("one"); - ctxt.output("two"); - Metrics.counter(RemoteExecutionTest.class, processUserCounterName).inc(); - } - emitted = true; - } + @SuppressWarnings("unused") + @ProcessElement + public void processElement(ProcessContext ctxt) { + // TODO(BEAM-6467): Impulse is producing two elements instead of one. + // So add this check to only emit these three elemenets. + if (!emitted) { + ctxt.output("zero"); + ctxt.output("one"); + ctxt.output("two"); + Metrics.counter(RemoteExecutionTest.class, processUserCounterName).inc(); + } + emitted = true; + } - @DoFn.FinishBundle - public void finishBundle() throws InterruptedException { - //Thread.sleep(2000); // TODO smarter test without sleeps??? - Metrics.counter(RemoteExecutionTest.class, finishUserCounterName).inc(100); - } - })) + @DoFn.FinishBundle + public void finishBundle() throws InterruptedException { + // Thread.sleep(2000); // TODO smarter test without sleeps??? + Metrics.counter(RemoteExecutionTest.class, finishUserCounterName).inc(100); + } + })) .setCoder(StringUtf8Coder.of()); SingleOutput pardo = @@ -626,15 +629,21 @@ public void onCompleted(ProcessBundleResponse response) { // separate ptransforms, should be labelled differnetly. Currently this does not work // because the MetricContainer is not being seeded properly with the step name. SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), processUserCounterName); - builder.setInt64Value(2); + builder.setUrnForUserMetric( + RemoteExecutionTest.class.getName(), processUserCounterName); + builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); + builder.setInt64Value(1); expected.add(builder.build()); + builder = new SimpleMonitoringInfoBuilder(); builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), startUserCounterName); + builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); builder.setInt64Value(10); expected.add(builder.build()); + builder = new SimpleMonitoringInfoBuilder(); builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), finishUserCounterName); + builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); builder.setInt64Value(100); expected.add(builder.build()); @@ -665,7 +674,7 @@ public void onCompleted(ProcessBundleResponse response) { builder.setInt64Value(6); expected.add(builder.build()); - assertEquals(7, result.size()); + // assertEquals(expected.size(), result.size()); assertThat(result, containsInAnyOrder(expected.toArray())); } }; @@ -683,6 +692,9 @@ public void onCompleted(ProcessBundleResponse response) { } } + // TODO(ajamato): Write a test where the ElementCount counters may be under + // different metrics containers. + @Test public void testExecutionWithUserState() throws Exception { Pipeline p = Pipeline.create(); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BeamFnDataWriteRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BeamFnDataWriteRunner.java index 4177814ef8dd..5e0ebb79c287 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BeamFnDataWriteRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BeamFnDataWriteRunner.java @@ -110,6 +110,7 @@ public BeamFnDataWriteRunner createRunnerForPTransform( startFunctionRegistry.register(pTransformId, runner::registerForOutput); pCollectionConsumerRegistry.register( getOnlyElement(pTransform.getInputsMap().values()), + pTransformId, (FnDataReceiver) (FnDataReceiver>) runner::consume); finishFunctionRegistry.register(pTransformId, runner::close); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BoundedSourceRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BoundedSourceRunner.java index 4923afdca574..811681d5ee1a 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BoundedSourceRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/BoundedSourceRunner.java @@ -95,7 +95,7 @@ public BoundedSourceRunner createRunnerForPTransform( FnDataReceiver runReadLoop = (FnDataReceiver>) runner::runReadLoop; for (String pCollectionId : pTransform.getInputsMap().values()) { - pCollectionConsumerRegistry.register(pCollectionId, runReadLoop); + pCollectionConsumerRegistry.register(pCollectionId, pTransformId, runReadLoop); } return runner; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/CombineRunners.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/CombineRunners.java index a6c4e504dad0..5ad289f8d51b 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/CombineRunners.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/CombineRunners.java @@ -163,8 +163,6 @@ public PrecombineRunner createRunnerForPTransform( pCollectionConsumerRegistry.getMultiplexingConsumer( Iterables.getOnlyElement(pTransform.getOutputsMap().values())); - // TODO make the receiver aware of its transform context as well. - // Create the runner. PrecombineRunner runner = new PrecombineRunner<>(pipelineOptions, combineFn, consumer, keyCoder, accumCoder); @@ -172,6 +170,7 @@ public PrecombineRunner createRunnerForPTransform( startFunctionRegistry.register(pTransformId, runner::startBundle); pCollectionConsumerRegistry.register( Iterables.getOnlyElement(pTransform.getInputsMap().values()), + pTransformId, (FnDataReceiver) (FnDataReceiver>>) runner::processElement); finishFunctionRegistry.register(pTransformId, runner::finishBundle); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/DoFnPTransformRunnerFactory.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/DoFnPTransformRunnerFactory.java index f4d478d23f89..847473ada330 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/DoFnPTransformRunnerFactory.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/DoFnPTransformRunnerFactory.java @@ -119,6 +119,7 @@ public final RunnerT createRunnerForPTransform( for (String localInputName : mainInput) { pCollectionConsumerRegistry.register( pTransform.getInputsOrThrow(localInputName), + pTransformId, (FnDataReceiver) (FnDataReceiver>) runner::processElement); } @@ -130,6 +131,7 @@ public final RunnerT createRunnerForPTransform( .getTimeDomain(); pCollectionConsumerRegistry.register( pTransform.getInputsOrThrow(localName), + pTransformId, (FnDataReceiver) timer -> runner.processTimer( diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FlattenRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FlattenRunner.java index e75b92f80bd1..b0e1eeca5ecc 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FlattenRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FlattenRunner.java @@ -77,7 +77,8 @@ public FlattenRunner createRunnerForPTransform( // TODO make the receiver aware of its transform context as well. for (String pCollectionId : pTransform.getInputsMap().values()) { - pCollectionConsumerRegistry.register(pCollectionId, (FnDataReceiver) receiver); + pCollectionConsumerRegistry.register( + pCollectionId, pTransformId, (FnDataReceiver) receiver); } return runner; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/MapFnRunners.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/MapFnRunners.java index 6f215069f604..fd340a8db08d 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/MapFnRunners.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/MapFnRunners.java @@ -119,6 +119,7 @@ public Mapper createRunnerForPTransform( pCollectionConsumerRegistry.register( Iterables.getOnlyElement(pTransform.getInputsMap().values()), + pTransformId, (FnDataReceiver) (FnDataReceiver>) mapper::map); return mapper; } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java index aaf459ea4e77..074e7f40f7e5 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java @@ -53,8 +53,8 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; import org.apache.beam.model.pipeline.v1.RunnerApi.WindowingStrategy; import org.apache.beam.runners.core.construction.PTransformTranslation; +import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; -import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.options.PipelineOptions; @@ -225,14 +225,15 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction (BeamFnApi.ProcessBundleDescriptor) fnApiRegistry.apply(bundleId); SetMultimap pCollectionIdsToConsumingPTransforms = HashMultimap.create(); - PCollectionConsumerRegistry pCollectionConsumerRegistry = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry pCollectionConsumerRegistry = + new PCollectionConsumerRegistry(metricsContainerRegistry); HashSet processedPTransformIds = new HashSet<>(); - MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry( - metricsContainerRegistry); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry( - metricsContainerRegistry); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); // Build a multimap of PCollection ids to PTransform ids which consume said PCollections for (Map.Entry entry : @@ -297,27 +298,39 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction splitListener); } - // Already in reverse topological order so we don't need to do anything. - for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { - LOG.debug("Starting function {}", startFunction); - startFunction.run(); - } + // There always needs to be a metricContainer in scope, not everything is calculated in the + // context of a PTransform. For example, element count metrics are calculated before entering + // a pTransform's context. + MetricsContainerImpl rootMetricsContainer = new MetricsContainerImpl(""); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(rootMetricsContainer)) { - queueingClient.drainAndBlock(); + // Already in reverse topological order so we don't need to do anything. + for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { + LOG.debug("Starting function {}", startFunction); + startFunction.run(); + } - // Need to reverse this since we want to call finish in topological order. - for (ThrowingRunnable finishFunction : - Lists.reverse(finishFunctionRegistry.getFunctions())) { - LOG.debug("Finishing function {}", finishFunction); - finishFunction.run(); - } - if (!allResiduals.isEmpty()) { - response.addAllResidualRoots(allResiduals.values()); + queueingClient.drainAndBlock(); + + // Need to reverse this since we want to call finish in topological order. + for (ThrowingRunnable finishFunction : + Lists.reverse(finishFunctionRegistry.getFunctions())) { + LOG.debug("Finishing function {}", finishFunction); + finishFunction.run(); + } + if (!allResiduals.isEmpty()) { + response.addAllResidualRoots(allResiduals.values()); + } + + for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { + response.addMonitoringInfos(mi); + } } - for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { + /* + for (MonitoringInfo mi : rootMetricsContainer.getMonitoringInfos()) { response.addMonitoringInfos(mi); - } + }*/ } return BeamFnApi.InstructionResponse.newBuilder().setProcessBundle(response); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index 5de116e0b516..ab570ae57a0a 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java @@ -42,6 +42,14 @@ public ElementCountFnDataReceiver(FnDataReceiver> original, Str labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); MonitoringInfoMetricName metricName = MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); + // TODO(BEAM-6505): Introducing a way for system counters to be instantiated on a consisntent + // metrics container. rather than using the currently scoped metrics container. + // There is a risk of accidentally creating the same metric under different metric containers + // which would create separate monitoringInfos for the same metrics. + // This will not happen for ElementCount because the producing pTransform for the pCollection + // always invokes the consumer, so it will always be instantiated under the same + // metric container scope. The use of the currently scoped MetricContainer is to use the + // pTransform of the current scope and attach it to the counter. this.counter = LabeledMetrics.counter(metricName); } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java index 8b8dbc409f31..cc436d8ee1c2 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java @@ -17,11 +17,15 @@ */ package org.apache.beam.fn.harness.data; +import java.io.Closeable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.beam.runners.core.metrics.MetricsContainerImpl; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ArrayListMultimap; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ListMultimap; @@ -36,10 +40,12 @@ public class PCollectionConsumerRegistry { private ListMultimap>> pCollectionIdsToConsumers; private Map pCollectionIdsToWrappedConsumer; + private MetricsContainerStepMap metricsContainerRegistry; - public PCollectionConsumerRegistry() { - pCollectionIdsToConsumers = ArrayListMultimap.create(); - pCollectionIdsToWrappedConsumer = new HashMap(); + public PCollectionConsumerRegistry(MetricsContainerStepMap metricsContainerRegistry) { + this.metricsContainerRegistry = metricsContainerRegistry; + this.pCollectionIdsToConsumers = ArrayListMultimap.create(); + this.pCollectionIdsToWrappedConsumer = new HashMap(); } /** @@ -48,12 +54,14 @@ public PCollectionConsumerRegistry() { * calling getMultiplexingConsumer(), or an exception will be thrown. * * @param pCollectionId + * @param pTransformId * @param consumer * @param the element type of the PCollection * @throws RuntimeException if {@code register()} is called after {@code * getMultiplexingConsumer()} is called. */ - public void register(String pCollectionId, FnDataReceiver> consumer) { + public void register( + String pCollectionId, String pTransformId, FnDataReceiver> consumer) { // Just save these consumers for now, but package them up later with an // ElementCountFnDataReceiver and possibly a MultiplexingFnDataReceiver // if there are multiple consumers. @@ -64,7 +72,18 @@ public void register(String pCollectionId, FnDataReceiver> "New consumers for a pCollectionId cannot be register()-d after " + "calling getMultiplexingConsumer."); } - pCollectionIdsToConsumers.put(pCollectionId, (FnDataReceiver) consumer); + // Wrap the consumer with extra logic to set the metric container with the appropriate + // PTransform context. This ensures that user metrics obtain the pTransform ID when they are + // created. + FnDataReceiver> wrapAndEnableMetricContainer = + (WindowedValue input) -> { + MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) { + // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. + consumer.accept(input); + } + }; + pCollectionIdsToConsumers.put(pCollectionId, (FnDataReceiver) wrapAndEnableMetricContainer); } /** @return the list of pcollection ids. */ diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java index 90b96aff422b..5d4d641eb1cf 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java @@ -24,8 +24,6 @@ import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * A class to to register and retrieve functions for bundle processing (i.e. the start, or finish @@ -52,18 +50,16 @@ * */ public class PTransformFunctionRegistry { - private static final Logger LOG = LoggerFactory.getLogger(PTransformFunctionRegistry.class); private List runnables = new ArrayList<>(); private MetricsContainerStepMap metricsContainerRegistry; /** - * * @param metricsContainerRegistry Used to get the appropriate metrics container for the * pTransform in order to set its context before invoking the pTransform specific function. */ public PTransformFunctionRegistry(MetricsContainerStepMap metricsContainerRegistry) { - this.metricsContainerRegistry = metricsContainerRegistry; + this.metricsContainerRegistry = metricsContainerRegistry; } /** diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/AssignWindowsRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/AssignWindowsRunnerTest.java index ce0a732b506b..f92531596a76 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/AssignWindowsRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/AssignWindowsRunnerTest.java @@ -34,6 +34,7 @@ import org.apache.beam.runners.core.construction.PTransformTranslation; import org.apache.beam.runners.core.construction.SdkComponents; import org.apache.beam.runners.core.construction.WindowingStrategyTranslation; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.fn.function.ThrowingFunction; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; @@ -169,8 +170,10 @@ public Coder windowCoder() { } }; Collection> outputs = new ArrayList<>(); - PCollectionConsumerRegistry pCollectionConsumerRegistry = new PCollectionConsumerRegistry(); - pCollectionConsumerRegistry.register("output", outputs::add); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry pCollectionConsumerRegistry = + new PCollectionConsumerRegistry(metricsContainerRegistry); + pCollectionConsumerRegistry.register("output", "ptransform", outputs::add); SdkComponents components = SdkComponents.create(); components.registerEnvironment(Environments.createDockerEnvironment("java")); MapFnRunners.forWindowedValueMapFnFactory(new AssignWindowsMapFnFactory<>()) diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataReadRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataReadRunnerTest.java index d6d27698429a..54a22204add5 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataReadRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataReadRunnerTest.java @@ -47,6 +47,7 @@ import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.MessageWithComponents; import org.apache.beam.runners.core.construction.CoderTranslation; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.fn.data.CompletableFutureInboundDataClient; @@ -126,12 +127,19 @@ public void testCreatingAndProcessingBeamFnDataReadRunner() throws Exception { List> outputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); String localOutputId = "outputPC"; + String pTransformId = "pTransformId"; consumers.register( - localOutputId, (FnDataReceiver) (FnDataReceiver>) outputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + localOutputId, + pTransformId, + (FnDataReceiver) (FnDataReceiver>) outputValues::add); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); RunnerApi.PTransform pTransform = RemoteGrpcPortRead.readFromPort(PORT_SPEC, localOutputId).toPTransform(); @@ -141,7 +149,7 @@ public void testCreatingAndProcessingBeamFnDataReadRunner() throws Exception { PipelineOptionsFactory.create(), mockBeamFnDataClient, null /* beamFnStateClient */, - "pTransformId", + pTransformId, pTransform, Suppliers.ofInstance(bundleId)::get, ImmutableMap.of( diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataWriteRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataWriteRunnerTest.java index 3f8ed0dce751..280e2b27dfbb 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataWriteRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BeamFnDataWriteRunnerTest.java @@ -46,6 +46,7 @@ import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.MessageWithComponents; import org.apache.beam.runners.core.construction.CoderTranslation; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.fn.data.CloseableFnDataReceiver; @@ -114,9 +115,13 @@ public void setUp() { public void testCreatingAndProcessingBeamFnDataWriteRunner() throws Exception { String bundleId = "57L"; - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); String localInputId = "inputPC"; RunnerApi.PTransform pTransform = diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BoundedSourceRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BoundedSourceRunnerTest.java index 5214b24cb8c7..50ceaa02f987 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BoundedSourceRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/BoundedSourceRunnerTest.java @@ -34,6 +34,7 @@ import org.apache.beam.fn.harness.data.PCollectionConsumerRegistry; import org.apache.beam.fn.harness.data.PTransformFunctionRegistry; import org.apache.beam.model.pipeline.v1.RunnerApi; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.io.BoundedSource; import org.apache.beam.sdk.io.CountingSource; @@ -124,11 +125,17 @@ public void testStart() throws Exception { public void testCreatingAndProcessingSourceFromFactory() throws Exception { List> outputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( - "outputPC", (FnDataReceiver) (FnDataReceiver>) outputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + "outputPC", + "pTransformId", + (FnDataReceiver) (FnDataReceiver>) outputValues::add); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); RunnerApi.FunctionSpec functionSpec = RunnerApi.FunctionSpec.newBuilder() diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/CombineRunnersTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/CombineRunnersTest.java index 21f6c4d95801..89a386a82209 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/CombineRunnersTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/CombineRunnersTest.java @@ -33,6 +33,7 @@ import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.construction.PipelineTranslation; import org.apache.beam.runners.core.construction.SdkComponents; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.BigEndianIntegerCoder; import org.apache.beam.sdk.coders.KvCoder; @@ -120,15 +121,20 @@ public void createPipeline() throws Exception { @Test public void testPrecombine() throws Exception { // Create a map of consumers and an output target to check output values. - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); Deque>> mainOutputValues = new ArrayDeque<>(); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_COMBINE_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); // Create runner. new CombineRunners.PrecombineFactory<>() @@ -186,15 +192,20 @@ public void testPrecombine() throws Exception { @Test public void testMergeAccumulators() throws Exception { // Create a map of consumers and an output target to check output values. - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); Deque>> mainOutputValues = new ArrayDeque<>(); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_COMBINE_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); // Create runner. MapFnRunners.forValueMapFnFactory(CombineRunners::createMergeAccumulatorsMapFunction) @@ -240,15 +251,20 @@ public void testMergeAccumulators() throws Exception { @Test public void testExtractOutputs() throws Exception { // Create a map of consumers and an output target to check output values. - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); Deque>> mainOutputValues = new ArrayDeque<>(); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_COMBINE_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); // Create runner. MapFnRunners.forValueMapFnFactory(CombineRunners::createExtractOutputsMapFunction) @@ -294,15 +310,20 @@ public void testExtractOutputs() throws Exception { @Test public void testCombineGroupedValues() throws Exception { // Create a map of consumers and an output target to check output values. - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); Deque>> mainOutputValues = new ArrayDeque<>(); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_COMBINE_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); // Create runner. MapFnRunners.forValueMapFnFactory(CombineRunners::createCombineGroupedValuesMapFunction) diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FlattenRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FlattenRunnerTest.java index fe661cd8c2ce..da3c48aee879 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FlattenRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FlattenRunnerTest.java @@ -29,6 +29,7 @@ import org.apache.beam.fn.harness.data.PCollectionConsumerRegistry; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.construction.PTransformTranslation; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.util.WindowedValue; @@ -65,9 +66,12 @@ public void testCreatingAndProcessingDoFlatten() throws Exception { .build(); List> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( "mainOutputTarget", + pTransformId, (FnDataReceiver) (FnDataReceiver>) mainOutputValues::add); new FlattenRunner.Factory<>() @@ -128,9 +132,12 @@ public void testFlattenWithDuplicateInputCollectionProducesMultipleOutputs() thr .build(); List> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( "mainOutputTarget", + pTransformId, (FnDataReceiver) (FnDataReceiver>) mainOutputValues::add); new FlattenRunner.Factory<>() diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java index 64ca20face18..fcf2a67d4a27 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java @@ -47,6 +47,7 @@ import org.apache.beam.runners.core.metrics.MetricUpdates; import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.MonitoringInfoMetricName; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.Pipeline; @@ -198,12 +199,17 @@ public void testUsingUserState() throws Exception { bagUserStateKey("combine", "X"), encode("X0"))); List> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( outputPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); new FnApiDoFnRunner.Factory<>() .createRunnerForPTransform( @@ -357,15 +363,21 @@ public void testBasicWithSideInputsAndOutputs() throws Exception { List> mainOutputValues = new ArrayList<>(); List> additionalOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( outputPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>) mainOutputValues::add); consumers.register( additionalPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>) additionalOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); new FnApiDoFnRunner.Factory<>() .createRunnerForPTransform( @@ -489,12 +501,17 @@ public void testSideInputIsAccessibleForDownstreamCallers() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(stateData); List>> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); new FnApiDoFnRunner.Factory<>() .createRunnerForPTransform( @@ -589,12 +606,17 @@ public void testUsingMetrics() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(stateData); List>> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( Iterables.getOnlyElement(pTransform.getOutputsMap().values()), + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>>) mainOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); new FnApiDoFnRunner.Factory<>() .createRunnerForPTransform( @@ -748,21 +770,28 @@ public void testTimers() throws Exception { List> mainOutputValues = new ArrayList<>(); List>> eventTimerOutputValues = new ArrayList<>(); List>> processingTimerOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( outputPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>) mainOutputValues::add); consumers.register( eventTimerOutputPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>>) eventTimerOutputValues::add); consumers.register( processingTimerOutputPCollectionId, + TEST_PTRANSFORM_ID, (FnDataReceiver) (FnDataReceiver>>) processingTimerOutputValues::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); new FnApiDoFnRunner.Factory<>() .createRunnerForPTransform( diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/MapFnRunnersTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/MapFnRunnersTest.java index d93cb6ac6126..95de1cda1aba 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/MapFnRunnersTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/MapFnRunnersTest.java @@ -32,6 +32,7 @@ import org.apache.beam.fn.harness.data.PTransformFunctionRegistry; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingFunction; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; @@ -59,11 +60,15 @@ public class MapFnRunnersTest { @Test public void testValueOnlyMapping() throws Exception { List> outputConsumer = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); - consumers.register("outputPC", outputConsumer::add); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); + consumers.register("outputPC", EXPECTED_ID, outputConsumer::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); ValueMapFnFactory factory = (ptId, pt) -> String::toUpperCase; MapFnRunners.forValueMapFnFactory(factory) @@ -95,11 +100,15 @@ public void testValueOnlyMapping() throws Exception { @Test public void testFullWindowedValueMapping() throws Exception { List> outputConsumer = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); - consumers.register("outputPC", outputConsumer::add); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); + consumers.register("outputPC", EXPECTED_ID, outputConsumer::add); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); MapFnRunners.forWindowedValueMapFnFactory(this::createMapFunctionForPTransform) .createRunnerForPTransform( @@ -130,11 +139,15 @@ public void testFullWindowedValueMapping() throws Exception { @Test public void testFullWindowedValueMappingWithCompressedWindow() throws Exception { List> outputConsumer = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); - consumers.register("outputPC", outputConsumer::add); - - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); + consumers.register("outputPC", EXPECTED_ID, outputConsumer::add); + + PTransformFunctionRegistry startFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); + PTransformFunctionRegistry finishFunctionRegistry = + new PTransformFunctionRegistry(metricsContainerRegistry); MapFnRunners.forWindowedValueMapFnFactory(this::createMapFunctionForPTransform) .createRunnerForPTransform( diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java index beba73e7d382..89f8e2021fea 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java @@ -23,6 +23,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.util.WindowedValue; import org.junit.Rule; @@ -44,13 +45,16 @@ public class PCollectionConsumerRegistryTest { @Test public void multipleConsumersSamePCollection() throws Exception { final String pCollectionA = "pCollectionA"; + final String pTransformId = "pTransformId"; - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); FnDataReceiver> consumerA1 = mock(FnDataReceiver.class); FnDataReceiver> consumerA2 = mock(FnDataReceiver.class); - consumers.register(pCollectionA, consumerA1); - consumers.register(pCollectionA, consumerA2); + consumers.register(pCollectionA, pTransformId, consumerA1); + consumers.register(pCollectionA, pTransformId, consumerA2); FnDataReceiver> wrapperConsumer = (FnDataReceiver>) @@ -65,24 +69,25 @@ public void multipleConsumersSamePCollection() throws Exception { // Check that the underlying consumers are each invoked per element. verify(consumerA1, times(numElements)).accept(element); verify(consumerA2, times(numElements)).accept(element); - assertThat(consumers.keySet(), contains(pCollectionA)); - assertThat(consumers.getUnderlyingConsumers(pCollectionA), contains(consumerA1, consumerA2)); } @Test public void throwsOnRegisteringAfterMultiplexingConsumerWasInitialized() throws Exception { final String pCollectionA = "pCollectionA"; + final String pTransformId = "pTransformId"; - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); FnDataReceiver> consumerA1 = mock(FnDataReceiver.class); FnDataReceiver> consumerA2 = mock(FnDataReceiver.class); - consumers.register(pCollectionA, consumerA1); + consumers.register(pCollectionA, pTransformId, consumerA1); consumers.getMultiplexingConsumer(pCollectionA); expectedException.expect(RuntimeException.class); expectedException.expectMessage("cannot be register()-d after"); - consumers.register(pCollectionA, consumerA2); + consumers.register(pCollectionA, pTransformId, consumerA2); } } diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java index ec41f6ab42fd..9383a2194a6f 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.junit.Test; import org.junit.runner.RunWith; @@ -32,7 +33,9 @@ public class PTransformFunctionRegistryTest { @Test public void functionsAreInvokedIndirectlyAfterRegisteringAndInvoking() throws Exception { - PTransformFunctionRegistry testObject = new PTransformFunctionRegistry(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PTransformFunctionRegistry testObject = + new PTransformFunctionRegistry(metricsContainerRegistry); ThrowingRunnable runnableA = mock(ThrowingRunnable.class); ThrowingRunnable runnableB = mock(ThrowingRunnable.class); From 11e67f317039e960e5f2ee3aea8fad731fc28697 Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Thu, 24 Jan 2019 18:11:01 -0800 Subject: [PATCH 07/26] Fixup after merge and make process work with user metrics as well --- .../apache/beam/fn/harness/control/ProcessBundleHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java index 074e7f40f7e5..d702c3b0b180 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java @@ -327,10 +327,9 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction } } - /* for (MonitoringInfo mi : rootMetricsContainer.getMonitoringInfos()) { response.addMonitoringInfos(mi); - }*/ + } } return BeamFnApi.InstructionResponse.newBuilder().setProcessBundle(response); From 3367b34fefae57b35709dcbe95a37f3b22b6847d Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 25 Jan 2019 11:22:26 -0800 Subject: [PATCH 08/26] Broken MetricContainerStepMap tests --- .../core/metrics/MetricsContainerImpl.java | 1 + .../core/metrics/MetricsContainerStepMap.java | 69 +++++++++++++++++-- .../harness/control/ProcessBundleHandler.java | 8 +-- 3 files changed, 65 insertions(+), 13 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index de6a24374862..fc791a99bea2 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -198,6 +198,7 @@ ImmutableList> extractCumulatives(MetricsMap> updates = ImmutableList.builder(); for (Map.Entry cell : cells.entries()) { UpdateT update = checkNotNull(cell.getValue().getCumulative()); + // TODO copy the old MetricKey instead of creating a new one, with a null stepName. updates.add(MetricUpdate.create(MetricKey.create(stepName, cell.getKey()), update)); } return updates.build(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 37ebb8ed3994..e82891938630 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -17,10 +17,14 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; + +import com.google.auto.value.AutoValue; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; @@ -36,6 +40,7 @@ import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Function; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Predicate; +import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.FluentIterable; /** @@ -44,18 +49,68 @@ *

This class is not thread-safe. */ public class MetricsContainerStepMap implements Serializable { - private Map metricsContainers; + + /** Key class to lookup the metric container for a step or unbound to any step. + * This is preferable to using null(which can't be used as a key). + * Additonally, this class could be extended to allow containers for other non pTransform + * contexts. + */ + @AutoValue + abstract static class MetricsContainerKey { + public static MetricsContainerKey unBounded() { + return new AutoValue_MetricsContainerStepMap_MetricsContainerKey(null); + } + + public static MetricsContainerKey forStep(String step) { + return new AutoValue_MetricsContainerStepMap_MetricsContainerKey(step); + } + + @Nullable + public abstract String getStepName(); + + @Override + public int hashCode() { + // Don't include name and namespace, since they are lazily set. + return Objects.hash(getStepName()); + } + + @Override + public boolean equals(Object o) { + // If the object is compared with itself then return true + if (o == this) { + return true; + } + if (!(o instanceof MetricsContainerKey)) { + return false; + } + MetricsContainerKey other = (MetricsContainerKey) o; + return Objects.equals(this.getStepName(), other.getStepName()); + } + } + + private Map metricsContainers; public MetricsContainerStepMap() { this.metricsContainers = new ConcurrentHashMap<>(); } + /* Returns the container that is not bound to any step name. */ + public MetricsContainerImpl getUnboundContainer() { + return getContainerForKey(MetricsContainerKey.unBounded()); + } + /** Returns the container for the given step name. */ public MetricsContainerImpl getContainer(String stepName) { - if (!metricsContainers.containsKey(stepName)) { - metricsContainers.put(stepName, new MetricsContainerImpl(stepName)); + checkArgument(!Strings.isNullOrEmpty(stepName), "stepName must be non-empty"); + return getContainerForKey(MetricsContainerKey.unBounded()); + } + + /** @return the container for the given key */ + private MetricsContainerImpl getContainerForKey(MetricsContainerKey key) { + if (!metricsContainers.containsKey(key)) { + metricsContainers.put(key, new MetricsContainerImpl(key.getStepName())); } - return metricsContainers.get(stepName); + return metricsContainers.get(key); } /** @@ -63,8 +118,8 @@ public MetricsContainerImpl getContainer(String stepName) { * MetricsContainerStepMap}. */ public void updateAll(MetricsContainerStepMap other) { - for (Map.Entry container : other.metricsContainers.entrySet()) { - getContainer(container.getKey()).update(container.getValue()); + for (Map.Entry container : other.metricsContainers.entrySet()) { + getContainerForKey(container.getKey()).update(container.getValue()); } } @@ -133,7 +188,7 @@ public static MetricResults asAttemptedOnlyMetricResults( return new MetricsContainerStepMapMetricResults(attemptedMetricsContainers); } - private Map getMetricsContainers() { + private Map getMetricsContainers() { return metricsContainers; } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java index d702c3b0b180..a5e0d21c1084 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/control/ProcessBundleHandler.java @@ -301,7 +301,7 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction // There always needs to be a metricContainer in scope, not everything is calculated in the // context of a PTransform. For example, element count metrics are calculated before entering // a pTransform's context. - MetricsContainerImpl rootMetricsContainer = new MetricsContainerImpl(""); + MetricsContainerImpl rootMetricsContainer = metricsContainerRegistry.getUnboundContainer(); try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(rootMetricsContainer)) { // Already in reverse topological order so we don't need to do anything. @@ -321,13 +321,9 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction if (!allResiduals.isEmpty()) { response.addAllResidualRoots(allResiduals.values()); } - - for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { - response.addMonitoringInfos(mi); - } } - for (MonitoringInfo mi : rootMetricsContainer.getMonitoringInfos()) { + for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { response.addMonitoringInfos(mi); } } From d406df62d4bddef831e49f002d9d6a322db803ee Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 25 Jan 2019 17:23:01 -0800 Subject: [PATCH 09/26] More tests passing --- .../core/construction/metrics/MetricKey.java | 4 +- .../core/metrics/MetricsContainerImpl.java | 6 +++ .../core/metrics/MetricsContainerStepMap.java | 2 +- .../beam/fn/harness/FnApiDoFnRunnerTest.java | 50 +++++++++++-------- 4 files changed, 38 insertions(+), 24 deletions(-) diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java index f4d1e9d4acb6..827666f22d3e 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java @@ -19,6 +19,7 @@ import com.google.auto.value.AutoValue; import java.io.Serializable; +import javax.annotation.Nullable; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; import org.apache.beam.sdk.metrics.MetricName; @@ -28,7 +29,8 @@ @AutoValue public abstract class MetricKey implements Serializable { - /** The step name that is associated with this metric. */ + /** The step name that is associated with this metric or Null if none is associated */ + @Nullable public abstract String stepName(); /** The name of the metric. */ diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index fc791a99bea2..f5a99e463a65 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -51,6 +51,11 @@ public class MetricsContainerImpl implements Serializable, MetricsContainer { private final String stepName; + //TODO rm + @Override + public String toString() { + return "MetricsContainerImpl: " + stepName + "."; + } private MetricsMap counters = new MetricsMap<>(CounterCell::new); @@ -122,6 +127,7 @@ ImmutableList> extractUpdates(MetricsMap> updates = ImmutableList.builder(); for (Map.Entry cell : cells.entries()) { if (cell.getValue().getDirty().beforeCommit()) { + // TODO copy the old MetricKey instead of creating a new one, with a null stepName. updates.add( MetricUpdate.create( MetricKey.create(stepName, cell.getKey()), cell.getValue().getCumulative())); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index e82891938630..58947e0d640c 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -102,7 +102,7 @@ public MetricsContainerImpl getUnboundContainer() { /** Returns the container for the given step name. */ public MetricsContainerImpl getContainer(String stepName) { checkArgument(!Strings.isNullOrEmpty(stepName), "stepName must be non-empty"); - return getContainerForKey(MetricsContainerKey.unBounded()); + return getContainerForKey(MetricsContainerKey.forStep(stepName)); } /** @return the container for the given key */ diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java index fcf2a67d4a27..67ec72515de5 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java @@ -37,6 +37,7 @@ import org.apache.beam.fn.harness.data.PCollectionConsumerRegistry; import org.apache.beam.fn.harness.data.PTransformFunctionRegistry; import org.apache.beam.fn.harness.state.FakeBeamFnStateClient; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Environment; @@ -559,7 +560,8 @@ public MetricUpdate create(String stepName, MetricName name, long value) { @Test public void testUsingMetrics() throws Exception { - MetricsContainerImpl metricsContainer = new MetricsContainerImpl("testUsingMetrics"); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + MetricsContainerImpl metricsContainer = metricsContainerRegistry.getUnboundContainer(); Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer); FixedWindows windowFn = FixedWindows.of(Duration.millis(1L)); IntervalWindow windowA = windowFn.assignWindow(new Instant(1L)); @@ -606,7 +608,7 @@ public void testUsingMetrics() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(stateData); List>> mainOutputValues = new ArrayList<>(); - MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(metricsContainerRegistry); consumers.register( @@ -648,30 +650,34 @@ public void testUsingMetrics() throws Exception { MetricsContainer mc = MetricsEnvironment.getCurrentContainer(); - List expectedMetrics = new ArrayList(); - MetricName metricName = - MetricName.named( - TestSideInputIsAccessibleForDownstreamCallersDoFn.class, - TestSideInputIsAccessibleForDownstreamCallersDoFn.USER_COUNTER_NAME); - expectedMetrics.add(create("testUsingMetrics", metricName, 2)); - - HashMap labels = new HashMap(); + List expected = new ArrayList(); + SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); + builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setPCollectionLabel("Window.Into()/Window.Assign.out"); + builder.setInt64Value(2); + expected.add(builder.build()); - labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "Window.Into()/Window.Assign.out"); - metricName = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - expectedMetrics.add(create("testUsingMetrics", metricName, 2)); - - labels.put( - SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, + builder = new SimpleMonitoringInfoBuilder(); + builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setPCollectionLabel( "pTransformId/ParMultiDo(TestSideInputIsAccessibleForDownstreamCallers).output"); - metricName = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - expectedMetrics.add(create("testUsingMetrics", metricName, 2)); + builder.setInt64Value(2); + expected.add(builder.build()); + + builder = new SimpleMonitoringInfoBuilder(); + builder.setUrnForUserMetric( + TestSideInputIsAccessibleForDownstreamCallersDoFn.class.getName(), + TestSideInputIsAccessibleForDownstreamCallersDoFn.USER_COUNTER_NAME); + builder.setPTransformLabel(TEST_PTRANSFORM_ID); + builder.setInt64Value(2); + expected.add(builder.build()); closeable.close(); - MetricUpdates updates = metricsContainer.getUpdates(); - assertThat(updates.counterUpdates(), containsInAnyOrder(expectedMetrics.toArray())); + List result = new ArrayList(); + for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { + result.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + } + assertThat(result, containsInAnyOrder(expected.toArray())); } private static class TestTimerfulDoFn extends DoFn, String> { From b94d070256e1535f3bee65930a864def4605e7d0 Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 25 Jan 2019 18:10:31 -0800 Subject: [PATCH 10/26] Did a bit of a pass on my own --- .../core/construction/metrics/MetricKey.java | 2 +- .../core/metrics/MetricsContainerImpl.java | 7 ---- .../core/metrics/MetricsContainerStepMap.java | 13 +++--- .../control/RemoteExecutionTest.java | 5 --- .../data/ElementCountFnDataReceiver.java | 29 ++++++++------ .../data/PCollectionConsumerRegistry.java | 3 +- .../data/PTransformFunctionRegistry.java | 1 - .../beam/fn/harness/FnApiDoFnRunnerTest.java | 3 -- .../data/ElementCountFnDataReceiverTest.java | 40 +++++++++---------- 9 files changed, 46 insertions(+), 57 deletions(-) diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java index 827666f22d3e..a7fbab4536f5 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricKey.java @@ -29,7 +29,7 @@ @AutoValue public abstract class MetricKey implements Serializable { - /** The step name that is associated with this metric or Null if none is associated */ + /** The step name that is associated with this metric or Null if none is associated. */ @Nullable public abstract String stepName(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index f5a99e463a65..de6a24374862 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -51,11 +51,6 @@ public class MetricsContainerImpl implements Serializable, MetricsContainer { private final String stepName; - //TODO rm - @Override - public String toString() { - return "MetricsContainerImpl: " + stepName + "."; - } private MetricsMap counters = new MetricsMap<>(CounterCell::new); @@ -127,7 +122,6 @@ ImmutableList> extractUpdates(MetricsMap> updates = ImmutableList.builder(); for (Map.Entry cell : cells.entries()) { if (cell.getValue().getDirty().beforeCommit()) { - // TODO copy the old MetricKey instead of creating a new one, with a null stepName. updates.add( MetricUpdate.create( MetricKey.create(stepName, cell.getKey()), cell.getValue().getCumulative())); @@ -204,7 +198,6 @@ ImmutableList> extractCumulatives(MetricsMap> updates = ImmutableList.builder(); for (Map.Entry cell : cells.entries()) { UpdateT update = checkNotNull(cell.getValue().getCumulative()); - // TODO copy the old MetricKey instead of creating a new one, with a null stepName. updates.add(MetricUpdate.create(MetricKey.create(stepName, cell.getKey()), update)); } return updates.build(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 58947e0d640c..bcceeba65ebe 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -50,13 +50,13 @@ */ public class MetricsContainerStepMap implements Serializable { - /** Key class to lookup the metric container for a step or unbound to any step. - * This is preferable to using null(which can't be used as a key). - * Additonally, this class could be extended to allow containers for other non pTransform - * contexts. + /** + * Key class to lookup the metric container for a step or unbound to any step. This is preferable + * to using null(which can't be used as a key). Additonally, this class could be extended to allow + * containers for other non pTransform contexts. */ @AutoValue - abstract static class MetricsContainerKey { + abstract static class MetricsContainerKey implements Serializable { public static MetricsContainerKey unBounded() { return new AutoValue_MetricsContainerStepMap_MetricsContainerKey(null); } @@ -118,7 +118,8 @@ private MetricsContainerImpl getContainerForKey(MetricsContainerKey key) { * MetricsContainerStepMap}. */ public void updateAll(MetricsContainerStepMap other) { - for (Map.Entry container : other.metricsContainers.entrySet()) { + for (Map.Entry container : + other.metricsContainers.entrySet()) { getContainerForKey(container.getKey()).update(container.getValue()); } } diff --git a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java index 0a3eca3138e5..94f3a81587fd 100644 --- a/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java +++ b/runners/java-fn-execution/src/test/java/org/apache/beam/runners/fnexecution/control/RemoteExecutionTest.java @@ -489,7 +489,6 @@ public Coder resultCoder() { } } - // TODO(ajamato): Test creating the metric in the ctor/object field. @Test public void testMetrics() throws Exception { final String processUserCounterName = "processUserCounter"; @@ -674,7 +673,6 @@ public void onCompleted(ProcessBundleResponse response) { builder.setInt64Value(6); expected.add(builder.build()); - // assertEquals(expected.size(), result.size()); assertThat(result, containsInAnyOrder(expected.toArray())); } }; @@ -692,9 +690,6 @@ public void onCompleted(ProcessBundleResponse response) { } } - // TODO(ajamato): Write a test where the ElementCount counters may be under - // different metrics containers. - @Test public void testExecutionWithUserState() throws Exception { Pipeline p = Pipeline.create(); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index ab570ae57a0a..42e571507f96 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java @@ -17,12 +17,16 @@ */ package org.apache.beam.fn.harness.data; +import java.io.Closeable; import java.util.HashMap; import org.apache.beam.runners.core.metrics.LabeledMetrics; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.MonitoringInfoMetricName; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.MetricsContainer; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; /** @@ -35,28 +39,29 @@ public class ElementCountFnDataReceiver implements FnDataReceiver> original; private Counter counter; + private MetricsContainer unboundMetricContainer; - public ElementCountFnDataReceiver(FnDataReceiver> original, String pCollection) { + public ElementCountFnDataReceiver( + FnDataReceiver> original, String pCollection, + MetricsContainerStepMap metricsContainerStepMap) { this.original = original; HashMap labels = new HashMap(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); MonitoringInfoMetricName metricName = MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - // TODO(BEAM-6505): Introducing a way for system counters to be instantiated on a consisntent - // metrics container. rather than using the currently scoped metrics container. - // There is a risk of accidentally creating the same metric under different metric containers - // which would create separate monitoringInfos for the same metrics. - // This will not happen for ElementCount because the producing pTransform for the pCollection - // always invokes the consumer, so it will always be instantiated under the same - // metric container scope. The use of the currently scoped MetricContainer is to use the - // pTransform of the current scope and attach it to the counter. this.counter = LabeledMetrics.counter(metricName); + // Place it in a metric container which is not bound to the step name. + // Though, this is not likely to happen for ElementCount because the producing pTransform for + // the pCollection always invokes the consumer. + this.unboundMetricContainer = metricsContainerStepMap.getUnboundContainer(); } @Override public void accept(WindowedValue input) throws Exception { - // Increment the counter for each window the element occurs in. - this.counter.inc(input.getWindows().size()); - this.original.accept(input); + try (Closeable close = MetricsEnvironment.scopedMetricsContainer(this.unboundMetricContainer)) { + // Increment the counter for each window the element occurs in. + this.counter.inc(input.getWindows().size()); + this.original.accept(input); + } } } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java index cc436d8ee1c2..8a35d83c6666 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java @@ -106,7 +106,8 @@ public FnDataReceiver> getMultiplexingConsumer(String pCollecti pCollectionIdsToConsumers.get(pCollectionId); FnDataReceiver> consumer = MultiplexingFnDataReceiver.forConsumers(consumers); - wrappedConsumer = new ElementCountFnDataReceiver(consumer, pCollectionId); + wrappedConsumer = new ElementCountFnDataReceiver( + consumer, pCollectionId, metricsContainerRegistry); pCollectionIdsToWrappedConsumer.put(pCollectionId, wrappedConsumer); } return wrappedConsumer; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java index 5d4d641eb1cf..b5d583b75f1f 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistry.java @@ -73,7 +73,6 @@ public void register(String pTransformId, ThrowingRunnable runnable) { () -> { MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId); try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) { - // TODO(ajamato): Setup the proper pTransform context for Metrics to use. // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. runnable.run(); } diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java index 67ec72515de5..b750ce311708 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.ServiceLoader; import org.apache.beam.fn.harness.data.PCollectionConsumerRegistry; @@ -45,11 +44,9 @@ import org.apache.beam.runners.core.construction.PipelineTranslation; import org.apache.beam.runners.core.construction.SdkComponents; import org.apache.beam.runners.core.construction.metrics.MetricKey; -import org.apache.beam.runners.core.metrics.MetricUpdates; import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; -import org.apache.beam.runners.core.metrics.MonitoringInfoMetricName; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.StringUtf8Coder; diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java index a18c2e9c89dc..3c73c6d72969 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java @@ -23,6 +23,7 @@ import java.io.Closeable; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.metrics.MetricsEnvironment; @@ -41,30 +42,27 @@ public class ElementCountFnDataReceiverTest { @Test public void testCountsElements() throws Exception { final String pCollectionA = "pCollectionA"; - final String stepA = "stepA"; - MetricsContainerImpl metricsContainer = new MetricsContainerImpl(stepA); - try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { + MetricsContainerStepMap metricContainerRegistry = new MetricsContainerStepMap(); - FnDataReceiver> consumer = mock(FnDataReceiver.class); - ElementCountFnDataReceiver wrapperConsumer = - new ElementCountFnDataReceiver(consumer, pCollectionA); - WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); - int numElements = 20; - for (int i = 0; i < numElements; i++) { - wrapperConsumer.accept(element); - } + FnDataReceiver> consumer = mock(FnDataReceiver.class); + ElementCountFnDataReceiver wrapperConsumer = + new ElementCountFnDataReceiver(consumer, pCollectionA, metricContainerRegistry); + WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); + int numElements = 20; + for (int i = 0; i < numElements; i++) { + wrapperConsumer.accept(element); + } - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); - builder.setPCollectionLabel(pCollectionA); - builder.setInt64Value(numElements); - MonitoringInfo expected = builder.build(); + SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); + builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setPCollectionLabel(pCollectionA); + builder.setInt64Value(numElements); + MonitoringInfo expected = builder.build(); - // Clear the timestamp before compairison. - MonitoringInfo first = metricsContainer.getMonitoringInfos().iterator().next(); - MonitoringInfo result = SimpleMonitoringInfoBuilder.clearTimestamp(first); - assertEquals(expected, result); - } + // Clear the timestamp before compairison. + MonitoringInfo first = metricContainerRegistry.getMonitoringInfos().iterator().next(); + MonitoringInfo result = SimpleMonitoringInfoBuilder.clearTimestamp(first); + assertEquals(expected, result); } } From 745ae62f2d88d5b6509ab3ba7f54f1ed69ed28db Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Fri, 25 Jan 2019 18:16:41 -0800 Subject: [PATCH 11/26] spotless --- .../beam/fn/harness/data/ElementCountFnDataReceiver.java | 3 ++- .../beam/fn/harness/data/PCollectionConsumerRegistry.java | 4 ++-- .../beam/fn/harness/data/ElementCountFnDataReceiverTest.java | 3 --- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index 42e571507f96..1b606cc4d22a 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java @@ -42,7 +42,8 @@ public class ElementCountFnDataReceiver implements FnDataReceiver> original, String pCollection, + FnDataReceiver> original, + String pCollection, MetricsContainerStepMap metricsContainerStepMap) { this.original = original; HashMap labels = new HashMap(); diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java index 8a35d83c6666..21a3fd63e145 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java @@ -106,8 +106,8 @@ public FnDataReceiver> getMultiplexingConsumer(String pCollecti pCollectionIdsToConsumers.get(pCollectionId); FnDataReceiver> consumer = MultiplexingFnDataReceiver.forConsumers(consumers); - wrappedConsumer = new ElementCountFnDataReceiver( - consumer, pCollectionId, metricsContainerRegistry); + wrappedConsumer = + new ElementCountFnDataReceiver(consumer, pCollectionId, metricsContainerRegistry); pCollectionIdsToWrappedConsumer.put(pCollectionId, wrappedConsumer); } return wrappedConsumer; diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java index 3c73c6d72969..ac8987f4c20c 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java @@ -20,13 +20,10 @@ import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.mock; -import java.io.Closeable; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; -import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.fn.data.FnDataReceiver; -import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; import org.junit.Test; From f5bc350fb69839d5401e72a574e2a41b3c3efbb3 Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Tue, 29 Jan 2019 16:36:29 -0800 Subject: [PATCH 12/26] Add tests for ElementCountFnDataReceiver, PCollectionConsumerRegistry, PTransformFunctionRegistry, remove use of MetricContainerKey due to risk of accesing heap for every element --- .../core/metrics/MetricsContainerStepMap.java | 78 +++++-------------- .../metrics/MetricsContainerImplTest.java | 2 + sdks/java/harness/build.gradle | 1 + .../data/ElementCountFnDataReceiver.java | 4 +- .../data/ElementCountFnDataReceiverTest.java | 42 ++++++++-- .../data/PCollectionConsumerRegistryTest.java | 41 +++++++++- .../data/PTransformFunctionRegistryTest.java | 46 ++++++++++- 7 files changed, 147 insertions(+), 67 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index bcceeba65ebe..71aac89c54eb 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -19,13 +19,17 @@ import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; +import com.google.common.collect.Iterables; import com.google.auto.value.AutoValue; import java.io.Serializable; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.runners.core.construction.metrics.MetricFiltering; @@ -50,45 +54,8 @@ */ public class MetricsContainerStepMap implements Serializable { - /** - * Key class to lookup the metric container for a step or unbound to any step. This is preferable - * to using null(which can't be used as a key). Additonally, this class could be extended to allow - * containers for other non pTransform contexts. - */ - @AutoValue - abstract static class MetricsContainerKey implements Serializable { - public static MetricsContainerKey unBounded() { - return new AutoValue_MetricsContainerStepMap_MetricsContainerKey(null); - } - - public static MetricsContainerKey forStep(String step) { - return new AutoValue_MetricsContainerStepMap_MetricsContainerKey(step); - } - - @Nullable - public abstract String getStepName(); - - @Override - public int hashCode() { - // Don't include name and namespace, since they are lazily set. - return Objects.hash(getStepName()); - } - - @Override - public boolean equals(Object o) { - // If the object is compared with itself then return true - if (o == this) { - return true; - } - if (!(o instanceof MetricsContainerKey)) { - return false; - } - MetricsContainerKey other = (MetricsContainerKey) o; - return Objects.equals(this.getStepName(), other.getStepName()); - } - } - - private Map metricsContainers; + private Map metricsContainers; + private MetricsContainerImpl unboundContainer = new MetricsContainerImpl(null); public MetricsContainerStepMap() { this.metricsContainers = new ConcurrentHashMap<>(); @@ -96,21 +63,19 @@ public MetricsContainerStepMap() { /* Returns the container that is not bound to any step name. */ public MetricsContainerImpl getUnboundContainer() { - return getContainerForKey(MetricsContainerKey.unBounded()); + return this.unboundContainer; } /** Returns the container for the given step name. */ public MetricsContainerImpl getContainer(String stepName) { - checkArgument(!Strings.isNullOrEmpty(stepName), "stepName must be non-empty"); - return getContainerForKey(MetricsContainerKey.forStep(stepName)); - } - - /** @return the container for the given key */ - private MetricsContainerImpl getContainerForKey(MetricsContainerKey key) { - if (!metricsContainers.containsKey(key)) { - metricsContainers.put(key, new MetricsContainerImpl(key.getStepName())); + if (stepName == null) { + // TODO(BEAM-6538): Disallow this in the future, some tests rely on an empty step name today. + return getUnboundContainer(); + } + if (!metricsContainers.containsKey(stepName)) { + metricsContainers.put(stepName, new MetricsContainerImpl(stepName)); } - return metricsContainers.get(key); + return metricsContainers.get(stepName); } /** @@ -118,10 +83,11 @@ private MetricsContainerImpl getContainerForKey(MetricsContainerKey key) { * MetricsContainerStepMap}. */ public void updateAll(MetricsContainerStepMap other) { - for (Map.Entry container : + for (Map.Entry container : other.metricsContainers.entrySet()) { - getContainerForKey(container.getKey()).update(container.getValue()); + getContainer(container.getKey()).update(container.getValue()); } + getUnboundContainer().update(other.getUnboundContainer()); } /** @@ -189,8 +155,8 @@ public static MetricResults asAttemptedOnlyMetricResults( return new MetricsContainerStepMapMetricResults(attemptedMetricsContainers); } - private Map getMetricsContainers() { - return metricsContainers; + private Iterable getMetricsContainers() { + return Iterables.concat(metricsContainers.values(), Collections.singleton(unboundContainer)); } private static class MetricsContainerStepMapMetricResults extends MetricResults { @@ -215,16 +181,14 @@ private MetricsContainerStepMapMetricResults( MetricsContainerStepMap attemptedMetricsContainers, MetricsContainerStepMap committedMetricsContainers, boolean isCommittedSupported) { - for (MetricsContainerImpl container : - attemptedMetricsContainers.getMetricsContainers().values()) { + for (MetricsContainerImpl container : attemptedMetricsContainers.getMetricsContainers()) { MetricUpdates cumulative = container.getCumulative(); mergeCounters(counters, cumulative.counterUpdates(), attemptedCounterUpdateFn()); mergeDistributions( distributions, cumulative.distributionUpdates(), attemptedDistributionUpdateFn()); mergeGauges(gauges, cumulative.gaugeUpdates(), attemptedGaugeUpdateFn()); } - for (MetricsContainerImpl container : - committedMetricsContainers.getMetricsContainers().values()) { + for (MetricsContainerImpl container : committedMetricsContainers.getMetricsContainers()) { MetricUpdates cumulative = container.getCumulative(); mergeCounters(counters, cumulative.counterUpdates(), committedCounterUpdateFn()); mergeDistributions( diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java index ba8749c60448..efcbb7eb9fec 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java @@ -160,11 +160,13 @@ public void testMonitoringInfosArePopulatedForUserCounters() { SimpleMonitoringInfoBuilder builder1 = new SimpleMonitoringInfoBuilder(); builder1.setUrnForUserMetric("ns", "name1"); builder1.setInt64Value(5); + builder1.setPTransformLabel("step1"); builder1.build(); SimpleMonitoringInfoBuilder builder2 = new SimpleMonitoringInfoBuilder(); builder2.setUrnForUserMetric("ns", "name2"); builder2.setInt64Value(4); + builder1.setPTransformLabel("step1"); builder2.build(); ArrayList actualMonitoringInfos = new ArrayList(); diff --git a/sdks/java/harness/build.gradle b/sdks/java/harness/build.gradle index 41df222470c4..3e7d015ad687 100644 --- a/sdks/java/harness/build.gradle +++ b/sdks/java/harness/build.gradle @@ -51,6 +51,7 @@ dependencies { } compile library.java.jackson_databind shadow library.java.vendored_guava_20_0 + shadowTest library.java.powermock compile library.java.joda_time compile library.java.slf4j_api compile library.java.vendored_grpc_1_13_1 diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index 1b606cc4d22a..cddc777a41da 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java @@ -44,7 +44,7 @@ public class ElementCountFnDataReceiver implements FnDataReceiver> original, String pCollection, - MetricsContainerStepMap metricsContainerStepMap) { + MetricsContainerStepMap metricContainerRegistry) { this.original = original; HashMap labels = new HashMap(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); @@ -54,7 +54,7 @@ public ElementCountFnDataReceiver( // Place it in a metric container which is not bound to the step name. // Though, this is not likely to happen for ElementCount because the producing pTransform for // the pCollection always invokes the consumer. - this.unboundMetricContainer = metricsContainerStepMap.getUnboundContainer(); + this.unboundMetricContainer = metricContainerRegistry.getUnboundContainer(); } @Override diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java index ac8987f4c20c..4d3a8d458f92 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java @@ -18,18 +18,29 @@ package org.apache.beam.fn.harness.data; import static junit.framework.TestCase.assertEquals; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.withSettings; +import static org.powermock.api.mockito.PowerMockito.mockStatic; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.fn.data.FnDataReceiver; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; /** Tests for {@link ElementCountFnDataReceiver}. */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(MetricsEnvironment.class) public class ElementCountFnDataReceiverTest { - /** * Test that the elements are counted, and a MonitoringInfo can be extracted from a * metricsContainer, if it is in scope. @@ -40,16 +51,17 @@ public class ElementCountFnDataReceiverTest { public void testCountsElements() throws Exception { final String pCollectionA = "pCollectionA"; - MetricsContainerStepMap metricContainerRegistry = new MetricsContainerStepMap(); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); FnDataReceiver> consumer = mock(FnDataReceiver.class); ElementCountFnDataReceiver wrapperConsumer = - new ElementCountFnDataReceiver(consumer, pCollectionA, metricContainerRegistry); + new ElementCountFnDataReceiver(consumer, pCollectionA, metricsContainerRegistry); WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); int numElements = 20; for (int i = 0; i < numElements; i++) { wrapperConsumer.accept(element); } + verify(consumer, times(numElements)).accept(element); SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); @@ -57,9 +69,29 @@ public void testCountsElements() throws Exception { builder.setInt64Value(numElements); MonitoringInfo expected = builder.build(); - // Clear the timestamp before compairison. - MonitoringInfo first = metricContainerRegistry.getMonitoringInfos().iterator().next(); + // Clear the timestamp before comparison. + MonitoringInfo first = metricsContainerRegistry.getMonitoringInfos().iterator().next(); MonitoringInfo result = SimpleMonitoringInfoBuilder.clearTimestamp(first); assertEquals(expected, result); } + + @Test + public void testScopedMetricContainerInvokedUponAccept() throws Exception { + mockStatic(MetricsEnvironment.class, withSettings().verboseLogging()); + final String pCollectionA = "pCollectionA"; + + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + + FnDataReceiver> consumer = mock(FnDataReceiver.class, withSettings().verboseLogging()); + ElementCountFnDataReceiver wrapperConsumer = + new ElementCountFnDataReceiver(consumer, pCollectionA, metricsContainerRegistry); + WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); + wrapperConsumer.accept(element); + + verify(consumer, times(1)).accept(element); + + // Verify that static scopedMetricsContainer is called with unbound container. + PowerMockito.verifyStatic(times(1)); + MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getUnboundContainer()); + } } diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java index 89f8e2021fea..79e42ea8546a 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java @@ -22,18 +22,25 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.mockStatic; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; +import org.apache.beam.sdk.fn.function.ThrowingRunnable; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; /** Tests for {@link PCollectionConsumerRegistryTest}. */ -@RunWith(JUnit4.class) +@RunWith(PowerMockRunner.class) +@PrepareForTest(MetricsEnvironment.class) public class PCollectionConsumerRegistryTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -90,4 +97,36 @@ public void throwsOnRegisteringAfterMultiplexingConsumerWasInitialized() throws expectedException.expectMessage("cannot be register()-d after"); consumers.register(pCollectionA, pTransformId, consumerA2); } + + @Test + public void testScopedMetricContainerInvokedUponAcceptingElement() throws Exception { + mockStatic(MetricsEnvironment.class); + final String pCollectionA = "pCollectionA"; + + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PCollectionConsumerRegistry consumers = + new PCollectionConsumerRegistry(metricsContainerRegistry); + FnDataReceiver> consumerA1 = mock(FnDataReceiver.class); + FnDataReceiver> consumerA2 = mock(FnDataReceiver.class); + + consumers.register("pCollectionA", "pTransformA", consumerA1); + consumers.register("pCollectionA", "pTransformB", consumerA2); + + FnDataReceiver> wrapperConsumer = + (FnDataReceiver>) + (FnDataReceiver) consumers.getMultiplexingConsumer(pCollectionA); + + WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); + wrapperConsumer.accept(element); + + // Verify that static scopedMetricsContainer is called with pTransformA's container. + PowerMockito.verifyStatic(times(1)); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.getContainer("pTransformA")); + + // Verify that static scopedMetricsContainer is called with pTransformB's container. + PowerMockito.verifyStatic(times(1)); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.getContainer("pTransformB")); + } } diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java index 9383a2194a6f..f18ca318916f 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java @@ -17,23 +17,38 @@ */ package org.apache.beam.fn.harness.data; +import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import java.io.Closeable; +import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingRunnable; +import org.apache.beam.sdk.metrics.MetricsContainer; +import org.apache.beam.sdk.metrics.MetricsEnvironment; +import org.apache.beam.vendor.grpc.v1p13p1.io.netty.util.internal.MathUtil; +import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.mockito.internal.verification.VerificationModeFactory; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; /** Tests for {@link PTransformFunctionRegistry}. */ -@RunWith(JUnit4.class) +@RunWith(PowerMockRunner.class) +@PrepareForTest(MetricsEnvironment.class) public class PTransformFunctionRegistryTest { @Test public void functionsAreInvokedIndirectlyAfterRegisteringAndInvoking() throws Exception { - MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + MetricsContainerStepMap metricsContainerRegistry = mock(MetricsContainerStepMap.class); PTransformFunctionRegistry testObject = new PTransformFunctionRegistry(metricsContainerRegistry); @@ -49,4 +64,31 @@ public void functionsAreInvokedIndirectlyAfterRegisteringAndInvoking() throws Ex verify(runnableA, times(1)).run(); verify(runnableB, times(1)).run(); } + + @Test + public void testScopedMetricContainerInvokedUponRunningFunctions() throws Exception { + mockStatic(MetricsEnvironment.class); + MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); + PTransformFunctionRegistry testObject = + new PTransformFunctionRegistry(metricsContainerRegistry); + + ThrowingRunnable runnableA = mock(ThrowingRunnable.class); + ThrowingRunnable runnableB = mock(ThrowingRunnable.class); + testObject.register("pTransformA", runnableA); + testObject.register("pTransformB", runnableB); + + for (ThrowingRunnable func : testObject.getFunctions()) { + func.run(); + } + + // Verify that static scopedMetricsContainer is called with pTransformA's container. + PowerMockito.verifyStatic(times(1)); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.getContainer("pTransformA")); + + // Verify that static scopedMetricsContainer is called with pTransformB's container. + PowerMockito.verifyStatic(times(1)); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.getContainer("pTransformB")); + } } From 76e1f3163bb4e2377d7eb1598f44f27e12f23a3d Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Tue, 29 Jan 2019 18:00:41 -0800 Subject: [PATCH 13/26] Added another test to MetricsContainerStepMap --- .../core/metrics/MetricsContainerImpl.java | 9 +++- .../core/metrics/MetricsContainerStepMap.java | 15 ++----- .../metrics/MetricsContainerStepMapTest.java | 43 +++++++++++++++++++ .../data/ElementCountFnDataReceiverTest.java | 4 +- .../data/PCollectionConsumerRegistryTest.java | 8 +--- .../data/PTransformFunctionRegistryTest.java | 16 +------ 6 files changed, 60 insertions(+), 35 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index de6a24374862..af0413264f7b 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -50,6 +50,7 @@ @Experimental(Kind.METRICS) public class MetricsContainerImpl implements Serializable, MetricsContainer { + @Nullable private final String stepName; private MetricsMap counters = new MetricsMap<>(CounterCell::new); @@ -60,7 +61,7 @@ public class MetricsContainerImpl implements Serializable, MetricsContainer { private MetricsMap gauges = new MetricsMap<>(GaugeCell::new); /** Create a new {@link MetricsContainerImpl} associated with the given {@code stepName}. */ - public MetricsContainerImpl(String stepName) { + public MetricsContainerImpl(@Nullable String stepName) { this.stepName = stepName; } @@ -158,7 +159,11 @@ private MonitoringInfo counterUpdateToMonitoringInfo(MetricUpdate metricUp builder.setUrnForUserMetric( metricUpdate.getKey().metricName().getNamespace(), metricUpdate.getKey().metricName().getName()); - builder.setPTransformLabel(metricUpdate.getKey().stepName()); + String stepName = ""; + if (metricUpdate.getKey().stepName() != null) { + stepName = metricUpdate.getKey().stepName(); + } + builder.setPTransformLabel(stepName); } builder.setInt64Value(metricUpdate.getUpdate()); builder.setTimestampToNow(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 71aac89c54eb..439c26bce251 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -17,19 +17,13 @@ */ package org.apache.beam.runners.core.metrics; -import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; - import com.google.common.collect.Iterables; -import com.google.auto.value.AutoValue; import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.runners.core.construction.metrics.MetricFiltering; @@ -44,7 +38,6 @@ import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Function; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Predicate; -import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.FluentIterable; /** @@ -83,8 +76,7 @@ public MetricsContainerImpl getContainer(String stepName) { * MetricsContainerStepMap}. */ public void updateAll(MetricsContainerStepMap other) { - for (Map.Entry container : - other.metricsContainers.entrySet()) { + for (Map.Entry container : other.metricsContainers.entrySet()) { getContainer(container.getKey()).update(container.getValue()); } getUnboundContainer().update(other.getUnboundContainer()); @@ -109,7 +101,8 @@ public boolean equals(Object o) { MetricsContainerStepMap that = (MetricsContainerStepMap) o; - return metricsContainers.equals(that.metricsContainers); + // TODO(BEAM-6546): The underlying MetricContainerImpls do not implement equals(). + return getMetricsContainers().equals(that.getMetricsContainers()); } @Override @@ -134,7 +127,7 @@ public static MetricResults asMetricResults( public Iterable getMonitoringInfos() { // Extract user metrics and store as MonitoringInfos. ArrayList monitoringInfos = new ArrayList(); - for (MetricsContainerImpl container : metricsContainers.values()) { + for (MetricsContainerImpl container : getMetricsContainers()) { for (MonitoringInfo mi : container.getMonitoringInfos()) { monitoringInfos.add(mi); } diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java index e2b9e4bb4af8..0bfca11c7bd7 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java @@ -20,16 +20,21 @@ import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults; import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asMetricResults; import static org.apache.beam.sdk.metrics.MetricResultsMatchers.metricsResult; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; import java.io.Closeable; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Distribution; import org.apache.beam.sdk.metrics.DistributionResult; import org.apache.beam.sdk.metrics.Gauge; import org.apache.beam.sdk.metrics.GaugeResult; +import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.metrics.Metrics; @@ -172,6 +177,44 @@ public void testGaugeCommittedUnsupportedInAttemptedAccumulatedMetricResults() { assertGauge(GAUGE_NAME, step1res, STEP1, GaugeResult.empty(), true); } + @Test + public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { + MetricsContainerStepMap baseMetricContainerRegistry = new MetricsContainerStepMap(); + + CounterCell c1 = + baseMetricContainerRegistry.getContainer(STEP1).getCounter(MetricName.named("ns", "name1")); + CounterCell c2 = + baseMetricContainerRegistry + .getUnboundContainer() + .getCounter(MetricName.named("ns", "name2")); + c1.inc(7); + c2.inc(14); + + MetricsContainerStepMap testObject = new MetricsContainerStepMap(); + testObject.updateAll(baseMetricContainerRegistry); + + List expected = new ArrayList(); + + SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); + builder.setUrnForUserMetric("ns", "name1"); + builder.setPTransformLabel(STEP1); + builder.setInt64Value(7); + expected.add(builder.build()); + + builder = new SimpleMonitoringInfoBuilder(); + builder.setUrnForUserMetric("ns", "name2"); + builder.setPTransformLabel(""); + builder.setInt64Value(14); + expected.add(builder.build()); + + ArrayList actual = new ArrayList(); + + for (MonitoringInfo mi : testObject.getMonitoringInfos()) { + actual.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + } + assertThat(actual, containsInAnyOrder(expected.toArray())); + } + @Test public void testAttemptedAndCommittedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java index 4d3a8d458f92..d88405a27722 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java @@ -18,7 +18,6 @@ package org.apache.beam.fn.harness.data; import static junit.framework.TestCase.assertEquals; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -82,7 +81,8 @@ public void testScopedMetricContainerInvokedUponAccept() throws Exception { MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); - FnDataReceiver> consumer = mock(FnDataReceiver.class, withSettings().verboseLogging()); + FnDataReceiver> consumer = + mock(FnDataReceiver.class, withSettings().verboseLogging()); ElementCountFnDataReceiver wrapperConsumer = new ElementCountFnDataReceiver(consumer, pCollectionA, metricsContainerRegistry); WindowedValue element = WindowedValue.valueInGlobalWindow("elem"); diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java index 79e42ea8546a..5452b4c5aa11 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistryTest.java @@ -26,14 +26,12 @@ import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.data.FnDataReceiver; -import org.apache.beam.sdk.fn.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -121,12 +119,10 @@ public void testScopedMetricContainerInvokedUponAcceptingElement() throws Except // Verify that static scopedMetricsContainer is called with pTransformA's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer( - metricsContainerRegistry.getContainer("pTransformA")); + MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformA")); // Verify that static scopedMetricsContainer is called with pTransformB's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer( - metricsContainerRegistry.getContainer("pTransformB")); + MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformB")); } } diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java index f18ca318916f..2069dfcc847d 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/PTransformFunctionRegistryTest.java @@ -17,26 +17,16 @@ */ package org.apache.beam.fn.harness.data; -import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; -import java.io.Closeable; -import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.fn.function.ThrowingRunnable; -import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; -import org.apache.beam.vendor.grpc.v1p13p1.io.netty.util.internal.MathUtil; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -83,12 +73,10 @@ public void testScopedMetricContainerInvokedUponRunningFunctions() throws Except // Verify that static scopedMetricsContainer is called with pTransformA's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer( - metricsContainerRegistry.getContainer("pTransformA")); + MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformA")); // Verify that static scopedMetricsContainer is called with pTransformB's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer( - metricsContainerRegistry.getContainer("pTransformB")); + MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformB")); } } From 6525491d0deda5f73cf25746f9a3d4f286219825 Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Tue, 29 Jan 2019 18:05:16 -0800 Subject: [PATCH 14/26] spotless --- .../apache/beam/runners/core/metrics/MetricsContainerImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index af0413264f7b..301217b1d68d 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java @@ -50,8 +50,7 @@ @Experimental(Kind.METRICS) public class MetricsContainerImpl implements Serializable, MetricsContainer { - @Nullable - private final String stepName; + @Nullable private final String stepName; private MetricsMap counters = new MetricsMap<>(CounterCell::new); From 8d3753561c897ff446bfa1d3d9b26db83c50314c Mon Sep 17 00:00:00 2001 From: Alex Amato Date: Tue, 29 Jan 2019 19:53:54 -0800 Subject: [PATCH 15/26] spotless --- .../beam/runners/core/metrics/MetricsContainerStepMap.java | 2 +- .../beam/runners/core/metrics/MetricsContainerImplTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 439c26bce251..145a38b46cec 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -17,7 +17,6 @@ */ package org.apache.beam.runners.core.metrics; -import com.google.common.collect.Iterables; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; @@ -39,6 +38,7 @@ import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Function; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Predicate; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.FluentIterable; +import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.Iterables; /** * Metrics containers by step. diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java index efcbb7eb9fec..063616757562 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java @@ -166,7 +166,7 @@ public void testMonitoringInfosArePopulatedForUserCounters() { SimpleMonitoringInfoBuilder builder2 = new SimpleMonitoringInfoBuilder(); builder2.setUrnForUserMetric("ns", "name2"); builder2.setInt64Value(4); - builder1.setPTransformLabel("step1"); + builder2.setPTransformLabel("step1"); builder2.build(); ArrayList actualMonitoringInfos = new ArrayList(); From d8dbc492fd3091dbd799d16a8e3c92d465006792 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 19:20:40 +0000 Subject: [PATCH 16/26] move Metric protos from model/fn-execution to model/pipeline --- .../src/main/proto/beam_fn_api.proto | 65 +------------ .../main/proto/beam_pipeline_metrics.proto | 93 +++++++++++++++++++ .../flink/metrics/FlinkMetricContainer.java | 10 +- .../metrics/FlinkMetricContainerTest.java | 14 +-- .../fn/control/BeamFnMapTaskExecutorTest.java | 5 +- sdks/python/apache_beam/metrics/cells.py | 15 +-- .../apache_beam/metrics/monitoring_infos.py | 4 +- 7 files changed, 120 insertions(+), 86 deletions(-) create mode 100644 model/pipeline/src/main/proto/beam_pipeline_metrics.proto diff --git a/model/fn-execution/src/main/proto/beam_fn_api.proto b/model/fn-execution/src/main/proto/beam_fn_api.proto index 819320c84921..b963f2e4fd42 100644 --- a/model/fn-execution/src/main/proto/beam_fn_api.proto +++ b/model/fn-execution/src/main/proto/beam_fn_api.proto @@ -38,6 +38,7 @@ option go_package = "fnexecution_v1"; option java_package = "org.apache.beam.model.fnexecution.v1"; option java_outer_classname = "BeamFnApi"; +import "beam_pipeline_metrics.proto"; import "beam_runner_api.proto"; import "endpoints.proto"; import "google/protobuf/descriptor.proto"; @@ -428,7 +429,7 @@ message MonitoringInfo { // The Metric or monitored state. oneof data { MonitoringTableData monitoring_table_data = 3; - Metric metric = 4; + org.apache.beam.model.pipeline.v1.Metric metric = 4; } enum MonitoringInfoLabels { @@ -494,68 +495,6 @@ message MonitoringInfoTypeUrns { } } -message Metric { - // (Required) The data for this metric. - oneof data { - CounterData counter_data = 1; - DistributionData distribution_data = 2; - ExtremaData extrema_data = 3; - } -} - -// Data associated with a Counter or Gauge metric. -// This is designed to be compatible with metric collection -// systems such as DropWizard. -message CounterData { - oneof value { - int64 int64_value = 1; - double double_value = 2; - string string_value = 3; - } -} - -// Extrema messages are used for calculating -// Top-N/Bottom-N metrics. -message ExtremaData { - oneof extrema { - IntExtremaData int_extrema_data = 1; - DoubleExtremaData double_extrema_data = 2; - } -} - -message IntExtremaData { - repeated int64 int_values = 1; -} - -message DoubleExtremaData { - repeated double double_values = 2; -} - -// Data associated with a distribution metric. -// This is based off of the current DistributionData metric. -// This is not a stackdriver or dropwizard compatible -// style of distribution metric. -message DistributionData { - oneof distribution { - IntDistributionData int_distribution_data = 1; - DoubleDistributionData double_distribution_data = 2; - } -} - -message IntDistributionData { - int64 count = 1; - int64 sum = 2; - int64 min = 3; - int64 max = 4; -} - -message DoubleDistributionData { - int64 count = 1; - double sum = 2; - double min = 3; - double max = 4; -} - // General MonitoredState information which contains // structured information which does not fit into a typical // metric format. For example, a table of important files diff --git a/model/pipeline/src/main/proto/beam_pipeline_metrics.proto b/model/pipeline/src/main/proto/beam_pipeline_metrics.proto new file mode 100644 index 000000000000..1a8614a543a7 --- /dev/null +++ b/model/pipeline/src/main/proto/beam_pipeline_metrics.proto @@ -0,0 +1,93 @@ +/* + * 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. + */ + +/* + * Protocol Buffers describing the Runner API, which is the runner-independent, + * SDK-independent definition of the Beam model. + */ + +syntax = "proto3"; + +package org.apache.beam.model.pipeline.v1; + +option go_package = "pipeline_v1"; +option java_package = "org.apache.beam.model.pipeline.v1"; +option java_outer_classname = "PipelineMetrics"; + +message Metric { + // (Required) The data for this metric. + oneof data { + CounterData counter_data = 1; + DistributionData distribution_data = 2; + ExtremaData extrema_data = 3; + } +} + +// Data associated with a Counter or Gauge metric. +// This is designed to be compatible with metric collection +// systems such as DropWizard. +message CounterData { + oneof value { + int64 int64_value = 1; + double double_value = 2; + string string_value = 3; + } +} + +// Extrema messages are used for calculating +// Top-N/Bottom-N metrics. +message ExtremaData { + oneof extrema { + IntExtremaData int_extrema_data = 1; + DoubleExtremaData double_extrema_data = 2; + } +} + +message IntExtremaData { + repeated int64 int_values = 1; +} + +message DoubleExtremaData { + repeated double double_values = 2; +} + +// Data associated with a distribution metric. +// This is based off of the current DistributionData metric. +// This is not a stackdriver or dropwizard compatible +// style of distribution metric. +message DistributionData { + oneof distribution { + IntDistributionData int_distribution_data = 1; + DoubleDistributionData double_distribution_data = 2; + } +} + +message IntDistributionData { + int64 count = 1; + int64 sum = 2; + int64 min = 3; + int64 max = 4; +} + +message DoubleDistributionData { + int64 count = 1; + double sum = 2; + double min = 3; + double max = 4; +} + diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java index 23d1f8356da3..348790a6fe4c 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java @@ -23,12 +23,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.CounterData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.DistributionData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.ExtremaData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.IntDistributionData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.CounterData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.DistributionData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.ExtremaData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.IntDistributionData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.Metric; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.metrics.Distribution; diff --git a/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java b/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java index 6b9435e89d2d..ea97f9343173 100644 --- a/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java +++ b/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java @@ -30,13 +30,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.apache.beam.model.fnexecution.v1.BeamFnApi; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.CounterData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.DoubleDistributionData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.IntDistributionData; -import org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo.MonitoringInfoLabels; +import org.apache.beam.model.pipeline.v1.PipelineMetrics; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.CounterData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.DoubleDistributionData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.IntDistributionData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.Metric; import org.apache.beam.runners.core.metrics.CounterCell; import org.apache.beam.runners.core.metrics.DistributionCell; import org.apache.beam.runners.core.metrics.DistributionData; @@ -193,7 +193,7 @@ public void testDropUnexpectedMonitoringInfoTypes() { .setMetric( Metric.newBuilder() .setDistributionData( - BeamFnApi.DistributionData.newBuilder() + PipelineMetrics.DistributionData.newBuilder() .setIntDistributionData( IntDistributionData.newBuilder() .setSum(30) @@ -209,7 +209,7 @@ public void testDropUnexpectedMonitoringInfoTypes() { .setMetric( Metric.newBuilder() .setDistributionData( - BeamFnApi.DistributionData.newBuilder() + PipelineMetrics.DistributionData.newBuilder() .setDoubleDistributionData( DoubleDistributionData.newBuilder() .setSum(30) diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/fn/control/BeamFnMapTaskExecutorTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/fn/control/BeamFnMapTaskExecutorTest.java index f38d31fd69e5..62f637229eec 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/fn/control/BeamFnMapTaskExecutorTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/fn/control/BeamFnMapTaskExecutorTest.java @@ -36,6 +36,7 @@ import org.apache.beam.model.fnexecution.v1.BeamFnApi; import org.apache.beam.model.fnexecution.v1.BeamFnApi.InstructionRequest; import org.apache.beam.model.fnexecution.v1.BeamFnApi.InstructionResponse; +import org.apache.beam.model.pipeline.v1.PipelineMetrics; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.StateInternals; import org.apache.beam.runners.core.TimerInternals; @@ -475,9 +476,9 @@ public void testExtractCounterUpdatesReturnsValidProgressTrackerCounterUpdatesIf .setType("beam:metrics:sum_int_64") .putLabels("PTRANSFORM", "ExpectedPTransform") .setMetric( - BeamFnApi.Metric.newBuilder() + PipelineMetrics.Metric.newBuilder() .setCounterData( - BeamFnApi.CounterData.newBuilder() + PipelineMetrics.CounterData.newBuilder() .setInt64Value(expectedCounterValue) .build()) .build()) diff --git a/sdks/python/apache_beam/metrics/cells.py b/sdks/python/apache_beam/metrics/cells.py index 65ca18582e14..6c09ca0a02ed 100644 --- a/sdks/python/apache_beam/metrics/cells.py +++ b/sdks/python/apache_beam/metrics/cells.py @@ -37,6 +37,7 @@ from apache_beam.metrics.metricbase import Distribution from apache_beam.metrics.metricbase import Gauge from apache_beam.portability.api import beam_fn_api_pb2 +from apache_beam.portability.api import beam_pipeline_metrics_pb2 __all__ = ['DistributionResult', 'GaugeResult'] @@ -171,8 +172,8 @@ def to_runner_api_monitoring_info(self): # and Distributions. Since there is no CounterData class this method # was added to CounterCell. Consider adding a CounterData class or # removing the GaugeData and DistributionData classes. - return beam_fn_api_pb2.Metric( - counter_data=beam_fn_api_pb2.CounterData( + return beam_pipeline_metrics_pb2.Metric( + counter_data=beam_pipeline_metrics_pb2.CounterData( int64_value=self.get_cumulative() ) ) @@ -404,8 +405,8 @@ def from_runner_api(proto): def to_runner_api_monitoring_info(self): """Returns a Metric with this value for use in a MonitoringInfo.""" - return beam_fn_api_pb2.Metric( - counter_data=beam_fn_api_pb2.CounterData( + return beam_pipeline_metrics_pb2.Metric( + counter_data=beam_pipeline_metrics_pb2.CounterData( int64_value=self.value ) ) @@ -478,9 +479,9 @@ def from_runner_api(proto): def to_runner_api_monitoring_info(self): """Returns a Metric with this value for use in a MonitoringInfo.""" - return beam_fn_api_pb2.Metric( - distribution_data=beam_fn_api_pb2.DistributionData( - int_distribution_data=beam_fn_api_pb2.IntDistributionData( + return beam_pipeline_metrics_pb2.Metric( + distribution_data=beam_pipeline_metrics_pb2.DistributionData( + int_distribution_data=beam_pipeline_metrics_pb2.IntDistributionData( count=self.count, sum=self.sum, min=self.min, max=self.max))) diff --git a/sdks/python/apache_beam/metrics/monitoring_infos.py b/sdks/python/apache_beam/metrics/monitoring_infos.py index bf1fd8ba4f81..3baaf47ea30d 100644 --- a/sdks/python/apache_beam/metrics/monitoring_infos.py +++ b/sdks/python/apache_beam/metrics/monitoring_infos.py @@ -29,9 +29,9 @@ from apache_beam.metrics.cells import GaugeData from apache_beam.metrics.cells import GaugeResult from apache_beam.portability import common_urns -from apache_beam.portability.api.beam_fn_api_pb2 import CounterData -from apache_beam.portability.api.beam_fn_api_pb2 import Metric from apache_beam.portability.api.beam_fn_api_pb2 import MonitoringInfo +from apache_beam.portability.api.beam_pipeline_metrics_pb2 import CounterData +from apache_beam.portability.api.beam_pipeline_metrics_pb2 import Metric ELEMENT_COUNT_URN = common_urns.monitoring_infos.ELEMENT_COUNT.urn START_BUNDLE_MSECS_URN = common_urns.monitoring_infos.START_BUNDLE_MSECS.urn From a245f3890365a2c88702656f1838d1977bbd465b Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 19:20:55 +0000 Subject: [PATCH 17/26] add MetricKey, MetricName protos --- .../src/main/proto/beam_pipeline_metrics.proto | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/model/pipeline/src/main/proto/beam_pipeline_metrics.proto b/model/pipeline/src/main/proto/beam_pipeline_metrics.proto index 1a8614a543a7..da0c70b1e312 100644 --- a/model/pipeline/src/main/proto/beam_pipeline_metrics.proto +++ b/model/pipeline/src/main/proto/beam_pipeline_metrics.proto @@ -29,6 +29,16 @@ option go_package = "pipeline_v1"; option java_package = "org.apache.beam.model.pipeline.v1"; option java_outer_classname = "PipelineMetrics"; +message MetricKey { + string step = 1; + MetricName metric_name = 2; +} + +message MetricName { + string namespace = 1; + string name = 2; +} + message Metric { // (Required) The data for this metric. oneof data { From 417341eb188948f622e839afc8ab2ca9f03c739a Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:47:10 +0000 Subject: [PATCH 18/26] add GetJobMetrics RPC, associated protos --- .../src/main/proto/beam_job_api.proto | 12 +++++ .../src/main/proto/beam_job_metrics.proto | 54 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 model/job-management/src/main/proto/beam_job_metrics.proto diff --git a/model/job-management/src/main/proto/beam_job_api.proto b/model/job-management/src/main/proto/beam_job_api.proto index cd2ddffdaf40..df6d51fc66a9 100644 --- a/model/job-management/src/main/proto/beam_job_api.proto +++ b/model/job-management/src/main/proto/beam_job_api.proto @@ -31,6 +31,7 @@ option java_outer_classname = "JobApi"; import "beam_runner_api.proto"; import "endpoints.proto"; +import "beam_job_metrics.proto"; import "google/protobuf/struct.proto"; @@ -57,6 +58,9 @@ service JobService { // Get the supported pipeline options of the runner rpc DescribePipelineOptions (DescribePipelineOptionsRequest) returns (DescribePipelineOptionsResponse); + + // Fetch metrics for a given job + rpc GetJobMetrics (GetJobMetricsRequest) returns (GetJobMetricsResponse); } @@ -155,6 +159,14 @@ message JobMessage { } } +message GetJobMetricsRequest { + string job_id = 1; // (required) +} + +message GetJobMetricsResponse { + repeated MetricStatus metric_statuses = 1; +} + message JobMessagesResponse { oneof response { JobMessage message_response = 1; diff --git a/model/job-management/src/main/proto/beam_job_metrics.proto b/model/job-management/src/main/proto/beam_job_metrics.proto new file mode 100644 index 000000000000..adf6987ec6fc --- /dev/null +++ b/model/job-management/src/main/proto/beam_job_metrics.proto @@ -0,0 +1,54 @@ +/* + * 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. + */ + +/* + * Protocol Buffers for sending metrics over the Job API, between a runner and job server + */ + +syntax = "proto3"; + +package org.apache.beam.model.job_management.v1; + +option go_package = "jobmanagement_v1"; +option java_package = "org.apache.beam.model.jobmanagement.v1"; +option java_outer_classname = "JobApiMetrics"; + +import "beam_pipeline_metrics.proto"; + +message CounterResult { + int64 attempted = 1; + int64 committed = 2; +} + +message DistributionResult { + org.apache.beam.model.pipeline.v1.IntDistributionData attempted = 1; + org.apache.beam.model.pipeline.v1.IntDistributionData committed = 2; +} + +message MetricResult { + oneof result { + CounterResult counter_result = 1; + DistributionResult distribution_result = 2; + } +} + +message MetricStatus { + org.apache.beam.model.pipeline.v1.MetricKey metric_key = 1; + MetricResult metric_result = 2; +} + From d7a3b6aa937f8fe6fc775c666ef34cb86087b354 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 15:24:39 +0000 Subject: [PATCH 19/26] protect against null step-name (e.g. for PCollection metrics) in MetricFiltering --- .../beam/runners/core/construction/metrics/MetricFiltering.java | 1 + 1 file changed, 1 insertion(+) diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricFiltering.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricFiltering.java index b6be3ce17d4e..dd04d21a603f 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricFiltering.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/metrics/MetricFiltering.java @@ -43,6 +43,7 @@ private MetricFiltering() {} public static boolean matches(MetricsFilter filter, MetricKey key) { return filter == null || (matchesName(key.metricName(), filter.names()) + && key.stepName() != null && matchesScope(key.stepName(), filter.steps())); } From 3c097fd83e550b5e4db8e09c394af21a7ddfd07e Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:52:26 +0000 Subject: [PATCH 20/26] add JobInvocation.getMetrics() API --- .../org/apache/beam/runners/flink/FlinkJobInvocation.java | 6 ++++++ .../runners/fnexecution/jobsubmission/JobInvocation.java | 3 +++ .../org/apache/beam/runners/samza/SamzaJobInvocation.java | 6 ++++++ 3 files changed, 15 insertions(+) diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java index efaa40aa4ea2..b39d76073c62 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java @@ -38,6 +38,7 @@ import org.apache.beam.runners.fnexecution.jobsubmission.JobInvocation; import org.apache.beam.runners.fnexecution.provisioning.JobInfo; import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ImmutableSet; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.Sets; @@ -252,6 +253,11 @@ public JobState.Enum getState() { return this.jobState; } + @Override + public MetricResults getMetrics() { + throw new UnsupportedOperationException(); + } + @Override public synchronized void addStateListener(Consumer stateStreamObserver) { stateStreamObserver.accept(getState()); diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java index 831edc942802..8c830e587aae 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java @@ -21,6 +21,7 @@ import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessage; import org.apache.beam.model.jobmanagement.v1.JobApi.JobState; import org.apache.beam.model.jobmanagement.v1.JobApi.JobState.Enum; +import org.apache.beam.sdk.metrics.MetricResults; /** Internal representation of a Job which has been invoked (prepared and run) by a client. */ public interface JobInvocation { @@ -37,6 +38,8 @@ public interface JobInvocation { /** Retrieve the job's current state. */ JobState.Enum getState(); + MetricResults getMetrics(); + /** Listen for job state changes with a {@link Consumer}. */ void addStateListener(Consumer stateStreamObserver); diff --git a/runners/samza/src/main/java/org/apache/beam/runners/samza/SamzaJobInvocation.java b/runners/samza/src/main/java/org/apache/beam/runners/samza/SamzaJobInvocation.java index d70e10af7532..98375d1e7d02 100644 --- a/runners/samza/src/main/java/org/apache/beam/runners/samza/SamzaJobInvocation.java +++ b/runners/samza/src/main/java/org/apache/beam/runners/samza/SamzaJobInvocation.java @@ -34,6 +34,7 @@ import org.apache.beam.runners.samza.util.PortablePipelineDotRenderer; import org.apache.beam.sdk.fn.IdGenerator; import org.apache.beam.sdk.fn.IdGenerators; +import org.apache.beam.sdk.metrics.MetricResults; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -77,6 +78,11 @@ public void start() { pipelineResult = invokeSamzaJob(); } + @Override + public MetricResults getMetrics() { + throw new UnsupportedOperationException(); + } + @Override public String getId() { return id; From 8b0074d6f8a54ec18f38ee9bf4941437ae005e42 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:56:48 +0000 Subject: [PATCH 21/26] populate metrics in FlinkJobInvocation --- .../org/apache/beam/runners/flink/FlinkJobInvocation.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java index b39d76073c62..33e37e475da3 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkJobInvocation.java @@ -76,6 +76,7 @@ public static FlinkJobInvocation create( private JobState.Enum jobState; private List> stateObservers; private List> messageObservers; + private MetricResults metrics; @Nullable private ListenableFuture invocationFuture; @@ -192,6 +193,10 @@ public void onSuccess(@Nullable PipelineResult pipelineResult) { pipelineResult.getState() == PipelineResult.State.DONE, "Success on non-Done state: " + pipelineResult.getState()); setState(JobState.Enum.DONE); + try { + metrics = pipelineResult.metrics(); + } catch (UnsupportedOperationException e) { + } } else { setState(JobState.Enum.UNSPECIFIED); } @@ -255,7 +260,7 @@ public JobState.Enum getState() { @Override public MetricResults getMetrics() { - throw new UnsupportedOperationException(); + return metrics; } @Override From 46bb6525ff20b3d9a24a8effc4521708cd2721f7 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:57:08 +0000 Subject: [PATCH 22/26] store flink metrics keyed by step name --- .../metrics/DoFnRunnerWithMetricsUpdate.java | 2 +- .../flink/metrics/FlinkMetricContainer.java | 35 ++++++++++++++++--- .../flink/metrics/ReaderInvocationUtil.java | 4 +-- .../FlinkExecutableStageFunction.java | 7 ++-- .../ExecutableStageDoFnOperator.java | 4 +-- .../metrics/FlinkMetricContainerTest.java | 16 ++++----- 6 files changed, 45 insertions(+), 23 deletions(-) diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/DoFnRunnerWithMetricsUpdate.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/DoFnRunnerWithMetricsUpdate.java index 024fc7696454..f5e3c34ca2dc 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/DoFnRunnerWithMetricsUpdate.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/DoFnRunnerWithMetricsUpdate.java @@ -90,7 +90,7 @@ public void finishBundle() { } // update metrics - container.updateMetrics(stepName); + container.updateMetrics(); } @Override diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java index 348790a6fe4c..e7dde7abacbf 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java @@ -19,6 +19,8 @@ import static org.apache.beam.runners.core.metrics.MetricUrns.parseUrn; import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL; import java.util.HashMap; import java.util.List; @@ -94,16 +96,39 @@ public MetricsContainer getMetricsContainer(String stepName) { : null; } + public MetricsContainer getUnboundMetricsContainer() { + return metricsAccumulator != null + ? metricsAccumulator.getLocalValue().getUnboundContainer() + : null; + } + /** * Update this container with metrics from the passed {@link MonitoringInfo}s, and send updates * along to Flink's internal metrics framework. */ - public void updateMetrics(String stepName, List monitoringInfos) { - MetricsContainer metricsContainer = getMetricsContainer(stepName); + public void updateMetrics(List monitoringInfos) { monitoringInfos.forEach( monitoringInfo -> { if (monitoringInfo.hasMetric()) { String urn = monitoringInfo.getUrn(); + Map labels = monitoringInfo.getLabelsMap(); + + MetricsContainer metricsContainer; + + String ptransform = labels.get(PTRANSFORM_LABEL); + if (ptransform != null) { + metricsContainer = getMetricsContainer(ptransform); + } else { + String pcollection = labels.get(PCOLLECTION_LABEL); + if (pcollection == null) { + throw new IllegalStateException( + String.format( + "No ptransform or pcollection label found on monitoringinfo %s", + monitoringInfo)); + } + metricsContainer = getUnboundMetricsContainer(); + } + MetricName metricName = parseUrn(urn); Metric metric = monitoringInfo.getMetric(); if (metric.hasCounterData()) { @@ -134,17 +159,17 @@ public void updateMetrics(String stepName, List monitoringInfos) } } }); - updateMetrics(stepName); + updateMetrics(); } /** * Update Flink's internal metrics ({@link this#flinkCounterCache}) with the latest metrics for a * given step. */ - void updateMetrics(String stepName) { + void updateMetrics() { MetricResults metricResults = asAttemptedOnlyMetricResults(metricsAccumulator.getLocalValue()); MetricQueryResults metricQueryResults = - metricResults.queryMetrics(MetricsFilter.builder().addStep(stepName).build()); + metricResults.queryMetrics(MetricsFilter.builder().build()); updateCounters(metricQueryResults.getCounters()); updateDistributions(metricQueryResults.getDistributions()); updateGauge(metricQueryResults.getGauges()); diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/ReaderInvocationUtil.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/ReaderInvocationUtil.java index 995baccb17eb..2a56afc533fa 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/ReaderInvocationUtil.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/ReaderInvocationUtil.java @@ -49,7 +49,7 @@ public boolean invokeStart(ReaderT reader) throws IOException { try (Closeable ignored = MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { boolean result = reader.start(); - container.updateMetrics(stepName); + container.updateMetrics(); return result; } } else { @@ -62,7 +62,7 @@ public boolean invokeAdvance(ReaderT reader) throws IOException { try (Closeable ignored = MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { boolean result = reader.advance(); - container.updateMetrics(stepName); + container.updateMetrics(); return result; } } else { diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java index e7dafa8968f8..cfd6e928dbe5 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java @@ -100,8 +100,6 @@ public class FlinkExecutableStageFunction extends AbstractRichFunction private final Map outputMap; private final FlinkExecutableStageContext.Factory contextFactory; private final Coder windowCoder; - // Unique name for namespacing metrics; currently just takes the input ID - private final String stageName; // Worker-local fields. These should only be constructed and consumed on Flink TaskManagers. private transient RuntimeContext runtimeContext; @@ -127,7 +125,6 @@ public FlinkExecutableStageFunction( this.outputMap = outputMap; this.contextFactory = contextFactory; this.windowCoder = windowCoder; - this.stageName = stagePayload.getInput(); } @Override @@ -151,12 +148,12 @@ public void open(Configuration parameters) throws Exception { new BundleProgressHandler() { @Override public void onProgress(ProcessBundleProgressResponse progress) { - container.updateMetrics(stageName, progress.getMonitoringInfosList()); + container.updateMetrics(progress.getMonitoringInfosList()); } @Override public void onCompleted(ProcessBundleResponse response) { - container.updateMetrics(stageName, response.getMonitoringInfosList()); + container.updateMetrics(response.getMonitoringInfosList()); } }; } diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java index eef86d7728e8..ed2a12baffcf 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java @@ -187,12 +187,12 @@ public void open() throws Exception { new BundleProgressHandler() { @Override public void onProgress(ProcessBundleProgressResponse progress) { - flinkMetricContainer.updateMetrics(stepName, progress.getMonitoringInfosList()); + flinkMetricContainer.updateMetrics(progress.getMonitoringInfosList()); } @Override public void onCompleted(ProcessBundleResponse response) { - flinkMetricContainer.updateMetrics(stepName, response.getMonitoringInfosList()); + flinkMetricContainer.updateMetrics(response.getMonitoringInfosList()); } }; diff --git a/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java b/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java index ea97f9343173..b1f8261b3156 100644 --- a/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java +++ b/runners/flink/src/test/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainerTest.java @@ -108,7 +108,7 @@ public void testCounter() { counter.inc(); assertThat(flinkCounter.getCount(), is(0L)); - container.updateMetrics("step"); + container.updateMetrics(); assertThat(flinkCounter.getCount(), is(2L)); } @@ -125,10 +125,10 @@ public void testGauge() { assertThat(flinkGauge.getValue(), is(GaugeResult.empty())); // first set will install the mocked gauge - container.updateMetrics("step"); + container.updateMetrics(); gauge.set(1); gauge.set(42); - container.updateMetrics("step"); + container.updateMetrics(); assertThat(flinkGauge.getValue().getValue(), is(42L)); } @@ -146,6 +146,7 @@ public void testMonitoringInfoUpdate() { SimpleMonitoringInfoBuilder userCountBuilder = new SimpleMonitoringInfoBuilder(); userCountBuilder.setUrnForUserMetric("ns1", "metric1"); userCountBuilder.setInt64Value(111); + userCountBuilder.setPTransformLabel("step"); MonitoringInfo userCountMonitoringInfo = userCountBuilder.build(); assertNotNull(userCountMonitoringInfo); @@ -159,8 +160,7 @@ public void testMonitoringInfoUpdate() { assertThat(userCounter.getCount(), is(0L)); assertThat(elemCounter.getCount(), is(0L)); - container.updateMetrics( - "step", ImmutableList.of(userCountMonitoringInfo, elemCountMonitoringInfo)); + container.updateMetrics(ImmutableList.of(userCountMonitoringInfo, elemCountMonitoringInfo)); assertThat(userCounter.getCount(), is(111L)); assertThat(elemCounter.getCount(), is(222L)); } @@ -224,7 +224,7 @@ public void testDropUnexpectedMonitoringInfoTypes() { when(metricGroup.counter("ns1.int_counter")).thenReturn(counter); flinkContainer.updateMetrics( - "step", ImmutableList.of(intCounter, doubleCounter, intDistribution, doubleDistribution)); + ImmutableList.of(intCounter, doubleCounter, intDistribution, doubleDistribution)); // Flink's MetricGroup should only have asked for one counter (the integer-typed one) to be // created (the double-typed one is dropped currently) @@ -273,12 +273,12 @@ public void testDistribution() { assertThat(flinkGauge.getValue(), is(DistributionResult.IDENTITY_ELEMENT)); // first set will install the mocked distribution - container.updateMetrics("step"); + container.updateMetrics(); distribution.update(42); distribution.update(-23); distribution.update(0); distribution.update(1); - container.updateMetrics("step"); + container.updateMetrics(); assertThat(flinkGauge.getValue().getMax(), is(42L)); assertThat(flinkGauge.getValue().getMin(), is(-23L)); assertThat(flinkGauge.getValue().getCount(), is(4L)); From 43c4e36e9df4e545a25518ab3227109c367afd08 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:57:56 +0000 Subject: [PATCH 23/26] implement GetJobMetrics RPC in InMemoryJobService --- .../beam/runners/core/metrics/Protos.java | 88 +++++++++++++++++++ .../jobsubmission/InMemoryJobService.java | 56 ++++++++++++ runners/reference/java/build.gradle | 1 + 3 files changed, 145 insertions(+) create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/Protos.java diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/Protos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/Protos.java new file mode 100644 index 000000000000..8c326099da1f --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/Protos.java @@ -0,0 +1,88 @@ +/* + * 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.beam.runners.core.metrics; + +import org.apache.beam.model.jobmanagement.v1.JobApiMetrics; +import org.apache.beam.model.jobmanagement.v1.JobApiMetrics.CounterResult; +import org.apache.beam.model.pipeline.v1.PipelineMetrics; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.IntDistributionData; +import org.apache.beam.model.pipeline.v1.PipelineMetrics.MetricKey; +import org.apache.beam.sdk.metrics.DistributionResult; +import org.apache.beam.sdk.metrics.MetricName; +import org.apache.beam.sdk.metrics.MetricResult; + +/** + * Conversions between {@link org.apache.beam.sdk.metrics} classes and corresponding {@link + * JobApiMetrics} and {@link PipelineMetrics} proto objects. + */ +public class Protos { + + public static MetricName toProto(PipelineMetrics.MetricName metricName) { + return MetricName.named(metricName.getNamespace(), metricName.getName()); + } + + public static MetricKey keyFromProto(MetricResult metricResult) { + MetricName metricName = metricResult.getName(); + return MetricKey.newBuilder() + .setStep(metricResult.getStep()) + .setMetricName( + PipelineMetrics.MetricName.newBuilder() + .setNamespace(metricName.getNamespace()) + .setName(metricName.getName())) + .build(); + } + + public static JobApiMetrics.DistributionResult distributionToProto( + MetricResult result) { + JobApiMetrics.DistributionResult.Builder builder = + JobApiMetrics.DistributionResult.newBuilder().setAttempted(toProto(result.getAttempted())); + try { + builder.setCommitted(toProto(result.getCommitted())); + } catch (UnsupportedOperationException ignored) { + } + + return builder.build(); + } + + public static IntDistributionData toProto(DistributionResult distributionResult) { + return IntDistributionData.newBuilder() + .setMin(distributionResult.getMin()) + .setMax(distributionResult.getMax()) + .setCount(distributionResult.getCount()) + .setSum(distributionResult.getSum()) + .build(); + } + + public static DistributionResult fromProto(IntDistributionData distributionData) { + return DistributionResult.create( + distributionData.getSum(), + distributionData.getCount(), + distributionData.getMin(), + distributionData.getMax()); + } + + public static CounterResult counterToProto(MetricResult result) { + CounterResult.Builder builder = CounterResult.newBuilder().setAttempted(result.getAttempted()); + try { + builder.setCommitted(result.getCommitted()); + } catch (UnsupportedOperationException ignored) { + } + + return builder.build(); + } +} diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java index 545641a358a9..5bba6f781b6a 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java @@ -17,6 +17,10 @@ */ package org.apache.beam.runners.fnexecution.jobsubmission; +import static org.apache.beam.runners.core.metrics.Protos.counterToProto; +import static org.apache.beam.runners.core.metrics.Protos.distributionToProto; +import static org.apache.beam.runners.core.metrics.Protos.keyFromProto; + import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -26,6 +30,8 @@ import org.apache.beam.model.jobmanagement.v1.JobApi.CancelJobResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.DescribePipelineOptionsRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.DescribePipelineOptionsResponse; +import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobMetricsRequest; +import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobMetricsResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessage; @@ -36,12 +42,17 @@ import org.apache.beam.model.jobmanagement.v1.JobApi.PrepareJobResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.RunJobRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.RunJobResponse; +import org.apache.beam.model.jobmanagement.v1.JobApiMetrics.MetricResult; +import org.apache.beam.model.jobmanagement.v1.JobApiMetrics.MetricStatus; import org.apache.beam.model.jobmanagement.v1.JobServiceGrpc; import org.apache.beam.model.pipeline.v1.Endpoints; import org.apache.beam.runners.core.construction.graph.PipelineValidator; import org.apache.beam.runners.fnexecution.FnService; import org.apache.beam.sdk.fn.function.ThrowingConsumer; import org.apache.beam.sdk.fn.stream.SynchronizedStreamObserver; +import org.apache.beam.sdk.metrics.MetricQueryResults; +import org.apache.beam.sdk.metrics.MetricResults; +import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.Struct; import org.apache.beam.vendor.grpc.v1p13p1.io.grpc.Status; @@ -328,6 +339,51 @@ public void describePipelineOptions( } } + @Override + public void getJobMetrics( + GetJobMetricsRequest request, StreamObserver responseObserver) { + String invocationId = request.getJobId(); + LOG.info("Running getJobMetrics for {}", invocationId); + try { + JobInvocation invocation = getInvocation(invocationId); + LOG.info("Found job invocation for metrics: {}", invocation); + MetricResults metrics = invocation.getMetrics(); + LOG.info("Got metrics: {}", metrics); + GetJobMetricsResponse.Builder builder = GetJobMetricsResponse.newBuilder(); + if (metrics != null) { + MetricQueryResults results = metrics.queryMetrics(MetricsFilter.builder().build()); + results + .getCounters() + .forEach( + counter -> + builder.addMetricStatuses( + MetricStatus.newBuilder() + .setMetricKey(keyFromProto(counter)) + .setMetricResult( + MetricResult.newBuilder() + .setCounterResult(counterToProto(counter))))); + results + .getDistributions() + .forEach( + distribution -> + builder.addMetricStatuses( + MetricStatus.newBuilder() + .setMetricKey(keyFromProto(distribution)) + .setMetricResult( + MetricResult.newBuilder() + .setDistributionResult(distributionToProto(distribution))))); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } catch (Exception e) { + String errMessage = + String.format("Encountered unexpected Exception for Invocation %s", invocationId); + LOG.error(errMessage, e); + responseObserver.onError(Status.INTERNAL.withCause(e).asException()); + } + LOG.info("Finished getJobMetrics for {}", invocationId); + } + @Override public void close() throws Exception { // TODO: throw error if jobs are running diff --git a/runners/reference/java/build.gradle b/runners/reference/java/build.gradle index 0638cc599831..0cda3aaceb57 100644 --- a/runners/reference/java/build.gradle +++ b/runners/reference/java/build.gradle @@ -33,6 +33,7 @@ dependencies { compile library.java.hamcrest_library shadow project(path: ":beam-model-pipeline", configuration: "shadow") shadow project(path: ":beam-runners-core-construction-java", configuration: "shadow") + shadow project(path: ":beam-runners-core-java", configuration: "shadow") shadow project(path: ":beam-runners-java-fn-execution", configuration: "shadow") shadow project(path: ":beam-sdks-java-fn-execution", configuration: "shadow") shadow project(path: ":beam-sdks-java-harness", configuration: "shadow") From 94abd52a182bfb9c0fe4e4f7f7a90814d3c626ed Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:58:51 +0000 Subject: [PATCH 24/26] surface metrics in JobServicePipelineResult --- .../reference/JobServicePipelineResult.java | 119 +++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-) diff --git a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java index fe7701abeb0f..3960e3e59a70 100644 --- a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java +++ b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java @@ -17,6 +17,14 @@ */ package org.apache.beam.runners.reference; +import static org.apache.beam.runners.core.metrics.Protos.fromProto; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -27,9 +35,19 @@ import org.apache.beam.model.jobmanagement.v1.JobApi.CancelJobResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateResponse; +import org.apache.beam.model.jobmanagement.v1.JobApiMetrics; import org.apache.beam.model.jobmanagement.v1.JobServiceGrpc.JobServiceBlockingStub; +import org.apache.beam.model.pipeline.v1.PipelineMetrics; +import org.apache.beam.runners.core.construction.metrics.MetricFiltering; +import org.apache.beam.runners.core.construction.metrics.MetricKey; +import org.apache.beam.runners.core.metrics.Protos; import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.metrics.DistributionResult; +import org.apache.beam.sdk.metrics.GaugeResult; +import org.apache.beam.sdk.metrics.MetricQueryResults; +import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricResults; +import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.ByteString; import org.joda.time.Duration; import org.slf4j.Logger; @@ -45,6 +63,7 @@ class JobServicePipelineResult implements PipelineResult, AutoCloseable { private final CloseableResource jobService; @Nullable private State terminationState; @Nullable private Runnable cleanup; + @Nullable private MetricResults metricResults; JobServicePipelineResult( ByteString jobId, CloseableResource jobService, Runnable cleanup) { @@ -121,12 +140,110 @@ public State waitUntilFinish() { @Override public MetricResults metrics() { - throw new UnsupportedOperationException("Not yet implemented."); + if (metricResults == null) { + LOG.info("Fetching MetricResults"); + JobApi.GetJobMetricsResponse response = + jobService + .get() + .getJobMetrics(JobApi.GetJobMetricsRequest.newBuilder().setJobIdBytes(jobId).build()); + List statuses = response.getMetricStatusesList(); + List> counters = new ArrayList<>(); + List> distributions = new ArrayList<>(); + List> gauges = + new ArrayList<>(); // TODO: plumb gauges through these metrics + statuses.forEach( + status -> { + PipelineMetrics.MetricKey key = status.getMetricKey(); + JobApiMetrics.MetricResult metricResult = status.getMetricResult(); + if (metricResult.hasCounterResult()) { + JobApiMetrics.CounterResult counterResult = metricResult.getCounterResult(); + counters.add( + MetricResult.create( + Protos.toProto(key.getMetricName()), + key.getStep(), + counterResult.getCommitted(), + counterResult.getAttempted())); + } else { + assert (metricResult.hasDistributionResult()); + JobApiMetrics.DistributionResult distributionResult = + metricResult.getDistributionResult(); + distributions.add( + MetricResult.create( + Protos.toProto(key.getMetricName()), + key.getStep(), + fromProto(distributionResult.getCommitted()), + fromProto(distributionResult.getAttempted()))); + } + }); + metricResults = + // TODO: factor this out to a named MetricResults subclass + new MetricResults() { + private void printResults( + List> results, String name, PrintStream ps) { + if (results.isEmpty()) { + return; + } + ps.println(String.format("\t%d %s:", results.size(), name)); + for (MetricResult result : results) { + ps.println("\t\t" + result.toString()); + } + } + + @Override + public String toString() { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (PrintStream ps = new PrintStream(baos, true, "UTF-8")) { + ps.println("MetricResults("); + printResults(counters, "counters", ps); + printResults(distributions, "distributions", ps); + printResults(gauges, "gauges", ps); + ps.println(")"); + } catch (UnsupportedEncodingException ignored) { + } + return new String(baos.toByteArray(), StandardCharsets.UTF_8); + } + + @Override + public MetricQueryResults queryMetrics(@Nullable MetricsFilter filter) { + List> counterResults = new ArrayList<>(); + List> distributionResults = new ArrayList<>(); + List> gaugeResults = new ArrayList<>(); + counters.forEach( + counter -> { + if (MetricFiltering.matches( + filter, MetricKey.create(counter.getStep(), counter.getName()))) { + counterResults.add(counter); + } + }); + distributions.forEach( + distribution -> { + if (MetricFiltering.matches( + filter, MetricKey.create(distribution.getStep(), distribution.getName()))) { + distributionResults.add(distribution); + } + }); + gauges.forEach( + gauge -> { + if (MetricFiltering.matches( + filter, MetricKey.create(gauge.getStep(), gauge.getName()))) { + gaugeResults.add(gauge); + } + }); + return MetricQueryResults.create(counterResults, distributionResults, gaugeResults); + } + }; + LOG.info("Received MetricResults: {}", metricResults); + } + LOG.info("Returning MetricResults: {}", metricResults); + return metricResults; } @Override public void close() { + LOG.info("Cleaning up job service…"); try (CloseableResource jobService = this.jobService) { + metrics(); + LOG.info("Got metrics during cleanup"); if (cleanup != null) { cleanup.run(); } From 75e15bd0e4478f79895ce3623a5b91bdc530af80 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 22:00:55 +0000 Subject: [PATCH 25/26] implement portable python metrics over job API --- .../runners/portability/portable_runner.py | 62 +++++++++++++++++-- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/sdks/python/apache_beam/runners/portability/portable_runner.py b/sdks/python/apache_beam/runners/portability/portable_runner.py index 42bca3327467..a83ed770de49 100644 --- a/sdks/python/apache_beam/runners/portability/portable_runner.py +++ b/sdks/python/apache_beam/runners/portability/portable_runner.py @@ -28,6 +28,11 @@ import grpc from apache_beam import metrics +from apache_beam.metrics.cells import DistributionResult +from apache_beam.metrics.execution import MetricKey +from apache_beam.metrics.execution import MetricResult +from apache_beam.metrics.metric import MetricResults +from apache_beam.metrics.metricbase import MetricName from apache_beam.options.pipeline_options import PortableOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.options.pipeline_options import StandardOptions @@ -292,13 +297,53 @@ def add_runner_options(parser): class PortableMetrics(metrics.metric.MetricResults): - def __init__(self): - pass + def __init__(self, metric_statuses): + self.counters = {} + self.distributions = {} + self.gauges = {} + for metric_status in metric_statuses: + metric_key_pb = metric_status.metric_key + metric_name = metric_key_pb.metric_name + metric_key = MetricKey( + metric_key_pb.step, + MetricName(metric_name.namespace, metric_name.name)) + + metric_result = metric_status.metric_result + if metric_result.HasField('counter_result'): + counter_result = metric_result.counter_result + self.counters[metric_key] = MetricResult( + metric_key, + counter_result.committed, + counter_result.attempted + ) + elif metric_result.HasField('distribution_result'): + distribution_result = metric_result.distribution_result + committed = \ + DistributionResult(distribution_result.committed) \ + if distribution_result.HasField('committed') else None + attempted = \ + DistributionResult(distribution_result.attempted) \ + if distribution_result.HasField('attempted') else None + self.distributions[metric_key] = \ + MetricResult(metric_key, committed, attempted) + else: + raise Exception( + 'MetricResult without counter or distribution: %s' % metric_result) + + @staticmethod + def _query_type(filter, metrics): + return [ + data + for key, data in metrics.items() + if MetricResults.matches(filter, key) + ] def query(self, filter=None): - return {'counters': [], - 'distributions': [], - 'gauges': []} + return { + 'counters': self._query_type(filter, self.counters), + 'distributions': self._query_type(filter, self.distributions), + 'gauges': self._query_type(filter, self.gauges) + } class PipelineResult(runner.PipelineResult): @@ -312,6 +357,7 @@ def __init__(self, job_service, job_id, message_stream, state_stream, self._message_stream = message_stream self._state_stream = state_stream self._cleanup_callbacks = cleanup_callbacks + self._metrics = None def cancel(self): try: @@ -337,7 +383,11 @@ def _pipeline_state_to_runner_api_state(pipeline_state): return beam_job_api_pb2.JobState.Enum.Value(pipeline_state) def metrics(self): - return PortableMetrics() + if not self._metrics: + job_metrics_response = self._job_service.GetJobMetrics( + beam_job_api_pb2.GetJobMetricsRequest(job_id=self._job_id)) + self._metrics = PortableMetrics(job_metrics_response.metric_statuses) + return self._metrics def _last_error_message(self): # Filter only messages with the "message_response" and error messages. From 85e066e64b5c3ddb38b70e33f1798b0e93cb594b Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 27 Jan 2019 20:42:36 +0000 Subject: [PATCH 26/26] enable Flink PVR metrics cases --- runners/flink/job-server/flink_job_server.gradle | 3 --- 1 file changed, 3 deletions(-) diff --git a/runners/flink/job-server/flink_job_server.gradle b/runners/flink/job-server/flink_job_server.gradle index e38e954dd639..c92db2f229e2 100644 --- a/runners/flink/job-server/flink_job_server.gradle +++ b/runners/flink/job-server/flink_job_server.gradle @@ -129,11 +129,8 @@ def portableValidatesRunnerTask(String name, Boolean streaming) { includeCategories 'org.apache.beam.sdk.testing.ValidatesRunner' excludeCategories 'org.apache.beam.sdk.testing.FlattenWithHeterogeneousCoders' excludeCategories 'org.apache.beam.sdk.testing.LargeKeys$Above100MB' - excludeCategories 'org.apache.beam.sdk.testing.UsesAttemptedMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesCommittedMetrics' - excludeCategories 'org.apache.beam.sdk.testing.UsesCounterMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesCustomWindowMerging' - excludeCategories 'org.apache.beam.sdk.testing.UsesDistributionMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesFailureMessage' excludeCategories 'org.apache.beam.sdk.testing.UsesGaugeMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesParDoLifecycle'