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 7ab693f2100f..d08cbbe9c7ca 100644 --- a/model/fn-execution/src/main/proto/beam_fn_api.proto +++ b/model/fn-execution/src/main/proto/beam_fn_api.proto @@ -501,48 +501,9 @@ 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; + int64 counter = 1; + IntDistributionData distribution = 2; + IntGaugeData gauge = 3; } } @@ -553,11 +514,9 @@ message IntDistributionData { int64 max = 4; } -message DoubleDistributionData { - int64 count = 1; - double sum = 2; - double min = 3; - double max = 4; +message IntGaugeData { + int64 value = 1; + int64 timestamp_ms = 2; } // General MonitoredState information which contains 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 9ce1855d3cd2..517c22586c6c 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 @@ -38,7 +38,11 @@ public abstract class MetricKey implements Serializable { @Override public String toString() { - return String.format("%s:%s", stepName(), metricName()); + return toString(":"); + } + + public String toString(String delimiter) { + return String.format("%s%s%s", stepName(), delimiter, metricName().toString(delimiter)); } public static MetricKey create(String stepName, MetricName metricName) { diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java new file mode 100644 index 000000000000..fb9bbfc09792 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java @@ -0,0 +1,41 @@ +/* + * 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.fnexecution.v1.BeamFnApi.IntDistributionData; +import org.apache.beam.sdk.metrics.DistributionResult; + +/** Convert distributions between protobuf and SDK representations. */ +public class DistributionProtos { + public static DistributionResult fromProto(IntDistributionData distributionData) { + return DistributionResult.create( + distributionData.getSum(), + distributionData.getCount(), + distributionData.getMin(), + distributionData.getMax()); + } + + public static IntDistributionData toProto(DistributionResult distributionResult) { + return IntDistributionData.newBuilder() + .setMin(distributionResult.getMin()) + .setMax(distributionResult.getMax()) + .setCount(distributionResult.getCount()) + .setSum(distributionResult.getSum()) + .build(); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java new file mode 100644 index 000000000000..f75e5fe3136a --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java @@ -0,0 +1,36 @@ +/* + * 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.fnexecution.v1.BeamFnApi.IntGaugeData; +import org.apache.beam.sdk.metrics.GaugeResult; +import org.joda.time.Instant; + +/** Convert gauges between protobuf and SDK representations. */ +public class GaugeProtos { + public static GaugeResult fromProto(IntGaugeData gaugeData) { + return GaugeResult.create(gaugeData.getValue(), new Instant(gaugeData.getTimestampMs())); + } + + public static IntGaugeData toProto(GaugeResult gauge) { + return IntGaugeData.newBuilder() + .setValue(gauge.getValue()) + .setTimestampMs(gauge.getTimestamp().getMillis()) + .build(); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/LabeledMetrics.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/LabeledMetrics.java index bf6295b0edb0..5b6a90fecf6a 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/LabeledMetrics.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/LabeledMetrics.java @@ -19,17 +19,18 @@ import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.DelegatingCounter; +import org.apache.beam.sdk.metrics.MetricName; /** * Define a metric on the current MetricContainer with a specific URN and a set of labels. This is a * more convenient way to collect the necessary fields to repackage the metric into a MonitoringInfo - * proto later. Intended for internal use only (SDK and RunnerHarness developement). + * proto later. Intended for internal use only (SDK and RunnerHarness development). */ public class LabeledMetrics { /** * Create a metric that can be incremented and decremented, and is aggregated by taking the sum. */ - public static Counter counter(MonitoringInfoMetricName metricName) { + public static Counter counter(MetricName metricName) { return new DelegatingCounter(metricName); } } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java index 6b40603081a1..190c6015533b 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java @@ -19,6 +19,7 @@ import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX; +import javax.annotation.Nullable; import org.apache.beam.sdk.metrics.MetricName; /** Utility for parsing a URN to a {@link MetricName}. */ @@ -29,9 +30,12 @@ public class MetricUrns { * *

Should be consistent with {@code parse_namespace_and_name} in monitoring_infos.py. */ + @Nullable public static MetricName parseUrn(String urn) { if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); + } else { + return null; } // If it is not a user counter, just use the first part of the URN, i.e. 'beam' String[] pieces = urn.split(":", 2); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java index 4583c9ddbf40..94a7d9896ee4 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java @@ -17,15 +17,19 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import javax.annotation.Nullable; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; @@ -39,9 +43,9 @@ public class MonitoringInfoMetricName extends MetricName { private String urn; @Nullable private String name; @Nullable private String namespace; - private HashMap labels = new HashMap(); + private Map labels = new HashMap<>(); - private MonitoringInfoMetricName(String urn, HashMap labels) { + private MonitoringInfoMetricName(String urn, Map labels) { checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); checkArgument(labels != null, "MonitoringInfoMetricName labels must be non-null"); // TODO(ajamato): Move SimpleMonitoringInfoBuilder to beam-runner-core-construction-java @@ -54,7 +58,7 @@ private MonitoringInfoMetricName(String urn, HashMap labels) { /** Parse the urn field into a name and namespace field. */ private void parseUrn() { - if (this.urn.startsWith(SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX)) { + if (this.urn.startsWith(USER_COUNTER_URN_PREFIX)) { List split = new ArrayList(Arrays.asList(this.getUrn().split(":"))); this.name = split.get(split.size() - 1); this.namespace = split.get(split.size() - 2); @@ -85,12 +89,31 @@ public String getUrn() { } /** @return The labels associated with this MonitoringInfo. */ - public HashMap getLabels() { + public Map getLabels() { return this.labels; } - public static MonitoringInfoMetricName named(String urn, HashMap labels) { - return new MonitoringInfoMetricName(urn, labels); + /** + * Polymorphic constructor of {@link MetricName}s. + * + *

