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/MetricsContainerImpl.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerImpl.java
index 2ba95cddb261..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
@@ -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)
+ .setLabelsAndUrn(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 5bf435e82d32..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;
@@ -36,6 +37,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<>();
@@ -44,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(
@@ -73,6 +77,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
deleted file mode 100644
index 4583c9ddbf40..000000000000
--- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java
+++ /dev/null
@@ -1,123 +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.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.Entry;
-import java.util.Objects;
-import javax.annotation.Nullable;
-import org.apache.beam.sdk.metrics.MetricName;
-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 HashMap labels = new HashMap();
-
- private MonitoringInfoMetricName(String urn, HashMap 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(SimpleMonitoringInfoBuilder.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 HashMap getLabels() {
- return this.labels;
- }
-
- public static MonitoringInfoMetricName named(String urn, HashMap labels) {
- return new MonitoringInfoMetricName(urn, labels);
- }
-
- @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.toString());
- 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..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
@@ -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;
@@ -35,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);
@@ -59,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<>();
}
}
@@ -89,8 +90,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..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
@@ -17,20 +17,20 @@
*/
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.sdk.metrics.MetricKey;
import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -56,29 +56,14 @@
*
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 {
- 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 +84,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);
}
@@ -137,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(userMetricUrn(namespace, name));
+ public SimpleMonitoringInfoBuilder setLabelsAndUrn(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 c1704aa63d00..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
@@ -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 = MetricName.of(ELEMENT_COUNT_URN);
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 = 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 aa74ff287b5a..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,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.runners.core.metrics.SimpleMonitoringInfoBuilder.clearTimestamp;
+import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
@@ -25,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;
@@ -38,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(
@@ -78,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);
@@ -103,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"));
@@ -150,53 +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(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "pcollection");
- MetricName name =
- MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.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(SimpleMonitoringInfoBuilder.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 13dd79d853c8..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.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.io.Serializable;
-import java.util.HashMap;
-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() {
- HashMap labels = new HashMap();
- String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN;
- MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels);
- assertEquals(null, name.getName());
- assertEquals(null, 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.ELEMENT_COUNT_URN;
- labels = new HashMap();
- MonitoringInfoMetricName 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();
- MonitoringInfoMetricName 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);
-
- assertEquals(name, name2);
- assertEquals(name.hashCode(), name2.hashCode());
- }
-
- @Test
- public void testNotEqualsDiffLabels() {
- HashMap labels = new HashMap();
- String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN;
- MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels);
-
- // Reconstruct and test equality and hash code equivalence
- urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN;
- labels = new HashMap();
- labels.put("label", "value1");
- MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels);
-
- assertNotEquals(name, name2);
- assertNotEquals(name.hashCode(), name2.hashCode());
- }
-
- @Test
- public void testNotEqualsDiffUrn() {
- HashMap labels = new HashMap();
- String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN;
- MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels);
-
- // Reconstruct and test equality and hash code equivalence
- urn = "differentUrn";
- labels = new HashMap();
- MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels);
-
- assertNotEquals(name, name2);
- assertNotEquals(name.hashCode(), name2.hashCode());
- }
-
- @Test
- public void testNullLabelsThrows() {
- thrown.expect(IllegalArgumentException.class);
- HashMap labels = null;
- MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.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 1b337ee9c152..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
@@ -17,26 +17,18 @@
*/
package org.apache.beam.runners.core.metrics;
-import java.util.HashMap;
+import static org.apache.beam.sdk.metrics.MetricUrns.ELEMENT_COUNT_URN;
+
import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo;
/**
* 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;
- }
-
/** @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..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
@@ -17,12 +17,14 @@
*/
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;
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;
@@ -36,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
@@ -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..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
@@ -18,6 +18,12 @@
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.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;
@@ -33,7 +39,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,43 +49,41 @@ 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());
}
@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);
- assertEquals(
- SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX + "myNamespace:myName",
- monitoringInfo.getUrn());
- assertEquals(SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN, monitoringInfo.getType());
+ 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(
- 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("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 ac42caf5a105..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
@@ -17,12 +17,15 @@
*/
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.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;
@@ -31,25 +34,19 @@
public class SimpleStateRegistryTest {
@Test
- public void testExecutionTimeUrnsBuildMonitoringInfos() throws Exception {
+ public void testExecutionTimeUrnsBuildMonitoringInfos() {
String testPTransformId = "pTransformId";
- HashMap labelsMetadata = new HashMap();
- labelsMetadata.put(SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL, testPTransformId);
+
+ MetricLabels labels = MetricLabels.ptransform(testPTransformId);
SimpleExecutionState startState =
new SimpleExecutionState(
- ExecutionStateTracker.START_STATE_NAME,
- SimpleMonitoringInfoBuilder.START_BUNDLE_MSECS_URN,
- labelsMetadata);
+ ExecutionStateTracker.START_STATE_NAME, START_BUNDLE_MSECS_URN, labels.map());
SimpleExecutionState processState =
new SimpleExecutionState(
- ExecutionStateTracker.PROCESS_STATE_NAME,
- SimpleMonitoringInfoBuilder.PROCESS_BUNDLE_MSECS_URN,
- labelsMetadata);
+ ExecutionStateTracker.PROCESS_STATE_NAME, PROCESS_BUNDLE_MSECS_URN, labels.map());
SimpleExecutionState finishState =
new SimpleExecutionState(
- ExecutionStateTracker.FINISH_STATE_NAME,
- SimpleMonitoringInfoBuilder.FINISH_BUNDLE_MSECS_URN,
- labelsMetadata);
+ ExecutionStateTracker.FINISH_STATE_NAME, FINISH_BUNDLE_MSECS_URN, labels.map());
SimpleStateRegistry testObject = new SimpleStateRegistry();
testObject.register(startState);
@@ -59,20 +56,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/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 87c9afd29875..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
@@ -17,12 +17,15 @@
*/
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.DistributionProtos.fromProto;
import java.util.HashMap;
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;
import org.apache.beam.model.pipeline.v1.MetricsApi.ExtremaData;
@@ -41,13 +44,14 @@
import org.apache.beam.sdk.metrics.MetricResults;
import org.apache.beam.sdk.metrics.MetricsContainer;
import org.apache.beam.sdk.metrics.MetricsFilter;
-import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting;
+import org.apache.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.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,
+ BiFunction 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());
+ 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 value) {
+ updateMetric(
+ metricKey,
+ flinkCounterCache,
+ (name, group) -> group.counter(name),
+ (counter, unused) -> {
+ counter.dec(counter.getCount());
+ counter.inc(value);
+ },
+ value);
+ }
- GaugeResult update = metricResult.getAttempted();
+ private void updateDistribution(MetricKey metricKey, DistributionResult value) {
+ updateMetric(
+ metricKey,
+ flinkDistributionGaugeCache,
+ (name, group) -> group.gauge(name, new FlinkDistributionGauge(value)),
+ FlinkDistributionGauge::update,
+ value);
+ }
- // 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 value) {
+ updateMetric(
+ metricKey,
+ flinkGaugeCache,
+ (name, group) -> group.gauge(name, new FlinkGauge(value)),
+ FlinkGauge::update,
+ value);
}
- @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/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..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
@@ -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);
@@ -86,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));
}
@@ -112,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));
@@ -164,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()
@@ -214,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
@@ -250,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/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/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/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/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..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
@@ -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;
@@ -634,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(SimpleMonitoringInfoBuilder.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.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(SimpleMonitoringInfoBuilder.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.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(SimpleMonitoringInfoBuilder.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(SimpleMonitoringInfoBuilder.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(SimpleMonitoringInfoBuilder.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