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/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; +} + 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..da0c70b1e312 --- /dev/null +++ b/model/pipeline/src/main/proto/beam_pipeline_metrics.proto @@ -0,0 +1,103 @@ +/* + * 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 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 { + 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/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())); } 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..9ce1855d3cd2 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,12 +29,18 @@ @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. */ 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/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index fa2b83453041..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,7 +50,7 @@ @Experimental(Kind.METRICS) public class MetricsContainerImpl implements Serializable, MetricsContainer { - private final String stepName; + @Nullable private final String stepName; private MetricsMap counters = new MetricsMap<>(CounterCell::new); @@ -60,7 +60,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,6 +158,11 @@ private MonitoringInfo counterUpdateToMonitoringInfo(MetricUpdate metricUp builder.setUrnForUserMetric( metricUpdate.getKey().metricName().getNamespace(), metricUpdate.getKey().metricName().getName()); + 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 f2c6f03da738..6193fb422e3d 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,10 +18,13 @@ package org.apache.beam.runners.core.metrics; import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; 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; @@ -35,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. @@ -42,14 +46,25 @@ *

This class is not thread-safe. */ public class MetricsContainerStepMap implements Serializable { + private Map metricsContainers; + private MetricsContainerImpl unboundContainer = new MetricsContainerImpl(null); public MetricsContainerStepMap() { this.metricsContainers = new ConcurrentHashMap<>(); } + /* Returns the container that is not bound to any step name. */ + public MetricsContainerImpl getUnboundContainer() { + return this.unboundContainer; + } + /** Returns the container for the given step name. */ public MetricsContainerImpl getContainer(String stepName) { + 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)); } @@ -64,6 +79,7 @@ public void updateAll(MetricsContainerStepMap other) { for (Map.Entry container : other.metricsContainers.entrySet()) { getContainer(container.getKey()).update(container.getValue()); } + getUnboundContainer().update(other.getUnboundContainer()); } /** @@ -85,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 @@ -106,6 +123,18 @@ 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 : getMetricsContainers()) { + for (MonitoringInfo mi : container.getMonitoringInfos()) { + monitoringInfos.add(mi); + } + } + return monitoringInfos; + } + /** * Returns {@link MetricResults} based on given {@link MetricsContainerStepMap} of attempted * metrics. @@ -119,8 +148,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 { @@ -145,16 +174,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( @@ -212,6 +239,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/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/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..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 @@ -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); + builder2.setPTransformLabel("step1"); builder2.build(); ArrayList actualMonitoringInfos = new ArrayList(); 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/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' 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..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 @@ -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; @@ -75,6 +76,7 @@ public static FlinkJobInvocation create( private JobState.Enum jobState; private List> stateObservers; private List> messageObservers; + private MetricResults metrics; @Nullable private ListenableFuture invocationFuture; @@ -191,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); } @@ -252,6 +258,11 @@ public JobState.Enum getState() { return this.jobState; } + @Override + public MetricResults getMetrics() { + return metrics; + } + @Override public synchronized void addStateListener(Consumer stateStreamObserver) { stateStreamObserver.accept(getState()); 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 23d1f8356da3..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,16 +19,18 @@ 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; 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; @@ -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 6b9435e89d2d..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 @@ -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; @@ -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)); } @@ -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) @@ -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)); 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/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/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/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 09cf59da06d0..47d5be5f21e5 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; @@ -499,7 +499,9 @@ 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()) @@ -508,19 +510,33 @@ public void testMetrics() throws Exception { ParDo.of( new DoFn() { private boolean emitted = false; + Counter startCounter = + Metrics.counter(RemoteExecutionTest.class, startUserCounterName); + @StartBundle + public void startBundle() throws InterruptedException { + startCounter.inc(10); + } + + @SuppressWarnings("unused") @ProcessElement - public void process(ProcessContext ctxt) { + 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, counterMetricName).inc(); + 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()); @@ -616,12 +632,26 @@ 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.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()); // The element counter should be counted only once for the pcollection. @@ -651,7 +681,6 @@ public void onCompleted(ProcessBundleResponse response) { builder.setInt64Value(6); expected.add(builder.build()); - assertEquals(5, result.size()); assertThat(result, containsInAnyOrder(expected.toArray())); } }; 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") 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(); } 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; 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..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 @@ -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. @@ -27,15 +31,55 @@ @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) { + 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, 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/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 26f30a898e06..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 @@ -54,6 +54,7 @@ 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.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.options.PipelineOptions; @@ -224,11 +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<>(); - PTransformFunctionRegistry startFunctionRegistry = new PTransformFunctionRegistry(); - PTransformFunctionRegistry finishFunctionRegistry = new PTransformFunctionRegistry(); + 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,12 +298,11 @@ 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)) { + // 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 = metricsContainerRegistry.getUnboundContainer(); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(rootMetricsContainer)) { // Already in reverse topological order so we don't need to do anything. for (ThrowingRunnable startFunction : startFunctionRegistry.getFunctions()) { @@ -317,10 +321,10 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction 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/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index 5de116e0b516..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 @@ -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,20 +39,30 @@ 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 metricContainerRegistry) { this.original = original; HashMap labels = new HashMap(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); MonitoringInfoMetricName metricName = MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); 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 = metricContainerRegistry.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 8b8dbc409f31..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 @@ -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. */ @@ -87,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 6d1e950f3fd6..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 @@ -17,11 +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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.beam.sdk.metrics.MetricsEnvironment; /** * A class to to register and retrieve functions for bundle processing (i.e. the start, or finish @@ -48,9 +50,17 @@ * */ 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 +71,11 @@ 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 container = metricsContainerRegistry.getContainer(pTransformId); + try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) { + // TODO(ajamato): Set the proper state sampler state for ExecutionTime Metrics to use. + runnable.run(); + } }; runnables.add(wrapped); } 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..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,12 +31,12 @@ 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; 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; @@ -44,10 +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.MonitoringInfoMetricName; +import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.StringUtf8Coder; @@ -198,12 +197,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 +361,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 +499,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( @@ -542,7 +557,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)); @@ -589,12 +605,17 @@ public void testUsingMetrics() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(stateData); List>> mainOutputValues = new ArrayList<>(); - PCollectionConsumerRegistry consumers = new PCollectionConsumerRegistry(); + + 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( @@ -626,30 +647,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(); - - labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "Window.Into()/Window.Assign.out"); - metricName = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - expectedMetrics.add(create("testUsingMetrics", metricName, 2)); + 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, + 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> { @@ -748,21 +773,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/ElementCountFnDataReceiverTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java index a18c2e9c89dc..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 @@ -19,19 +19,27 @@ import static junit.framework.TestCase.assertEquals; 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 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; +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. @@ -41,30 +49,49 @@ 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 metricsContainerRegistry = 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, 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); - 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 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 beba73e7d382..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 @@ -22,17 +22,23 @@ 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.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(); @@ -44,13 +50,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 +74,55 @@ 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); + } + + @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 ec41f6ab42fd..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 @@ -20,19 +20,27 @@ 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.function.ThrowingRunnable; +import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.junit.Test; 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 PTransformFunctionRegistry}. */ -@RunWith(JUnit4.class) +@RunWith(PowerMockRunner.class) +@PrepareForTest(MetricsEnvironment.class) public class PTransformFunctionRegistryTest { @Test public void functionsAreInvokedIndirectlyAfterRegisteringAndInvoking() throws Exception { - PTransformFunctionRegistry testObject = new PTransformFunctionRegistry(); + MetricsContainerStepMap metricsContainerRegistry = mock(MetricsContainerStepMap.class); + PTransformFunctionRegistry testObject = + new PTransformFunctionRegistry(metricsContainerRegistry); ThrowingRunnable runnableA = mock(ThrowingRunnable.class); ThrowingRunnable runnableB = mock(ThrowingRunnable.class); @@ -46,4 +54,29 @@ 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")); + } } 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/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/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. 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 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.