From 20818b0aecc6c1e4e8f2f13deef1a5b45a6c0925 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Tue, 19 Feb 2019 06:50:36 +0000 Subject: [PATCH 1/4] mv metric URN constants from SimpleMonitoringInfoBuilder to MetricUrns --- .../core/construction/Environments.java | 1 + .../core/construction/ModelCoders.java | 2 +- .../construction/PTransformTranslation.java | 2 +- .../WindowingStrategyTranslation.java | 4 +- .../construction/graph/PipelineValidator.java | 2 +- .../core/construction/CommonCoderTest.java | 2 +- .../core/construction/EnvironmentsTest.java | 1 + .../runners/core/metrics/LabeledMetrics.java | 3 +- .../beam/runners/core/metrics/MetricUrns.java | 43 --------- .../core/metrics/MetricsTranslation.java | 2 + .../metrics/MonitoringInfoMetricName.java | 37 ++++++-- .../core/metrics/SimpleExecutionState.java | 5 +- .../metrics/SimpleMonitoringInfoBuilder.java | 35 ++------ .../core/metrics/LabeledMetricsTest.java | 8 +- .../metrics/MetricsContainerImplTest.java | 9 +- .../metrics/MonitoringInfoMetricNameTest.java | 46 +++++----- .../core/metrics/MonitoringInfoTestUtil.java | 17 ++-- .../metrics/SimpleExecutionStateTest.java | 3 +- .../SimpleMonitoringInfoBuilderTest.java | 25 +++--- .../core/metrics/SimpleStateRegistryTest.java | 24 +++-- .../SpecMonitoringInfoValidatorTest.java | 15 ++-- .../flink/metrics/FlinkMetricContainer.java | 2 +- .../FlinkDefaultExecutableStageContext.java | 2 +- .../metrics/FlinkMetricContainerTest.java | 14 +-- .../CreateExecutableStageNodeFunction.java | 1 + .../worker/graph/RegisterNodeFunction.java | 2 +- .../environment/DockerEnvironmentFactory.java | 2 +- .../ExternalEnvironmentFactory.java | 2 +- .../ProcessEnvironmentFactory.java | 2 +- .../control/RemoteExecutionTest.java | 18 ++-- .../apache/beam/sdk/metrics}/BeamUrns.java | 2 +- .../beam/sdk/metrics/DistributionProtos.java | 40 +++++++++ .../apache/beam/sdk/metrics/MetricUrns.java | 88 +++++++++++++++++++ .../apache/beam/sdk/metrics/MetricsTest.java | 12 --- .../extensions/gcp/GcpCoreApiSurfaceTest.java | 2 + sdks/java/harness/build.gradle | 1 + .../beam/fn/harness/CombineRunners.java | 2 +- .../fn/harness/WindowMappingFnRunner.java | 2 +- .../fn/harness/WindowMergingFnRunner.java | 2 +- .../data/ElementCountFnDataReceiver.java | 13 +-- .../data/PCollectionConsumerRegistry.java | 10 +-- .../data/PTransformFunctionRegistry.java | 11 ++- .../beam/fn/harness/FnApiDoFnRunnerTest.java | 5 +- .../data/ElementCountFnDataReceiverTest.java | 3 +- 44 files changed, 309 insertions(+), 215 deletions(-) delete mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java rename {runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction => sdks/java/core/src/main/java/org/apache/beam/sdk/metrics}/BeamUrns.java (96%) create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/DistributionProtos.java create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/Environments.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/Environments.java index 0d8c9c31c052..7eb5075ae00d 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/Environments.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/Environments.java @@ -34,6 +34,7 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.ReadPayload; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardEnvironments; import org.apache.beam.model.pipeline.v1.RunnerApi.WindowIntoPayload; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.ByteString; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.InvalidProtocolBufferException; diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/ModelCoders.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/ModelCoders.java index 3c6dfbab8f99..5dd5ffdbfb43 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/ModelCoders.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/ModelCoders.java @@ -17,7 +17,7 @@ */ package org.apache.beam.runners.core.construction; -import static org.apache.beam.runners.core.construction.BeamUrns.getUrn; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformTranslation.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformTranslation.java index a072ab31aa38..703aa828d43c 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformTranslation.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/PTransformTranslation.java @@ -17,7 +17,7 @@ */ package org.apache.beam.runners.core.construction; -import static org.apache.beam.runners.core.construction.BeamUrns.getUrn; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import java.io.IOException; diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/WindowingStrategyTranslation.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/WindowingStrategyTranslation.java index 0838b27c8625..20b82a3c3f6d 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/WindowingStrategyTranslation.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/WindowingStrategyTranslation.java @@ -17,7 +17,7 @@ */ package org.apache.beam.runners.core.construction; -import static org.apache.beam.runners.core.construction.BeamUrns.getUrn; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import java.io.IOException; import java.io.Serializable; @@ -30,6 +30,7 @@ import org.apache.beam.model.pipeline.v1.StandardWindowFns.GlobalWindowsPayload; import org.apache.beam.model.pipeline.v1.StandardWindowFns.SessionsPayload; import org.apache.beam.model.pipeline.v1.StandardWindowFns.SlidingWindowsPayload; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.windowing.FixedWindows; import org.apache.beam.sdk.transforms.windowing.GlobalWindows; import org.apache.beam.sdk.transforms.windowing.Sessions; @@ -354,6 +355,7 @@ public static RunnerApi.WindowingStrategy toProto( .withOnTimeBehavior(onTimeBehavior); } + /** Convert an {@link SdkFunctionSpec} to a {@link WindowFn}. */ public static WindowFn windowFnFromProto(SdkFunctionSpec windowFnSpec) { try { String s = windowFnSpec.getSpec().getUrn(); diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/PipelineValidator.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/PipelineValidator.java index aa1470708087..ddb60ad385af 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/PipelineValidator.java +++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/PipelineValidator.java @@ -17,7 +17,7 @@ */ package org.apache.beam.runners.core.construction.graph; -import static org.apache.beam.runners.core.construction.BeamUrns.getUrn; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import java.util.Map; diff --git a/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/CommonCoderTest.java b/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/CommonCoderTest.java index 080e7b7c70b0..b27c1616d5dc 100644 --- a/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/CommonCoderTest.java +++ b/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/CommonCoderTest.java @@ -17,7 +17,7 @@ */ package org.apache.beam.runners.core.construction; -import static org.apache.beam.runners.core.construction.BeamUrns.getUrn; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.MoreObjects.firstNonNull; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkNotNull; import static org.hamcrest.Matchers.equalTo; diff --git a/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/EnvironmentsTest.java b/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/EnvironmentsTest.java index d7a6c0a29271..fc662cbb7153 100644 --- a/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/EnvironmentsTest.java +++ b/runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/EnvironmentsTest.java @@ -38,6 +38,7 @@ import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.io.CountingSource; import org.apache.beam.sdk.io.Read; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.DoFnSchemaInformation; import org.apache.beam.sdk.transforms.ParDo; 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..c36c1181bca9 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,6 +19,7 @@ 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 @@ -29,7 +30,7 @@ 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 deleted file mode 100644 index ba47812ddf78..000000000000 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.USER_COUNTER_URN_PREFIX; - -import org.apache.beam.sdk.metrics.MetricName; - -/** Utility for parsing a URN to a {@link MetricName}. */ -public class MetricUrns { - /** - * Parse a {@link MetricName} from a {@link - * org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum}. - * - *

Should be consistent with {@code parse_namespace_and_name} in monitoring_infos.py. - */ - public static MetricName parseUrn(String urn) { - if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { - urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); - } - // If it is not a user counter, just use the first part of the URN, i.e. 'beam' - String[] pieces = urn.split(":", 2); - if (pieces.length != 2) { - throw new IllegalArgumentException("Invalid metric URN: " + urn); - } - return MetricName.named(pieces[0], pieces[1]); - } -} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java index 5bf435e82d32..24450a14f3d3 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java @@ -36,6 +36,7 @@ public abstract class MetricsTranslation { private MetricsTranslation() {} + /** Convert some proto user-metric updates to {@link MetricUpdates}. */ public static MetricUpdates metricUpdatesFromProto( String ptransformName, Collection userMetricUpdates) { List> counterUpdates = new ArrayList<>(); @@ -73,6 +74,7 @@ public static MetricUpdates metricUpdatesFromProto( return MetricUpdates.create(counterUpdates, distributionUpdates, gaugeUpdates); } + /** Convert a {@link MetricUpdates} to user-metric update protos. */ public static Map> metricUpdatesToProto( MetricUpdates metricUpdates) { LoadingCache> fnMetrics = 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..0c7829a3c327 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,16 +17,20 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.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.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.sdk.metrics.MetricName; +import org.apache.beam.sdk.metrics.MetricUrns; 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 MetricUrns#USER_COUNTER_URN_PREFIX 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 @@ -115,7 +138,7 @@ public boolean equals(Object o) { @Override public String toString() { StringBuilder builder = new StringBuilder(); - builder.append(this.urn.toString()); + builder.append(this.urn); builder.append(" "); builder.append(this.labels.toString()); return builder.toString(); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java index 9ae6741875fb..fd1ef98aaaae 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java @@ -17,6 +17,8 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; + import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -89,8 +91,7 @@ public long getTotalMillis() { @VisibleForTesting public String getLullMessage(Thread trackedThread, Duration millis) { // TODO(ajamato): Share getLullMessage code with DataflowExecutionState. - String userStepName = - this.labelsMetadata.getOrDefault(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, null); + String userStepName = this.labelsMetadata.getOrDefault(PTRANSFORM_LABEL, null); StringBuilder message = new StringBuilder(); message.append("Processing stuck"); if (userStepName != null) { 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 92893d908f76..afff9f9380d3 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,20 +17,19 @@ */ package org.apache.beam.runners.core.metrics; -import static org.apache.beam.model.pipeline.v1.MetricsApi.labelProps; import static org.apache.beam.model.pipeline.v1.MetricsApi.monitoringInfoSpec; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.SUM_INT64_TYPE_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; +import static org.apache.beam.sdk.metrics.MetricUrns.urn; import java.time.Instant; import java.util.HashMap; import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; -import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels; -import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoLabelProps; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoSpec; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoSpecs; -import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoTypeUrns; -import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,25 +59,10 @@ * builder.setInt64Value(1); MonitoringInfo mi = builder.build(); */ public class SimpleMonitoringInfoBuilder { - public static final String ELEMENT_COUNT_URN = - BeamUrns.getUrn(MonitoringInfoUrns.Enum.ELEMENT_COUNT); - public static final String START_BUNDLE_MSECS_URN = - BeamUrns.getUrn(MonitoringInfoUrns.Enum.START_BUNDLE_MSECS); - public static final String PROCESS_BUNDLE_MSECS_URN = - BeamUrns.getUrn(MonitoringInfoUrns.Enum.PROCESS_BUNDLE_MSECS); - public static final String FINISH_BUNDLE_MSECS_URN = - BeamUrns.getUrn(MonitoringInfoUrns.Enum.FINISH_BUNDLE_MSECS); - public static final String USER_COUNTER_URN_PREFIX = - BeamUrns.getUrn(MonitoringInfoUrns.Enum.USER_COUNTER_URN_PREFIX); - public static final String SUM_INT64_TYPE_URN = - BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.SUM_INT64_TYPE); private static final HashMap specs = new HashMap(); - public static final String PCOLLECTION_LABEL = getLabelString(MonitoringInfoLabels.PCOLLECTION); - public static final String PTRANSFORM_LABEL = getLabelString(MonitoringInfoLabels.TRANSFORM); - private final boolean validateAndDropInvalid; private static final Logger LOG = LoggerFactory.getLogger(SimpleMonitoringInfoBuilder.class); @@ -99,13 +83,6 @@ public class SimpleMonitoringInfoBuilder { } } - /** Returns the label string constant defined in the MonitoringInfoLabel enum proto. */ - private static String getLabelString(MonitoringInfoLabels label) { - MonitoringInfoLabelProps props = - label.getValueDescriptor().getOptions().getExtension(labelProps); - return props.getName(); - } - public SimpleMonitoringInfoBuilder() { this(true); } @@ -144,7 +121,7 @@ public SimpleMonitoringInfoBuilder setUrn(String urn) { * @param name */ public SimpleMonitoringInfoBuilder setUrnForUserMetric(String namespace, String name) { - this.builder.setUrn(userMetricUrn(namespace, name)); + this.builder.setUrn(urn(namespace, name)); return this; } 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..e5633c32b431 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 @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,6 +25,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; @@ -41,8 +43,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { MetricsEnvironment.setCurrentContainer(null); assertNull(MetricsEnvironment.getCurrentContainer()); HashMap labels = new HashMap(); - String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); Counter counter = LabeledMetrics.counter(name); counter.inc(); @@ -54,8 +55,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { @Test public void testOperationsUpdateCounterFromContainerWhenContainerIsPresent() { HashMap labels = new HashMap(); - String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_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/MetricsContainerImplTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java index aa74ff287b5a..76cdf88797a7 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 @@ -18,6 +18,8 @@ package org.apache.beam.runners.core.metrics; import static org.apache.beam.runners.core.metrics.MetricUpdateMatchers.metricUpdate; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; @@ -181,14 +183,13 @@ public void testMonitoringInfosArePopulatedForUserCounters() { public void testMonitoringInfosArePopulatedForABeamCounter() { MetricsContainerImpl testObject = new MetricsContainerImpl("step1"); HashMap labels = new HashMap(); - labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "pcollection"); - MetricName name = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); + labels.put(PCOLLECTION_LABEL, "pcollection"); + MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); CounterCell c1 = testObject.getCounter(name); c1.inc(2L); SimpleMonitoringInfoBuilder builder1 = new SimpleMonitoringInfoBuilder(); - builder1.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder1.setUrn(ELEMENT_COUNT_URN); builder1.setPCollectionLabel("pcollection"); builder1.setInt64Value(2); builder1.build(); 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..fdb817f8e7b6 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 @@ -17,11 +17,14 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; 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,20 +36,19 @@ public class MonitoringInfoMetricNameTest implements Serializable { @Test public void testElementCountConstruction() { - HashMap labels = new HashMap(); - String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); - assertEquals(null, name.getName()); - assertEquals(null, name.getNamespace()); + Map labels = new HashMap<>(); + String urn = ELEMENT_COUNT_URN; + MonitoringInfoMetricName name = + (MonitoringInfoMetricName) MonitoringInfoMetricName.named(urn, labels); assertEquals(labels, name.getLabels()); assertEquals(urn, name.getUrn()); assertEquals(name, name); // test self equals; // Reconstruct and test equality and hash code equivalence - urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + urn = ELEMENT_COUNT_URN; + labels = new HashMap<>(); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -56,18 +58,16 @@ public void testElementCountConstruction() { public void testUserCounterUrnConstruction() { String urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); HashMap labels = new HashMap(); - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + 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); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -75,15 +75,15 @@ public void testUserCounterUrnConstruction() { @Test public void testNotEqualsDiffLabels() { - HashMap labels = new HashMap(); - String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + Map labels = new HashMap<>(); + String urn = ELEMENT_COUNT_URN; + MetricName name = MonitoringInfoMetricName.named(urn, labels); // Reconstruct and test equality and hash code equivalence - urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; + urn = ELEMENT_COUNT_URN; 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 +91,14 @@ public void testNotEqualsDiffLabels() { @Test public void testNotEqualsDiffUrn() { - HashMap labels = new HashMap(); - String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + Map labels = new HashMap<>(); + String urn = ELEMENT_COUNT_URN; + 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); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertNotEquals(name, name2); assertNotEquals(name.hashCode(), name2.hashCode()); @@ -107,8 +107,8 @@ public void testNotEqualsDiffUrn() { @Test public void testNullLabelsThrows() { thrown.expect(IllegalArgumentException.class); - HashMap labels = null; - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); + Map labels = null; + MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); } @Test 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 1b337ee9c152..1ffe908cf9b1 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 @@ -17,26 +17,29 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; + import java.util.HashMap; +import java.util.Map; import org.apache.beam.model.pipeline.v1.MetricsApi.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() { - HashMap labels = new HashMap(); - labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "testPCollection"); - MonitoringInfoMetricName name = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - return name; + public static MetricName testElementCountName() { + Map labels = new HashMap<>(); + labels.put(PCOLLECTION_LABEL, "testPCollection"); + return MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); } /** @return A basic MonitoringInfo which matches the testElementCountName. */ public static MonitoringInfo testElementCountMonitoringInfo(long value) { SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("testPCollection"); builder.setInt64Value(value); return builder.build(); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java index 2290619e726f..e4e496911050 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasEntry; @@ -59,7 +60,7 @@ public void testTakeSampleIncrementsTotal() { @Test public void testGetLullReturnsARelevantMessageWithStepName() { HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, "myPTransform"); + labelsMetadata.put(PTRANSFORM_LABEL, "myPTransform"); SimpleExecutionState testObject = new SimpleExecutionState("myState", null, labelsMetadata); String message = testObject.getLullMessage(new Thread(), Duration.millis(100_000)); assertThat(message, containsString("myState")); 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 18e7829d6e71..b1beb5bfdc63 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 @@ -18,6 +18,10 @@ package org.apache.beam.runners.core.metrics; import static junit.framework.TestCase.assertEquals; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.SUM_INT64_TYPE_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -33,7 +37,7 @@ public class SimpleMonitoringInfoBuilderTest { @Test public void testReturnsNullIfSpecRequirementsNotMet() { SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); assertNull(builder.build()); builder.setInt64Value(1); @@ -43,11 +47,9 @@ public void testReturnsNullIfSpecRequirementsNotMet() { // Pass now that the spec is fully met. MonitoringInfo monitoringInfo = builder.build(); assertTrue(monitoringInfo != null); - assertEquals( - "myPcollection", - monitoringInfo.getLabelsOrDefault(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, null)); - assertEquals(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, monitoringInfo.getUrn()); - assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); + assertEquals("myPcollection", monitoringInfo.getLabelsOrDefault(PCOLLECTION_LABEL, null)); + assertEquals(ELEMENT_COUNT_URN, monitoringInfo.getUrn()); + assertEquals(SUM_INT64_TYPE_URN, monitoringInfo.getType()); assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); } @@ -61,10 +63,8 @@ public void testUserCounter() { // Pass now that the spec is fully met. MonitoringInfo monitoringInfo = builder.build(); assertTrue(monitoringInfo != null); - assertEquals( - SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "myNamespace:myName", - monitoringInfo.getUrn()); - assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); + assertEquals(USER_COUNTER_URN_PREFIX + "myNamespace:myName", monitoringInfo.getUrn()); + assertEquals(SUM_INT64_TYPE_URN, monitoringInfo.getType()); assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); } @@ -77,9 +77,8 @@ public void testUserMetricWithInvalidDelimiterCharacterIsReplaced() { MonitoringInfo monitoringInfo = builder.build(); assertTrue(monitoringInfo != null); assertEquals( - SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "myNamespace_withInvalidChar:myName", - monitoringInfo.getUrn()); - assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType()); + USER_COUNTER_URN_PREFIX + "myNamespace_withInvalidChar:myName", monitoringInfo.getUrn()); + assertEquals(SUM_INT64_TYPE_URN, monitoringInfo.getType()); assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); } } diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java index ac42caf5a105..eaf6719c8481 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java @@ -17,6 +17,10 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.FINISH_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PROCESS_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.START_BUNDLE_MSECS_URN; import static org.junit.Assert.assertThat; import java.util.ArrayList; @@ -34,22 +38,16 @@ public class SimpleStateRegistryTest { public void testExecutionTimeUrnsBuildMonitoringInfos() throws Exception { String testPTransformId = "pTransformId"; HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, testPTransformId); + labelsMetadata.put(PTRANSFORM_LABEL, testPTransformId); SimpleExecutionState startState = new SimpleExecutionState( - ExecutionStateTracker.START_STATE_NAME, - SimpleMonitoringInfoBuilder.START_BUNDLE_MSECS_URN, - labelsMetadata); + ExecutionStateTracker.START_STATE_NAME, START_BUNDLE_MSECS_URN, labelsMetadata); SimpleExecutionState processState = new SimpleExecutionState( - ExecutionStateTracker.PROCESS_STATE_NAME, - SimpleMonitoringInfoBuilder.PROCESS_BUNDLE_MSECS_URN, - labelsMetadata); + ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labelsMetadata); SimpleExecutionState finishState = new SimpleExecutionState( - ExecutionStateTracker.FINISH_STATE_NAME, - SimpleMonitoringInfoBuilder.FINISH_BUNDLE_MSECS_URN, - labelsMetadata); + ExecutionStateTracker.FINISH_STATE_NAME, FINISH_BUNDLE_MSECS_URN, labelsMetadata); SimpleStateRegistry testObject = new SimpleStateRegistry(); testObject.register(startState); @@ -59,20 +57,20 @@ public void testExecutionTimeUrnsBuildMonitoringInfos() throws Exception { List> matchers = new ArrayList>(); SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.START_BUNDLE_MSECS_URN); + builder.setUrn(START_BUNDLE_MSECS_URN); builder.setInt64Value(0); builder.setPTransformLabel(testPTransformId); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); // Check for execution time metrics for the testPTransformId builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.PROCESS_BUNDLE_MSECS_URN); + builder.setUrn(PROCESS_BUNDLE_MSECS_URN); builder.setInt64Value(0); builder.setPTransformLabel(testPTransformId); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.FINISH_BUNDLE_MSECS_URN); + builder.setUrn(FINISH_BUNDLE_MSECS_URN); builder.setInt64Value(0); builder.setPTransformLabel(testPTransformId); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SpecMonitoringInfoValidatorTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SpecMonitoringInfoValidatorTest.java index bffcd8a12d88..26907d0254d2 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SpecMonitoringInfoValidatorTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SpecMonitoringInfoValidatorTest.java @@ -17,6 +17,9 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.SUM_INT64_TYPE_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -48,16 +51,16 @@ public void validateReturnsErrorOnInvalidMonitoringInfoType() { public void validateReturnsNoErrorOnValidMonitoringInfo() { MonitoringInfo testInput = MonitoringInfo.newBuilder() - .setUrn(SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "someCounter") - .setType(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN) + .setUrn(USER_COUNTER_URN_PREFIX + "someCounter") + .setType(SUM_INT64_TYPE_URN) .putLabels("dummy", "value") .build(); assertFalse(testObject.validate(testInput).isPresent()); testInput = MonitoringInfo.newBuilder() - .setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN) - .setType(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN) + .setUrn(ELEMENT_COUNT_URN) + .setType(SUM_INT64_TYPE_URN) .putLabels("PTRANSFORM", "value") .putLabels("PCOLLECTION", "anotherValue") .build(); @@ -68,8 +71,8 @@ public void validateReturnsNoErrorOnValidMonitoringInfo() { public void validateReturnsErrorOnInvalidMonitoringInfoLabels() { MonitoringInfo testInput = MonitoringInfo.newBuilder() - .setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN) - .setType(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN) + .setUrn(ELEMENT_COUNT_URN) + .setType(SUM_INT64_TYPE_URN) .putLabels("PTRANSFORM", "unexpectedLabel") .build(); assertTrue(testObject.validate(testInput).isPresent()); 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 87c9afd29875..bb4f5ad0ef09 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,8 +17,8 @@ */ 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.sdk.metrics.MetricUrns.parseUrn; import java.util.HashMap; import java.util.List; diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkDefaultExecutableStageContext.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkDefaultExecutableStageContext.java index ccad6742e7bb..0949c7d027d4 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkDefaultExecutableStageContext.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkDefaultExecutableStageContext.java @@ -22,7 +22,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardEnvironments; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.core.construction.Environments; import org.apache.beam.runners.core.construction.PipelineOptionsTranslation; import org.apache.beam.runners.core.construction.graph.ExecutableStage; @@ -34,6 +33,7 @@ import org.apache.beam.runners.fnexecution.environment.ExternalEnvironmentFactory; import org.apache.beam.runners.fnexecution.environment.ProcessEnvironmentFactory; import org.apache.beam.runners.fnexecution.provisioning.JobInfo; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.options.PortablePipelineOptions; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.MoreObjects; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions; 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 8a623bff18bc..bf6a6ae98d6f 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 @@ -17,10 +17,10 @@ */ package org.apache.beam.runners.flink.metrics; -import static org.apache.beam.model.pipeline.v1.MetricsApi.labelProps; -import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; -import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX; import static org.apache.beam.runners.flink.metrics.FlinkMetricContainer.getFlinkMetricNameString; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; @@ -37,7 +37,6 @@ import org.apache.beam.model.pipeline.v1.MetricsApi.IntDistributionData; import org.apache.beam.model.pipeline.v1.MetricsApi.Metric; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; -import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels; import org.apache.beam.runners.core.metrics.CounterCell; import org.apache.beam.runners.core.metrics.DistributionCell; import org.apache.beam.runners.core.metrics.DistributionData; @@ -68,13 +67,6 @@ public class FlinkMetricContainerTest { @Mock private RuntimeContext runtimeContext; @Mock private MetricGroup metricGroup; - static final String PTRANSFORM_LABEL = - MonitoringInfoLabels.forNumber(MonitoringInfoLabels.TRANSFORM_VALUE) - .getValueDescriptor() - .getOptions() - .getExtension(labelProps) - .getName(); - @Before public void beforeTest() { MockitoAnnotations.initMocks(this); diff --git a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/CreateExecutableStageNodeFunction.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/CreateExecutableStageNodeFunction.java index a2cf3ab6065d..39036e7d9c50 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/CreateExecutableStageNodeFunction.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/CreateExecutableStageNodeFunction.java @@ -68,6 +68,7 @@ import org.apache.beam.runners.dataflow.worker.util.WorkerPropertyNames; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.fn.IdGenerator; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.windowing.FixedWindows; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow.IntervalWindowCoder; diff --git a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/RegisterNodeFunction.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/RegisterNodeFunction.java index 6dea449e4406..32f63d7b692a 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/RegisterNodeFunction.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/graph/RegisterNodeFunction.java @@ -45,7 +45,6 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.SideInput; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardPTransforms; import org.apache.beam.runners.core.SideInputReader; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.core.construction.CoderTranslation; import org.apache.beam.runners.core.construction.Environments; import org.apache.beam.runners.core.construction.PTransformTranslation; @@ -74,6 +73,7 @@ import org.apache.beam.runners.fnexecution.wire.WireCoders; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.fn.IdGenerator; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.Materializations; import org.apache.beam.sdk.util.WindowedValue.FullWindowedValueCoder; import org.apache.beam.sdk.values.KV; diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/DockerEnvironmentFactory.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/DockerEnvironmentFactory.java index 94834fcbb471..60c35a29267a 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/DockerEnvironmentFactory.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/DockerEnvironmentFactory.java @@ -27,7 +27,6 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Environment; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.fnexecution.GrpcFnServer; import org.apache.beam.runners.fnexecution.ServerFactory; import org.apache.beam.runners.fnexecution.artifact.ArtifactRetrievalService; @@ -37,6 +36,7 @@ import org.apache.beam.runners.fnexecution.logging.GrpcLoggingService; import org.apache.beam.runners.fnexecution.provisioning.StaticGrpcProvisionService; import org.apache.beam.sdk.fn.IdGenerator; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.options.ManualDockerEnvironmentOptions; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions; diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java index 9c633ac4b3fd..f20f8c3bf074 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java @@ -23,7 +23,6 @@ import org.apache.beam.model.fnexecution.v1.BeamFnExternalWorkerPoolGrpc; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Environment; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.fnexecution.GrpcFnServer; import org.apache.beam.runners.fnexecution.artifact.ArtifactRetrievalService; import org.apache.beam.runners.fnexecution.control.ControlClientPool; @@ -33,6 +32,7 @@ import org.apache.beam.runners.fnexecution.provisioning.StaticGrpcProvisionService; import org.apache.beam.sdk.fn.IdGenerator; import org.apache.beam.sdk.fn.channel.ManagedChannelFactory; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ProcessEnvironmentFactory.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ProcessEnvironmentFactory.java index bb3de8ce1d79..dd241f5f04e5 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ProcessEnvironmentFactory.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ProcessEnvironmentFactory.java @@ -21,7 +21,6 @@ import java.util.concurrent.TimeoutException; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Environment; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.fnexecution.GrpcFnServer; import org.apache.beam.runners.fnexecution.artifact.ArtifactRetrievalService; import org.apache.beam.runners.fnexecution.control.ControlClientPool; @@ -30,6 +29,7 @@ import org.apache.beam.runners.fnexecution.logging.GrpcLoggingService; import org.apache.beam.runners.fnexecution.provisioning.StaticGrpcProvisionService; import org.apache.beam.sdk.fn.IdGenerator; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ImmutableList; import org.slf4j.Logger; 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 e32cd790a4a3..b0a8a6d3b365 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,6 +17,10 @@ */ package org.apache.beam.runners.fnexecution.control; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.FINISH_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PROCESS_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.START_BUNDLE_MSECS_URN; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkState; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -656,33 +660,33 @@ public void onCompleted(ProcessBundleResponse response) { // The element counter should be counted only once for the pcollection. // So there should be only two elements. builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("impulse.out"); builder.setInt64Value(2); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("create/ParMultiDo(Anonymous).output"); builder.setInt64Value(3); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); // Verify that the element count is not double counted if two PCollections consume it. builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("processA/ParMultiDo(Anonymous).output"); builder.setInt64Value(6); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("processB/ParMultiDo(Anonymous).output"); builder.setInt64Value(6); matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); // Check for execution time metrics for the testPTransformId builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.START_BUNDLE_MSECS_URN); + builder.setUrn(START_BUNDLE_MSECS_URN); builder.setInt64TypeUrn(); builder.setPTransformLabel(testPTransformId); matchers.add( @@ -692,7 +696,7 @@ public void onCompleted(ProcessBundleResponse response) { // Check for execution time metrics for the testPTransformId builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.PROCESS_BUNDLE_MSECS_URN); + builder.setUrn(PROCESS_BUNDLE_MSECS_URN); builder.setInt64TypeUrn(); builder.setPTransformLabel(testPTransformId); matchers.add( @@ -701,7 +705,7 @@ public void onCompleted(ProcessBundleResponse response) { MonitoringInfoMatchers.valueGreaterThan(0))); builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.FINISH_BUNDLE_MSECS_URN); + builder.setUrn(FINISH_BUNDLE_MSECS_URN); builder.setInt64TypeUrn(); builder.setPTransformLabel(testPTransformId); matchers.add( diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/BeamUrns.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/BeamUrns.java similarity index 96% rename from runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/BeamUrns.java rename to sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/BeamUrns.java index 0729ce92d589..e13fb33f5086 100644 --- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/BeamUrns.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/BeamUrns.java @@ -15,7 +15,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.beam.runners.core.construction; +package org.apache.beam.sdk.metrics; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.ProtocolMessageEnum; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/DistributionProtos.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/DistributionProtos.java new file mode 100644 index 000000000000..9f37e52b22c1 --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/DistributionProtos.java @@ -0,0 +1,40 @@ +/* + * 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.sdk.metrics; + +import org.apache.beam.model.pipeline.v1.MetricsApi.IntDistributionData; + +/** 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/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java new file mode 100644 index 000000000000..02396a518713 --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.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.sdk.metrics; + +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels.PCOLLECTION; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels.TRANSFORM; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoTypeUrns.Enum.DISTRIBUTION_INT64_TYPE; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoTypeUrns.Enum.LATEST_INT64_TYPE; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoTypeUrns.Enum.SUM_INT64_TYPE; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum.ELEMENT_COUNT; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum.FINISH_BUNDLE_MSECS; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum.PROCESS_BUNDLE_MSECS; +import static org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum.START_BUNDLE_MSECS; +import static org.apache.beam.model.pipeline.v1.MetricsApi.labelProps; +import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; +import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; + +import javax.annotation.Nullable; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoLabelProps; +import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; + +/** Utility for parsing a URN to a {@link org.apache.beam.sdk.metrics.MetricName}. */ +public class MetricUrns { + public static final String ELEMENT_COUNT_URN = getUrn(ELEMENT_COUNT); + public static final String START_BUNDLE_MSECS_URN = getUrn(START_BUNDLE_MSECS); + public static final String PROCESS_BUNDLE_MSECS_URN = getUrn(PROCESS_BUNDLE_MSECS); + public static final String FINISH_BUNDLE_MSECS_URN = getUrn(FINISH_BUNDLE_MSECS); + public static final String USER_COUNTER_URN_PREFIX = getUrn(Enum.USER_COUNTER_URN_PREFIX); + public static final String SUM_INT64_TYPE_URN = getUrn(SUM_INT64_TYPE); + public static final String DISTRIBUTION_INT64_TYPE_URN = getUrn(DISTRIBUTION_INT64_TYPE); + public static final String LATEST_INT64_TYPE_URN = getUrn(LATEST_INT64_TYPE); + public static final String PCOLLECTION_LABEL = getLabelString(PCOLLECTION); + public static final String PTRANSFORM_LABEL = getLabelString(TRANSFORM); + + /** + * Parse a {@link MetricName} from a {@link + * org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoUrns.Enum}. + * + *

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); + if (pieces.length != 2) { + throw new IllegalArgumentException("Invalid user-metric URN: " + urn); + } + return MetricName.named(pieces[0], pieces[1]); + } + + /** @return The metric URN for a user metric, with a proper URN prefix. */ + public static String urn(String namespace, String name) { + checkArgument(namespace != null, "Metric namespace must be non-null"); + checkArgument(!Strings.isNullOrEmpty(name), "Metric name must be non-empty"); + String fixedMetricNamespace = namespace.replace(':', '_'); + String fixedMetricName = name.replace(':', '_'); + return String.format("%s%s:%s", USER_COUNTER_URN_PREFIX, fixedMetricNamespace, fixedMetricName); + } + + /** Returns the label string constant defined in the MonitoringInfoLabel enum proto. */ + private static String getLabelString(MonitoringInfoLabels label) { + MonitoringInfoLabelProps props = + label.getValueDescriptor().getOptions().getExtension(labelProps); + return props.getName(); + } +} diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java index 6f7863d1270f..df6af8e0393d 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java @@ -168,24 +168,12 @@ public void testCounterWithEmptyName() { Metrics.counter(NS, ""); } - @Test - public void testCounterWithEmptyNamespace() { - thrown.expect(IllegalArgumentException.class); - Metrics.counter("", NAME); - } - @Test public void testDistributionWithEmptyName() { thrown.expect(IllegalArgumentException.class); Metrics.distribution(NS, ""); } - @Test - public void testDistributionWithEmptyNamespace() { - thrown.expect(IllegalArgumentException.class); - Metrics.distribution("", NAME); - } - @Test public void testDistributionToCell() { MetricsContainer mockContainer = Mockito.mock(MetricsContainer.class); diff --git a/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java b/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java index 37cd2ea6d643..b3add8b73c01 100644 --- a/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java +++ b/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java @@ -56,7 +56,9 @@ public void testGcpCoreApiSurface() throws Exception { classesInPackage("com.fasterxml.jackson.annotation"), classesInPackage("java"), classesInPackage("javax"), + classesInPackage("org.apache.beam.model"), classesInPackage("org.apache.beam.sdk"), + classesInPackage("org.apache.beam.vendor.grpc"), classesInPackage("org.joda.time")); assertThat(apiSurface, containsOnlyClassesMatching(allowedClasses)); diff --git a/sdks/java/harness/build.gradle b/sdks/java/harness/build.gradle index 30c957f9bd2a..a137f7129ae3 100644 --- a/sdks/java/harness/build.gradle +++ b/sdks/java/harness/build.gradle @@ -49,6 +49,7 @@ dependencies { dependOnProjects.each { compile project(path: it, configuration: "shadow") } + shadow project(path: ":beam-sdks-java-core", configuration: "shadow") compile library.java.jackson_databind shadow library.java.vendored_guava_20_0 shadowTest library.java.powermock 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 ee196e17fde1..d99f751a7ad3 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 @@ -31,12 +31,12 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.PCollection; import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardPTransforms; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.core.construction.RehydratedComponents; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.function.ThrowingFunction; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.transforms.Combine.CombineFn; import org.apache.beam.sdk.util.SerializableUtils; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMappingFnRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMappingFnRunner.java index 396fa1ebbe3d..9acaf7c1c2e6 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMappingFnRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMappingFnRunner.java @@ -23,9 +23,9 @@ import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; import org.apache.beam.model.pipeline.v1.RunnerApi.SdkFunctionSpec; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardPTransforms; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.core.construction.PCollectionViewTranslation; import org.apache.beam.sdk.function.ThrowingFunction; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.WindowMappingFn; import org.apache.beam.sdk.values.KV; diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMergingFnRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMergingFnRunner.java index 904018db5041..df0e06cd9ec4 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMergingFnRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/WindowMergingFnRunner.java @@ -27,9 +27,9 @@ import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform; import org.apache.beam.model.pipeline.v1.RunnerApi.StandardPTransforms; -import org.apache.beam.runners.core.construction.BeamUrns; import org.apache.beam.runners.core.construction.WindowingStrategyTranslation; import org.apache.beam.sdk.function.ThrowingFunction; +import org.apache.beam.sdk.metrics.BeamUrns; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.WindowFn; import org.apache.beam.sdk.transforms.windowing.WindowFn.MergeContext; 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..12676a5eeebf 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,14 +17,18 @@ */ package org.apache.beam.fn.harness.data; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; + import java.io.Closeable; import java.util.HashMap; +import java.util.Map; 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.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; @@ -46,10 +50,9 @@ public ElementCountFnDataReceiver( 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); + Map labels = new HashMap(); + labels.put(PCOLLECTION_LABEL, pCollection); + MetricName metricName = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); this.counter = LabeledMetrics.counter(metricName); // Collect the metric in a metric container which is not bound to the step name. // This is required to count elements from impulse steps, which will produce elements outside 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 7bee75304afb..de37752aa990 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,6 +17,9 @@ */ package org.apache.beam.fn.harness.data; +import static org.apache.beam.sdk.metrics.MetricUrns.PROCESS_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; + import java.io.Closeable; import java.util.HashMap; import java.util.List; @@ -27,7 +30,6 @@ import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleExecutionState; -import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.runners.core.metrics.SimpleStateRegistry; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.metrics.MetricsEnvironment; @@ -86,12 +88,10 @@ public void register( } HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, pTransformId); + labelsMetadata.put(PTRANSFORM_LABEL, pTransformId); SimpleExecutionState state = new SimpleExecutionState( - ExecutionStateTracker.PROCESS_STATE_NAME, - SimpleMonitoringInfoBuilder.PROCESS_BUNDLE_MSECS_URN, - labelsMetadata); + ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labelsMetadata); executionStates.register(state); // 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 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 6b20fe5662f0..2bcc8dcd0684 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,6 +17,10 @@ */ package org.apache.beam.fn.harness.data; +import static org.apache.beam.sdk.metrics.MetricUrns.FINISH_BUNDLE_MSECS_URN; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.START_BUNDLE_MSECS_URN; + import java.io.Closeable; import java.util.ArrayList; import java.util.HashMap; @@ -26,7 +30,6 @@ import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.SimpleExecutionState; -import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.runners.core.metrics.SimpleStateRegistry; import org.apache.beam.sdk.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; @@ -88,12 +91,12 @@ public PTransformFunctionRegistry( */ public void register(String pTransformId, ThrowingRunnable runnable) { HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, pTransformId); + labelsMetadata.put(PTRANSFORM_LABEL, pTransformId); String executionTimeUrn = ""; if (executionStateName.equals(ExecutionStateTracker.START_STATE_NAME)) { - executionTimeUrn = SimpleMonitoringInfoBuilder.START_BUNDLE_MSECS_URN; + executionTimeUrn = START_BUNDLE_MSECS_URN; } else if (executionStateName.equals(ExecutionStateTracker.FINISH_STATE_NAME)) { - executionTimeUrn = SimpleMonitoringInfoBuilder.FINISH_BUNDLE_MSECS_URN; + executionTimeUrn = FINISH_BUNDLE_MSECS_URN; } SimpleExecutionState state = 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 69684e715c62..3ca4ef855817 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 @@ -17,6 +17,7 @@ */ package org.apache.beam.fn.harness; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.apache.beam.sdk.util.WindowedValue.timestampedValueInGlobalWindow; import static org.apache.beam.sdk.util.WindowedValue.valueInGlobalWindow; import static org.hamcrest.Matchers.contains; @@ -663,13 +664,13 @@ public void testUsingMetrics() throws Exception { List expected = new ArrayList(); SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel("Window.Into()/Window.Assign.out"); builder.setInt64Value(2); expected.add(builder.build()); builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel( "pTransformId/ParMultiDo(TestSideInputIsAccessibleForDownstreamCallers).output"); builder.setInt64Value(2); 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 549049551f57..ade686b445a6 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiverTest.java @@ -18,6 +18,7 @@ package org.apache.beam.fn.harness.data; import static junit.framework.TestCase.assertEquals; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -63,7 +64,7 @@ public void testCountsElements() throws Exception { verify(consumer, times(numElements)).accept(element); SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN); + builder.setUrn(ELEMENT_COUNT_URN); builder.setPCollectionLabel(pCollectionA); builder.setInt64Value(numElements); MonitoringInfo expected = builder.build(); From b10a2e79bdcd65b787ecd01b65495bde454e5332 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Tue, 19 Feb 2019 07:35:37 +0000 Subject: [PATCH 2/4] Metric{Key,Labels,Name}, querying refactor --- .../core/metrics/MetricsContainerImpl.java | 49 ++--- .../core/metrics/MetricsContainerStepMap.java | 38 ++-- .../core/metrics/MetricsTranslation.java | 5 +- .../metrics/MonitoringInfoMetricName.java | 146 -------------- .../core/metrics/SimpleExecutionState.java | 7 +- .../metrics/SimpleMonitoringInfoBuilder.java | 19 +- .../core/LateDataDroppingDoFnRunnerTest.java | 2 +- .../beam/runners/core/ReduceFnRunnerTest.java | 14 +- .../runners/core/StatefulDoFnRunnerTest.java | 2 +- .../core/metrics/LabeledMetricsTest.java | 4 +- .../metrics/MetricsContainerImplTest.java | 56 +++--- .../metrics/MetricsContainerStepMapTest.java | 94 ++++----- .../metrics/MonitoringInfoMetricNameTest.java | 127 ------------ .../core/metrics/MonitoringInfoTestUtil.java | 11 - .../metrics/SimpleExecutionStateTest.java | 10 +- .../SimpleMonitoringInfoBuilderTest.java | 21 +- .../core/metrics/SimpleStateRegistryTest.java | 15 +- .../direct/DirectTransformExecutor.java | 3 +- .../portable/DirectTransformExecutor.java | 2 +- .../runners/direct/DirectMetricsTest.java | 48 +++-- .../direct/portable/DirectMetricsTest.java | 48 +++-- .../extensions/metrics/MetricsHttpSink.java | 4 +- .../metrics/CustomMetricQueryResults.java | 4 +- .../metrics/DoFnRunnerWithMetricsUpdate.java | 10 +- .../flink/metrics/FlinkMetricContainer.java | 189 ++++++++++-------- .../flink/metrics/ReaderInvocationUtil.java | 8 +- .../metrics/FlinkMetricContainerTest.java | 95 +++++---- .../runners/dataflow/DataflowMetrics.java | 8 +- .../worker/BatchModeExecutionContext.java | 2 +- .../worker/StreamingStepMetricsContainer.java | 4 +- .../worker/IntrinsicMapTaskExecutorTest.java | 2 +- .../dataflow/worker/SimpleParDoFnTest.java | 2 +- .../StreamingGroupAlsoByWindowFnsTest.java | 2 +- .../dataflow/worker/TestOperationContext.java | 4 +- .../worker/WorkItemStatusClientTest.java | 2 +- .../common/worker/MapTaskExecutorTest.java | 2 +- .../control/RemoteExecutionTest.java | 135 ++++++++----- .../samza/metrics/SamzaMetricsContainer.java | 2 +- .../beam/runners/spark/io/SourceRDD.java | 3 +- .../spark/io/SparkUnboundedSource.java | 3 +- .../spark/metrics/SparkBeamMetric.java | 25 +-- .../SparkGroupAlsoByWindowViaWindowSet.java | 2 +- .../spark/stateful/StateSpecFunctions.java | 2 +- .../translation/DoFnRunnerWithMetrics.java | 2 +- .../spark/io/ReaderToIteratorAdapterTest.java | 3 +- .../spark/metrics/SparkBeamMetricTest.java | 6 +- .../ResumeFromCheckpointStreamingTest.java | 14 +- .../streaming/StreamingSourceMetricsTest.java | 7 +- .../beam/sdk/metrics/MetricFiltering.java | 3 +- .../apache/beam/sdk/metrics/MetricKey.java | 67 ++++++- .../apache/beam/sdk/metrics/MetricName.java | 103 +++++++--- .../beam/sdk/metrics/MetricsFilter.java | 12 ++ .../beam/sdk/metrics/labels/MetricLabels.java | 162 +++++++++++++++ .../beam/sdk/metrics/labels/package-info.java | 19 ++ .../apache/beam/sdk/testing/TestPipeline.java | 6 +- .../beam/sdk/metrics/MetricFilteringTest.java | 23 +-- .../sdk/metrics/MetricResultsMatchers.java | 2 +- .../apache/beam/sdk/metrics/MetricsTest.java | 12 +- .../extensions/gcp/GcpCoreApiSurfaceTest.java | 2 - .../sql/impl/rel/BeamEnumerableConverter.java | 8 +- .../data/ElementCountFnDataReceiver.java | 12 +- .../data/PCollectionConsumerRegistry.java | 9 +- .../data/PTransformFunctionRegistry.java | 11 +- .../fn/harness/AssignWindowsRunnerTest.java | 2 +- .../beam/fn/harness/FnApiDoFnRunnerTest.java | 51 ++--- .../data/ElementCountFnDataReceiverTest.java | 3 +- .../data/PCollectionConsumerRegistryTest.java | 6 +- .../data/PTransformFunctionRegistryTest.java | 6 +- .../apache/beam/sdk/io/kafka/KafkaIOTest.java | 24 +-- .../sdk/testutils/metrics/MetricsReader.java | 17 +- 70 files changed, 893 insertions(+), 930 deletions(-) delete mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java delete mode 100644 runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/MetricLabels.java create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/package-info.java 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 2ba95cddb261..b5583ad3a479 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 @@ -22,7 +22,6 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Map; -import java.util.Map.Entry; import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; @@ -32,6 +31,7 @@ import org.apache.beam.sdk.metrics.MetricKey; import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; +import org.apache.beam.sdk.metrics.labels.MetricLabels; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ImmutableList; /** @@ -50,7 +50,7 @@ @Experimental(Kind.METRICS) public class MetricsContainerImpl implements Serializable, MetricsContainer { - @Nullable private final String stepName; + private final MetricLabels labels; private MetricsMap counters = new MetricsMap<>(CounterCell::new); @@ -59,9 +59,17 @@ public class MetricsContainerImpl implements Serializable, MetricsContainer { private MetricsMap gauges = new MetricsMap<>(GaugeCell::new); + public static MetricsContainerImpl ptransform(String ptransform) { + return new MetricsContainerImpl(MetricLabels.ptransform(ptransform)); + } + + public static MetricsContainerImpl pcollection(String pcollection) { + return new MetricsContainerImpl(MetricLabels.pcollection(pcollection)); + } + /** Create a new {@link MetricsContainerImpl} associated with the given {@code stepName}. */ - public MetricsContainerImpl(@Nullable String stepName) { - this.stepName = stepName; + public MetricsContainerImpl(MetricLabels labels) { + this.labels = labels; } /** @@ -124,7 +132,7 @@ ImmutableList> extractUpdates(MetricsMap metricUpdate) { - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(true); - MetricName metricName = metricUpdate.getKey().metricName(); - if (metricName instanceof MonitoringInfoMetricName) { - MonitoringInfoMetricName monitoringInfoName = (MonitoringInfoMetricName) metricName; - // Represents a specific MonitoringInfo for a specific URN. - builder.setUrn(monitoringInfoName.getUrn()); - for (Entry e : monitoringInfoName.getLabels().entrySet()) { - builder.setLabel(e.getKey(), e.getValue()); - } - } else { // Note: (metricName instanceof MetricName) is always True. - // Represents a user counter. - builder.setUrnForUserMetric( - metricUpdate.getKey().metricName().getNamespace(), - metricUpdate.getKey().metricName().getName()); - // Drop if the stepname is not set. All user counters must be - // defined for a PTransform. They must be defined on a container bound to a step. - if (this.stepName == null) { - return null; - } - builder.setPTransformLabel(metricUpdate.getKey().stepName()); - } - builder.setInt64Value(metricUpdate.getUpdate()); - builder.setTimestampToNow(); - return builder.build(); + return new SimpleMonitoringInfoBuilder(true) + .handleMetricKey(metricUpdate.getKey()) + .setInt64Value(metricUpdate.getUpdate()) + .setTimestampToNow() + .build(); } /** Return the cumulative values for any metrics in this container as MonitoringInfos. */ @@ -207,7 +196,7 @@ ImmutableList> extractCumulatives(MetricsMap> updates = ImmutableList.builder(); for (Map.Entry cell : cells.entries()) { UpdateT update = checkNotNull(cell.getValue().getCumulative()); - updates.add(MetricUpdate.create(MetricKey.create(stepName, cell.getKey()), update)); + updates.add(MetricUpdate.create(MetricKey.of(cell.getKey(), labels), update)); } return updates.build(); } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index 4f05984a719c..1b5df0fbdc3a 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java @@ -17,9 +17,7 @@ */ package org.apache.beam.runners.core.metrics; -import static java.util.Collections.singleton; import static java.util.stream.Collectors.toList; -import static org.apache.beam.vendor.guava.v20_0.com.google.common.collect.Iterables.concat; import java.io.Serializable; import java.util.ArrayList; @@ -32,6 +30,7 @@ import org.apache.beam.sdk.metrics.MetricKey; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricResults; +import org.apache.beam.sdk.metrics.labels.MetricLabels; /** * Metrics containers by step. @@ -39,29 +38,26 @@ *

This class is not thread-safe. */ public class MetricsContainerStepMap implements Serializable { - - private Map metricsContainers; - private MetricsContainerImpl unboundContainer = new MetricsContainerImpl(null); + private Map metricsContainers; public MetricsContainerStepMap() { this.metricsContainers = new ConcurrentHashMap<>(); } - /* Returns the container that is not bound to any step name. */ - public MetricsContainerImpl getUnboundContainer() { - return this.unboundContainer; + public MetricsContainerImpl ptransformContainer(String ptransform) { + return getContainer(MetricLabels.ptransform(ptransform)); + } + + public MetricsContainerImpl pcollectionContainer(String pcollection) { + return getContainer(MetricLabels.pcollection(pcollection)); } /** 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)); + public MetricsContainerImpl getContainer(MetricLabels labels) { + if (!metricsContainers.containsKey(labels)) { + metricsContainers.put(labels, new MetricsContainerImpl(labels)); } - return metricsContainers.get(stepName); + return metricsContainers.get(labels); } /** @@ -69,18 +65,18 @@ public MetricsContainerImpl getContainer(String stepName) { * MetricsContainerStepMap}. */ public void updateAll(MetricsContainerStepMap other) { - for (Map.Entry container : other.metricsContainers.entrySet()) { + for (Map.Entry container : + other.metricsContainers.entrySet()) { getContainer(container.getKey()).update(container.getValue()); } - getUnboundContainer().update(other.getUnboundContainer()); } /** * Update {@link MetricsContainerImpl} for given step in this map with all values from given * {@link MetricsContainerImpl}. */ - public void update(String step, MetricsContainerImpl container) { - getContainer(step).update(container); + public void update(MetricLabels labels, MetricsContainerImpl container) { + getContainer(labels).update(container); } @Override @@ -172,7 +168,7 @@ public String toString() { } private Iterable getMetricsContainers() { - return concat(metricsContainers.values(), singleton(unboundContainer)); + return metricsContainers.values(); } @SuppressWarnings("ConstantConditions") diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java index 24450a14f3d3..ed5101613529 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsTranslation.java @@ -26,6 +26,7 @@ import org.apache.beam.sdk.annotations.Experimental.Kind; import org.apache.beam.sdk.metrics.MetricKey; import org.apache.beam.sdk.metrics.MetricName; +import org.apache.beam.sdk.metrics.labels.MetricLabels; import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.CacheBuilder; import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.CacheLoader; import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.LoadingCache; @@ -45,7 +46,9 @@ public static MetricUpdates metricUpdatesFromProto( for (BeamFnApi.Metrics.User userMetricUpdate : userMetricUpdates) { MetricKey metricKey = - MetricKey.create(ptransformName, metricNameFromProto(userMetricUpdate.getMetricName())); + MetricKey.of( + metricNameFromProto(userMetricUpdate.getMetricName()), + MetricLabels.ptransform(ptransformName)); switch (userMetricUpdate.getDataCase()) { case COUNTER_DATA: counterUpdates.add( 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 deleted file mode 100644 index 0c7829a3c327..000000000000 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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.sdk.metrics.MetricUrns.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.pipeline.v1.MetricsApi.MonitoringInfo; -import org.apache.beam.sdk.metrics.MetricName; -import org.apache.beam.sdk.metrics.MetricUrns; -import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; - -/** - * An implementation of {@code MetricKey} based on a MonitoringInfo's URN and label to represent the - * key instead of only a name+namespace. This is useful when defining system defined metrics with a - * specific urn via a {@code CounterContainer}. - */ -public class MonitoringInfoMetricName extends MetricName { - - private String urn; - @Nullable private String name; - @Nullable private String namespace; - private Map labels = new HashMap(); - - 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 - // and ensure all necessary labels are set for the specific URN. - this.urn = urn; - for (Entry entry : labels.entrySet()) { - this.labels.put(entry.getKey(), entry.getValue()); - } - } - - /** Parse the urn field into a name and namespace field. */ - private void parseUrn() { - 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); - } - } - - /** @return the parsed namespace from the user metric URN, otherwise null. */ - @Override - public String getNamespace() { - if (this.namespace == null) { - parseUrn(); - } - return this.namespace; - } - - /** @return the parsed name from the user metric URN, otherwise null. */ - @Override - public String getName() { - if (this.name == null) { - parseUrn(); - } - return this.name; - } - - /** @return the urn of this MonitoringInfo metric. */ - public String getUrn() { - return this.urn; - } - - /** @return The labels associated with this MonitoringInfo. */ - public Map getLabels() { - return this.labels; - } - - /** - * Polymorphic constructor of {@link MetricName}s. - * - *

If `urn` is a {@link MetricUrns#USER_COUNTER_URN_PREFIX 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 - public int hashCode() { - // Don't include name and namespace, since they are lazily set. - return Objects.hash(urn, labels); - } - - @Override - public boolean equals(Object o) { - // If the object is compared with itself then return true - if (o == this) { - return true; - } - if (!(o instanceof MonitoringInfoMetricName)) { - return false; - } - MonitoringInfoMetricName other = (MonitoringInfoMetricName) o; - return this.urn.equals(other.urn) && this.labels.equals(other.labels); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(this.urn); - builder.append(" "); - builder.append(this.labels.toString()); - return builder.toString(); - } -} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java index fd1ef98aaaae..16dcb3a83cf6 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleExecutionState.java @@ -37,7 +37,7 @@ */ public class SimpleExecutionState extends ExecutionState { private long totalMillis = 0; - private HashMap labelsMetadata; + private Map labelsMetadata; private String urn; private static final Logger LOG = LoggerFactory.getLogger(SimpleExecutionState.class); @@ -61,13 +61,12 @@ public class SimpleExecutionState extends ExecutionState { * @param urn A optional string urn for an execution time metric. * @param labelsMetadata arbitrary metadata to use for reporting purposes. */ - public SimpleExecutionState( - String stateName, String urn, HashMap labelsMetadata) { + public SimpleExecutionState(String stateName, String urn, Map labelsMetadata) { super(stateName); this.urn = urn; this.labelsMetadata = labelsMetadata; if (this.labelsMetadata == null) { - this.labelsMetadata = new HashMap(); + this.labelsMetadata = new HashMap<>(); } } 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 afff9f9380d3..fa18d9bbe384 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 @@ -30,6 +30,7 @@ import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoSpec; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoSpecs; +import org.apache.beam.sdk.metrics.MetricKey; import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +56,7 @@ *

Example Usage (ElementCount counter): * *

SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - * builder.setUrn(SimpleMonitoringInfoBuilder.setUrnForUserMetric("myNamespace", "myName")); + * builder.setUrn(SimpleMonitoringInfoBuilder.userMetric("myNamespace", "myName")); * builder.setInt64Value(1); MonitoringInfo mi = builder.build(); */ public class SimpleMonitoringInfoBuilder { @@ -114,17 +115,17 @@ public SimpleMonitoringInfoBuilder setUrn(String urn) { return this; } - /** - * Sets the urn of the MonitoringInfo to a proper user metric URN for the given params. - * - * @param namespace - * @param name - */ - public SimpleMonitoringInfoBuilder setUrnForUserMetric(String namespace, String name) { - this.builder.setUrn(urn(namespace, name)); + public SimpleMonitoringInfoBuilder handleMetricKey(MetricKey key) { + builder.setUrn(key.metricName().urn()).putAllLabels(key.labels().map()); return this; } + /** Sets the urn of the MonitoringInfo to a proper user metric URN for the given params. */ + public SimpleMonitoringInfoBuilder userMetric(String ptransform, String namespace, String name) { + builder.setUrn(urn(namespace, name)); + return setPTransformLabel(ptransform); + } + /** Sets the timestamp of the MonitoringInfo to the current time. */ public SimpleMonitoringInfoBuilder setTimestampToNow() { Instant time = Instant.now(); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/LateDataDroppingDoFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/LateDataDroppingDoFnRunnerTest.java index 490ab1f1e5a4..de752b7afeec 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/LateDataDroppingDoFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/LateDataDroppingDoFnRunnerTest.java @@ -56,7 +56,7 @@ public void setUp() { @Test public void testLateDataFilter() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); when(mockTimerInternals.currentInputWatermarkTime()).thenReturn(new Instant(15L)); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/ReduceFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/ReduceFnRunnerTest.java index 7da0461e6003..acbf9ebca97c 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/ReduceFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/ReduceFnRunnerTest.java @@ -201,7 +201,7 @@ public void testProcessingTimeTimerDoesNotGc() throws Exception { @Test public void testOnElementBufferingDiscarding() throws Exception { // Test basic execution of a trigger using a non-combining window set and discarding mode. - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); ReduceFnTester, IntervalWindow> tester = ReduceFnTester.nonCombining( @@ -727,7 +727,7 @@ public void testOnElementCombiningWithContext() throws Exception { @Test public void testWatermarkHoldAndLateData() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); // Test handling of late data. Specifically, ensure the watermark hold is correct. Duration allowedLateness = Duration.millis(10); @@ -965,7 +965,7 @@ public void testMergingWatermarkHoldLateNewWindowMerged() throws Exception { @Test public void testMergingLateWatermarkHolds() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); Duration gapDuration = Duration.millis(10); Duration allowedLateness = Duration.standardMinutes(100); @@ -999,7 +999,7 @@ public void testMergingLateWatermarkHolds() throws Exception { @Test public void testMergingWatermarkHoldAndLateDataFuzz() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); // Test handling of late data. Specifically, ensure the watermark hold is correct. Duration allowedLateness = Duration.standardMinutes(100); @@ -1723,7 +1723,7 @@ public void testMergingWithClosedDoesNotPoison() throws Exception { */ @Test public void testDropDataMultipleWindowsFinishedTrigger() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); ReduceFnTester tester = ReduceFnTester.combining( @@ -1774,7 +1774,7 @@ public void testDropDataMultipleWindowsFinishedTrigger() throws Exception { @Test public void testIdempotentEmptyPanesDiscarding() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); // Test uninteresting (empty) panes don't increment the index or otherwise // modify PaneInfo. @@ -1829,7 +1829,7 @@ public void testIdempotentEmptyPanesDiscarding() throws Exception { @Test public void testIdempotentEmptyPanesAccumulating() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); // Test uninteresting (empty) panes don't increment the index or otherwise // modify PaneInfo. diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/StatefulDoFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/StatefulDoFnRunnerTest.java index 3e0f1aabcaac..2e892b3d821a 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/StatefulDoFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/StatefulDoFnRunnerTest.java @@ -90,7 +90,7 @@ public void setup() { @Test public void testLateDropping() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("any"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("any"); MetricsEnvironment.setCurrentContainer(container); timerInternals.advanceInputWatermark(new Instant(BoundedWindow.TIMESTAMP_MAX_VALUE)); 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 e5633c32b431..fb0297c60c92 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 @@ -43,7 +43,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { MetricsEnvironment.setCurrentContainer(null); assertNull(MetricsEnvironment.getCurrentContainer()); HashMap labels = new HashMap(); - MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); + MetricName name = MetricName.of(ELEMENT_COUNT_URN); Counter counter = LabeledMetrics.counter(name); counter.inc(); @@ -55,7 +55,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { @Test public void testOperationsUpdateCounterFromContainerWhenContainerIsPresent() { HashMap labels = new HashMap(); - MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); + MetricName name = MetricName.of(ELEMENT_COUNT_URN); 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/MetricsContainerImplTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerImplTest.java index 76cdf88797a7..9e9d6e3765d4 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 @@ -18,8 +18,8 @@ package org.apache.beam.runners.core.metrics; import static org.apache.beam.runners.core.metrics.MetricUpdateMatchers.metricUpdate; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.clearTimestamp; import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; @@ -27,7 +27,6 @@ import static org.junit.Assert.assertThat; import java.util.ArrayList; -import java.util.HashMap; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.sdk.metrics.MetricName; import org.junit.Test; @@ -40,7 +39,7 @@ public class MetricsContainerImplTest { @Test public void testCounterDeltas() { - MetricsContainerImpl container = new MetricsContainerImpl("step1"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("step1"); CounterCell c1 = container.getCounter(MetricName.named("ns", "name1")); CounterCell c2 = container.getCounter(MetricName.named("ns", "name2")); assertThat( @@ -80,7 +79,7 @@ public void testCounterDeltas() { @Test public void testCounterCumulatives() { - MetricsContainerImpl container = new MetricsContainerImpl("step1"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("step1"); CounterCell c1 = container.getCounter(MetricName.named("ns", "name1")); CounterCell c2 = container.getCounter(MetricName.named("ns", "name2")); c1.inc(2L); @@ -105,7 +104,7 @@ public void testCounterCumulatives() { @Test public void testDistributionDeltas() { - MetricsContainerImpl container = new MetricsContainerImpl("step1"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("step1"); DistributionCell c1 = container.getDistribution(MetricName.named("ns", "name1")); DistributionCell c2 = container.getDistribution(MetricName.named("ns", "name2")); @@ -152,52 +151,51 @@ public void testDistributionDeltas() { @Test public void testMonitoringInfosArePopulatedForUserCounters() { - MetricsContainerImpl testObject = new MetricsContainerImpl("step1"); + MetricsContainerImpl testObject = MetricsContainerImpl.ptransform("step1"); CounterCell c1 = testObject.getCounter(MetricName.named("ns", "name1")); CounterCell c2 = testObject.getCounter(MetricName.named("ns", "name2")); c1.inc(2L); c2.inc(4L); c1.inc(3L); - SimpleMonitoringInfoBuilder builder1 = new SimpleMonitoringInfoBuilder(); - builder1.setUrnForUserMetric("ns", "name1"); - builder1.setInt64Value(5); - builder1.setPTransformLabel("step1"); - builder1.build(); + MonitoringInfo expected1 = + new SimpleMonitoringInfoBuilder() + .userMetric("step1", "ns", "name1") + .setInt64Value(5) + .build(); - SimpleMonitoringInfoBuilder builder2 = new SimpleMonitoringInfoBuilder(); - builder2.setUrnForUserMetric("ns", "name2"); - builder2.setInt64Value(4); - builder2.setPTransformLabel("step1"); - builder2.build(); + MonitoringInfo expected2 = + new SimpleMonitoringInfoBuilder() + .userMetric("step1", "ns", "name2") + .setInt64Value(4) + .build(); ArrayList actualMonitoringInfos = new ArrayList(); for (MonitoringInfo mi : testObject.getMonitoringInfos()) { - actualMonitoringInfos.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + actualMonitoringInfos.add(clearTimestamp(mi)); } - assertThat(actualMonitoringInfos, containsInAnyOrder(builder1.build(), builder2.build())); + assertThat(actualMonitoringInfos, containsInAnyOrder(expected1, expected2)); } @Test public void testMonitoringInfosArePopulatedForABeamCounter() { - MetricsContainerImpl testObject = new MetricsContainerImpl("step1"); - HashMap labels = new HashMap(); - labels.put(PCOLLECTION_LABEL, "pcollection"); - MetricName name = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); + MetricsContainerImpl testObject = MetricsContainerImpl.pcollection("pcollection"); + MetricName name = MetricName.of(ELEMENT_COUNT_URN); CounterCell c1 = testObject.getCounter(name); c1.inc(2L); - SimpleMonitoringInfoBuilder builder1 = new SimpleMonitoringInfoBuilder(); - builder1.setUrn(ELEMENT_COUNT_URN); - builder1.setPCollectionLabel("pcollection"); - builder1.setInt64Value(2); - builder1.build(); + MonitoringInfo expected = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("pcollection") + .setInt64Value(2) + .build(); ArrayList actualMonitoringInfos = new ArrayList(); for (MonitoringInfo mi : testObject.getMonitoringInfos()) { - actualMonitoringInfos.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + actualMonitoringInfos.add(clearTimestamp(mi)); } - assertThat(actualMonitoringInfos, containsInAnyOrder(builder1.build())); + assertThat(actualMonitoringInfos, containsInAnyOrder(expected)); } } 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 21a361dec753..4193a378a955 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 @@ -19,7 +19,10 @@ 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.runners.core.metrics.MonitoringInfoTestUtil.testElementCountMonitoringInfo; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.clearTimestamp; import static org.apache.beam.sdk.metrics.MetricResultsMatchers.metricsResult; +import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; @@ -34,12 +37,14 @@ 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.MetricKey; 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; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.metrics.MetricsFilter; +import org.apache.beam.sdk.metrics.labels.MetricLabels; import org.hamcrest.collection.IsIterableWithSize; import org.joda.time.Instant; import org.junit.Rule; @@ -53,6 +58,7 @@ public class MetricsContainerStepMapTest { private static final Logger LOG = LoggerFactory.getLogger(MetricsContainerStepMapTest.class); private static final String NAMESPACE = MetricsContainerStepMapTest.class.getName(); + private static final String UNUSED_STEP = "unusedStep"; private static final String STEP1 = "myStep1"; private static final String STEP2 = "myStep2"; private static final String COUNTER_NAME = "myCounter"; @@ -70,7 +76,7 @@ public class MetricsContainerStepMapTest { private static final MetricsContainerImpl metricsContainer; static { - metricsContainer = new MetricsContainerImpl(null); + metricsContainer = MetricsContainerImpl.ptransform(UNUSED_STEP); try (Closeable ignored = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { counter.inc(VALUE); distribution.update(VALUE); @@ -86,14 +92,13 @@ public class MetricsContainerStepMapTest { @Test public void testAttemptedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); - attemptedMetrics.update(STEP1, metricsContainer); - attemptedMetrics.update(STEP2, metricsContainer); - attemptedMetrics.update(STEP2, metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); MetricResults metricResults = asAttemptedOnlyMetricResults(attemptedMetrics); - MetricQueryResults step1res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP1).build()); + MetricQueryResults step1res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP1)); assertIterableSize(step1res.getCounters(), 1); assertIterableSize(step1res.getDistributions(), 1); @@ -108,8 +113,7 @@ public void testAttemptedAccumulatedMetricResults() { false); assertGauge(GAUGE_NAME, step1res, STEP1, GaugeResult.create(VALUE, Instant.now()), false); - MetricQueryResults step2res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP2).build()); + MetricQueryResults step2res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP2)); assertIterableSize(step2res.getCounters(), 1); assertIterableSize(step2res.getDistributions(), 1); @@ -134,11 +138,10 @@ public void testAttemptedAccumulatedMetricResults() { @Test public void testCounterCommittedUnsupportedInAttemptedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); - attemptedMetrics.update(STEP1, metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); MetricResults metricResults = asAttemptedOnlyMetricResults(attemptedMetrics); - MetricQueryResults step1res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP1).build()); + MetricQueryResults step1res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP1)); thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("This runner does not currently support committed metrics results."); @@ -149,11 +152,10 @@ public void testCounterCommittedUnsupportedInAttemptedAccumulatedMetricResults() @Test public void testDistributionCommittedUnsupportedInAttemptedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); - attemptedMetrics.update(STEP1, metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); MetricResults metricResults = asAttemptedOnlyMetricResults(attemptedMetrics); - MetricQueryResults step1res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP1).build()); + MetricQueryResults step1res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP1)); thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("This runner does not currently support committed metrics results."); @@ -165,11 +167,10 @@ public void testDistributionCommittedUnsupportedInAttemptedAccumulatedMetricResu @Test public void testGaugeCommittedUnsupportedInAttemptedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); - attemptedMetrics.update(STEP1, metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); MetricResults metricResults = asAttemptedOnlyMetricResults(attemptedMetrics); - MetricQueryResults step1res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP1).build()); + MetricQueryResults step1res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP1)); thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("This runner does not currently support committed metrics results."); @@ -177,26 +178,19 @@ public void testGaugeCommittedUnsupportedInAttemptedAccumulatedMetricResults() { assertGauge(GAUGE_NAME, step1res, STEP1, GaugeResult.empty(), true); } - @Test - public void testUserMetricDroppedOnUnbounded() { - MetricsContainerStepMap testObject = new MetricsContainerStepMap(); - CounterCell c1 = testObject.getUnboundContainer().getCounter(MetricName.named("ns", "name1")); - c1.inc(5); - - List expected = new ArrayList(); - assertThat(testObject.getMonitoringInfos(), containsInAnyOrder(expected.toArray())); - } - @Test public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { MetricsContainerStepMap baseMetricContainerRegistry = new MetricsContainerStepMap(); - CounterCell c1 = - baseMetricContainerRegistry.getContainer(STEP1).getCounter(MetricName.named("ns", "name1")); + MetricName name = MetricName.named("ns", "name1"); + MetricLabels labels = MetricLabels.ptransform(STEP1); + MetricKey key = MetricKey.of(name, labels); + + CounterCell c1 = baseMetricContainerRegistry.getContainer(labels).getCounter(name); CounterCell c2 = baseMetricContainerRegistry - .getUnboundContainer() - .getCounter(MonitoringInfoTestUtil.testElementCountName()); + .getContainer(MetricLabels.pcollection("testPCollection")) + .getCounter(MetricName.of(ELEMENT_COUNT_URN)); c1.inc(7); c2.inc(14); @@ -206,18 +200,18 @@ public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { List expected = new ArrayList(); - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric("ns", "name1"); - builder.setPTransformLabel(STEP1); - builder.setInt64Value(7); - expected.add(builder.build()); + expected.add( + new SimpleMonitoringInfoBuilder() + .userMetric(STEP1, "ns", "name1") + .setInt64Value(7) + .build()); - expected.add(MonitoringInfoTestUtil.testElementCountMonitoringInfo(14)); + expected.add(testElementCountMonitoringInfo(14)); ArrayList actual = new ArrayList(); for (MonitoringInfo mi : testObject.getMonitoringInfos()) { - actual.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + actual.add(clearTimestamp(mi)); } assertThat(actual, containsInAnyOrder(expected.toArray())); } @@ -225,21 +219,20 @@ public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { @Test public void testAttemptedAndCommittedAccumulatedMetricResults() { MetricsContainerStepMap attemptedMetrics = new MetricsContainerStepMap(); - attemptedMetrics.update(STEP1, metricsContainer); - attemptedMetrics.update(STEP1, metricsContainer); - attemptedMetrics.update(STEP2, metricsContainer); - attemptedMetrics.update(STEP2, metricsContainer); - attemptedMetrics.update(STEP2, metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); + attemptedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); MetricsContainerStepMap committedMetrics = new MetricsContainerStepMap(); - committedMetrics.update(STEP1, metricsContainer); - committedMetrics.update(STEP2, metricsContainer); - committedMetrics.update(STEP2, metricsContainer); + committedMetrics.update(MetricLabels.ptransform(STEP1), metricsContainer); + committedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); + committedMetrics.update(MetricLabels.ptransform(STEP2), metricsContainer); MetricResults metricResults = asMetricResults(attemptedMetrics, committedMetrics); - MetricQueryResults step1res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP1).build()); + MetricQueryResults step1res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP1)); assertIterableSize(step1res.getCounters(), 1); assertIterableSize(step1res.getDistributions(), 1); @@ -263,8 +256,7 @@ public void testAttemptedAndCommittedAccumulatedMetricResults() { true); assertGauge(GAUGE_NAME, step1res, STEP1, GaugeResult.create(VALUE, Instant.now()), true); - MetricQueryResults step2res = - metricResults.queryMetrics(MetricsFilter.builder().addStep(STEP2).build()); + MetricQueryResults step2res = metricResults.queryMetrics(MetricsFilter.ptransform(STEP2)); assertIterableSize(step2res.getCounters(), 1); assertIterableSize(step2res.getDistributions(), 1); @@ -288,7 +280,7 @@ public void testAttemptedAndCommittedAccumulatedMetricResults() { true); assertGauge(GAUGE_NAME, step2res, STEP2, GaugeResult.create(VALUE, Instant.now()), true); - MetricQueryResults allres = metricResults.queryMetrics(MetricsFilter.builder().build()); + MetricQueryResults allres = metricResults.allMetrics(); assertIterableSize(allres.getCounters(), 2); assertIterableSize(allres.getDistributions(), 2); 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 deleted file mode 100644 index fdb817f8e7b6..000000000000 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -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; - -/** Tests for {@link MonitoringInfoMetricName}. */ -public class MonitoringInfoMetricNameTest implements Serializable { - - @Rule public final transient ExpectedException thrown = ExpectedException.none(); - - @Test - public void testElementCountConstruction() { - Map labels = new HashMap<>(); - String urn = ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = - (MonitoringInfoMetricName) MonitoringInfoMetricName.named(urn, labels); - assertEquals(labels, name.getLabels()); - assertEquals(urn, name.getUrn()); - - assertEquals(name, name); // test self equals; - - // Reconstruct and test equality and hash code equivalence - urn = ELEMENT_COUNT_URN; - labels = new HashMap<>(); - MetricName name2 = MonitoringInfoMetricName.named(urn, labels); - - assertEquals(name, name2); - assertEquals(name.hashCode(), name2.hashCode()); - } - - @Test - public void testUserCounterUrnConstruction() { - String urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); - HashMap labels = new HashMap(); - MetricName name = MonitoringInfoMetricName.named(urn, labels); - assertEquals("name", name.getName()); - assertEquals("namespace", name.getNamespace()); - - assertEquals(name, name); // test self equals; - - // Reconstruct and test equality and hash code equivalence - urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); - labels = new HashMap(); - MetricName name2 = MonitoringInfoMetricName.named(urn, labels); - - assertEquals(name, name2); - assertEquals(name.hashCode(), name2.hashCode()); - } - - @Test - public void testNotEqualsDiffLabels() { - Map labels = new HashMap<>(); - String urn = ELEMENT_COUNT_URN; - MetricName name = MonitoringInfoMetricName.named(urn, labels); - - // Reconstruct and test equality and hash code equivalence - urn = ELEMENT_COUNT_URN; - labels = new HashMap(); - labels.put("label", "value1"); - MetricName name2 = MonitoringInfoMetricName.named(urn, labels); - - assertNotEquals(name, name2); - assertNotEquals(name.hashCode(), name2.hashCode()); - } - - @Test - public void testNotEqualsDiffUrn() { - Map labels = new HashMap<>(); - String urn = ELEMENT_COUNT_URN; - MetricName name = MonitoringInfoMetricName.named(urn, labels); - - // Reconstruct and test equality and hash code equivalence - urn = "differentUrn"; - labels = new HashMap(); - MetricName name2 = MonitoringInfoMetricName.named(urn, labels); - - assertNotEquals(name, name2); - assertNotEquals(name.hashCode(), name2.hashCode()); - } - - @Test - public void testNullLabelsThrows() { - thrown.expect(IllegalArgumentException.class); - Map labels = null; - MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); - } - - @Test - public void testNullUrnThrows() { - HashMap labels = new HashMap(); - thrown.expect(IllegalArgumentException.class); - MonitoringInfoMetricName.named(null, labels); - } - - @Test - public void testEmptyUrnThrows() { - HashMap 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 1ffe908cf9b1..1767cafed44e 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 @@ -18,24 +18,13 @@ package org.apache.beam.runners.core.metrics; import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; -import java.util.HashMap; -import java.util.Map; import org.apache.beam.model.pipeline.v1.MetricsApi.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 MetricName testElementCountName() { - Map labels = new HashMap<>(); - labels.put(PCOLLECTION_LABEL, "testPCollection"); - return MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); - } - /** @return A basic MonitoringInfo which matches the testElementCountName. */ public static MonitoringInfo testElementCountMonitoringInfo(long value) { SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java index e4e496911050..6868ec509be5 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals; import java.util.HashMap; +import java.util.Map; import org.joda.time.Duration; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,14 +38,13 @@ public class SimpleExecutionStateTest { public void testLabelsAndNameAreExtracted() { String stateName = "myState"; HashMap labelsMetadata = new HashMap(); - labelsMetadata.put("k1", "v1"); - labelsMetadata.put("k2", "v2"); + labelsMetadata.put(PTRANSFORM_LABEL, "step"); SimpleExecutionState testObject = new SimpleExecutionState(stateName, null, labelsMetadata); assertEquals(testObject.getStateName(), stateName); - assertEquals(2, testObject.getLabels().size()); - assertThat(testObject.getLabels(), hasEntry("k1", "v1")); - assertThat(testObject.getLabels(), hasEntry("k2", "v2")); + Map extracted = testObject.getLabels(); + assertEquals(1, extracted.size()); + assertThat(extracted, hasEntry("PTRANSFORM", "step")); } @Test 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 b1beb5bfdc63..d983e49aeb54 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 @@ -20,8 +20,10 @@ import static junit.framework.TestCase.assertEquals; import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; import static org.apache.beam.sdk.metrics.MetricUrns.SUM_INT64_TYPE_URN; import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -55,30 +57,33 @@ public void testReturnsNullIfSpecRequirementsNotMet() { @Test public void testUserCounter() { - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric("myNamespace", "myName"); + SimpleMonitoringInfoBuilder builder = + new SimpleMonitoringInfoBuilder().userMetric("step", "myNamespace", "myName"); assertNull(builder.build()); builder.setInt64Value(1); // Pass now that the spec is fully met. MonitoringInfo monitoringInfo = builder.build(); - assertTrue(monitoringInfo != null); + assertNotNull(monitoringInfo); assertEquals(USER_COUNTER_URN_PREFIX + "myNamespace:myName", monitoringInfo.getUrn()); assertEquals(SUM_INT64_TYPE_URN, monitoringInfo.getType()); + assertEquals("step", monitoringInfo.getLabelsOrThrow(PTRANSFORM_LABEL)); assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); } @Test public void testUserMetricWithInvalidDelimiterCharacterIsReplaced() { - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric("myNamespace:withInvalidChar", "myName"); - builder.setInt64Value(1); + MonitoringInfo monitoringInfo = + new SimpleMonitoringInfoBuilder() + .userMetric("step", "myNamespace:withInvalidChar", "myName") + .setInt64Value(1) + .build(); // Pass now that the spec is fully met. - MonitoringInfo monitoringInfo = builder.build(); - assertTrue(monitoringInfo != null); + assertNotNull(monitoringInfo); assertEquals( USER_COUNTER_URN_PREFIX + "myNamespace_withInvalidChar:myName", monitoringInfo.getUrn()); assertEquals(SUM_INT64_TYPE_URN, monitoringInfo.getType()); + assertEquals("step", monitoringInfo.getLabelsOrThrow(PTRANSFORM_LABEL)); assertEquals(1, monitoringInfo.getMetric().getCounterData().getInt64Value()); } } diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java index eaf6719c8481..3ce117fb38eb 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleStateRegistryTest.java @@ -19,14 +19,13 @@ import static org.apache.beam.sdk.metrics.MetricUrns.FINISH_BUNDLE_MSECS_URN; import static org.apache.beam.sdk.metrics.MetricUrns.PROCESS_BUNDLE_MSECS_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; import static org.apache.beam.sdk.metrics.MetricUrns.START_BUNDLE_MSECS_URN; import static org.junit.Assert.assertThat; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +import org.apache.beam.sdk.metrics.labels.MetricLabels; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; @@ -35,19 +34,19 @@ public class SimpleStateRegistryTest { @Test - public void testExecutionTimeUrnsBuildMonitoringInfos() throws Exception { + public void testExecutionTimeUrnsBuildMonitoringInfos() { String testPTransformId = "pTransformId"; - HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(PTRANSFORM_LABEL, testPTransformId); + + MetricLabels labels = MetricLabels.ptransform(testPTransformId); SimpleExecutionState startState = new SimpleExecutionState( - ExecutionStateTracker.START_STATE_NAME, START_BUNDLE_MSECS_URN, labelsMetadata); + ExecutionStateTracker.START_STATE_NAME, START_BUNDLE_MSECS_URN, labels.map()); SimpleExecutionState processState = new SimpleExecutionState( - ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labelsMetadata); + ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labels.map()); SimpleExecutionState finishState = new SimpleExecutionState( - ExecutionStateTracker.FINISH_STATE_NAME, FINISH_BUNDLE_MSECS_URN, labelsMetadata); + ExecutionStateTracker.FINISH_STATE_NAME, FINISH_BUNDLE_MSECS_URN, labels.map()); SimpleStateRegistry testObject = new SimpleStateRegistry(); testObject.register(startState); diff --git a/runners/direct-java/src/main/java/org/apache/beam/runners/direct/DirectTransformExecutor.java b/runners/direct-java/src/main/java/org/apache/beam/runners/direct/DirectTransformExecutor.java index 5ac6cbad238d..8f95c3c0d1fc 100644 --- a/runners/direct-java/src/main/java/org/apache/beam/runners/direct/DirectTransformExecutor.java +++ b/runners/direct-java/src/main/java/org/apache/beam/runners/direct/DirectTransformExecutor.java @@ -107,7 +107,8 @@ public TransformExecutor create( @Override public void run() { - MetricsContainerImpl metricsContainer = new MetricsContainerImpl(transform.getFullName()); + MetricsContainerImpl metricsContainer = + MetricsContainerImpl.ptransform(transform.getFullName()); try (Closeable metricsScope = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { Collection> enforcements = new ArrayList<>(); for (ModelEnforcementFactory enforcementFactory : modelEnforcements) { diff --git a/runners/direct-java/src/main/java/org/apache/beam/runners/direct/portable/DirectTransformExecutor.java b/runners/direct-java/src/main/java/org/apache/beam/runners/direct/portable/DirectTransformExecutor.java index b4e742a39285..4a7833bc76b0 100644 --- a/runners/direct-java/src/main/java/org/apache/beam/runners/direct/portable/DirectTransformExecutor.java +++ b/runners/direct-java/src/main/java/org/apache/beam/runners/direct/portable/DirectTransformExecutor.java @@ -88,7 +88,7 @@ public TransformExecutor create( @Override public void run() { - MetricsContainerImpl metricsContainer = new MetricsContainerImpl(transform.getId()); + MetricsContainerImpl metricsContainer = MetricsContainerImpl.ptransform(transform.getId()); try (Closeable metricsScope = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) { TransformEvaluator evaluator = evaluatorRegistry.forApplication(transform, inputBundle); if (evaluator == null) { diff --git a/runners/direct-java/src/test/java/org/apache/beam/runners/direct/DirectMetricsTest.java b/runners/direct-java/src/test/java/org/apache/beam/runners/direct/DirectMetricsTest.java index a7c8c3ac41de..ac976fb07029 100644 --- a/runners/direct-java/src/test/java/org/apache/beam/runners/direct/DirectMetricsTest.java +++ b/runners/direct-java/src/test/java/org/apache/beam/runners/direct/DirectMetricsTest.java @@ -80,24 +80,24 @@ public void testApplyCommittedNoFilter() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("step1", NAME2), 8L)), + MetricUpdate.create(MetricKey.ptransform("step1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME2), 8L)), ImmutableList.of( MetricUpdate.create( - MetricKey.create("step1", NAME1), DistributionData.create(8, 2, 3, 5))), + MetricKey.ptransform("step1", NAME1), DistributionData.create(8, 2, 3, 5))), ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME4), GaugeData.create(15L))))); + MetricUpdate.create(MetricKey.ptransform("step1", NAME4), GaugeData.create(15L))))); metrics.commitLogical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step2", NAME1), 7L), - MetricUpdate.create(MetricKey.create("step1", NAME2), 4L)), + MetricUpdate.create(MetricKey.ptransform("step2", NAME1), 7L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME2), 4L)), ImmutableList.of( MetricUpdate.create( - MetricKey.create("step1", NAME1), DistributionData.create(4, 1, 4, 4))), + MetricKey.ptransform("step1", NAME1), DistributionData.create(4, 1, 4, 4))), ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME4), GaugeData.create(27L))))); + MetricUpdate.create(MetricKey.ptransform("step1", NAME4), GaugeData.create(27L))))); MetricQueryResults results = metrics.allMetrics(); assertThat( @@ -138,16 +138,16 @@ public void testApplyAttemptedCountersQueryOneNamespace() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("step1", NAME3), 8L)), + MetricUpdate.create(MetricKey.ptransform("step1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME3), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step2", NAME1), 7L), - MetricUpdate.create(MetricKey.create("step1", NAME3), 4L)), + MetricUpdate.create(MetricKey.ptransform("step2", NAME1), 7L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME3), 4L)), ImmutableList.of(), ImmutableList.of())); @@ -174,21 +174,20 @@ public void testApplyAttemptedQueryCompositeScope() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Outer1/Inner1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("Outer1/Inner2", NAME1), 8L)), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner2", NAME1), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Outer1/Inner1", NAME1), 12L), - MetricUpdate.create(MetricKey.create("Outer2/Inner2", NAME1), 18L)), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner1", NAME1), 12L), + MetricUpdate.create(MetricKey.ptransform("Outer2/Inner2", NAME1), 18L)), ImmutableList.of(), ImmutableList.of())); - MetricQueryResults results = - metrics.queryMetrics(MetricsFilter.builder().addStep("Outer1").build()); + MetricQueryResults results = metrics.queryMetrics(MetricsFilter.ptransform("Outer1")); assertThat( results.getCounters(), @@ -210,21 +209,20 @@ public void testPartialScopeMatchingInMetricsQuery() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Top1/Outer1/Inner1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("Top1/Outer1/Inner2", NAME1), 8L)), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer1/Inner1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer1/Inner2", NAME1), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Top2/Outer1/Inner1", NAME1), 12L), - MetricUpdate.create(MetricKey.create("Top1/Outer2/Inner2", NAME1), 18L)), + MetricUpdate.create(MetricKey.ptransform("Top2/Outer1/Inner1", NAME1), 12L), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer2/Inner2", NAME1), 18L)), ImmutableList.of(), ImmutableList.of())); - MetricQueryResults results = - metrics.queryMetrics(MetricsFilter.builder().addStep("Top1/Outer1").build()); + MetricQueryResults results = metrics.queryMetrics(MetricsFilter.ptransform("Top1/Outer1")); assertThat( results.getCounters(), @@ -232,7 +230,7 @@ public void testPartialScopeMatchingInMetricsQuery() { attemptedMetricsResult("ns1", "name1", "Top1/Outer1/Inner1", 5L), attemptedMetricsResult("ns1", "name1", "Top1/Outer1/Inner2", 8L))); - results = metrics.queryMetrics(MetricsFilter.builder().addStep("Inner2").build()); + results = metrics.queryMetrics(MetricsFilter.ptransform("Inner2")); assertThat( results.getCounters(), diff --git a/runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/DirectMetricsTest.java b/runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/DirectMetricsTest.java index 59faca362bb8..653759c5bbd2 100644 --- a/runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/DirectMetricsTest.java +++ b/runners/direct-java/src/test/java/org/apache/beam/runners/direct/portable/DirectMetricsTest.java @@ -69,24 +69,24 @@ public void testApplyCommittedNoFilter() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("step1", NAME2), 8L)), + MetricUpdate.create(MetricKey.ptransform("step1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME2), 8L)), ImmutableList.of( MetricUpdate.create( - MetricKey.create("step1", NAME1), DistributionData.create(8, 2, 3, 5))), + MetricKey.ptransform("step1", NAME1), DistributionData.create(8, 2, 3, 5))), ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME4), GaugeData.create(15L))))); + MetricUpdate.create(MetricKey.ptransform("step1", NAME4), GaugeData.create(15L))))); metrics.commitLogical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step2", NAME1), 7L), - MetricUpdate.create(MetricKey.create("step1", NAME2), 4L)), + MetricUpdate.create(MetricKey.ptransform("step2", NAME1), 7L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME2), 4L)), ImmutableList.of( MetricUpdate.create( - MetricKey.create("step1", NAME1), DistributionData.create(4, 1, 4, 4))), + MetricKey.ptransform("step1", NAME1), DistributionData.create(4, 1, 4, 4))), ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME4), GaugeData.create(27L))))); + MetricUpdate.create(MetricKey.ptransform("step1", NAME4), GaugeData.create(27L))))); MetricQueryResults results = metrics.allMetrics(); assertThat( @@ -127,16 +127,16 @@ public void testApplyAttemptedCountersQueryOneNamespace() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("step1", NAME3), 8L)), + MetricUpdate.create(MetricKey.ptransform("step1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME3), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("step2", NAME1), 7L), - MetricUpdate.create(MetricKey.create("step1", NAME3), 4L)), + MetricUpdate.create(MetricKey.ptransform("step2", NAME1), 7L), + MetricUpdate.create(MetricKey.ptransform("step1", NAME3), 4L)), ImmutableList.of(), ImmutableList.of())); @@ -163,21 +163,20 @@ public void testApplyAttemptedQueryCompositeScope() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Outer1/Inner1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("Outer1/Inner2", NAME1), 8L)), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner2", NAME1), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Outer1/Inner1", NAME1), 12L), - MetricUpdate.create(MetricKey.create("Outer2/Inner2", NAME1), 18L)), + MetricUpdate.create(MetricKey.ptransform("Outer1/Inner1", NAME1), 12L), + MetricUpdate.create(MetricKey.ptransform("Outer2/Inner2", NAME1), 18L)), ImmutableList.of(), ImmutableList.of())); - MetricQueryResults results = - metrics.queryMetrics(MetricsFilter.builder().addStep("Outer1").build()); + MetricQueryResults results = metrics.queryMetrics(MetricsFilter.ptransform("Outer1")); assertThat( results.getCounters(), @@ -199,21 +198,20 @@ public void testPartialScopeMatchingInMetricsQuery() { bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Top1/Outer1/Inner1", NAME1), 5L), - MetricUpdate.create(MetricKey.create("Top1/Outer1/Inner2", NAME1), 8L)), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer1/Inner1", NAME1), 5L), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer1/Inner2", NAME1), 8L)), ImmutableList.of(), ImmutableList.of())); metrics.updatePhysical( bundle1, MetricUpdates.create( ImmutableList.of( - MetricUpdate.create(MetricKey.create("Top2/Outer1/Inner1", NAME1), 12L), - MetricUpdate.create(MetricKey.create("Top1/Outer2/Inner2", NAME1), 18L)), + MetricUpdate.create(MetricKey.ptransform("Top2/Outer1/Inner1", NAME1), 12L), + MetricUpdate.create(MetricKey.ptransform("Top1/Outer2/Inner2", NAME1), 18L)), ImmutableList.of(), ImmutableList.of())); - MetricQueryResults results = - metrics.queryMetrics(MetricsFilter.builder().addStep("Top1/Outer1").build()); + MetricQueryResults results = metrics.queryMetrics(MetricsFilter.ptransform("Top1/Outer1")); assertThat( results.getCounters(), @@ -221,7 +219,7 @@ public void testPartialScopeMatchingInMetricsQuery() { attemptedMetricsResult("ns1", "name1", "Top1/Outer1/Inner1", 5L), attemptedMetricsResult("ns1", "name1", "Top1/Outer1/Inner2", 8L))); - results = metrics.queryMetrics(MetricsFilter.builder().addStep("Inner2").build()); + results = metrics.queryMetrics(MetricsFilter.ptransform("Inner2")); assertThat( results.getCounters(), diff --git a/runners/extensions-java/metrics/src/main/java/org/apache/beam/runners/extensions/metrics/MetricsHttpSink.java b/runners/extensions-java/metrics/src/main/java/org/apache/beam/runners/extensions/metrics/MetricsHttpSink.java index 649cef909ca0..2d589113dffe 100644 --- a/runners/extensions-java/metrics/src/main/java/org/apache/beam/runners/extensions/metrics/MetricsHttpSink.java +++ b/runners/extensions-java/metrics/src/main/java/org/apache/beam/runners/extensions/metrics/MetricsHttpSink.java @@ -88,8 +88,8 @@ public MetricNameSerializer(Class t) { public void serialize(MetricName value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); - gen.writeObjectField("name", value.name()); - gen.writeObjectField("namespace", value.namespace()); + gen.writeObjectField("name", value.getName()); + gen.writeObjectField("namespace", value.getNamespace()); gen.writeEndObject(); } } diff --git a/runners/extensions-java/metrics/src/test/java/org/apache/beam/runners/extensions/metrics/CustomMetricQueryResults.java b/runners/extensions-java/metrics/src/test/java/org/apache/beam/runners/extensions/metrics/CustomMetricQueryResults.java index a9cea996680b..d2b9a75ca7fa 100644 --- a/runners/extensions-java/metrics/src/test/java/org/apache/beam/runners/extensions/metrics/CustomMetricQueryResults.java +++ b/runners/extensions-java/metrics/src/test/java/org/apache/beam/runners/extensions/metrics/CustomMetricQueryResults.java @@ -22,7 +22,6 @@ import org.apache.beam.sdk.metrics.DistributionResult; import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.sdk.metrics.MetricKey; -import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricsSink; @@ -41,8 +40,7 @@ class CustomMetricQueryResults extends MetricQueryResults { private List> makeResults( String step, String name, T committed, T attempted) { - MetricName metricName = MetricName.named(NAMESPACE, name); - MetricKey key = MetricKey.create(step, metricName); + MetricKey key = MetricKey.ptransform(step, NAMESPACE, name); return Collections.singletonList( isCommittedSupported ? MetricResult.create(key, committed, attempted) 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..dc760826a687 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 @@ -49,7 +49,7 @@ public DoFnRunnerWithMetricsUpdate( @Override public void startBundle() { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { delegate.startBundle(); } catch (IOException e) { throw new RuntimeException(e); @@ -59,7 +59,7 @@ public void startBundle() { @Override public void processElement(final WindowedValue elem) { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { delegate.processElement(elem); } catch (IOException e) { throw new RuntimeException(e); @@ -73,7 +73,7 @@ public void onTimer( final Instant timestamp, final TimeDomain timeDomain) { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { delegate.onTimer(timerId, window, timestamp, timeDomain); } catch (IOException e) { throw new RuntimeException(e); @@ -83,14 +83,14 @@ public void onTimer( @Override public void finishBundle() { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { delegate.finishBundle(); } catch (IOException e) { throw new RuntimeException(e); } // update metrics - container.updateMetrics(stepName); + container.updateFlinkMetrics(stepName); } @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 bb4f5ad0ef09..5300d1b67817 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 @@ -18,11 +18,13 @@ package org.apache.beam.runners.flink.metrics; import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults; -import static org.apache.beam.sdk.metrics.MetricUrns.parseUrn; +import static org.apache.beam.sdk.metrics.DistributionProtos.fromProto; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.CounterData; import org.apache.beam.model.pipeline.v1.MetricsApi.DistributionData; import org.apache.beam.model.pipeline.v1.MetricsApi.ExtremaData; @@ -41,13 +43,15 @@ 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.beam.sdk.metrics.labels.MetricLabels; 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; @@ -89,127 +93,138 @@ public FlinkMetricContainer(RuntimeContext runtimeContext) { this.metricsAccumulator = (MetricsAccumulator) metricsAccumulator; } - public MetricsContainer getMetricsContainer(String stepName) { + @Nullable + public MetricsContainer getMetricsContainer(MetricLabels labels) { return metricsAccumulator != null - ? metricsAccumulator.getLocalValue().getContainer(stepName) + ? metricsAccumulator.getLocalValue().getContainer(labels) : null; } + @Nullable + public MetricsContainer ptransformContainer(String ptransform) { + return getMetricsContainer(MetricLabels.ptransform(ptransform)); + } + /** * 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); 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 key = MetricKey.create(monitoringInfo.getUrn(), monitoringInfo.getLabelsMap()); + MetricName metricName = key.metricName(); + + MetricsContainer container = getMetricsContainer(key.labels()); + + if (metric.hasCounterData()) { + CounterData counterData = metric.getCounterData(); + if (counterData.getValueCase() == CounterData.ValueCase.INT64_VALUE) { + org.apache.beam.sdk.metrics.Counter counter = container.getCounter(metricName); + counter.inc(counterData.getInt64Value()); + updateCounter(key, counterData.getInt64Value()); + } else { + LOG.warn("Unsupported CounterData type: {}", counterData); } + } else if (metric.hasDistributionData()) { + DistributionData distributionData = metric.getDistributionData(); + if (distributionData.hasIntDistributionData()) { + Distribution distribution = container.getDistribution(metricName); + IntDistributionData intDistributionData = distributionData.getIntDistributionData(); + DistributionResult distributionResult = fromProto(intDistributionData); + distribution.update( + distributionResult.getSum(), + distributionResult.getCount(), + distributionResult.getMin(), + distributionResult.getMax()); + updateDistribution(key, distributionResult); + } else { + LOG.warn("Unsupported DistributionData type: {}", distributionData); + } + } else if (metric.hasExtremaData()) { + ExtremaData extremaData = metric.getExtremaData(); + LOG.warn("Extrema metric unsupported: {}", extremaData); } }); - updateMetrics(stepName); } /** * Update Flink's internal metrics ({@link this#flinkCounterCache}) with the latest metrics for a * given step. */ - void updateMetrics(String stepName) { + void updateFlinkMetrics(String stepName) { 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.getKey()); - - 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 = metricResult.getKey(); + fn.accept(key, metricResult.getAttempted()); } } - private void updateDistributions(Iterable> distributions) { - for (MetricResult metricResult : distributions) { - String flinkMetricName = getFlinkMetricNameString(metricResult.getKey()); - - 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.getKey()); + 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(MetricKey metricKey) { - MetricName metricName = metricKey.metricName(); - // 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(); + 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..780fe033a730 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 @@ -47,9 +47,9 @@ public ReaderInvocationUtil( public boolean invokeStart(ReaderT reader) throws IOException { if (enableMetrics) { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { boolean result = reader.start(); - container.updateMetrics(stepName); + container.updateFlinkMetrics(stepName); return result; } } else { @@ -60,9 +60,9 @@ public boolean invokeStart(ReaderT reader) throws IOException { public boolean invokeAdvance(ReaderT reader) throws IOException { if (enableMetrics) { try (Closeable ignored = - MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) { + MetricsEnvironment.scopedMetricsContainer(container.ptransformContainer(stepName))) { boolean result = reader.advance(); - container.updateMetrics(stepName); + container.updateFlinkMetrics(stepName); return result; } } else { 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 bf6a6ae98d6f..f6a7892b94fd 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 @@ -78,25 +78,25 @@ public void beforeTest() { @Test public void testMetricNameGeneration() { - MetricKey key = MetricKey.create("step", MetricName.named("namespace", "name")); + MetricKey key = MetricKey.ptransform("step", "namespace", "name"); String name = getFlinkMetricNameString(key); - assertThat(name, is("namespace.name")); + 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"); + MetricsContainer step = container.ptransformContainer("step"); MetricName metricName = MetricName.named("namespace", "name"); Counter counter = step.getCounter(metricName); counter.inc(); counter.inc(); assertThat(flinkCounter.getCount(), is(0L)); - container.updateMetrics("step"); + container.updateFlinkMetrics("step"); assertThat(flinkCounter.getCount(), is(2L)); } @@ -104,45 +104,46 @@ 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"); + MetricsContainer step = container.ptransformContainer("step"); MetricName metricName = MetricName.named("namespace", "name"); Gauge gauge = step.getGauge(metricName); assertThat(flinkGauge.getValue(), is(GaugeResult.empty())); // first set will install the mocked gauge - container.updateMetrics("step"); + container.updateFlinkMetrics("step"); gauge.set(1); gauge.set(42); - container.updateMetrics("step"); + container.updateFlinkMetrics("step"); assertThat(flinkGauge.getValue().getValue(), is(42L)); } @Test public void testMonitoringInfoUpdate() { FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); - MetricsContainer step = container.getMetricsContainer("step"); + MetricsContainer step = container.ptransformContainer("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("pcoll.beam.metric.element_count.v1")).thenReturn(elemCounter); - SimpleMonitoringInfoBuilder userCountBuilder = new SimpleMonitoringInfoBuilder(); - userCountBuilder.setUrnForUserMetric("ns1", "metric1"); - userCountBuilder.setInt64Value(111); - MonitoringInfo userCountMonitoringInfo = userCountBuilder.build(); + MonitoringInfo userCountMonitoringInfo = + new SimpleMonitoringInfoBuilder() + .userMetric("step", "ns1", "metric1") + .setInt64Value(111) + .build(); assertNotNull(userCountMonitoringInfo); - SimpleMonitoringInfoBuilder elemCountBuilder = new SimpleMonitoringInfoBuilder(); - elemCountBuilder.setUrn(ELEMENT_COUNT_URN); - elemCountBuilder.setInt64Value(222); - elemCountBuilder.setPTransformLabel("step"); - elemCountBuilder.setPCollectionLabel("pcoll"); - MonitoringInfo elemCountMonitoringInfo = elemCountBuilder.build(); + MonitoringInfo elemCountMonitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setInt64Value(222) + .setPCollectionLabel("pcoll") + .build(); assertNotNull(elemCountMonitoringInfo); assertThat(userCounter.getCount(), is(0L)); @@ -156,7 +157,7 @@ public void testMonitoringInfoUpdate() { @Test public void testDropUnexpectedMonitoringInfoTypes() { FlinkMetricContainer flinkContainer = new FlinkMetricContainer(runtimeContext); - MetricsContainer step = flinkContainer.getMetricsContainer("step"); + MetricsContainer container = flinkContainer.ptransformContainer("step"); MonitoringInfo intCounter = MonitoringInfo.newBuilder() @@ -206,31 +207,49 @@ public void testDropUnexpectedMonitoringInfoTypes() { .setMax(5)))) .build(); - // Mock out the counter 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); + // Mock out the counter and distribution that Flink returns + SimpleCounter flinkCounter = new SimpleCounter(); + + DistributionData distributionData = DistributionData.create(30, 10, 1, 5); + DistributionResult distributionResult = distributionData.extractResult(); + FlinkDistributionGauge distributionGauge = new FlinkDistributionGauge(distributionResult); + + // Simulate Flink's metric system returning the counter and distribution above in response to + // queries for corresponding metric names + when(metricGroup.counter("step.ns1.int_counter")).thenReturn(flinkCounter); + when(metricGroup.gauge( + eq("step.ns3.int_distribution"), + argThat( + new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + DistributionResult actual = ((FlinkDistributionGauge) argument).getValue(); + return actual.equals(distributionResult); + } + }))) + .thenReturn(distributionGauge); 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")); + verify(metricGroup).counter(eq("step.ns1.int_counter")); // Verify that the counter injected into flink has the right value - assertThat(counter.getCount(), is(111L)); + assertThat(flinkCounter.getCount(), is(111L)); // Verify the counter in the java SDK MetricsContainer long count = - ((CounterCell) step.getCounter(MetricName.named("ns1", "int_counter"))).getCumulative(); + ((CounterCell) container.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"), + eq("step.ns3.int_distribution"), argThat( new ArgumentMatcher() { @Override @@ -242,31 +261,31 @@ public boolean matches(Object argument) { })); // 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", "int_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"); + MetricsContainer step = container.ptransformContainer("step"); MetricName metricName = MetricName.named("namespace", "name"); Distribution distribution = step.getDistribution(metricName); assertThat(flinkGauge.getValue(), is(DistributionResult.IDENTITY_ELEMENT)); // first set will install the mocked distribution - container.updateMetrics("step"); + container.updateFlinkMetrics("step"); distribution.update(42); distribution.update(-23); distribution.update(0); distribution.update(1); - container.updateMetrics("step"); + container.updateFlinkMetrics("step"); 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/src/main/java/org/apache/beam/runners/dataflow/DataflowMetrics.java b/runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/DataflowMetrics.java index 57b92cb065fb..fbc490541698 100644 --- a/runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/DataflowMetrics.java +++ b/runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/DataflowMetrics.java @@ -32,7 +32,6 @@ import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.sdk.metrics.MetricFiltering; import org.apache.beam.sdk.metrics.MetricKey; -import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricResults; @@ -253,11 +252,10 @@ private MetricKey getMetricHashKey(MetricUpdate metricUpdate) { } fullStepName = dataflowPipelineJob.transformStepNames.inverse().get(fullStepName).getFullName(); - return MetricKey.create( + return MetricKey.ptransform( fullStepName, - MetricName.named( - metricUpdate.getName().getContext().get("namespace"), - metricUpdate.getName().getName())); + metricUpdate.getName().getContext().get("namespace"), + metricUpdate.getName().getName()); } private void buildMetricsIndex() { diff --git a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/BatchModeExecutionContext.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/BatchModeExecutionContext.java index 79330028ea69..56b3073395de 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/BatchModeExecutionContext.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/BatchModeExecutionContext.java @@ -93,7 +93,7 @@ private static MetricsContainerRegistry createMetricsConta return new MetricsContainerRegistry() { @Override protected MetricsContainerImpl createContainer(String stepName) { - return new MetricsContainerImpl(stepName); + return MetricsContainerImpl.ptransform(stepName); } }; } diff --git a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingStepMetricsContainer.java b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingStepMetricsContainer.java index fbf635da6c2a..ec0abb1ca080 100644 --- a/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingStepMetricsContainer.java +++ b/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingStepMetricsContainer.java @@ -95,7 +95,7 @@ public CounterUpdate apply(Map.Entry entry) { } return MetricsToCounterUpdateConverter.fromCounter( - MetricKey.create(stepName, entry.getKey()), false, value); + MetricKey.ptransform(stepName, entry.getKey()), false, value); } }) .filter(Predicates.notNull()); @@ -114,7 +114,7 @@ public CounterUpdate apply(Map.Entry entry) { } return MetricsToCounterUpdateConverter.fromDistribution( - MetricKey.create(stepName, entry.getKey()), false, value); + MetricKey.ptransform(stepName, entry.getKey()), false, value); } }) .filter(Predicates.notNull()); diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorTest.java index 67d3670c827f..28325a1cbe19 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorTest.java @@ -176,7 +176,7 @@ private TestOperationContext createContext(String stepName, ExecutionStateTracke return TestOperationContext.create( counterSet, NameContext.create("test", stepName, stepName, stepName), - new MetricsContainerImpl(stepName), + MetricsContainerImpl.ptransform(stepName), tracker); } diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/SimpleParDoFnTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/SimpleParDoFnTest.java index c07982479ab2..b05f636e0330 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/SimpleParDoFnTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/SimpleParDoFnTest.java @@ -456,7 +456,7 @@ public void testStateTracking() throws Exception { TestOperationContext.create( new CounterSet(), NameContextsForTests.nameContextForTest(), - new MetricsContainerImpl(NameContextsForTests.ORIGINAL_NAME), + MetricsContainerImpl.ptransform(NameContextsForTests.ORIGINAL_NAME), tracker); class StateTestingDoFn extends DoFn { diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingGroupAlsoByWindowFnsTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingGroupAlsoByWindowFnsTest.java index f6a63f2a0500..e4f62554b58e 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingGroupAlsoByWindowFnsTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingGroupAlsoByWindowFnsTest.java @@ -328,7 +328,7 @@ public void testSlidingWindows() throws Exception { @Test public void testSlidingWindowsAndLateData() throws Exception { - MetricsContainerImpl container = new MetricsContainerImpl("step"); + MetricsContainerImpl container = MetricsContainerImpl.ptransform("step"); MetricsEnvironment.setCurrentContainer(container); TupleTag>> outputTag = new TupleTag<>(); ListOutputManager outputManager = new ListOutputManager(); diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/TestOperationContext.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/TestOperationContext.java index a58f234dd12f..cc83940c47d2 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/TestOperationContext.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/TestOperationContext.java @@ -129,7 +129,7 @@ public static TestOperationContext create(CounterSet counterSet) { return new TestOperationContext( counterSet, NameContextsForTests.nameContextForTest(), - new MetricsContainerImpl(NameContextsForTests.SYSTEM_NAME), + MetricsContainerImpl.ptransform(NameContextsForTests.SYSTEM_NAME), ExecutionStateTracker.newForTest()); } @@ -137,7 +137,7 @@ public static TestOperationContext create(CounterSet counterSet, NameContext nam return new TestOperationContext( counterSet, nameContext, - new MetricsContainerImpl(nameContext.systemName()), + MetricsContainerImpl.ptransform(nameContext.systemName()), ExecutionStateTracker.newForTest()); } diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/WorkItemStatusClientTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/WorkItemStatusClientTest.java index 9fcdb147ffed..9842855856e3 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/WorkItemStatusClientTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/WorkItemStatusClientTest.java @@ -389,7 +389,7 @@ public void populateCounterUpdatesWithMetricsAndCounters() throws Exception { .setCumulative(true) .setInteger(DataflowCounterUpdateExtractor.longToSplitInt(42)); - MetricsContainerImpl metricsContainer = new MetricsContainerImpl("step"); + MetricsContainerImpl metricsContainer = MetricsContainerImpl.ptransform("step"); BatchModeExecutionContext context = mock(BatchModeExecutionContext.class); when(context.extractMetricUpdates(anyBoolean())).thenReturn(ImmutableList.of(expectedMetric)); when(context.extractMsecCounters(anyBoolean())).thenReturn(Collections.emptyList()); diff --git a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/util/common/worker/MapTaskExecutorTest.java b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/util/common/worker/MapTaskExecutorTest.java index ad0b862e2281..821d79148ae2 100644 --- a/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/util/common/worker/MapTaskExecutorTest.java +++ b/runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/util/common/worker/MapTaskExecutorTest.java @@ -168,7 +168,7 @@ private TestOperationContext createContext(String stepName, ExecutionStateTracke return TestOperationContext.create( counterSet, NameContext.create("test", stepName, stepName, stepName), - new MetricsContainerImpl(stepName), + MetricsContainerImpl.ptransform(stepName), tracker); } 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 b0a8a6d3b365..8a1a6938d276 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 @@ -638,79 +638,104 @@ public void onProgress(ProcessBundleProgressResponse progress) {} public void onCompleted(ProcessBundleResponse response) { List> matchers = new ArrayList>(); - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric( - RemoteExecutionTest.class.getName(), processUserCounterName); - builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); - builder.setInt64Value(1); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); - - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), startUserCounterName); - builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); - builder.setInt64Value(10); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); - - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), finishUserCounterName); - builder.setPTransformLabel("create/ParMultiDo(Anonymous)"); - builder.setInt64Value(100); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); + MonitoringInfo monitoringInfo = + new SimpleMonitoringInfoBuilder() + .userMetric( + "create/ParMultiDo(Anonymous)", + RemoteExecutionTest.class.getName(), + processUserCounterName) + .setInt64Value(1) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); + + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .userMetric( + "create/ParMultiDo(Anonymous)", + RemoteExecutionTest.class.getName(), + startUserCounterName) + .setInt64Value(10) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); + + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .userMetric( + "create/ParMultiDo(Anonymous)", + RemoteExecutionTest.class.getName(), + finishUserCounterName) + .setInt64Value(100) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); // The element counter should be counted only once for the pcollection. // So there should be only two elements. - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel("impulse.out"); - builder.setInt64Value(2); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); - - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel("create/ParMultiDo(Anonymous).output"); - builder.setInt64Value(3); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("impulse.out") + .setInt64Value(2) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); + + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("create/ParMultiDo(Anonymous).output") + .setInt64Value(3) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); // Verify that the element count is not double counted if two PCollections consume it. - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel("processA/ParMultiDo(Anonymous).output"); - builder.setInt64Value(6); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); - - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel("processB/ParMultiDo(Anonymous).output"); - builder.setInt64Value(6); - matchers.add(MonitoringInfoMatchers.matchSetFields(builder.build())); + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("processA/ParMultiDo(Anonymous).output") + .setInt64Value(6) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); + + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("processB/ParMultiDo(Anonymous).output") + .setInt64Value(6) + .build(); + matchers.add(MonitoringInfoMatchers.matchSetFields(monitoringInfo)); // Check for execution time metrics for the testPTransformId - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(START_BUNDLE_MSECS_URN); - builder.setInt64TypeUrn(); - builder.setPTransformLabel(testPTransformId); + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(START_BUNDLE_MSECS_URN) + .setInt64TypeUrn() + .setPTransformLabel(testPTransformId) + .build(); matchers.add( allOf( - MonitoringInfoMatchers.matchSetFields(builder.build()), + MonitoringInfoMatchers.matchSetFields(monitoringInfo), MonitoringInfoMatchers.valueGreaterThan(0))); // Check for execution time metrics for the testPTransformId - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(PROCESS_BUNDLE_MSECS_URN); - builder.setInt64TypeUrn(); - builder.setPTransformLabel(testPTransformId); + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(PROCESS_BUNDLE_MSECS_URN) + .setInt64TypeUrn() + .setPTransformLabel(testPTransformId) + .build(); matchers.add( allOf( - MonitoringInfoMatchers.matchSetFields(builder.build()), + MonitoringInfoMatchers.matchSetFields(monitoringInfo), MonitoringInfoMatchers.valueGreaterThan(0))); - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(FINISH_BUNDLE_MSECS_URN); - builder.setInt64TypeUrn(); - builder.setPTransformLabel(testPTransformId); + monitoringInfo = + new SimpleMonitoringInfoBuilder() + .setUrn(FINISH_BUNDLE_MSECS_URN) + .setInt64TypeUrn() + .setPTransformLabel(testPTransformId) + .build(); matchers.add( allOf( - MonitoringInfoMatchers.matchSetFields(builder.build()), + MonitoringInfoMatchers.matchSetFields(monitoringInfo), MonitoringInfoMatchers.valueGreaterThan(0))); for (Matcher matcher : matchers) { diff --git a/runners/samza/src/main/java/org/apache/beam/runners/samza/metrics/SamzaMetricsContainer.java b/runners/samza/src/main/java/org/apache/beam/runners/samza/metrics/SamzaMetricsContainer.java index e7e7b3ae683e..7d8a9cb03301 100644 --- a/runners/samza/src/main/java/org/apache/beam/runners/samza/metrics/SamzaMetricsContainer.java +++ b/runners/samza/src/main/java/org/apache/beam/runners/samza/metrics/SamzaMetricsContainer.java @@ -49,7 +49,7 @@ public SamzaMetricsContainer(MetricsRegistryMap metricsRegistry) { } public MetricsContainer getContainer(String stepName) { - return this.metricsContainers.getContainer(stepName); + return this.metricsContainers.ptransformContainer(stepName); } public MetricsContainerStepMap getContainers() { diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SourceRDD.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SourceRDD.java index b6582dd6fa2a..6b30b2808b34 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SourceRDD.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SourceRDD.java @@ -136,7 +136,8 @@ private BoundedSource.BoundedReader createReader(SourcePartition partition @Override public scala.collection.Iterator> compute( final Partition split, final TaskContext context) { - final MetricsContainer metricsContainer = metricsAccum.localValue().getContainer(stepName); + final MetricsContainer metricsContainer = + metricsAccum.localValue().ptransformContainer(stepName); @SuppressWarnings("unchecked") final BoundedSource.BoundedReader reader = createReader((SourcePartition) split); diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SparkUnboundedSource.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SparkUnboundedSource.java index cd60db0e9461..4e1b4373f6d6 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SparkUnboundedSource.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/io/SparkUnboundedSource.java @@ -214,7 +214,8 @@ public scala.Option> compute(Time validTime) { : globalHighWatermarkForBatch; // Update metrics reported in the read final Gauge gauge = Metrics.gauge(NAMESPACE, READ_DURATION_MILLIS); - final MetricsContainer container = metadata.getMetricsContainers().getContainer(stepName); + final MetricsContainer container = + metadata.getMetricsContainers().ptransformContainer(stepName); try (Closeable ignored = MetricsEnvironment.scopedMetricsContainer(container)) { final long readDurationMillis = metadata.getReadDurationMillis(); if (readDurationMillis > maxReadDuration) { diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/metrics/SparkBeamMetric.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/metrics/SparkBeamMetric.java index 11b4e043e99d..aa023b3352e3 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/metrics/SparkBeamMetric.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/metrics/SparkBeamMetric.java @@ -21,8 +21,8 @@ import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults; import com.codahale.metrics.Metric; -import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.sdk.metrics.DistributionResult; @@ -67,23 +67,14 @@ class SparkBeamMetric implements Metric { String renderName(MetricResult metricResult) { MetricKey key = metricResult.getKey(); MetricName name = key.metricName(); - String step = key.stepName(); - - ArrayList pieces = new ArrayList<>(); - - if (step != null) { - step = step.replaceAll(ILLEGAL_CHARACTERS, "_"); - if (step.endsWith("_")) { - step = step.substring(0, step.length() - 1); - } - pieces.add(step); - } - - pieces.addAll( - ImmutableList.of(name.getNamespace(), name.getName()).stream() + List pieces = + ImmutableList.of(key.labels().value(), name.getNamespace(), name.getName()).stream() .map(str -> str.replaceAll(ILLEGAL_CHARACTERS, "_")) - .collect(toList())); - + .collect(toList()); + String label = pieces.get(0); + if (label.endsWith("_")) { + pieces.set(0, label.substring(0, label.length() - 1)); + } return String.join(".", pieces); } } diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/SparkGroupAlsoByWindowViaWindowSet.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/SparkGroupAlsoByWindowViaWindowSet.java index 6d67474fee3a..efa83adcc5c6 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/SparkGroupAlsoByWindowViaWindowSet.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/SparkGroupAlsoByWindowViaWindowSet.java @@ -431,7 +431,7 @@ private Collection filterTimersEligibleForProcessing( final SystemReduceFn, Iterable, W> reduceFn = SystemReduceFn.buffering(wvCoder.getValueCoder()); - final MetricsContainerImpl cellProvider = new MetricsContainerImpl("cellProvider"); + final MetricsContainerImpl cellProvider = MetricsContainerImpl.ptransform("cellProvider"); final CounterCell droppedDueToClosedWindow = cellProvider.getCounter( diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/StateSpecFunctions.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/StateSpecFunctions.java index 2b4e03de18ef..a773c93b9e96 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/StateSpecFunctions.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/stateful/StateSpecFunctions.java @@ -113,7 +113,7 @@ public Tuple2, Metadata> apply( State> state) { MetricsContainerStepMap metricsContainers = new MetricsContainerStepMap(); - MetricsContainer metricsContainer = metricsContainers.getContainer(stepName); + MetricsContainer metricsContainer = metricsContainers.ptransformContainer(stepName); // Add metrics container to the scope of org.apache.beam.sdk.io.Source.Reader methods // since they may report metrics. diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/DoFnRunnerWithMetrics.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/DoFnRunnerWithMetrics.java index 25f88aab6d64..2c63a6cc188c 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/DoFnRunnerWithMetrics.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/DoFnRunnerWithMetrics.java @@ -92,6 +92,6 @@ public void finishBundle() { } private MetricsContainer metricsContainer() { - return metricsAccum.localValue().getContainer(stepName); + return metricsAccum.localValue().ptransformContainer(stepName); } } diff --git a/runners/spark/src/test/java/org/apache/beam/runners/spark/io/ReaderToIteratorAdapterTest.java b/runners/spark/src/test/java/org/apache/beam/runners/spark/io/ReaderToIteratorAdapterTest.java index e0f5901a4010..8d45e9340154 100644 --- a/runners/spark/src/test/java/org/apache/beam/runners/spark/io/ReaderToIteratorAdapterTest.java +++ b/runners/spark/src/test/java/org/apache/beam/runners/spark/io/ReaderToIteratorAdapterTest.java @@ -87,7 +87,8 @@ public Source getCurrentSource() { private final TestReader testReader = new TestReader(); private final SourceRDD.Bounded.ReaderToIteratorAdapter readerIterator = - new SourceRDD.Bounded.ReaderToIteratorAdapter<>(new MetricsContainerImpl(""), testReader); + new SourceRDD.Bounded.ReaderToIteratorAdapter<>( + MetricsContainerImpl.ptransform(""), testReader); private void assertReaderRange(final int start, final int end) { for (int i = start; i < end; i++) { diff --git a/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkBeamMetricTest.java b/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkBeamMetricTest.java index a1d6fe83870f..02572bb2d150 100644 --- a/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkBeamMetricTest.java +++ b/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkBeamMetricTest.java @@ -21,7 +21,6 @@ import static org.junit.Assert.assertThat; import org.apache.beam.sdk.metrics.MetricKey; -import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricResult; import org.junit.Test; @@ -31,10 +30,7 @@ public class SparkBeamMetricTest { public void testRenderName() { MetricResult metricResult = MetricResult.create( - MetricKey.create( - "myStep.one.two(three)", MetricName.named("myNameSpace//", "myName()")), - 123, - 456); + MetricKey.ptransform("myStep.one.two(three)", "myNameSpace//", "myName()"), 123, 456); String renderedName = new SparkBeamMetric().renderName(metricResult); assertThat( "Metric name was not rendered correctly", diff --git a/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/ResumeFromCheckpointStreamingTest.java b/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/ResumeFromCheckpointStreamingTest.java index ceb87a17b30b..604477433cbf 100644 --- a/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/ResumeFromCheckpointStreamingTest.java +++ b/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/ResumeFromCheckpointStreamingTest.java @@ -212,12 +212,7 @@ public void testWithResume() throws Exception { long successAssertions = 0; Iterable> counterResults = res.metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - PAssertWithoutFlatten.class, PAssert.SUCCESS_COUNTER)) - .build()) + .queryMetrics(MetricsFilter.user(PAssertWithoutFlatten.class, PAssert.SUCCESS_COUNTER)) .getCounters(); for (MetricResult counter : counterResults) { if (counter.getAttempted() > 0) { @@ -232,12 +227,7 @@ public void testWithResume() throws Exception { long failedAssertions = 0; Iterable> failCounterResults = res.metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - PAssertWithoutFlatten.class, PAssert.FAILURE_COUNTER)) - .build()) + .queryMetrics(MetricsFilter.user(PAssertWithoutFlatten.class, PAssert.FAILURE_COUNTER)) .getCounters(); for (MetricResult counter : failCounterResults) { if (counter.getAttempted() > 0) { diff --git a/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/StreamingSourceMetricsTest.java b/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/StreamingSourceMetricsTest.java index 60f7fa98ddbf..c4a0fc69bda8 100644 --- a/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/StreamingSourceMetricsTest.java +++ b/runners/spark/src/test/java/org/apache/beam/runners/spark/translation/streaming/StreamingSourceMetricsTest.java @@ -27,7 +27,6 @@ import org.apache.beam.sdk.io.GenerateSequence; import org.apache.beam.sdk.io.Source; import org.apache.beam.sdk.metrics.MetricName; -import org.apache.beam.sdk.metrics.MetricNameFilter; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.sdk.metrics.SourceMetrics; @@ -59,11 +58,7 @@ public void testUnboundedSourceMetrics() { pipelineResult .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())) - .build()); + MetricsFilter.user(ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())); assertThat( metrics.getCounters(), diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java index bab5e818f3fd..9ac7e879240e 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java @@ -40,7 +40,8 @@ private MetricFiltering() {} public static boolean matches(MetricsFilter filter, MetricKey key) { return filter == null || (matchesName(key.metricName(), filter.names()) - && matchesScope(key.stepName(), filter.steps())); + && key.ptransform() != null + && matchesScope(key.ptransform(), filter.steps())); } /** diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java index 323e246e7a81..2543274c9105 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java @@ -19,28 +19,81 @@ import com.google.auto.value.AutoValue; import java.io.Serializable; +import java.util.Map; 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.labels.MetricLabels; /** Metrics are keyed by the step name they are associated with and the name of the metric. */ @Experimental(Kind.METRICS) @AutoValue public abstract class MetricKey implements Serializable { - /** The step name that is associated with this metric or Null if none is associated. */ + public abstract MetricName metricName(); + + public abstract MetricLabels labels(); + + /** + * The ptransform name that is associated with this metric; throws if none is associated. + * + *

TODO(ryan): remove this? + */ + public String stepName() { + String ptransform = ptransform(); + if (ptransform == null) { + throw new IllegalArgumentException("Metric doesn't have PTRANSFORM name: " + this.toString()); + } + return ptransform; + } + + /** The ptransform name that is associated with this metric, or Null if none is associated. */ @Nullable - public abstract String stepName(); + public String ptransform() { + return labels().ptransform(); + } - /** The name of the metric. */ - public abstract MetricName metricName(); + /** The pcollection name that is associated with this metric, or Null if none is associated. */ + @Nullable + public String pcollection() { + return labels().pcollection(); + } + + public boolean isUserMetric() { + return metricName().isUserMetric(); + } @Override public String toString() { - return String.format("%s:%s", stepName(), metricName()); + return toString(":"); + } + + public String toString(String delimiter) { + if (isUserMetric()) { + return String.join(delimiter, stepName(), metricName().toString(delimiter)); + } + return String.join(delimiter, labels().value(), metricName().urn().replaceAll(":", delimiter)); + } + + public static MetricKey of(MetricName metricName, MetricLabels labels) { + return new AutoValue_MetricKey(metricName, labels); + } + + public static MetricKey ptransform(String ptransform, MetricName name) { + return new AutoValue_MetricKey(name, MetricLabels.ptransform(ptransform)); + } + + public static MetricKey ptransform(String ptransform, String namespace, String name) { + return new AutoValue_MetricKey( + MetricName.named(namespace, name), MetricLabels.ptransform(ptransform)); + } + + public static MetricKey ptransform(String ptransform, Class namespace, String name) { + return new AutoValue_MetricKey( + MetricName.named(namespace, name), MetricLabels.ptransform(ptransform)); } - public static MetricKey create(@Nullable String stepName, MetricName metricName) { - return new AutoValue_MetricKey(stepName, metricName); + public static MetricKey create(String urn, Map labels) { + return new AutoValue_MetricKey(MetricName.of(urn), MetricLabels.create(labels)); } } 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..60b9f6d69174 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 @@ -17,63 +17,102 @@ */ package org.apache.beam.sdk.metrics; -import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; +import static org.apache.beam.sdk.metrics.MetricUrns.USER_COUNTER_URN_PREFIX; import com.google.auto.value.AutoValue; import java.io.Serializable; +import java.util.List; +import javax.annotation.Nullable; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; -import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; +import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Splitter; /** - * The name of a metric consists of a {@link #getNamespace} and a {@link #getName}. The {@link - * #getNamespace} allows grouping related metrics together and also prevents collisions between - * multiple metrics with the same name. + * Wrapper for {@link org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo} URN. + * + *

"User" metrics (URN {@link MetricUrns#USER_COUNTER_URN_PREFIX}) are defined by a "namespace" + * and "name", and are the most commonly dealt with by user code, so structured constructors and + * accessors are provided in terms of those strings. + * + *

The {@link #namespace} allows grouping related metrics together and also prevents collisions + * between multiple metrics with the same name. */ @Experimental(Kind.METRICS) @AutoValue public abstract class MetricName implements Serializable { - /** The namespace associated with this metric. */ - public abstract String getNamespace(); + public abstract String urn(); + + @Nullable private String name; - /** - * The namespace associated with this metric. - * - * @deprecated to be removed once Dataflow no longer requires this method. - */ - @Deprecated - public String namespace() { - return getNamespace(); + @Nullable private String namespace; + + /** Parse the urn field into a name and namespace field. */ + private boolean parseUrn(boolean raise) { + if (namespace != null && name != null) { + return true; + } + String urn = urn(); + if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { + urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); + } else { + if (raise) { + throw new IllegalStateException( + "Attempting to access namespace/name of a non-user metric: " + urn); + } + return false; + } + // If it is not a user counter, just use the first part of the URN, i.e. 'beam' + List pieces = Splitter.on(':').splitToList(urn); + if (pieces.size() != 2) { + throw new IllegalStateException("Invalid metric user-metric URN: " + urn); + } + + namespace = pieces.get(0); + name = pieces.get(1); + return true; } - /** The name of this metric. */ - public abstract String getName(); + public Boolean isUserMetric() { + return parseUrn(false); + } + + /** @return the parsed namespace from the user metric URN, otherwise throws. */ + public String getNamespace() { + if (this.namespace == null) { + parseUrn(true); + } + return this.namespace; + } + /** @return the parsed name from the user metric URN, otherwise throws. */ + public String getName() { + if (this.name == null) { + parseUrn(true); + } + return this.name; + } @Override public String toString() { - return String.format("%s:%s", getNamespace(), getName()); + return toString(":"); + } + + public String toString(String delimiter) { + if (isUserMetric()) { + return String.join(delimiter, namespace, name); + } + return urn().replaceAll(":", delimiter); } - /** - * The name of this metric. - * - * @deprecated to be removed once Dataflow no longer requires this method. - */ - @Deprecated - public String name() { - return getName(); + public static MetricName of(String urn) { + return new AutoValue_MetricName(urn); } public static MetricName named(String namespace, String name) { - checkArgument(!Strings.isNullOrEmpty(namespace), "Metric namespace must be non-empty"); - checkArgument(!Strings.isNullOrEmpty(name), "Metric name must be non-empty"); - return new AutoValue_MetricName(namespace, name); + return new AutoValue_MetricName(MetricUrns.urn(namespace, name)); } public static MetricName named(Class namespace, String name) { - checkArgument(namespace != null, "Metric namespace must be non-null"); - checkArgument(!Strings.isNullOrEmpty(name), "Metric name must be non-empty"); - return new AutoValue_MetricName(namespace.getName(), name); + return new AutoValue_MetricName(MetricUrns.urn(namespace.getName(), name)); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricsFilter.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricsFilter.java index bc4137cdfb2f..56983fb34593 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricsFilter.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricsFilter.java @@ -44,6 +44,18 @@ public static Builder builder() { return new AutoValue_MetricsFilter.Builder(); } + public static MetricsFilter ptransform(String ptransform) { + return MetricsFilter.builder().addStep(ptransform).build(); + } + + public static MetricsFilter user(Class namespace, String name) { + return MetricsFilter.builder().addNameFilter(MetricNameFilter.named(namespace, name)).build(); + } + + public static MetricsFilter user(String namespace, String name) { + return MetricsFilter.builder().addNameFilter(MetricNameFilter.named(namespace, name)).build(); + } + /** Builder for creating a {@link MetricsFilter}. */ @AutoValue.Builder public abstract static class Builder { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/MetricLabels.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/MetricLabels.java new file mode 100644 index 000000000000..03c2b28b76ba --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/MetricLabels.java @@ -0,0 +1,162 @@ +/* + * 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.sdk.metrics.labels; + +import static java.util.stream.Collectors.joining; +import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; +import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; + +import com.google.auto.value.AutoValue; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Interface around the allowed sets of labels that a metric may have. + * + *

Supported types: + * + *

    + *
  1. {@link MetricLabels.PTransform PTRANSFORM only} + *
  2. {@link MetricLabels.PCollection PCOLLECTION only} + *
+ */ +public abstract class MetricLabels implements Serializable { + /** Only instantiate this class as one of the concrete types below. */ + private MetricLabels() {} + + public abstract String key(); + + public abstract String value(); + + private Map map; + + public Map map() { + if (map == null) { + map = new HashMap(); + map.put(key(), value()); + } + return map; + } + + @Nullable + public abstract String ptransform(); + + @Nullable + public abstract String pcollection(); + + @Override + public String toString() { + return toString("{", ":", "}"); + } + + public String toString(String openLabels, String labelKVDelimiter, String closeLabels) { + return String.format("%s%s%s%s%s", openLabels, key(), labelKVDelimiter, value(), closeLabels); + } + + public static MetricLabels ptransform(String ptransform) { + return PTransform.of(ptransform); + } + + public static MetricLabels pcollection(String pcollection) { + return PCollection.of(pcollection); + } + + public static MetricLabels create(Map labels) { + String ptransform = labels.get(PTRANSFORM_LABEL); + if (ptransform != null) { + return ptransform(ptransform); + } + String pcollection = labels.get(PCOLLECTION_LABEL); + if (pcollection != null) { + return pcollection(pcollection); + } + throw new IllegalStateException( + "Can't create MetricLabels from MonitoringInfo labels: " + + labels.entrySet().stream() + .map(entry -> String.format("%s: %s", entry.getKey(), entry.getValue())) + .collect(joining(", "))); + } + + /** {@link MetricLabels} implementation for metrics scoped to only to a PTransform. */ + @AutoValue + public abstract static class PTransform extends MetricLabels { + + public abstract String name(); + + public static PTransform of(String name) { + return new AutoValue_MetricLabels_PTransform(name); + } + + @Nullable + @Override + public String ptransform() { + return name(); + } + + @Nullable + @Override + public String pcollection() { + return null; + } + + @Override + public String key() { + return PTRANSFORM_LABEL; + } + + @Override + public String value() { + return name(); + } + } + + /** {@link MetricLabels} implementation for metrics scoped to only to a PCollection. */ + @AutoValue + public abstract static class PCollection extends MetricLabels { + + public abstract String name(); + + public static PCollection of(String name) { + return new AutoValue_MetricLabels_PCollection(name); + } + + @Nullable + @Override + public String ptransform() { + return null; + } + + @Nullable + @Override + public String pcollection() { + return name(); + } + + @Override + public String key() { + return PCOLLECTION_LABEL; + } + + @Override + public String value() { + return name(); + } + } +} diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/package-info.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/package-info.java new file mode 100644 index 000000000000..d816b2f482b6 --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/labels/package-info.java @@ -0,0 +1,19 @@ +/* + * 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. + */ +/** Utilities for working with metric ptransform- and pcollection-labels. */ +package org.apache.beam.sdk.metrics.labels; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/testing/TestPipeline.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/testing/TestPipeline.java index 6967a649d63e..aa8f31013183 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/testing/TestPipeline.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/testing/TestPipeline.java @@ -32,7 +32,6 @@ import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.io.FileSystems; -import org.apache.beam.sdk.metrics.MetricNameFilter; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.metrics.MetricsFilter; @@ -499,10 +498,7 @@ public static void verifyPAssertsSucceeded(Pipeline pipeline, PipelineResult pip Iterable> successCounterResults = pipelineResult .metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter(MetricNameFilter.named(PAssert.class, PAssert.SUCCESS_COUNTER)) - .build()) + .queryMetrics(MetricsFilter.user(PAssert.class, PAssert.SUCCESS_COUNTER)) .getCounters(); for (MetricResult counter : successCounterResults) { if (counter.getAttempted() > 0) { diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricFilteringTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricFilteringTest.java index 57be99cc6a73..deefefea0a42 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricFilteringTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricFilteringTest.java @@ -44,8 +44,7 @@ public void testMatchCompositeStepNameFilters() { .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .addStep("myStep") .build(), - MetricKey.create( - "myBigStep/myStep", MetricName.named(MetricFilteringTest.class, "myMetricName")))); + MetricKey.ptransform("myBigStep/myStep", MetricFilteringTest.class, "myMetricName"))); // Unsuccessful match. assertFalse( @@ -54,9 +53,8 @@ public void testMatchCompositeStepNameFilters() { .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .addStep("myOtherStep") .build(), - MetricKey.create( - "myOtherStepNoMatch/myStep", - MetricName.named(MetricFilteringTest.class, "myMetricName")))); + MetricKey.ptransform( + "myOtherStepNoMatch/myStep", MetricFilteringTest.class, "myMetricName"))); } @Test @@ -69,8 +67,7 @@ public void testMatchStepNameFilters() { .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .addStep("myStep") .build(), - MetricKey.create( - "myStep", MetricName.named(MetricFilteringTest.class, "myMetricName")))); + MetricKey.ptransform("myStep", MetricFilteringTest.class, "myMetricName"))); // Unsuccessful match. assertFalse( @@ -79,8 +76,7 @@ public void testMatchStepNameFilters() { .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .addStep("myOtherStep") .build(), - MetricKey.create( - "myStep", MetricName.named(MetricFilteringTest.class, "myMetricName")))); + MetricKey.ptransform("myStep", MetricFilteringTest.class, "myMetricName"))); } @Test @@ -92,8 +88,7 @@ public void testMatchClassNamespaceFilters() { MetricsFilter.builder() .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .build(), - MetricKey.create( - "anyStep", MetricName.named(MetricFilteringTest.class, "myMetricName")))); + MetricKey.ptransform("anyStep", MetricFilteringTest.class, "myMetricName"))); // Unsuccessful match. assertFalse( @@ -101,7 +96,7 @@ public void testMatchClassNamespaceFilters() { MetricsFilter.builder() .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class, "myMetricName")) .build(), - MetricKey.create("anyStep", MetricName.named(MetricFiltering.class, "myMetricName")))); + MetricKey.ptransform("anyStep", MetricFiltering.class, "myMetricName"))); } @Test @@ -113,7 +108,7 @@ public void testMatchStringNamespaceFilters() { MetricsFilter.builder() .addNameFilter(MetricNameFilter.named("myNamespace", "myMetricName")) .build(), - MetricKey.create("anyStep", MetricName.named("myNamespace", "myMetricName")))); + MetricKey.ptransform("anyStep", "myNamespace", "myMetricName"))); // Unsuccessful match. assertFalse( @@ -121,7 +116,7 @@ public void testMatchStringNamespaceFilters() { MetricsFilter.builder() .addNameFilter(MetricNameFilter.named("myOtherNamespace", "myMetricName")) .build(), - MetricKey.create("anyStep", MetricName.named("myNamespace", "myMetricname")))); + MetricKey.ptransform("anyStep", "myNamespace", "myMetricname"))); } @Test diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricResultsMatchers.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricResultsMatchers.java index db437c33dc4f..0216d9d2e15d 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricResultsMatchers.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricResultsMatchers.java @@ -192,7 +192,7 @@ private static void describeMetricsResultMembersMismatch( String namespace, String name, String step) { - MetricKey key = MetricKey.create(step, MetricName.named(namespace, name)); + MetricKey key = MetricKey.ptransform(step, namespace, name); if (!Objects.equals(key, item.getKey())) { mismatchDescription .appendText("inKey: ") diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java index df6af8e0393d..14dc79d0856d 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/metrics/MetricsTest.java @@ -273,11 +273,7 @@ public void testBoundedSourceMetrics() { pipelineResult .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())) - .build()); + MetricsFilter.user(ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())); assertThat( metrics.getCounters(), @@ -304,11 +300,7 @@ public void testUnboundedSourceMetrics() { pipelineResult .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())) - .build()); + MetricsFilter.user(ELEMENTS_READ.getNamespace(), ELEMENTS_READ.getName())); assertThat( metrics.getCounters(), diff --git a/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java b/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java index b3add8b73c01..37cd2ea6d643 100644 --- a/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java +++ b/sdks/java/extensions/google-cloud-platform-core/src/test/java/org/apache/beam/sdk/extensions/gcp/GcpCoreApiSurfaceTest.java @@ -56,9 +56,7 @@ public void testGcpCoreApiSurface() throws Exception { classesInPackage("com.fasterxml.jackson.annotation"), classesInPackage("java"), classesInPackage("javax"), - classesInPackage("org.apache.beam.model"), classesInPackage("org.apache.beam.sdk"), - classesInPackage("org.apache.beam.vendor.grpc"), classesInPackage("org.joda.time")); assertThat(apiSurface, containsOnlyClassesMatching(allowedClasses)); diff --git a/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamEnumerableConverter.java b/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamEnumerableConverter.java index e3971f56ab2d..f22358b0da12 100644 --- a/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamEnumerableConverter.java +++ b/sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/rel/BeamEnumerableConverter.java @@ -38,7 +38,6 @@ import org.apache.beam.sdk.extensions.sql.impl.utils.CalciteUtils.DateType; import org.apache.beam.sdk.extensions.sql.impl.utils.CalciteUtils.TimeType; import org.apache.beam.sdk.metrics.Counter; -import org.apache.beam.sdk.metrics.MetricNameFilter; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.Metrics; @@ -325,12 +324,7 @@ private static Enumerable count(PipelineOptions options, BeamRelNode nod if (!containsUnboundedPCollection(pipeline)) { result.waitUntilFinish(); MetricQueryResults metrics = - result - .metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter(MetricNameFilter.named(BeamEnumerableConverter.class, "rows")) - .build()); + result.metrics().queryMetrics(MetricsFilter.user(BeamEnumerableConverter.class, "rows")); Iterator> iterator = metrics.getCounters().iterator(); if (iterator.hasNext()) { count = iterator.next().getAttempted(); 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 12676a5eeebf..27ba3cda37e7 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 @@ -18,19 +18,16 @@ package org.apache.beam.fn.harness.data; import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PCOLLECTION_LABEL; import java.io.Closeable; -import java.util.HashMap; -import java.util.Map; 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.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.metrics.labels.MetricLabels; import org.apache.beam.sdk.util.WindowedValue; /** @@ -50,14 +47,13 @@ public ElementCountFnDataReceiver( String pCollection, MetricsContainerStepMap metricContainerRegistry) { this.original = original; - Map labels = new HashMap(); - labels.put(PCOLLECTION_LABEL, pCollection); - MetricName metricName = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); + MetricLabels labels = MetricLabels.pcollection(pCollection); + MetricName metricName = MetricName.of(ELEMENT_COUNT_URN); this.counter = LabeledMetrics.counter(metricName); // Collect the metric in a metric container which is not bound to the step name. // This is required to count elements from impulse steps, which will produce elements outside // of a pTransform context. - this.unboundMetricContainer = metricContainerRegistry.getUnboundContainer(); + this.unboundMetricContainer = metricContainerRegistry.getContainer(labels); } @Override 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 de37752aa990..2ae76f804255 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 @@ -18,7 +18,6 @@ package org.apache.beam.fn.harness.data; import static org.apache.beam.sdk.metrics.MetricUrns.PROCESS_BUNDLE_MSECS_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; import java.io.Closeable; import java.util.HashMap; @@ -33,6 +32,7 @@ import org.apache.beam.runners.core.metrics.SimpleStateRegistry; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.metrics.MetricsEnvironment; +import org.apache.beam.sdk.metrics.labels.MetricLabels; 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; @@ -87,11 +87,10 @@ public void register( + "calling getMultiplexingConsumer."); } - HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(PTRANSFORM_LABEL, pTransformId); + MetricLabels labels = MetricLabels.ptransform(pTransformId); SimpleExecutionState state = new SimpleExecutionState( - ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labelsMetadata); + ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labels.map()); executionStates.register(state); // 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 @@ -99,7 +98,7 @@ public void register( // Process Bundle Execution time metric. FnDataReceiver> wrapAndEnableMetricContainer = (WindowedValue input) -> { - MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId); + MetricsContainerImpl container = metricsContainerRegistry.getContainer(labels); try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) { try (Closeable trackerCloseable = this.stateTracker.enterState(state)) { consumer.accept(input); 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 2bcc8dcd0684..3d9b5e082da0 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 @@ -18,12 +18,10 @@ package org.apache.beam.fn.harness.data; import static org.apache.beam.sdk.metrics.MetricUrns.FINISH_BUNDLE_MSECS_URN; -import static org.apache.beam.sdk.metrics.MetricUrns.PTRANSFORM_LABEL; import static org.apache.beam.sdk.metrics.MetricUrns.START_BUNDLE_MSECS_URN; import java.io.Closeable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.ExecutionStateTracker; @@ -33,6 +31,7 @@ import org.apache.beam.runners.core.metrics.SimpleStateRegistry; import org.apache.beam.sdk.function.ThrowingRunnable; import org.apache.beam.sdk.metrics.MetricsEnvironment; +import org.apache.beam.sdk.metrics.labels.MetricLabels; /** * A class to to register and retrieve functions for bundle processing (i.e. the start, or finish @@ -90,8 +89,7 @@ public PTransformFunctionRegistry( * @param runnable */ public void register(String pTransformId, ThrowingRunnable runnable) { - HashMap labelsMetadata = new HashMap(); - labelsMetadata.put(PTRANSFORM_LABEL, pTransformId); + MetricLabels labels = MetricLabels.ptransform(pTransformId); String executionTimeUrn = ""; if (executionStateName.equals(ExecutionStateTracker.START_STATE_NAME)) { executionTimeUrn = START_BUNDLE_MSECS_URN; @@ -100,12 +98,13 @@ public void register(String pTransformId, ThrowingRunnable runnable) { } SimpleExecutionState state = - new SimpleExecutionState(this.executionStateName, executionTimeUrn, labelsMetadata); + new SimpleExecutionState(this.executionStateName, executionTimeUrn, labels.map()); + executionStates.register(state); ThrowingRunnable wrapped = () -> { - MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId); + MetricsContainerImpl container = metricsContainerRegistry.getContainer(labels); try (Closeable metricCloseable = MetricsEnvironment.scopedMetricsContainer(container)) { try (Closeable trackerCloseable = this.stateTracker.enterState(state)) { runnable.run(); 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 0ab1e19f785f..8536de5fef53 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 @@ -184,7 +184,7 @@ public Coder windowCoder() { null /* pipelineOptions */, null /* beamFnDataClient */, null /* beamFnStateClient */, - null /* pTransformId */, + "ptransform" /* pTransformId */, PTransform.newBuilder() .putInputs("in", "input") .putOutputs("out", "output") 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 3ca4ef855817..3686e42906b7 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 @@ -59,6 +59,7 @@ import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; +import org.apache.beam.sdk.metrics.labels.MetricLabels; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.state.BagState; import org.apache.beam.sdk.state.CombiningState; @@ -564,13 +565,14 @@ public void testSideInputIsAccessibleForDownstreamCallers() throws Exception { /** @return a test MetricUpdate for expected metrics to compare against */ public MetricUpdate create(String stepName, MetricName name, long value) { - return MetricUpdate.create(MetricKey.create(stepName, name), value); + return MetricUpdate.create(MetricKey.ptransform(stepName, name), value); } @Test public void testUsingMetrics() throws Exception { MetricsContainerStepMap metricsContainerRegistry = new MetricsContainerStepMap(); - MetricsContainerImpl metricsContainer = metricsContainerRegistry.getUnboundContainer(); + MetricsContainerImpl metricsContainer = + metricsContainerRegistry.getContainer(MetricLabels.ptransform(TEST_PTRANSFORM_ID)); Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer); FixedWindows windowFn = FixedWindows.of(Duration.millis(1L)); IntervalWindow windowA = windowFn.assignWindow(new Instant(1L)); @@ -639,7 +641,7 @@ public void testUsingMetrics() throws Exception { fakeClient, TEST_PTRANSFORM_ID, pTransform, - Suppliers.ofInstance("57L")::get, + () -> "57L", pProto.getComponents().getPcollectionsMap(), pProto.getComponents().getCodersMap(), pProto.getComponents().getWindowingStrategiesMap(), @@ -662,34 +664,33 @@ public void testUsingMetrics() throws Exception { MetricsContainer mc = MetricsEnvironment.getCurrentContainer(); - List expected = new ArrayList(); - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel("Window.Into()/Window.Assign.out"); - builder.setInt64Value(2); - expected.add(builder.build()); - - builder = new SimpleMonitoringInfoBuilder(); - builder.setUrn(ELEMENT_COUNT_URN); - builder.setPCollectionLabel( - "pTransformId/ParMultiDo(TestSideInputIsAccessibleForDownstreamCallers).output"); - 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()); + MonitoringInfo[] expected = { + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel("Window.Into()/Window.Assign.out") + .setInt64Value(2) + .build(), + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setPCollectionLabel( + "pTransformId/ParMultiDo(TestSideInputIsAccessibleForDownstreamCallers).output") + .setInt64Value(2) + .build(), + new SimpleMonitoringInfoBuilder() + .userMetric( + TEST_PTRANSFORM_ID, + TestSideInputIsAccessibleForDownstreamCallersDoFn.class.getName(), + TestSideInputIsAccessibleForDownstreamCallersDoFn.USER_COUNTER_NAME) + .setInt64Value(2) + .build() + }; closeable.close(); List result = new ArrayList(); for (MonitoringInfo mi : metricsContainerRegistry.getMonitoringInfos()) { result.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); } - assertThat(result, containsInAnyOrder(expected.toArray())); + assertThat(result, containsInAnyOrder(expected)); } private static class TestTimerfulDoFn extends DoFn, String> { 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 ade686b445a6..f189707bd573 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 @@ -93,6 +93,7 @@ public void testScopedMetricContainerInvokedUponAccept() throws Exception { // Verify that static scopedMetricsContainer is called with unbound container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getUnboundContainer()); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.pcollectionContainer(pCollectionA)); } } 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 2b72fe91a6ec..bdf986f5e4d2 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 @@ -123,10 +123,12 @@ public void testScopedMetricContainerInvokedUponAcceptingElement() throws Except // Verify that static scopedMetricsContainer is called with pTransformA's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformA")); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.ptransformContainer("pTransformA")); // Verify that static scopedMetricsContainer is called with pTransformB's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformB")); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.ptransformContainer("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 08b41606cfe0..aa70f815ade0 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 @@ -75,10 +75,12 @@ public void testScopedMetricContainerInvokedUponRunningFunctions() throws Except // Verify that static scopedMetricsContainer is called with pTransformA's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformA")); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.ptransformContainer("pTransformA")); // Verify that static scopedMetricsContainer is called with pTransformB's container. PowerMockito.verifyStatic(times(1)); - MetricsEnvironment.scopedMetricsContainer(metricsContainerRegistry.getContainer("pTransformB")); + MetricsEnvironment.scopedMetricsContainer( + metricsContainerRegistry.ptransformContainer("pTransformB")); } } diff --git a/sdks/java/io/kafka/src/test/java/org/apache/beam/sdk/io/kafka/KafkaIOTest.java b/sdks/java/io/kafka/src/test/java/org/apache/beam/sdk/io/kafka/KafkaIOTest.java index 14a789f62f6a..4c6005585cfa 100644 --- a/sdks/java/io/kafka/src/test/java/org/apache/beam/sdk/io/kafka/KafkaIOTest.java +++ b/sdks/java/io/kafka/src/test/java/org/apache/beam/sdk/io/kafka/KafkaIOTest.java @@ -962,12 +962,8 @@ public void testUnboundedSourceMetrics() { result .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - backlogElementsOfSplit.getNamespace(), - backlogElementsOfSplit.getName())) - .build()); + MetricsFilter.user( + backlogElementsOfSplit.getNamespace(), backlogElementsOfSplit.getName())); // since gauge values may be inconsistent in some environments assert only on their existence. assertThat(backlogElementsMetrics.getGauges(), IsIterableWithSize.iterableWithSize(1)); @@ -976,11 +972,8 @@ public void testUnboundedSourceMetrics() { result .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - backlogBytesOfSplit.getNamespace(), backlogBytesOfSplit.getName())) - .build()); + MetricsFilter.user( + backlogBytesOfSplit.getNamespace(), backlogBytesOfSplit.getName())); // since gauge values may be inconsistent in some environments assert only on their existence. assertThat(backlogBytesMetrics.getGauges(), IsIterableWithSize.iterableWithSize(1)); @@ -990,12 +983,9 @@ public void testUnboundedSourceMetrics() { result .metrics() .queryMetrics( - MetricsFilter.builder() - .addNameFilter( - MetricNameFilter.named( - KafkaUnboundedReader.METRIC_NAMESPACE, - KafkaUnboundedReader.CHECKPOINT_MARK_COMMITS_ENQUEUED_METRIC)) - .build()); + MetricsFilter.user( + KafkaUnboundedReader.METRIC_NAMESPACE, + KafkaUnboundedReader.CHECKPOINT_MARK_COMMITS_ENQUEUED_METRIC)); assertThat(commitsEnqueuedMetrics.getCounters(), IsIterableWithSize.iterableWithSize(1)); assertThat( diff --git a/sdks/java/testing/test-utils/src/main/java/org/apache/beam/sdk/testutils/metrics/MetricsReader.java b/sdks/java/testing/test-utils/src/main/java/org/apache/beam/sdk/testutils/metrics/MetricsReader.java index 2ea069a586e6..f32bb83427f6 100644 --- a/sdks/java/testing/test-utils/src/main/java/org/apache/beam/sdk/testutils/metrics/MetricsReader.java +++ b/sdks/java/testing/test-utils/src/main/java/org/apache/beam/sdk/testutils/metrics/MetricsReader.java @@ -22,7 +22,6 @@ import java.util.stream.StreamSupport; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.metrics.DistributionResult; -import org.apache.beam.sdk.metrics.MetricNameFilter; import org.apache.beam.sdk.metrics.MetricQueryResults; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricsFilter; @@ -61,13 +60,7 @@ public MetricsReader(PipelineResult result, String namespace) { * attempted metrics because some runners don't support committed metrics. */ public long getCounterMetric(String name) { - MetricQueryResults metrics = - result - .metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter(MetricNameFilter.named(namespace, name)) - .build()); + MetricQueryResults metrics = result.metrics().queryMetrics(MetricsFilter.user(namespace, name)); Iterable> counters = metrics.getCounters(); checkIfMetricResultIsUnique(name, counters); @@ -120,13 +113,7 @@ private Long getGreatestMax(Iterable> distribut } private Iterable> getDistributions(String name) { - MetricQueryResults metrics = - result - .metrics() - .queryMetrics( - MetricsFilter.builder() - .addNameFilter(MetricNameFilter.named(namespace, name)) - .build()); + MetricQueryResults metrics = result.metrics().queryMetrics(MetricsFilter.user(namespace, name)); return metrics.getDistributions(); } From 31aa7463e7c05ec665909527e0093cf63def8c27 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Thu, 7 Mar 2019 21:44:06 +0000 Subject: [PATCH 3/4] cr feedback --- .../core/metrics/MetricsContainerImpl.java | 2 +- .../metrics/SimpleMonitoringInfoBuilder.java | 2 +- .../flink/metrics/FlinkMetricContainer.java | 26 +++++++++---------- .../apache/beam/sdk/metrics/MetricName.java | 8 +++--- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java index b5583ad3a479..c86b41d024fa 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 @@ -154,7 +154,7 @@ public MetricUpdates getUpdates() { @Nullable private MonitoringInfo counterUpdateToMonitoringInfo(MetricUpdate metricUpdate) { return new SimpleMonitoringInfoBuilder(true) - .handleMetricKey(metricUpdate.getKey()) + .setLabelsAndUrn(metricUpdate.getKey()) .setInt64Value(metricUpdate.getUpdate()) .setTimestampToNow() .build(); 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 fa18d9bbe384..bd0b04bc9483 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 @@ -115,7 +115,7 @@ public SimpleMonitoringInfoBuilder setUrn(String urn) { return this; } - public SimpleMonitoringInfoBuilder handleMetricKey(MetricKey key) { + public SimpleMonitoringInfoBuilder setLabelsAndUrn(MetricKey key) { builder.setUrn(key.metricName().urn()).putAllLabels(key.labels().map()); return this; } 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 5300d1b67817..c64b4184389d 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 @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.BiFunction; import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.CounterData; import org.apache.beam.model.pipeline.v1.MetricsApi.DistributionData; @@ -51,7 +52,6 @@ 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; @@ -179,7 +179,7 @@ private void updateMetrics( private void updateMetric( MetricKey key, Map flinkMetricMap, - TriFunction create, + BiFunction create, BiConsumer update, T value) { String flinkMetricName = getFlinkMetricNameString(key); @@ -187,40 +187,40 @@ private void updateMetric( // update flink metric FlinkT metric = flinkMetricMap.get(flinkMetricName); if (metric == null) { - metric = create.apply(flinkMetricName, runtimeContext.getMetricGroup(), value); + metric = create.apply(flinkMetricName, runtimeContext.getMetricGroup()); flinkMetricMap.put(flinkMetricName, metric); } update.accept(metric, value); } - private void updateCounter(MetricKey metricKey, long attempted) { + private void updateCounter(MetricKey metricKey, long value) { updateMetric( metricKey, flinkCounterCache, - (name, group, value) -> group.counter(name), - (counter, value) -> { + (name, group) -> group.counter(name), + (counter, unused) -> { counter.dec(counter.getCount()); counter.inc(value); }, - attempted); + value); } - private void updateDistribution(MetricKey metricKey, DistributionResult attempted) { + private void updateDistribution(MetricKey metricKey, DistributionResult value) { updateMetric( metricKey, flinkDistributionGaugeCache, - (name, group, value) -> group.gauge(name, new FlinkDistributionGauge(value)), + (name, group) -> group.gauge(name, new FlinkDistributionGauge(value)), FlinkDistributionGauge::update, - attempted); + value); } - private void updateGauge(MetricKey metricKey, GaugeResult attempted) { + private void updateGauge(MetricKey metricKey, GaugeResult value) { updateMetric( metricKey, flinkGaugeCache, - (name, group, value) -> group.gauge(name, new FlinkGauge(value)), + (name, group) -> group.gauge(name, new FlinkGauge(value)), FlinkGauge::update, - attempted); + value); } static String getFlinkMetricNameString(MetricKey metricKey) { 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 60b9f6d69174..0245280607d6 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,17 +52,17 @@ private boolean parseUrn(boolean raise) { if (namespace != null && name != null) { return true; } + String urn = urn(); - if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { - urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); - } else { + if (!urn.startsWith(USER_COUNTER_URN_PREFIX)) { if (raise) { throw new IllegalStateException( "Attempting to access namespace/name of a non-user metric: " + urn); } return false; } - // If it is not a user counter, just use the first part of the URN, i.e. 'beam' + urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); + List pieces = Splitter.on(':').splitToList(urn); if (pieces.size() != 2) { throw new IllegalStateException("Invalid metric user-metric URN: " + urn); From adc78725787ec751c0ab560776400a9be837a5ec Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Thu, 7 Mar 2019 21:44:21 +0000 Subject: [PATCH 4/4] cr feedback: harmonize urn-parsing in MetricUrns, dataflow --- ...UserMonitoringInfoToCounterUpdateTransformer.java | 10 +++++----- .../java/org/apache/beam/sdk/metrics/MetricName.java | 8 ++++---- .../java/org/apache/beam/sdk/metrics/MetricUrns.java | 12 ++++++++---- 3 files changed, 17 insertions(+), 13 deletions(-) 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 cb6545667c80..2e864f7f81ef 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 @@ -31,6 +31,8 @@ import org.apache.beam.runners.dataflow.worker.DataflowExecutionContext.DataflowStepContext; import org.apache.beam.runners.dataflow.worker.MetricsToCounterUpdateConverter.Origin; import org.apache.beam.runners.dataflow.worker.counters.DataflowCounterUpdateExtractor; +import org.apache.beam.sdk.metrics.MetricName; +import org.apache.beam.sdk.metrics.MetricUrns; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -101,12 +103,10 @@ public CounterUpdate transform(MonitoringInfo monitoringInfo) { CounterStructuredNameAndMetadata name = new CounterStructuredNameAndMetadata(); - String nameWithNamespace = urn.substring(BEAM_METRICS_USER_PREFIX.length()).replace("^:", ""); + MetricName metricName = MetricUrns.parseUrn(urn); - final int lastColonIndex = nameWithNamespace.lastIndexOf(':'); - String counterName = nameWithNamespace.substring(lastColonIndex + 1); - String counterNamespace = - lastColonIndex == -1 ? "" : nameWithNamespace.substring(0, lastColonIndex); + String counterName = metricName.getName(); + String counterNamespace = metricName.getNamespace(); DataflowStepContext stepContext = transformIdMapping.get(ptransform); name.setName( 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 0245280607d6..ab550f56d190 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 @@ -64,12 +64,12 @@ private boolean parseUrn(boolean raise) { urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); List pieces = Splitter.on(':').splitToList(urn); - if (pieces.size() != 2) { - throw new IllegalStateException("Invalid metric user-metric URN: " + urn); + if (pieces.size() < 1) { + throw new IllegalArgumentException("Invalid user-metric URN: " + urn); } + namespace = String.join("", pieces.subList(0, pieces.size() - 1)); + name = pieces.get(pieces.size() - 1); - namespace = pieces.get(0); - name = pieces.get(1); return true; } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java index 02396a518713..890c74ea546d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricUrns.java @@ -31,9 +31,11 @@ import static org.apache.beam.sdk.metrics.BeamUrns.getUrn; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; +import java.util.List; import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo.MonitoringInfoLabels; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfoLabelProps; +import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Splitter; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; /** Utility for parsing a URN to a {@link org.apache.beam.sdk.metrics.MetricName}. */ @@ -62,12 +64,14 @@ public static MetricName parseUrn(String urn) { } 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); - if (pieces.length != 2) { + + List pieces = Splitter.on(':').splitToList(urn); + if (pieces.size() < 1) { throw new IllegalArgumentException("Invalid user-metric URN: " + urn); } - return MetricName.named(pieces[0], pieces[1]); + String namespace = String.join("", pieces.subList(0, pieces.size() - 1)); + String name = pieces.get(pieces.size() - 1); + return MetricName.named(namespace, name); } /** @return The metric URN for a user metric, with a proper URN prefix. */