If `urn` is a {@link SimpleMonitoringInfoBuilder#USER_COUNTER_URN_PREFIX user metric}, + * return a {@link MetricName} auto-value (which will {@link Object#equals equal} and {@link + * Object#hashCode hash} consistently with other {@link MetricName}s. + * + *

Otherwise, return a concrete {@link MonitoringInfoMetricName} representing a "system" + * metric. + */ + public static MetricName named(String urn, Map labels) { + MetricName metricName = MetricUrns.parseUrn(urn); + if (metricName == null) { + return new MonitoringInfoMetricName(urn, labels); + } + return metricName; + } + + /** @return a MetricName for a specific urn and labels map. */ + public static MetricName create(MonitoringInfo monitoringInfo) { + return named(monitoringInfo.getUrn(), monitoringInfo.getLabelsMap()); } @Override @@ -113,11 +136,15 @@ public boolean equals(Object o) { } @Override - public String toString() { + public String toString(String delimiter) { + if (getNamespace() != null && getName() != null) { + return super.toString(delimiter); + } StringBuilder builder = new StringBuilder(); - builder.append(this.urn.toString()); - builder.append(" "); - builder.append(this.labels.toString()); + if (labels.containsKey(PCOLLECTION_LABEL)) { + builder.append(labels.get(PCOLLECTION_LABEL)).append(delimiter); + } + builder.append(this.urn.replaceAll(":", delimiter)); return builder.toString(); } } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java new file mode 100644 index 000000000000..ac08b7306a93 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java @@ -0,0 +1,64 @@ +/* + * 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 static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL; + +import java.util.function.Consumer; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric; +import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; +import org.apache.beam.runners.core.construction.metrics.MetricKey; +import org.apache.beam.sdk.metrics.DistributionResult; +import org.apache.beam.sdk.metrics.GaugeResult; + +/** + * Helpers for working with {@link Metric}s and converting {@link MonitoringInfo}s to {@link + * MetricKey}s. + */ +public class MonitoringInfos { + + /** + * Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, + * or gauge). + */ + public static void processMetric( + Metric metric, + Consumer counterFn, + Consumer distributionFn, + Consumer gaugeFn) { + Metric.DataCase dataCase = metric.getDataCase(); + switch (dataCase) { + case COUNTER: + counterFn.accept(metric.getCounter()); + break; + case DISTRIBUTION: + distributionFn.accept(DistributionProtos.fromProto(metric.getDistribution())); + break; + case GAUGE: + gaugeFn.accept(GaugeProtos.fromProto(metric.getGauge())); + break; + case DATA_NOT_SET: + throw new IllegalStateException("Metric value not set: " + metric); + } + } + + public static MetricKey keyFromMonitoringInfo(MonitoringInfo monitoringInfo) { + String ptransform = monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL); + return MetricKey.create(ptransform, MonitoringInfoMetricName.create(monitoringInfo)); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java index c39f15ddf565..03c214a5bb30 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java @@ -17,6 +17,9 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.model.fnexecution.v1.BeamFnApi.IntDistributionData; +import static org.apache.beam.model.fnexecution.v1.BeamFnApi.IntGaugeData; + import java.time.Instant; import java.util.HashMap; import javax.annotation.Nullable; @@ -29,6 +32,8 @@ import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfoTypeUrns; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfoUrns; import org.apache.beam.runners.core.construction.BeamUrns; +import org.apache.beam.sdk.metrics.DistributionResult; +import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,6 +75,10 @@ public class SimpleMonitoringInfoBuilder { BeamUrns.getUrn(MonitoringInfoUrns.Enum.USER_COUNTER_URN_PREFIX); public static final String SUM_INT64_TYPE_URN = BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.SUM_INT64_TYPE); + public static final String DISTRIBUTION_INT64_TYPE_URN = + BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.DISTRIBUTION_INT64_TYPE); + public static final String LATEST_INT64_TYPE_URN = + BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.LATEST_INT64_TYPE); private static final HashMap specs = new HashMap(); @@ -155,7 +164,7 @@ public SimpleMonitoringInfoBuilder setTimestampToNow() { /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropriate type URN. */ public SimpleMonitoringInfoBuilder setInt64Value(long value) { - this.builder.getMetricBuilder().getCounterDataBuilder().setInt64Value(value); + this.builder.getMetricBuilder().setCounter(value); this.setInt64TypeUrn(); return this; } @@ -166,6 +175,36 @@ public SimpleMonitoringInfoBuilder setInt64TypeUrn() { return this; } + public SimpleMonitoringInfoBuilder setIntDistributionValue(DistributionData value) { + return setIntDistributionValue(value.extractResult()); + } + + public SimpleMonitoringInfoBuilder setIntDistributionValue(DistributionResult value) { + return setIntDistributionValue(DistributionProtos.toProto(value)); + } + + /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropraite type URN. */ + public SimpleMonitoringInfoBuilder setIntDistributionValue(IntDistributionData value) { + this.builder.getMetricBuilder().setDistribution(value); + this.builder.setType(DISTRIBUTION_INT64_TYPE_URN); + return this; + } + + public SimpleMonitoringInfoBuilder setGaugeValue(GaugeData value) { + return setGaugeValue(value.extractResult()); + } + + public SimpleMonitoringInfoBuilder setGaugeValue(GaugeResult value) { + return setGaugeValue(GaugeProtos.toProto(value)); + } + + /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropraite type URN. */ + public SimpleMonitoringInfoBuilder setGaugeValue(IntGaugeData value) { + this.builder.getMetricBuilder().setGauge(value); + this.builder.setType(LATEST_INT64_TYPE_URN); + return this; + } + /** Sets the PTRANSFORM MonitoringInfo label to the given param. */ public SimpleMonitoringInfoBuilder setPTransformLabel(String pTransform) { // TODO(ajamato): Add validation that it is a valid pTransform name in the bundle descriptor. diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java index c1704aa63d00..3bde94f2ed13 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.HashMap; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.junit.Rule; @@ -42,7 +43,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { assertNull(MetricsEnvironment.getCurrentContainer()); HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); Counter counter = LabeledMetrics.counter(name); counter.inc(); @@ -55,7 +56,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { public void testOperationsUpdateCounterFromContainerWhenContainerIsPresent() { HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); MetricsContainer mockContainer = Mockito.mock(MetricsContainer.class); Counter mockCounter = Mockito.mock(Counter.class); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMatchers.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMatchers.java index 62fae471d0f9..34fb7546fe59 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMatchers.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMatchers.java @@ -17,6 +17,8 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric.DataCase.COUNTER; + import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; @@ -45,9 +47,9 @@ protected boolean matchesSafely(MonitoringInfo item) { return false; } - if (mi.getMetric().hasCounterData()) { - long valueToMatch = mi.getMetric().getCounterData().getInt64Value(); - if (valueToMatch != item.getMetric().getCounterData().getInt64Value()) { + if (mi.getMetric().getDataCase() == COUNTER) { + long valueToMatch = mi.getMetric().getCounter(); + if (valueToMatch != item.getMetric().getCounter()) { return false; } } @@ -63,10 +65,8 @@ public void describeTo(Description description) { .appendValue(mi.getLabels()) .appendText(", type=") .appendValue(mi.getType()); - if (mi.getMetric().hasCounterData()) { - description - .appendText(", value=") - .appendValue(mi.getMetric().getCounterData().getInt64Value()); + if (mi.getMetric().getDataCase() == COUNTER) { + description.appendText(", value=").appendValue(mi.getMetric().getCounter()); } } }; @@ -83,7 +83,7 @@ public static TypeSafeMatcher valueGreaterThan(final long value) @Override protected boolean matchesSafely(MonitoringInfo item) { - if (item.getMetric().getCounterData().getInt64Value() < value) { + if (item.getMetric().getCounter() < value) { return false; } return true; diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java index 13dd79d853c8..50bffc636e90 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java @@ -22,6 +22,8 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.Map; +import org.apache.beam.sdk.metrics.MetricName; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -33,9 +35,10 @@ public class MonitoringInfoMetricNameTest implements Serializable { @Test public void testElementCountConstruction() { - HashMap labels = new HashMap(); + Map labels = new HashMap<>(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MonitoringInfoMetricName name = + (MonitoringInfoMetricName) MonitoringInfoMetricName.named(urn, labels); assertEquals(null, name.getName()); assertEquals(null, name.getNamespace()); assertEquals(labels, name.getLabels()); @@ -45,8 +48,8 @@ public void testElementCountConstruction() { // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + labels = new HashMap<>(); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -55,19 +58,17 @@ public void testElementCountConstruction() { @Test public void testUserCounterUrnConstruction() { String urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); - HashMap labels = new HashMap(); - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + Map labels = new HashMap<>(); + MetricName name = MonitoringInfoMetricName.named(urn, labels); assertEquals("name", name.getName()); assertEquals("namespace", name.getNamespace()); - assertEquals(labels, name.getLabels()); - assertEquals(urn, name.getUrn()); assertEquals(name, name); // test self equals; // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); - labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + labels = new HashMap<>(); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -75,15 +76,15 @@ public void testUserCounterUrnConstruction() { @Test public void testNotEqualsDiffLabels() { - HashMap labels = new HashMap(); + Map labels = new HashMap<>(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - labels = new HashMap(); + labels = new HashMap<>(); labels.put("label", "value1"); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertNotEquals(name, name2); assertNotEquals(name.hashCode(), name2.hashCode()); @@ -91,14 +92,14 @@ public void testNotEqualsDiffLabels() { @Test public void testNotEqualsDiffUrn() { - HashMap labels = new HashMap(); + Map labels = new HashMap<>(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); // Reconstruct and test equality and hash code equivalence urn = "differentUrn"; - labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + labels = new HashMap<>(); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertNotEquals(name, name2); assertNotEquals(name.hashCode(), name2.hashCode()); @@ -107,20 +108,20 @@ public void testNotEqualsDiffUrn() { @Test public void testNullLabelsThrows() { thrown.expect(IllegalArgumentException.class); - HashMap labels = null; + Map labels = null; MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); } @Test public void testNullUrnThrows() { - HashMap labels = new HashMap(); - thrown.expect(IllegalArgumentException.class); + Map labels = new HashMap<>(); + thrown.expect(NullPointerException.class); MonitoringInfoMetricName.named(null, labels); } @Test public void testEmptyUrnThrows() { - HashMap labels = new HashMap(); + Map labels = new HashMap<>(); thrown.expect(IllegalArgumentException.class); MonitoringInfoMetricName.named("", labels); } diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java index ed64f76b3279..60c742d180fb 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java @@ -19,16 +19,17 @@ import java.util.HashMap; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; +import org.apache.beam.sdk.metrics.MetricName; /** * Provides convenient one line factories for unit tests that need to generate test MonitoringInfos. */ public class MonitoringInfoTestUtil { /** @return A basic MonitoringInfoMetricName to test. */ - public static MonitoringInfoMetricName testElementCountName() { + public static MetricName testElementCountName() { HashMap labels = new HashMap(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "testPCollection"); - MonitoringInfoMetricName name = + MetricName name = MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); return name; } diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilderTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilderTest.java index 14fa70300917..d79ece69589b 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilderTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilderTest.java @@ -48,7 +48,7 @@ public void testReturnsNullIfSpecRequirementsNotMet() { monitoringInfo.getLabelsOrDefault(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, null)); assertEquals(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, monitoringInfo.getUrn()); assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); - assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); + assertEquals(1, monitoringInfo.getMetric().getCounter()); } @Test @@ -65,7 +65,7 @@ public void testUserCounter() { SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "myNamespace:myName", monitoringInfo.getUrn()); assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); - assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); + assertEquals(1, monitoringInfo.getMetric().getCounter()); } @Test @@ -80,6 +80,6 @@ public void testUserMetricWithInvalidDelimiterCharacterIsReplaced() { SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "myNamespace_withInvalidChar:myName", monitoringInfo.getUrn()); assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); - assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); + assertEquals(1, monitoringInfo.getMetric().getCounter()); } } 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..e0623ad0bb15 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 @@ -17,21 +17,19 @@ */ package org.apache.beam.runners.flink.metrics; -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.MonitoringInfos.keyFromMonitoringInfo; +import static org.apache.beam.runners.core.metrics.MonitoringInfos.processMetric; 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 java.util.function.BiConsumer; import org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric; import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo; +import org.apache.beam.runners.core.construction.metrics.MetricKey; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; -import org.apache.beam.sdk.metrics.Distribution; import org.apache.beam.sdk.metrics.DistributionResult; import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.sdk.metrics.MetricName; @@ -40,13 +38,14 @@ import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsFilter; -import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.apache.flink.api.common.accumulators.Accumulator; import org.apache.flink.api.common.functions.RuntimeContext; import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.MetricOptions; import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.Gauge; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.util.function.TriFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,121 +93,128 @@ 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) { + LOG.info("Flink updating metrics with {} monitoring infos", monitoringInfos.size()); monitoringInfos.forEach( monitoringInfo -> { - if (monitoringInfo.hasMetric()) { - String urn = monitoringInfo.getUrn(); - MetricName metricName = parseUrn(urn); - Metric metric = monitoringInfo.getMetric(); - if (metric.hasCounterData()) { - CounterData counterData = metric.getCounterData(); - if (counterData.getValueCase() == CounterData.ValueCase.INT64_VALUE) { - org.apache.beam.sdk.metrics.Counter counter = - metricsContainer.getCounter(metricName); - counter.inc(counterData.getInt64Value()); - } else { - LOG.warn("Unsupported CounterData type: {}", counterData); - } - } else if (metric.hasDistributionData()) { - DistributionData distributionData = metric.getDistributionData(); - if (distributionData.hasIntDistributionData()) { - Distribution distribution = metricsContainer.getDistribution(metricName); - IntDistributionData intDistributionData = distributionData.getIntDistributionData(); - distribution.update( - intDistributionData.getSum(), - intDistributionData.getCount(), - intDistributionData.getMin(), - intDistributionData.getMax()); - } else { - LOG.warn("Unsupported DistributionData type: {}", distributionData); - } - } else if (metric.hasExtremaData()) { - ExtremaData extremaData = metric.getExtremaData(); - LOG.warn("Extrema metric unsupported: {}", extremaData); - } + if (!monitoringInfo.hasMetric()) { + LOG.info("Skipping metric-less MonitoringInfo: {}", monitoringInfo); + return; + } + + Metric metric = monitoringInfo.getMetric(); + + MetricKey metricKey = keyFromMonitoringInfo(monitoringInfo); + + String ptransform = metricKey.stepName(); + MetricName metricName = metricKey.metricName(); + + MetricsContainer container = getMetricsContainer(ptransform); + if (container == null) { + LOG.warn("Can't add monitoringinfo to null MetricsContainer: {}", monitoringInfo); + return; } + + // Update Beam metrics + processMetric( + metric, + update -> container.getCounter(metricName).inc(update), + update -> + container + .getDistribution(metricName) + .update(update.getSum(), update.getCount(), update.getMin(), update.getMax()), + update -> container.getGauge(metricName).set(update.getValue())); + + // Update Flink internal metrics + processMetric( + metric, + counter -> updateCounter(metricKey, counter), + distribution -> updateDistribution(metricKey, distribution), + gauge -> updateGauge(metricKey, gauge)); }); - updateMetrics(stepName); } /** * 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()); - updateCounters(metricQueryResults.getCounters()); - updateDistributions(metricQueryResults.getDistributions()); - updateGauge(metricQueryResults.getGauges()); - } - - private void updateCounters(Iterable> counters) { - for (MetricResult metricResult : counters) { - String flinkMetricName = getFlinkMetricNameString(metricResult); + metricResults.queryMetrics(MetricsFilter.builder().build()); - Long update = metricResult.getAttempted(); + updateMetrics(metricQueryResults.getCounters(), this::updateCounter); + updateMetrics(metricQueryResults.getDistributions(), this::updateDistribution); + updateMetrics(metricQueryResults.getGauges(), this::updateGauge); + } - // update flink metric - Counter counter = - flinkCounterCache.computeIfAbsent( - flinkMetricName, n -> runtimeContext.getMetricGroup().counter(n)); - counter.dec(counter.getCount()); - counter.inc(update); + private void updateMetrics( + Iterable> metricResults, BiConsumer fn) { + for (MetricResult metricResult : metricResults) { + MetricKey key = MetricKey.create(metricResult.getStep(), metricResult.getName()); + fn.accept(key, metricResult.getAttempted()); } } - private void updateDistributions(Iterable> distributions) { - for (MetricResult metricResult : distributions) { - String flinkMetricName = getFlinkMetricNameString(metricResult); - - DistributionResult update = metricResult.getAttempted(); - - // update flink metric - FlinkDistributionGauge gauge = flinkDistributionGaugeCache.get(flinkMetricName); - if (gauge == null) { - gauge = - runtimeContext - .getMetricGroup() - .gauge(flinkMetricName, new FlinkDistributionGauge(update)); - flinkDistributionGaugeCache.put(flinkMetricName, gauge); - } else { - gauge.update(update); - } + private void updateMetric( + MetricKey key, + Map flinkMetricMap, + TriFunction create, + BiConsumer update, + T value) { + String flinkMetricName = getFlinkMetricNameString(key); + + // update flink metric + FlinkT metric = flinkMetricMap.get(flinkMetricName); + if (metric == null) { + metric = create.apply(flinkMetricName, runtimeContext.getMetricGroup(), value); + flinkMetricMap.put(flinkMetricName, metric); } + update.accept(metric, value); } - private void updateGauge(Iterable> gauges) { - for (MetricResult metricResult : gauges) { - String flinkMetricName = getFlinkMetricNameString(metricResult); + private void updateCounter(MetricKey metricKey, long attempted) { + updateMetric( + metricKey, + flinkCounterCache, + (name, group, value) -> group.counter(name), + (counter, value) -> { + counter.dec(counter.getCount()); + counter.inc(value); + }, + attempted); + } - GaugeResult update = metricResult.getAttempted(); + private void updateDistribution(MetricKey metricKey, DistributionResult attempted) { + updateMetric( + metricKey, + flinkDistributionGaugeCache, + (name, group, value) -> group.gauge(name, new FlinkDistributionGauge(value)), + FlinkDistributionGauge::update, + attempted); + } - // update flink metric - FlinkGauge gauge = flinkGaugeCache.get(flinkMetricName); - if (gauge == null) { - gauge = runtimeContext.getMetricGroup().gauge(flinkMetricName, new FlinkGauge(update)); - flinkGaugeCache.put(flinkMetricName, gauge); - } else { - gauge.update(update); - } - } + private void updateGauge(MetricKey metricKey, GaugeResult attempted) { + updateMetric( + metricKey, + flinkGaugeCache, + (name, group, value) -> group.gauge(name, new FlinkGauge(value)), + FlinkGauge::update, + attempted); } - @VisibleForTesting - static String getFlinkMetricNameString(MetricResult metricResult) { - MetricName metricName = metricResult.getName(); - // We use only the MetricName here, the step name is already contained - // in the operator name which is passed to Flink's MetricGroup to which - // the metric with the following name will be added. - return metricName.getNamespace() + METRIC_KEY_SEPARATOR + metricName.getName(); + static String getFlinkMetricNameString(MetricKey metricKey) { + return metricKey.toString(METRIC_KEY_SEPARATOR); } /** Flink {@link Gauge} for {@link DistributionResult}. */ 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 c728f2c797f9..17bba4fe6b4f 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..e48390e69dba 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,11 @@ 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.runners.core.construction.metrics.MetricKey; import org.apache.beam.runners.core.metrics.CounterCell; import org.apache.beam.runners.core.metrics.DistributionCell; import org.apache.beam.runners.core.metrics.DistributionData; @@ -49,7 +47,6 @@ 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.MetricResult; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.vendor.grpc.v1p13p1.com.google.common.collect.ImmutableList; import org.apache.flink.api.common.functions.RuntimeContext; @@ -59,7 +56,6 @@ import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** Tests for {@link FlinkMetricContainer}. */ @@ -86,19 +82,15 @@ public void beforeTest() { @Test public void testMetricNameGeneration() { - MetricResult mock = Mockito.mock(MetricResult.class); - when(mock.getStep()).thenReturn("step"); - MetricName metricName = MetricName.named("namespace", "name"); - when(mock.getName()).thenReturn(metricName); - - String name = FlinkMetricContainer.getFlinkMetricNameString(mock); - assertThat(name, is("namespace.name")); + MetricKey key = MetricKey.create("step", MetricName.named("namespace", "name")); + String name = FlinkMetricContainer.getFlinkMetricNameString(key); + assertThat(name, is("step.namespace.name")); } @Test public void testCounter() { SimpleCounter flinkCounter = new SimpleCounter(); - when(metricGroup.counter("namespace.name")).thenReturn(flinkCounter); + when(metricGroup.counter("step.namespace.name")).thenReturn(flinkCounter); FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); MetricsContainer step = container.getMetricsContainer("step"); @@ -108,7 +100,7 @@ public void testCounter() { counter.inc(); assertThat(flinkCounter.getCount(), is(0L)); - container.updateMetrics("step"); + container.updateMetrics(); assertThat(flinkCounter.getCount(), is(2L)); } @@ -116,7 +108,7 @@ public void testCounter() { public void testGauge() { FlinkMetricContainer.FlinkGauge flinkGauge = new FlinkMetricContainer.FlinkGauge(GaugeResult.empty()); - when(metricGroup.gauge(eq("namespace.name"), anyObject())).thenReturn(flinkGauge); + when(metricGroup.gauge(eq("step.namespace.name"), anyObject())).thenReturn(flinkGauge); FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); MetricsContainer step = container.getMetricsContainer("step"); @@ -125,10 +117,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)); } @@ -138,14 +130,15 @@ public void testMonitoringInfoUpdate() { MetricsContainer step = container.getMetricsContainer("step"); SimpleCounter userCounter = new SimpleCounter(); - when(metricGroup.counter("ns1.metric1")).thenReturn(userCounter); + when(metricGroup.counter("step.ns1.metric1")).thenReturn(userCounter); SimpleCounter elemCounter = new SimpleCounter(); - when(metricGroup.counter("beam.metric:element_count:v1")).thenReturn(elemCounter); + when(metricGroup.counter("step.pcoll.beam.metric.element_count.v1")).thenReturn(elemCounter); SimpleMonitoringInfoBuilder userCountBuilder = new SimpleMonitoringInfoBuilder(); userCountBuilder.setUrnForUserMetric("ns1", "metric1"); userCountBuilder.setInt64Value(111); + userCountBuilder.setPTransformLabel("step"); MonitoringInfo userCountMonitoringInfo = userCountBuilder.build(); assertNotNull(userCountMonitoringInfo); @@ -159,112 +152,98 @@ 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)); } @Test - public void testDropUnexpectedMonitoringInfoTypes() { + public void testSupportMultipleMonitoringInfoTypes() { FlinkMetricContainer flinkContainer = new FlinkMetricContainer(runtimeContext); - MetricsContainer step = flinkContainer.getMetricsContainer("step"); + MetricsContainer container = flinkContainer.getMetricsContainer("step"); - MonitoringInfo intCounter = + MonitoringInfo counter1 = MonitoringInfo.newBuilder() - .setUrn(USER_COUNTER_URN_PREFIX + "ns1:int_counter") + .setUrn(USER_COUNTER_URN_PREFIX + "ns1:counter1") .putLabels(PTRANSFORM_LABEL, "step") - .setMetric( - Metric.newBuilder().setCounterData(CounterData.newBuilder().setInt64Value(111))) + .setMetric(Metric.newBuilder().setCounter(111)) .build(); - MonitoringInfo doubleCounter = + MonitoringInfo counter2 = MonitoringInfo.newBuilder() - .setUrn(USER_COUNTER_URN_PREFIX + "ns2:double_counter") + .setUrn(USER_COUNTER_URN_PREFIX + "ns2:counter2") .putLabels(PTRANSFORM_LABEL, "step") - .setMetric( - Metric.newBuilder().setCounterData(CounterData.newBuilder().setDoubleValue(222))) - .build(); - - MonitoringInfo intDistribution = - MonitoringInfo.newBuilder() - .setUrn(USER_COUNTER_URN_PREFIX + "ns3:int_distribution") - .putLabels(PTRANSFORM_LABEL, "step") - .setMetric( - Metric.newBuilder() - .setDistributionData( - BeamFnApi.DistributionData.newBuilder() - .setIntDistributionData( - IntDistributionData.newBuilder() - .setSum(30) - .setCount(10) - .setMin(1) - .setMax(5)))) + .setMetric(Metric.newBuilder().setCounter(222)) .build(); - MonitoringInfo doubleDistribution = + MonitoringInfo distribution = MonitoringInfo.newBuilder() - .setUrn(USER_COUNTER_URN_PREFIX + "ns4:double_distribution") + .setUrn(USER_COUNTER_URN_PREFIX + "ns3:distribution") .putLabels(PTRANSFORM_LABEL, "step") .setMetric( Metric.newBuilder() - .setDistributionData( - BeamFnApi.DistributionData.newBuilder() - .setDoubleDistributionData( - DoubleDistributionData.newBuilder() - .setSum(30) - .setCount(10) - .setMin(1) - .setMax(5)))) + .setDistribution( + IntDistributionData.newBuilder() + .setSum(30) + .setCount(10) + .setMin(1) + .setMax(5))) .build(); - // Mock out the counter that Flink returns; the distribution gets created by + // Mock out the counters that Flink returns; the distribution gets created by // FlinkMetricContainer, not by Flink itself, so we verify it in a different way below - SimpleCounter counter = new SimpleCounter(); - when(metricGroup.counter("ns1.int_counter")).thenReturn(counter); - - flinkContainer.updateMetrics( - "step", 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) - verify(metricGroup).counter(eq("ns1.int_counter")); + SimpleCounter flinkCounter1 = new SimpleCounter(); + SimpleCounter flinkCounter2 = new SimpleCounter(); - // Verify that the counter injected into flink has the right value - assertThat(counter.getCount(), is(111L)); + DistributionData distributionData = DistributionData.create(30, 10, 1, 5); + DistributionResult distributionResult = distributionData.extractResult(); + FlinkDistributionGauge distributionGauge = new FlinkDistributionGauge(distributionResult); - // Verify the counter in the java SDK MetricsContainer - long count = - ((CounterCell) step.getCounter(MetricName.named("ns1", "int_counter"))).getCumulative(); - assertThat(count, is(111L)); - - // The one Flink distribution that gets created is a FlinkDistributionGauge; here we verify its - // initial (and in this test, final) value - verify(metricGroup) - .gauge( - eq("ns3.int_distribution"), + when(metricGroup.counter("step.ns1.counter1")).thenReturn(flinkCounter1); + when(metricGroup.counter("step.ns2.counter2")).thenReturn(flinkCounter2); + when(metricGroup.gauge( + eq("step.ns3.distribution"), argThat( new ArgumentMatcher() { @Override public boolean matches(Object argument) { DistributionResult actual = ((FlinkDistributionGauge) argument).getValue(); - DistributionResult expected = DistributionResult.create(30, 10, 1, 5); - return actual.equals(expected); + return actual.equals(distributionResult); } - })); + }))) + .thenReturn(distributionGauge); + + flinkContainer.updateMetrics(ImmutableList.of(counter1, counter2, distribution)); + + verify(metricGroup).counter(eq("step.ns1.counter1")); + verify(metricGroup).counter(eq("step.ns2.counter2")); + + // Verify that the counters injected into flink has the right value + assertThat(flinkCounter1.getCount(), is(111L)); + assertThat(flinkCounter2.getCount(), is(222L)); + + // Verify the counter in the java SDK MetricsContainer + long count1 = + ((CounterCell) container.getCounter(MetricName.named("ns1", "counter1"))).getCumulative(); + assertThat(count1, is(111L)); + + long count2 = + ((CounterCell) container.getCounter(MetricName.named("ns2", "counter2"))).getCumulative(); + assertThat(count2, is(222L)); // Verify that the Java SDK MetricsContainer holds the same information - DistributionData distributionData = - ((DistributionCell) step.getDistribution(MetricName.named("ns3", "int_distribution"))) + DistributionData actualDistributionData = + ((DistributionCell) container.getDistribution(MetricName.named("ns3", "distribution"))) .getCumulative(); - assertThat(distributionData, is(DistributionData.create(30, 10, 1, 5))); + assertThat(actualDistributionData, is(distributionData)); } @Test public void testDistribution() { FlinkMetricContainer.FlinkDistributionGauge flinkGauge = new FlinkMetricContainer.FlinkDistributionGauge(DistributionResult.IDENTITY_ELEMENT); - when(metricGroup.gauge(eq("namespace.name"), anyObject())).thenReturn(flinkGauge); + when(metricGroup.gauge(eq("step.namespace.name"), anyObject())).thenReturn(flinkGauge); FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); MetricsContainer step = container.getMetricsContainer("step"); @@ -273,12 +252,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/main/java/org/apache/beam/runners/dataflow/worker/fn/control/MSecMonitoringInfoToCounterUpdateTransformer.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/MSecMonitoringInfoToCounterUpdateTransformer.java index 45cd65b0f6e1..d27f861ab28b 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/MSecMonitoringInfoToCounterUpdateTransformer.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/MSecMonitoringInfoToCounterUpdateTransformer.java @@ -115,7 +115,7 @@ public CounterUpdate transform(MonitoringInfo monitoringInfo) { return null; } - long value = monitoringInfo.getMetric().getCounterData().getInt64Value(); + long value = monitoringInfo.getMetric().getCounter(); String urn = monitoringInfo.getUrn(); final String ptransform = monitoringInfo.getLabelsMap().get("PTRANSFORM"); diff --git a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/UserMonitoringInfoToCounterUpdateTransformer.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/UserMonitoringInfoToCounterUpdateTransformer.java index b3c9353a510b..99d8bb44a698 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/UserMonitoringInfoToCounterUpdateTransformer.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/control/UserMonitoringInfoToCounterUpdateTransformer.java @@ -97,7 +97,7 @@ public CounterUpdate transform(MonitoringInfo monitoringInfo) { return null; } - long value = monitoringInfo.getMetric().getCounterData().getInt64Value(); + long value = monitoringInfo.getMetric().getCounter(); String urn = monitoringInfo.getUrn(); final String ptransform = monitoringInfo.getLabelsMap().get("PTRANSFORM"); 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..a8299f9655cb 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 @@ -474,13 +474,7 @@ public void testExtractCounterUpdatesReturnsValidProgressTrackerCounterUpdatesIf .setUrn("beam:metric:user:ExpectedCounter") .setType("beam:metrics:sum_int_64") .putLabels("PTRANSFORM", "ExpectedPTransform") - .setMetric( - BeamFnApi.Metric.newBuilder() - .setCounterData( - BeamFnApi.CounterData.newBuilder() - .setInt64Value(expectedCounterValue) - .build()) - .build()) + .setMetric(BeamFnApi.Metric.newBuilder().setCounter(expectedCounterValue).build()) .build(); InstructionRequestHandler instructionRequestHandler = 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 ae23ff0c23bd..50ad26847a44 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 @@ -52,7 +52,11 @@ public String namespace() { @Override public String toString() { - return String.format("%s:%s", getNamespace(), getName()); + return toString(":"); + } + + public String toString(String delimiter) { + return String.format("%s%s%s", getNamespace(), delimiter, getName()); } /** 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 3f4712262143..719a978bb0e5 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 @@ -25,6 +25,7 @@ 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.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; @@ -48,7 +49,7 @@ public ElementCountFnDataReceiver( this.original = original; HashMap labels = new HashMap(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); - MonitoringInfoMetricName metricName = + MetricName metricName = MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); this.counter = LabeledMetrics.counter(metricName); // Collect the metric in a metric container which is not bound to the step name. diff --git a/sdks/python/apache_beam/metrics/cells.py b/sdks/python/apache_beam/metrics/cells.py index 65ca18582e14..9943b4595921 100644 --- a/sdks/python/apache_beam/metrics/cells.py +++ b/sdks/python/apache_beam/metrics/cells.py @@ -172,9 +172,7 @@ def to_runner_api_monitoring_info(self): # 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( - int64_value=self.get_cumulative() - ) + counter=self.get_cumulative() ) @@ -405,9 +403,7 @@ 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( - int64_value=self.value - ) + counter=self.value ) @@ -479,9 +475,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( - distribution_data=beam_fn_api_pb2.DistributionData( - int_distribution_data=beam_fn_api_pb2.IntDistributionData( - count=self.count, sum=self.sum, min=self.min, max=self.max))) + distribution=beam_fn_api_pb2.IntDistributionData( + count=self.count, sum=self.sum, min=self.min, max=self.max)) class MetricAggregator(object): diff --git a/sdks/python/apache_beam/metrics/monitoring_infos.py b/sdks/python/apache_beam/metrics/monitoring_infos.py index bf1fd8ba4f81..f71470149592 100644 --- a/sdks/python/apache_beam/metrics/monitoring_infos.py +++ b/sdks/python/apache_beam/metrics/monitoring_infos.py @@ -29,7 +29,6 @@ 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 @@ -77,7 +76,7 @@ def to_timestamp_secs(timestamp_proto): def extract_counter_value(monitoring_info_proto): """Returns the int coutner value of the monitoring info.""" if is_counter(monitoring_info_proto) or is_gauge(monitoring_info_proto): - return monitoring_info_proto.metric.counter_data.int64_value + return monitoring_info_proto.metric.counter return None @@ -88,7 +87,7 @@ def extract_distribution(monitoring_info_proto): monitoring_info_proto: The monitoring infor for the distribution. """ if is_distribution(monitoring_info_proto): - return monitoring_info_proto.metric.distribution_data.int_distribution_data + return monitoring_info_proto.metric.distribution return None @@ -120,9 +119,7 @@ def int64_counter(urn, metric, ptransform='', tag=''): labels = create_labels(ptransform=ptransform, tag=tag) if isinstance(metric, int): metric = Metric( - counter_data=CounterData( - int64_value=metric - ) + counter=metric ) return create_monitoring_info(urn, SUM_INT64_TYPE, metric, labels) diff --git a/sdks/python/apache_beam/runners/portability/fn_api_runner_test.py b/sdks/python/apache_beam/runners/portability/fn_api_runner_test.py index aadf4a8ddca1..ec19027da2d8 100644 --- a/sdks/python/apache_beam/runners/portability/fn_api_runner_test.py +++ b/sdks/python/apache_beam/runners/portability/fn_api_runner_test.py @@ -689,10 +689,10 @@ def assert_has_monitoring_info( for m in monitoring_infos: if m.labels == labels and m.urn == urn: if (ge_value is not None and - m.metric.counter_data.int64_value >= ge_value): + m.metric.counter >= ge_value): found = found + 1 elif (value is not None and - m.metric.counter_data.int64_value == value): + m.metric.counter == value): found = found + 1 ge_value_str = {'ge_value' : ge_value} if ge_value else '' value_str = {'value' : value} if value else ''