From d4b48ca1befd84533963457dbd9328ec9006250f Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:52:26 +0000 Subject: [PATCH 01/14] add JobInvocation.getMetrics() API --- .../runners/fnexecution/jobsubmission/JobInvocation.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java index 292e6e85ad4e..3e68e977d95d 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java @@ -32,6 +32,7 @@ import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.model.pipeline.v1.RunnerApi.Pipeline; import org.apache.beam.sdk.PipelineResult; +import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.vendor.guava.v20_0.com.google.common.util.concurrent.FutureCallback; import org.apache.beam.vendor.guava.v20_0.com.google.common.util.concurrent.Futures; import org.apache.beam.vendor.guava.v20_0.com.google.common.util.concurrent.ListenableFuture; @@ -153,6 +154,10 @@ public JobState.Enum getState() { return this.jobState; } + public MetricResults getMetrics() { + throw new UnsupportedOperationException(); + } + /** Listen for job state changes with a {@link Consumer}. */ public synchronized void addStateListener(Consumer stateStreamObserver) { stateStreamObserver.accept(getState()); From 51b211fa2f657fe57bb658448901abe0ff5819a7 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 25 Jan 2019 21:56:48 +0000 Subject: [PATCH 02/14] populate metrics in FlinkJobInvocation --- .../runners/fnexecution/jobsubmission/JobInvocation.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java index 3e68e977d95d..39c38545fadc 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/JobInvocation.java @@ -52,6 +52,8 @@ public class JobInvocation { private List> stateObservers; private List> messageObservers; private JobState.Enum jobState; + private MetricResults metrics; + @Nullable private ListenableFuture invocationFuture; public JobInvocation( @@ -93,6 +95,7 @@ public void onSuccess(@Nullable PipelineResult pipelineResult) { pipelineResult.getState() == PipelineResult.State.DONE, "Success on non-Done state: " + pipelineResult.getState()); setState(JobState.Enum.DONE); + metrics = pipelineResult.metrics(); } else { setState(JobState.Enum.UNSPECIFIED); } @@ -155,7 +158,7 @@ public JobState.Enum getState() { } public MetricResults getMetrics() { - throw new UnsupportedOperationException(); + return metrics; } /** Listen for job state changes with a {@link Consumer}. */ From d141a26ca50b29612606db7474a5bd3216e37d77 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 10 Feb 2019 17:38:29 +0000 Subject: [PATCH 03/14] GetJobMetrics proto RPC --- .../job-management/src/main/proto/beam_job_api.proto | 12 ++++++++++++ model/pipeline/src/main/proto/metrics.proto | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/model/job-management/src/main/proto/beam_job_api.proto b/model/job-management/src/main/proto/beam_job_api.proto index 4a0ecea05226..a2ac598f69af 100644 --- a/model/job-management/src/main/proto/beam_job_api.proto +++ b/model/job-management/src/main/proto/beam_job_api.proto @@ -29,6 +29,7 @@ option go_package = "jobmanagement_v1"; option java_package = "org.apache.beam.model.jobmanagement.v1"; option java_outer_classname = "JobApi"; +import "metrics.proto"; import "beam_runner_api.proto"; import "endpoints.proto"; import "google/protobuf/struct.proto"; @@ -56,6 +57,9 @@ service JobService { // Get the supported pipeline options of the runner rpc DescribePipelineOptions (DescribePipelineOptionsRequest) returns (DescribePipelineOptionsResponse); + + // Fetch metrics for a given job + rpc GetJobMetrics (GetJobMetricsRequest) returns (GetJobMetricsResponse); } @@ -154,6 +158,14 @@ message JobMessage { } } +message GetJobMetricsRequest { + string job_id = 1; // (required) +} + +message GetJobMetricsResponse { + org.apache.beam.model.pipeline.v1.MetricResults metrics = 1; +} + message JobMessagesResponse { oneof response { JobMessage message_response = 1; diff --git a/model/pipeline/src/main/proto/metrics.proto b/model/pipeline/src/main/proto/metrics.proto index 822c99271b35..ee7b92610fd1 100644 --- a/model/pipeline/src/main/proto/metrics.proto +++ b/model/pipeline/src/main/proto/metrics.proto @@ -137,6 +137,12 @@ extend google.protobuf.EnumValueOptions { MonitoringInfoSpec monitoring_info_spec = 207174266; } +// All metrics for a given job. Each runner may or may not support "committed" metrics. +message MetricResults { + repeated MonitoringInfo attempted = 1; + repeated MonitoringInfo committed = 2; +} + message MonitoringInfo { // The name defining the metric or monitored state. string urn = 1; From 546b1e3af77d0959e46754dffb4a51aa2db70ac7 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 22 Feb 2019 19:58:23 +0000 Subject: [PATCH 04/14] MetricResultsProtos --- .../core/metrics/DistributionProtos.java | 41 ++++ .../runners/core/metrics/GaugeProtos.java | 30 +++ .../core/metrics/MetricResultsProtos.java | 224 ++++++++++++++++++ .../metrics/MonitoringInfoMetricName.java | 15 +- .../runners/core/metrics/MonitoringInfos.java | 108 +++++++++ .../metrics/SimpleMonitoringInfoBuilder.java | 84 ++++++- 6 files changed, 489 insertions(+), 13 deletions(-) create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java new file mode 100644 index 000000000000..0b1539515401 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/DistributionProtos.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.beam.runners.core.metrics; + +import org.apache.beam.model.pipeline.v1.MetricsApi.IntDistributionData; +import org.apache.beam.sdk.metrics.DistributionResult; + +/** Convert distributions between protobuf and SDK representations. */ +public class DistributionProtos { + public static DistributionResult fromProto(IntDistributionData distributionData) { + return DistributionResult.create( + distributionData.getSum(), + distributionData.getCount(), + distributionData.getMin(), + distributionData.getMax()); + } + + public static IntDistributionData toProto(DistributionResult distributionResult) { + return IntDistributionData.newBuilder() + .setMin(distributionResult.getMin()) + .setMax(distributionResult.getMax()) + .setCount(distributionResult.getCount()) + .setSum(distributionResult.getSum()) + .build(); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java new file mode 100644 index 000000000000..1b775125b823 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.beam.runners.core.metrics; + +import org.apache.beam.sdk.metrics.GaugeResult; +import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.Timestamp; +import org.joda.time.Instant; + +/** Convert gauges from proto to SDK representations. */ +public class GaugeProtos { + public static GaugeResult fromProto(long value, Timestamp timestamp) { + return GaugeResult.create( + value, new Instant(timestamp.getSeconds() * 1000 + timestamp.getNanos() / 1000)); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java new file mode 100644 index 000000000000..c3cc1e10884e --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java @@ -0,0 +1,224 @@ +/* + * 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 java.util.stream.Collectors.toList; +import static org.apache.beam.runners.core.metrics.MonitoringInfos.forEachMetricType; +import static org.apache.beam.runners.core.metrics.MonitoringInfos.keyFromMonitoringInfo; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; +import org.apache.beam.model.pipeline.v1.MetricsApi; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +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.MetricQueryResults; +import org.apache.beam.sdk.metrics.MetricResult; +import org.apache.beam.sdk.metrics.MetricResults; + +/** + * Convert between Java SDK {@link MetricResults} and corresponding protobuf {@link + * MetricsApi.MetricResults}. + * + *

Their structures are similar, but the former distinguishes "attempted" and "committed" values + * at the lowest level (a {@link MetricResult} contains both), while the latter separates them into + * two lists of {@link MonitoringInfo}s at the top level ({@link + * MetricsApi.MetricResults#getAttemptedList attempted}, {@link + * MetricsApi.MetricResults#getCommittedList} committed}. + * + *

The proto form also holds more kinds of values, so some {@link MonitoringInfo}s may be dropped + * from converting to the Java SDK form. + */ +public class MetricResultsProtos { + + /** Convert metric results from proto to Java SDK form. */ + public static MetricResults fromProto(MetricsApi.MetricResults metricResults) { + return new MetricResultsBuilder(metricResults).build(); + } + + /** Convert metric results from Java SDK to proto form. */ + public static MetricsApi.MetricResults toProto(MetricResults metricResults) { + MetricsApi.MetricResults.Builder builder = MetricsApi.MetricResults.newBuilder(); + MetricQueryResults results = metricResults.allMetrics(); + results + .getCounters() + .forEach( + counter -> + addMetricResultToBuilder( + builder, counter, SimpleMonitoringInfoBuilder::setInt64Value)); + results + .getDistributions() + .forEach( + distribution -> + addMetricResultToBuilder( + builder, distribution, SimpleMonitoringInfoBuilder::setIntDistributionValue)); + results + .getGauges() + .forEach( + gauge -> + addMetricResultToBuilder( + builder, gauge, SimpleMonitoringInfoBuilder::setGaugeValue)); + return builder.build(); + } + + /** + * Add this {@link MetricResult}'s "attempted" and "committed" values to the corresponding lists + * of {@param builder}. + */ + private static void addMetricResultToBuilder( + MetricsApi.MetricResults.Builder builder, + MetricResult metricResult, + BiConsumer set) { + MetricKey metricKey = metricResult.getKey(); + addMetricToBuilder( + builder, + metricKey, + metricResult.getAttempted(), + set, + MetricsApi.MetricResults.Builder::addAttempted); + T committed = metricResult.getCommittedOrNull(); + if (committed != null) { + addMetricToBuilder( + builder, + metricKey, + metricResult.getCommitted(), + set, + MetricsApi.MetricResults.Builder::addCommitted); + } + } + + /** + * Add a metric key and value (from a {@link MetricResult}) to a {@link + * MetricsApi.MetricResults.Builder}. + * + * @param builder proto {@link MetricsApi.MetricResults.Builder} to add to + * @param set set this metric's value on a {@link SimpleMonitoringInfoBuilder} (via an API that's + * specific to this metric's type, as provided by the caller) + * @param add add the {@link MonitoringInfo} created from this key/value to either the "attempted" + * or "committed" list of the {@link MetricsApi.MetricResults.Builder builder} + */ + private static void addMetricToBuilder( + MetricsApi.MetricResults.Builder builder, + MetricKey metricKey, + T value, + BiConsumer set, + BiConsumer add) { + if (value != null) { + SimpleMonitoringInfoBuilder partial = + new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey); + set.accept(partial, value); + MonitoringInfo monitoringInfo = partial.build(); + if (monitoringInfo != null) { + add.accept(builder, monitoringInfo); + } + } + } + + /** + * Helper for converting {@link MetricsApi.MetricResults} to {@link MetricResults}. + * + *

The former separates "attempted" and "committed" metrics at the highest level, while the + * latter splits on metric-type (counter, distribution, or gauge) first, so converting basically + * amounts pivoting those between those two. + */ + private static class MetricResultsBuilder { + private final Map> counters = new ConcurrentHashMap<>(); + private final Map> distributions = + new ConcurrentHashMap<>(); + private final Map> gauges = + new ConcurrentHashMap<>(); + + /** + * Populate metric-type-specific maps with {@link MonitoringInfo}s from a {@link + * MetricsApi.MetricResults}. + */ + public MetricResultsBuilder(MetricsApi.MetricResults metrics) { + add(metrics.getAttemptedList(), false); + add(metrics.getCommittedList(), true); + } + + public MetricResults build() { + return new DefaultMetricResults(build(counters), build(distributions), build(gauges)); + } + + private void add(Iterable monitoringInfos, Boolean committed) { + for (MonitoringInfo monitoringInfo : monitoringInfos) { + addMonitoringInfo(monitoringInfo, committed); + } + } + + /** Helper for turning a map of result-builders into a sequence of results. */ + private static List> build(Map> map) { + return map.values().stream().map(MetricResultBuilder::build).collect(toList()); + } + + private void addMonitoringInfo(MonitoringInfo monitoringInfo, Boolean committed) { + MetricKey metricKey = keyFromMonitoringInfo(monitoringInfo); + forEachMetricType( + monitoringInfo.getMetric(), + monitoringInfo.getType(), + monitoringInfo.getTimestamp(), + counter -> addMetricToResultMap(metricKey, counter, committed, counters), + distribution -> addMetricToResultMap(metricKey, distribution, committed, distributions), + gauge -> addMetricToResultMap(metricKey, gauge, committed, gauges)); + } + + private void addMetricToResultMap( + MetricKey key, T value, Boolean committed, Map> map) { + if (committed) { + MetricResultBuilder builder = map.get(key); + if (builder == null) { + throw new IllegalStateException( + String.format("No attempted value found for committed metric %s: %s", key, value)); + } + builder.setCommitted(value); + } else { + map.put(key, new MetricResultBuilder(key, value)); + } + } + + /** + * Helper class for storing and combining {@link MetricResult#getAttempted attempted} and {@link + * MetricResult#getCommitted committed} values, to obtain complete {@link MetricResult}s. + * + *

Used while traversing {@link MonitoringInfo} lists where they are stored separately. + */ + private static class MetricResultBuilder { + private final MetricKey key; + private final T attempted; + @Nullable private T committed; + + public MetricResultBuilder(MetricKey key, T attempted) { + this.key = key; + this.attempted = attempted; + } + + public void setCommitted(T committed) { + this.committed = committed; + } + + public MetricResult build() { + return MetricResult.create(key, committed, attempted); + } + } + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java index 4583c9ddbf40..e2e8a34f41e7 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java @@ -23,9 +23,11 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import javax.annotation.Nullable; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; @@ -39,9 +41,9 @@ public class MonitoringInfoMetricName extends MetricName { private String urn; @Nullable private String name; @Nullable private String namespace; - private HashMap labels = new HashMap(); + private Map labels = new HashMap(); - private MonitoringInfoMetricName(String urn, HashMap labels) { + private MonitoringInfoMetricName(String urn, Map labels) { checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); checkArgument(labels != null, "MonitoringInfoMetricName labels must be non-null"); // TODO(ajamato): Move SimpleMonitoringInfoBuilder to beam-runner-core-construction-java @@ -85,14 +87,19 @@ public String getUrn() { } /** @return The labels associated with this MonitoringInfo. */ - public HashMap getLabels() { + public Map getLabels() { return this.labels; } - public static MonitoringInfoMetricName named(String urn, HashMap labels) { + public static MonitoringInfoMetricName named(String urn, Map labels) { return new MonitoringInfoMetricName(urn, labels); } + /** @return a MetricName for a specific urn and labels map. */ + public static MetricName create(MonitoringInfo monitoringInfo) { + return named(monitoringInfo.getUrn(), monitoringInfo.getLabelsMap()); + } + @Override public int hashCode() { // Don't include name and namespace, since they are lazily set. diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java new file mode 100644 index 000000000000..7afd02923b29 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java @@ -0,0 +1,108 @@ +/* + * 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.DistributionProtos.fromProto; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.LATEST_INT64_TYPE_URN; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.SUM_INT64_TYPE_URN; + +import java.util.function.Consumer; +import org.apache.beam.model.pipeline.v1.MetricsApi; +import org.apache.beam.model.pipeline.v1.MetricsApi.Metric; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +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.vendor.grpc.v1p13p1.com.google.protobuf.Timestamp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Helpers for working with {@link Metric}s and converting {@link MonitoringInfo}s to {@link + * MetricKey}s. + */ +public class MonitoringInfos { + private static final Logger LOG = LoggerFactory.getLogger(MonitoringInfos.class); + + /** + * Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution, + * or gauge), and gracefully dropping / warning about unexpected and unsupported states. + */ + public static void forEachMetricType( + Metric metric, + String type, + Timestamp timestamp, + Consumer counterFn, + Consumer distributionFn, + Consumer gaugeFn) { + Metric.DataCase dataCase = metric.getDataCase(); + switch (dataCase) { + case COUNTER_DATA: + MetricsApi.CounterData counterData = metric.getCounterData(); + switch (counterData.getValueCase()) { + case INT64_VALUE: + long value = counterData.getInt64Value(); + if (type.equals(SUM_INT64_TYPE_URN)) { + counterFn.accept(value); + } else if (type.equals(LATEST_INT64_TYPE_URN)) { + gaugeFn.accept(GaugeProtos.fromProto(value, timestamp)); + } else { + LOG.warn("Unsupported counter metric type ({}): {}", type, metric); + } + break; + case DOUBLE_VALUE: + case STRING_VALUE: + LOG.warn("Unsupported metric type: {}", metric); + break; + case VALUE_NOT_SET: + throw new IllegalStateException("Counter value not set: " + metric); + } + break; + case DISTRIBUTION_DATA: + MetricsApi.DistributionData distributionData = metric.getDistributionData(); + switch (distributionData.getDistributionCase()) { + case INT_DISTRIBUTION_DATA: + distributionFn.accept(fromProto(distributionData.getIntDistributionData())); + break; + case DOUBLE_DISTRIBUTION_DATA: + LOG.warn("Unsupported metric type (double distribution): {}", metric); + break; + case DISTRIBUTION_NOT_SET: + throw new IllegalStateException("Distribution value not set: " + metric); + } + break; + case EXTREMA_DATA: + LOG.warn("Unsupported metric type (extrema): {}", metric); + break; + case DATA_NOT_SET: + throw new IllegalStateException("Metric value not set: " + metric); + } + } + + /** + * Create a {@link MetricKey} from a {@link MonitoringInfo} + * + *

Could be moved to {@link MetricKey}, but kept separate here for now while some metrics + * package/module-dependency questions are being resolved. + */ + public static MetricKey keyFromMonitoringInfo(MonitoringInfo monitoringInfo) { + String ptransform = monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL); + return MetricKey.create(ptransform, MonitoringInfoMetricName.create(monitoringInfo)); + } +} diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/SimpleMonitoringInfoBuilder.java index 92893d908f76..f48c8e815b3e 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 @@ -19,10 +19,12 @@ 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.runners.core.metrics.DistributionProtos.toProto; import java.time.Instant; import java.util.HashMap; import javax.annotation.Nullable; +import org.apache.beam.model.pipeline.v1.MetricsApi.IntDistributionData; 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; @@ -31,6 +33,11 @@ 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.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.vendor.grpc.v1p13p1.com.google.protobuf.Timestamp; import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -72,6 +79,10 @@ public class SimpleMonitoringInfoBuilder { BeamUrns.getUrn(MonitoringInfoUrns.Enum.USER_COUNTER_URN_PREFIX); public static final String SUM_INT64_TYPE_URN = BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.SUM_INT64_TYPE); + public static final String DISTRIBUTION_INT64_TYPE_URN = + BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.DISTRIBUTION_INT64_TYPE); + public static final String LATEST_INT64_TYPE_URN = + BeamUrns.getUrn(MonitoringInfoTypeUrns.Enum.LATEST_INT64_TYPE); private static final HashMap specs = new HashMap(); @@ -137,6 +148,23 @@ public SimpleMonitoringInfoBuilder setUrn(String urn) { return this; } + public SimpleMonitoringInfoBuilder setLabelsAndUrnFrom(MetricKey key) { + MetricName metricName = key.metricName(); + if (metricName instanceof MonitoringInfoMetricName) { + MonitoringInfoMetricName name = (MonitoringInfoMetricName) metricName; + builder.setUrn(name.getUrn()).putAllLabels(name.getLabels()); + } else { + setUrnForUserMetric(metricName.getNamespace(), metricName.getName()); + String ptransform = key.stepName(); + if (ptransform != null) { + setPTransformLabel(ptransform); + } else { + LOG.warn("User metric {} without step name set", metricName); + } + } + return this; + } + /** * Sets the urn of the MonitoringInfo to a proper user metric URN for the given params. * @@ -148,17 +176,21 @@ public SimpleMonitoringInfoBuilder setUrnForUserMetric(String namespace, String return this; } + /** Sets the timestamp of the MonitoringInfo to the specified time. */ + public SimpleMonitoringInfoBuilder setTimestamp(Instant instant) { + this.builder.setTimestamp( + Timestamp.newBuilder().setSeconds(instant.getEpochSecond()).setNanos(instant.getNano())); + return this; + } + /** Sets the timestamp of the MonitoringInfo to the current time. */ public SimpleMonitoringInfoBuilder setTimestampToNow() { - Instant time = Instant.now(); - this.builder.getTimestampBuilder().setSeconds(time.getEpochSecond()).setNanos(time.getNano()); - return this; + return setTimestamp(Instant.now()); } /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropriate type URN. */ public SimpleMonitoringInfoBuilder setInt64Value(long value) { - this.builder.getMetricBuilder().getCounterDataBuilder().setInt64Value(value); - this.setInt64TypeUrn(); + this.setInt64TypeUrn().builder.getMetricBuilder().getCounterDataBuilder().setInt64Value(value); return this; } @@ -168,17 +200,51 @@ public SimpleMonitoringInfoBuilder setInt64TypeUrn() { return this; } + public SimpleMonitoringInfoBuilder setIntDistributionValue(DistributionData value) { + return setIntDistributionValue(value.extractResult()); + } + + public SimpleMonitoringInfoBuilder setIntDistributionValue(DistributionResult value) { + return setIntDistributionValue(toProto(value)); + } + + /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropraite type URN. */ + public SimpleMonitoringInfoBuilder setIntDistributionValue(IntDistributionData value) { + this.builder + .setType(DISTRIBUTION_INT64_TYPE_URN) + .getMetricBuilder() + .getDistributionDataBuilder() + .setIntDistributionData(value); + return this; + } + + public SimpleMonitoringInfoBuilder setGaugeValue(GaugeData value) { + return setGaugeValue(value.extractResult()); + } + + public SimpleMonitoringInfoBuilder setGaugeValue(GaugeResult value) { + return setGaugeValue(value.getValue()); + } + + /** Sets the int64Value of the CounterData in the MonitoringInfo, and the appropraite type URN. */ + public SimpleMonitoringInfoBuilder setGaugeValue(long value) { + this.builder + .setType(LATEST_INT64_TYPE_URN) + .getMetricBuilder() + .getCounterDataBuilder() + .setInt64Value(value); + return this; + } + /** Sets the PTRANSFORM MonitoringInfo label to the given param. */ public SimpleMonitoringInfoBuilder setPTransformLabel(String pTransform) { // TODO(ajamato): Add validation that it is a valid pTransform name in the bundle descriptor. - setLabel(PTRANSFORM_LABEL, pTransform); - return this; + return setLabel(PTRANSFORM_LABEL, pTransform); } /** Sets the PCOLLECTION MonitoringInfo label to the given param. */ public SimpleMonitoringInfoBuilder setPCollectionLabel(String pCollection) { - setLabel(PCOLLECTION_LABEL, pCollection); - return this; + return setLabel(PCOLLECTION_LABEL, pCollection); } /** Sets the MonitoringInfo label to the given name and value. */ From 68fad482401e813b8ae994a631930a1e62e11d0c Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 10 Feb 2019 17:39:48 +0000 Subject: [PATCH 05/14] InMemoryJobService.getJobMetrics --- .../jobsubmission/InMemoryJobService.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java index 642d3bd56343..98b316db247e 100644 --- a/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java +++ b/runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/jobsubmission/InMemoryJobService.java @@ -17,6 +17,8 @@ */ package org.apache.beam.runners.fnexecution.jobsubmission; +import static org.apache.beam.runners.core.metrics.MetricResultsProtos.toProto; + import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -26,6 +28,8 @@ import org.apache.beam.model.jobmanagement.v1.JobApi.CancelJobResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.DescribePipelineOptionsRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.DescribePipelineOptionsResponse; +import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobMetricsRequest; +import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobMetricsResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateRequest; import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateResponse; import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessage; @@ -42,6 +46,7 @@ import org.apache.beam.runners.fnexecution.FnService; import org.apache.beam.sdk.fn.stream.SynchronizedStreamObserver; import org.apache.beam.sdk.function.ThrowingConsumer; +import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.Struct; import org.apache.beam.vendor.grpc.v1p13p1.io.grpc.Status; @@ -330,6 +335,29 @@ public void describePipelineOptions( } } + @Override + public void getJobMetrics( + GetJobMetricsRequest request, StreamObserver responseObserver) { + String invocationId = request.getJobId(); + LOG.info("Running getJobMetrics for {}", invocationId); + try { + JobInvocation invocation = getInvocation(invocationId); + LOG.info("Found job invocation for metrics: {}", invocation); + MetricResults metrics = invocation.getMetrics(); + LOG.info("Got metrics: {}", metrics); + GetJobMetricsResponse response = + GetJobMetricsResponse.newBuilder().setMetrics(toProto(metrics)).build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (Exception e) { + String errMessage = + String.format("Encountered unexpected Exception for Invocation %s", invocationId); + LOG.error(errMessage, e); + responseObserver.onError(Status.INTERNAL.withCause(e).asException()); + } + LOG.info("Finished getJobMetrics for {}", invocationId); + } + @Override public void close() throws Exception { // TODO: throw error if jobs are running From ef3212d838518c89f8366e933648aa5451453328 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 10 Feb 2019 17:40:26 +0000 Subject: [PATCH 06/14] JobServicePipelineResult.metrics() --- runners/reference/java/build.gradle | 1 + .../runners/reference/CloseableResource.java | 2 +- .../reference/JobServicePipelineResult.java | 20 ++++++++++++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/runners/reference/java/build.gradle b/runners/reference/java/build.gradle index 87a61332fe56..6881cb281a4b 100644 --- a/runners/reference/java/build.gradle +++ b/runners/reference/java/build.gradle @@ -33,6 +33,7 @@ dependencies { compile library.java.hamcrest_library shadow project(path: ":beam-model-pipeline", configuration: "shadow") shadow project(path: ":beam-runners-core-construction-java", configuration: "shadow") + shadow project(path: ":beam-runners-core-java", configuration: "shadow") shadow project(path: ":beam-runners-java-fn-execution", configuration: "shadow") shadow project(path: ":beam-sdks-java-fn-execution", configuration: "shadow") shadow project(path: ":beam-sdks-java-harness", configuration: "shadow") diff --git a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/CloseableResource.java b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/CloseableResource.java index 96ba29464266..c1de06488f0b 100644 --- a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/CloseableResource.java +++ b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/CloseableResource.java @@ -65,7 +65,7 @@ public static CloseableResource of(T resource, Closer closer) { /** Gets the underlying resource. */ public T get() { checkState(closer != null, "%s has transferred ownership", CloseableResource.class.getName()); - checkState(!isClosed, "% is closed", CloseableResource.class.getName()); + checkState(!isClosed, "%s is closed", CloseableResource.class.getName()); return resource; } diff --git a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java index fe7701abeb0f..efe24c73f1e6 100644 --- a/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java +++ b/runners/reference/java/src/main/java/org/apache/beam/runners/reference/JobServicePipelineResult.java @@ -17,6 +17,8 @@ */ package org.apache.beam.runners.reference; +import static org.apache.beam.runners.core.metrics.MetricResultsProtos.fromProto; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -45,6 +47,7 @@ class JobServicePipelineResult implements PipelineResult, AutoCloseable { private final CloseableResource jobService; @Nullable private State terminationState; @Nullable private Runnable cleanup; + @Nullable private MetricResults metricResults; JobServicePipelineResult( ByteString jobId, CloseableResource jobService, Runnable cleanup) { @@ -121,12 +124,27 @@ public State waitUntilFinish() { @Override public MetricResults metrics() { - throw new UnsupportedOperationException("Not yet implemented."); + if (metricResults == null) { + LOG.info("Fetching MetricResults"); + JobApi.GetJobMetricsResponse response = + jobService + .get() + .getJobMetrics(JobApi.GetJobMetricsRequest.newBuilder().setJobIdBytes(jobId).build()); + + metricResults = fromProto(response.getMetrics()); + LOG.info("Received MetricResults: {}", metricResults); + return metricResults; + } + LOG.info("Returning MetricResults: {}", metricResults); + return metricResults; } @Override public void close() { + LOG.info("Cleaning up job service…"); try (CloseableResource jobService = this.jobService) { + metrics(); + LOG.info("Got metrics during cleanup"); if (cleanup != null) { cleanup.run(); } From 1722076fe11ffefd0dca9aeeba22788b7f2562c8 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sun, 10 Feb 2019 17:42:40 +0000 Subject: [PATCH 07/14] python portable metrics --- sdks/python/apache_beam/metrics/execution.py | 10 ++ .../runners/portability/portable_runner.py | 100 ++++++++++++++++-- 2 files changed, 102 insertions(+), 8 deletions(-) diff --git a/sdks/python/apache_beam/metrics/execution.py b/sdks/python/apache_beam/metrics/execution.py index ba190ff981e9..860eb9f12b56 100644 --- a/sdks/python/apache_beam/metrics/execution.py +++ b/sdks/python/apache_beam/metrics/execution.py @@ -40,6 +40,8 @@ from apache_beam.metrics.cells import CounterCell from apache_beam.metrics.cells import DistributionCell from apache_beam.metrics.cells import GaugeCell +from apache_beam.metrics.metricbase import MetricName +from apache_beam.metrics.monitoring_infos import parse_namespace_and_name from apache_beam.metrics.monitoring_infos import user_metric_urn from apache_beam.portability.api import beam_fn_api_pb2 from apache_beam.runners.worker import statesampler @@ -79,6 +81,14 @@ def __repr__(self): def __hash__(self): return hash((self.step, self.metric)) + @classmethod + def from_monitoring_info(cls, monitoring_info_proto): + # TODO: use canonical string + ptransform = monitoring_info_proto.labels['PTRANSFORM'] + namespace, name = parse_namespace_and_name(monitoring_info_proto) + metric_name = MetricName(namespace, name) + return MetricKey(ptransform, metric_name) + class MetricResult(object): """Keeps track of the status of a metric within a single bundle. diff --git a/sdks/python/apache_beam/runners/portability/portable_runner.py b/sdks/python/apache_beam/runners/portability/portable_runner.py index 97d9c01a5899..2cfe0209560e 100644 --- a/sdks/python/apache_beam/runners/portability/portable_runner.py +++ b/sdks/python/apache_beam/runners/portability/portable_runner.py @@ -28,7 +28,12 @@ import grpc -from apache_beam import metrics +from apache_beam.metrics.cells import DistributionResult +from apache_beam.metrics.execution import MetricKey +from apache_beam.metrics.execution import MetricResult +from apache_beam.metrics.metric import MetricResults +from apache_beam.metrics.monitoring_infos import LATEST_INT64_TYPE +from apache_beam.metrics.monitoring_infos import SUM_INT64_TYPE from apache_beam.options.pipeline_options import DebugOptions from apache_beam.options.pipeline_options import PortableOptions from apache_beam.options.pipeline_options import SetupOptions @@ -320,14 +325,88 @@ def add_runner_options(parser): state_stream, cleanup_callbacks) -class PortableMetrics(metrics.metric.MetricResults): - def __init__(self): - pass +class PortableMetrics(MetricResults): + + @classmethod + def add_monitoring_info(cls, metric_key, value, committed, metrics): + if committed: + if not metric_key in metrics: + raise Exception( + 'No attempted value found preceding committed metrics value: ' + \ + '%s -> %s' % ( + metric_key, + value + ) + ) + metrics[metric_key].committed = value + else: + metrics[metric_key] = MetricResult(metric_key, None, value) + + def add_monitoring_infos(self, monitoring_infos, committed): + for monitoring_info in monitoring_infos: + metric_key = MetricKey.from_monitoring_info(monitoring_info) + if not monitoring_info.HasField('metric'): + continue + + metric = monitoring_info.metric + if metric.HasField('counter_data'): + counter_data = metric.counter_data + if counter_data.HasField('int64_value'): + int_counter_data = counter_data.int64_value + if monitoring_info.type == SUM_INT64_TYPE: + self.add_monitoring_info( + metric_key, int_counter_data, committed, self.counters) + elif monitoring_info.type == LATEST_INT64_TYPE: + self.add_monitoring_info( + metric_key, int_counter_data, committed, self.gauges) + else: + logging.warning( + "Unsupported counter type %s: %s" % ( + monitoring_info.type, monitoring_info)) + else: + logging.info("Dropping unsupported counter metric: %s" % metric) + elif metric.HasField('distribution_data'): + distribution_data = metric.distribution_data + if distribution_data.HasField('int_distribution_data'): + distribution = distribution_data.int_distribution_data + elif distribution_data.HasField('double_distribution_data'): + distribution = distribution_data.double_distribution_data + else: + logging.error( + "Valud not set on distribution_data: %s" % monitoring_info) + continue + distribution_result = DistributionResult(distribution) + self.add_monitoring_info( + metric_key, distribution_result, committed, self.distributions) + elif metric.HasField('extrema_data'): + logging.info( + "Unsupported metric type (extrema_data): %s" % monitoring_info) + else: + raise Exception('Metric value not set for key: %s' % metric_key) + + def __init__(self, job_metrics_response): + self.counters = {} + self.distributions = {} + self.gauges = {} + + # Process "attempted" metrics + self.add_monitoring_infos(job_metrics_response.metrics.attempted, False) + self.add_monitoring_infos(job_metrics_response.metrics.committed, True) + + @staticmethod + def _query_type(filter, metrics): + return [ + data + for key, data in metrics.items() + if MetricResults.matches(filter, key) + ] def query(self, filter=None): - return {'counters': [], - 'distributions': [], - 'gauges': []} + return { + 'counters': self._query_type(filter, self.counters), + 'distributions': self._query_type(filter, self.distributions), + 'gauges': self._query_type(filter, self.gauges) + } class PipelineResult(runner.PipelineResult): @@ -341,6 +420,7 @@ def __init__(self, job_service, job_id, message_stream, state_stream, self._message_stream = message_stream self._state_stream = state_stream self._cleanup_callbacks = cleanup_callbacks + self._metrics = None def cancel(self): try: @@ -366,7 +446,11 @@ def _pipeline_state_to_runner_api_state(pipeline_state): return beam_job_api_pb2.JobState.Enum.Value(pipeline_state) def metrics(self): - return PortableMetrics() + if not self._metrics: + job_metrics_response = self._job_service.GetJobMetrics( + beam_job_api_pb2.GetJobMetricsRequest(job_id=self._job_id)) + self._metrics = PortableMetrics(job_metrics_response) + return self._metrics def _last_error_message(self): # Filter only messages with the "message_response" and error messages. From 681a9c014e8d4f0aed6f2399af536dda50c5d3e7 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Wed, 27 Feb 2019 20:39:09 +0000 Subject: [PATCH 08/14] MetricUpdatesProtos: convert MetricUpdates to MonitoringInfos --- .../core/metrics/MetricUpdatesProtos.java | 66 +++++++++++++++++++ .../core/metrics/MetricsContainerImpl.java | 50 ++------------ .../core/metrics/MetricsContainerStepMap.java | 4 +- .../metrics/MetricsContainerStepMapTest.java | 34 ++++++++-- 4 files changed, 100 insertions(+), 54 deletions(-) create mode 100644 runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java new file mode 100644 index 000000000000..60cba7248336 --- /dev/null +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java @@ -0,0 +1,66 @@ +/* + * 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 java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; +import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +import org.apache.beam.sdk.metrics.MetricKey; + +/** Convert {@link MetricUpdates} to a {@link List} of {@link MonitoringInfo}. */ +public class MetricUpdatesProtos { + public static List toProto(MetricUpdates metricUpdates) { + ArrayList monitoringInfos = new ArrayList<>(); + + fromMetrics( + monitoringInfos, + metricUpdates.counterUpdates(), + SimpleMonitoringInfoBuilder::setInt64Value); + fromMetrics( + monitoringInfos, + metricUpdates.distributionUpdates(), + SimpleMonitoringInfoBuilder::setIntDistributionValue); + fromMetrics( + monitoringInfos, metricUpdates.gaugeUpdates(), SimpleMonitoringInfoBuilder::setGaugeValue); + + return monitoringInfos; + } + + private static MonitoringInfo addMetric( + MetricUpdates.MetricUpdate metricUpdate, BiConsumer fn) { + SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(true); + MetricKey metricKey = metricUpdate.getKey(); + builder.setLabelsAndUrnFrom(metricKey); + + fn.accept(builder, metricUpdate.getUpdate()); + return builder.setTimestampToNow().build(); + } + + private static void fromMetrics( + ArrayList monitoringInfos, + Iterable> metrics, + BiConsumer fn) { + for (MetricUpdates.MetricUpdate metric : metrics) { + MonitoringInfo monitoringInfo = addMetric(metric, fn); + if (monitoringInfo != null) { + monitoringInfos.add(monitoringInfo); + } + } + } +} 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..360367f0ca6a 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 @@ -17,12 +17,12 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.runners.core.metrics.MetricUpdatesProtos.toProto; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; -import java.util.ArrayList; +import java.util.List; 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; @@ -139,51 +139,9 @@ public MetricUpdates getUpdates() { extractUpdates(counters), extractUpdates(distributions), extractUpdates(gauges)); } - /** - * @param metricUpdate - * @return The MonitoringInfo generated from the metricUpdate. - */ - @Nullable - private MonitoringInfo counterUpdateToMonitoringInfo(MetricUpdate 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 the cumulative values for any metrics in this container as MonitoringInfos. */ - public Iterable getMonitoringInfos() { - // Extract user metrics and store as MonitoringInfos. - ArrayList monitoringInfos = new ArrayList(); - MetricUpdates metricUpdates = this.getUpdates(); - - for (MetricUpdate metricUpdate : metricUpdates.counterUpdates()) { - MonitoringInfo mi = counterUpdateToMonitoringInfo(metricUpdate); - if (mi != null) { - monitoringInfos.add(counterUpdateToMonitoringInfo(metricUpdate)); - } - } - return monitoringInfos; + public List getMonitoringInfos() { + return toProto(getUpdates()); } private void commitUpdates(MetricsMap> cells) { 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..c15c274d07cb 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 @@ -159,9 +159,7 @@ public Iterable getMonitoringInfos() { // Extract user metrics and store as MonitoringInfos. ArrayList monitoringInfos = new ArrayList<>(); for (MetricsContainerImpl container : getMetricsContainers()) { - for (MonitoringInfo mi : container.getMonitoringInfos()) { - monitoringInfos.add(mi); - } + monitoringInfos.addAll(container.getMonitoringInfos()); } return monitoringInfos; } 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..3895dee50528 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 @@ -17,8 +17,13 @@ */ package org.apache.beam.runners.core.metrics; +import static java.util.stream.Collectors.toList; +import static java.util.stream.StreamSupport.stream; 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.SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.clearTimestamp; import static org.apache.beam.sdk.metrics.MetricResultsMatchers.metricsResult; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; @@ -27,7 +32,9 @@ import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Distribution; @@ -178,13 +185,30 @@ public void testGaugeCommittedUnsupportedInAttemptedAccumulatedMetricResults() { } @Test - public void testUserMetricDroppedOnUnbounded() { + public void testSystemMetricInUnboundedContainer() { MetricsContainerStepMap testObject = new MetricsContainerStepMap(); - CounterCell c1 = testObject.getUnboundContainer().getCounter(MetricName.named("ns", "name1")); + Map labels = new HashMap<>(); + labels.put(PCOLLECTION_LABEL, "pcoll"); + CounterCell c1 = + testObject + .getUnboundContainer() + .getCounter(MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels)); c1.inc(5); - List expected = new ArrayList(); - assertThat(testObject.getMonitoringInfos(), containsInAnyOrder(expected.toArray())); + MonitoringInfo[] expected = { + clearTimestamp( + new SimpleMonitoringInfoBuilder() + .setUrn(ELEMENT_COUNT_URN) + .setInt64TypeUrn() + .setPCollectionLabel("pcoll") + .setInt64Value(5) + .build()) + }; + assertThat( + stream(testObject.getMonitoringInfos().spliterator(), false) + .map(SimpleMonitoringInfoBuilder::clearTimestamp) + .collect(toList()), + containsInAnyOrder(expected)); } @Test @@ -217,7 +241,7 @@ public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { ArrayList actual = new ArrayList(); for (MonitoringInfo mi : testObject.getMonitoringInfos()) { - actual.add(SimpleMonitoringInfoBuilder.clearTimestamp(mi)); + actual.add(clearTimestamp(mi)); } assertThat(actual, containsInAnyOrder(expected.toArray())); } From 16b543218fb98c842002094479c52ec84c7d57f3 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 22 Feb 2019 21:09:18 +0000 Subject: [PATCH 09/14] MetricName.toString(String delimiter) --- .../metrics/MonitoringInfoMetricName.java | 29 +++++++++++++++---- .../apache/beam/sdk/metrics/MetricKey.java | 19 +++++++++++- .../apache/beam/sdk/metrics/MetricName.java | 6 +++- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java index e2e8a34f41e7..b05255db69cf 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.core.metrics; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; import java.util.ArrayList; @@ -28,6 +29,7 @@ import java.util.Objects; import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +import org.apache.beam.sdk.metrics.MetricKey; import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings; @@ -119,12 +121,27 @@ public boolean equals(Object o) { return this.urn.equals(other.urn) && this.labels.equals(other.labels); } + /** + * String-representation of this {@link MonitoringInfoMetricName} with a custom delimiter. + * + *

See discussion on {@link MetricKey#toString}; metric "label" info is currently split between + * {@link MetricKey#stepName} and {@link MonitoringInfoMetricName#labels} (the former holds {@link + * SimpleMonitoringInfoBuilder#PTRANSFORM_LABEL ptransform} info, and the latter {@link + * SimpleMonitoringInfoBuilder#PCOLLECTION_LABEL info}. + * + *

For now, we bake in the assumption here that {@link MonitoringInfoMetricName#toString} is + * only responsible for inlining the pcollection label to the string representation. + * + *

Later, {@link MonitoringInfoMetricName} and {@link MetricKey} will be merged, and this + * handling unified. + */ @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(this.urn.toString()); - builder.append(" "); - builder.append(this.labels.toString()); - return builder.toString(); + public String toString(String delimiter) { + StringBuilder sb = new StringBuilder(); + if (labels.containsKey(PCOLLECTION_LABEL)) { + sb.append(labels.get(PCOLLECTION_LABEL)).append(delimiter); + } + sb.append(urn.replaceAll(":", delimiter)); + return sb.toString(); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java index 323e246e7a81..e75c74b6cd6b 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricKey.java @@ -37,7 +37,24 @@ public abstract class MetricKey implements Serializable { @Override public String toString() { - return String.format("%s:%s", stepName(), metricName()); + return toString(":"); + } + + /** + * Convenient representation of a metric's identifying information, with an arbitrary delimiter. + * + *

Metrics currently have either a {@link MetricKey#stepName ptransform-scope} or a + * pcollection-scope; whichever label is present has its value inlined in this string + * representation as the first delimited segment. + * + *

These two metric scopes are currently stored in different places, with only the + * ptransform-scope handled here, but will be unified in the future. + */ + public String toString(String delimiter) { + if (stepName() == null) { + return metricName().toString(delimiter); + } + return String.join(delimiter, stepName(), metricName().toString(delimiter)); } public static MetricKey create(@Nullable String stepName, MetricName metricName) { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java index ae23ff0c23bd..98571a4c65ae 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricName.java @@ -52,7 +52,11 @@ public String namespace() { @Override public String toString() { - return String.format("%s:%s", getNamespace(), getName()); + return toString(":"); + } + + public String toString(String delimiter) { + return String.join(delimiter, getNamespace(), getName()); } /** From af94f44de918bbfb30bef5874a9816e24665329f Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 22 Feb 2019 21:10:05 +0000 Subject: [PATCH 10/14] polymorphic MetricName ctor --- .../runners/core/metrics/LabeledMetrics.java | 3 +- .../beam/runners/core/metrics/MetricUrns.java | 4 +++ .../metrics/MonitoringInfoMetricName.java | 22 +++++++++++--- .../core/metrics/LabeledMetricsTest.java | 5 ++-- .../metrics/MetricsContainerStepMapTest.java | 8 ++--- .../metrics/MonitoringInfoMetricNameTest.java | 30 ++++++++++--------- .../core/metrics/MonitoringInfoTestUtil.java | 10 +++---- .../data/ElementCountFnDataReceiver.java | 10 ++++--- 8 files changed, 58 insertions(+), 34 deletions(-) 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 index ba47812ddf78..841fb770db77 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUrns.java @@ -19,6 +19,7 @@ import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX; +import javax.annotation.Nullable; import org.apache.beam.sdk.metrics.MetricName; /** Utility for parsing a URN to a {@link MetricName}. */ @@ -29,9 +30,12 @@ public class MetricUrns { * *

Should be consistent with {@code parse_namespace_and_name} in monitoring_infos.py. */ + @Nullable public static MetricName parseUrn(String urn) { if (urn.startsWith(USER_COUNTER_URN_PREFIX)) { urn = urn.substring(USER_COUNTER_URN_PREFIX.length()); + } else { + return null; } // If it is not a user counter, just use the first part of the URN, i.e. 'beam' String[] pieces = urn.split(":", 2); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java index b05255db69cf..6587a74fea88 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java @@ -46,8 +46,6 @@ public class MonitoringInfoMetricName extends MetricName { private Map labels = new HashMap(); private MonitoringInfoMetricName(String urn, Map labels) { - checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); - checkArgument(labels != null, "MonitoringInfoMetricName labels must be non-null"); // TODO(ajamato): Move SimpleMonitoringInfoBuilder to beam-runner-core-construction-java // and ensure all necessary labels are set for the specific URN. this.urn = urn; @@ -93,8 +91,24 @@ public Map getLabels() { return this.labels; } - public static MonitoringInfoMetricName named(String urn, Map labels) { - return new MonitoringInfoMetricName(urn, labels); + /** + * Polymorphic constructor of {@link MetricName}s. + * + *

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

Otherwise, return a concrete {@link MonitoringInfoMetricName} representing a "system" + * metric. + */ + public static MetricName named(String urn, Map labels) { + checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty"); + checkArgument(labels != null, "MonitoringInfoMetricName labels must be non-null"); + MetricName metricName = MetricUrns.parseUrn(urn); + if (metricName == null) { + return new MonitoringInfoMetricName(urn, labels); + } + return metricName; } /** @return a MetricName for a specific urn and labels map. */ diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java index c1704aa63d00..3bde94f2ed13 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/LabeledMetricsTest.java @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.HashMap; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.junit.Rule; @@ -42,7 +43,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { assertNull(MetricsEnvironment.getCurrentContainer()); HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); Counter counter = LabeledMetrics.counter(name); counter.inc(); @@ -55,7 +56,7 @@ public void testCounterDoesNotFailOperationsWhenNoMetricsContainerPresent() { public void testOperationsUpdateCounterFromContainerWhenContainerIsPresent() { HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); MetricsContainer mockContainer = Mockito.mock(MetricsContainer.class); Counter mockCounter = Mockito.mock(Counter.class); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMapTest.java index 3895dee50528..2246c74efa9a 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 @@ -21,6 +21,8 @@ import static java.util.stream.StreamSupport.stream; 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.MonitoringInfoTestUtil.testElementCountName; import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.clearTimestamp; @@ -218,9 +220,7 @@ public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { CounterCell c1 = baseMetricContainerRegistry.getContainer(STEP1).getCounter(MetricName.named("ns", "name1")); CounterCell c2 = - baseMetricContainerRegistry - .getUnboundContainer() - .getCounter(MonitoringInfoTestUtil.testElementCountName()); + baseMetricContainerRegistry.getUnboundContainer().getCounter(testElementCountName()); c1.inc(7); c2.inc(14); @@ -236,7 +236,7 @@ public void testUpdateAllUpdatesUnboundedAndBoundedContainers() { builder.setInt64Value(7); expected.add(builder.build()); - expected.add(MonitoringInfoTestUtil.testElementCountMonitoringInfo(14)); + expected.add(testElementCountMonitoringInfo(14)); ArrayList actual = new ArrayList(); diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java index 13dd79d853c8..e1deac4ef5b5 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricNameTest.java @@ -19,9 +19,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import java.io.Serializable; import java.util.HashMap; +import org.apache.beam.sdk.metrics.MetricName; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -35,9 +37,10 @@ public class MonitoringInfoMetricNameTest implements Serializable { 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()); + MonitoringInfoMetricName name = + (MonitoringInfoMetricName) MonitoringInfoMetricName.named(urn, labels); + assertNull(name.getName()); + assertNull(name.getNamespace()); assertEquals(labels, name.getLabels()); assertEquals(urn, name.getUrn()); @@ -46,7 +49,7 @@ public void testElementCountConstruction() { // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -56,18 +59,16 @@ public void testElementCountConstruction() { public void testUserCounterUrnConstruction() { String urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); HashMap labels = new HashMap(); - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); assertEquals("name", name.getName()); assertEquals("namespace", name.getNamespace()); - assertEquals(labels, name.getLabels()); - assertEquals(urn, name.getUrn()); assertEquals(name, name); // test self equals; // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.userMetricUrn("namespace", "name"); labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertEquals(name, name2); assertEquals(name.hashCode(), name2.hashCode()); @@ -77,13 +78,14 @@ public void testUserCounterUrnConstruction() { public void testNotEqualsDiffLabels() { HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MonitoringInfoMetricName name = + (MonitoringInfoMetricName) MonitoringInfoMetricName.named(urn, labels); // Reconstruct and test equality and hash code equivalence urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - labels = new HashMap(); + labels = new HashMap<>(); labels.put("label", "value1"); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertNotEquals(name, name2); assertNotEquals(name.hashCode(), name2.hashCode()); @@ -93,12 +95,12 @@ public void testNotEqualsDiffLabels() { public void testNotEqualsDiffUrn() { HashMap labels = new HashMap(); String urn = SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; - MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels); + MetricName name = MonitoringInfoMetricName.named(urn, labels); // Reconstruct and test equality and hash code equivalence urn = "differentUrn"; - labels = new HashMap(); - MonitoringInfoMetricName name2 = MonitoringInfoMetricName.named(urn, labels); + labels = new HashMap<>(); + MetricName name2 = MonitoringInfoMetricName.named(urn, labels); assertNotEquals(name, name2); assertNotEquals(name.hashCode(), name2.hashCode()); 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..2b40bc80d8c7 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MonitoringInfoTestUtil.java @@ -18,19 +18,19 @@ package org.apache.beam.runners.core.metrics; import java.util.HashMap; +import java.util.Map; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +import org.apache.beam.sdk.metrics.MetricName; /** * Provides convenient one line factories for unit tests that need to generate test MonitoringInfos. */ public class MonitoringInfoTestUtil { /** @return A basic MonitoringInfoMetricName to test. */ - public static MonitoringInfoMetricName testElementCountName() { - HashMap labels = new HashMap(); + public static MetricName testElementCountName() { + Map labels = new HashMap<>(); labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, "testPCollection"); - MonitoringInfoMetricName name = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); - return name; + return MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); } /** @return A basic MonitoringInfo which matches the testElementCountName. */ diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java index 3f4712262143..cd10bfbd6f08 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/ElementCountFnDataReceiver.java @@ -17,14 +17,17 @@ */ package org.apache.beam.fn.harness.data; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; + import java.io.Closeable; import java.util.HashMap; import org.apache.beam.runners.core.metrics.LabeledMetrics; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; import org.apache.beam.runners.core.metrics.MonitoringInfoMetricName; -import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder; import org.apache.beam.sdk.fn.data.FnDataReceiver; import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.MetricName; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.util.WindowedValue; @@ -47,9 +50,8 @@ public ElementCountFnDataReceiver( MetricsContainerStepMap metricContainerRegistry) { this.original = original; HashMap labels = new HashMap(); - labels.put(SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL, pCollection); - MonitoringInfoMetricName metricName = - MonitoringInfoMetricName.named(SimpleMonitoringInfoBuilder.ELEMENT_COUNT_URN, labels); + labels.put(PCOLLECTION_LABEL, pCollection); + MetricName metricName = MonitoringInfoMetricName.named(ELEMENT_COUNT_URN, labels); this.counter = LabeledMetrics.counter(metricName); // Collect the metric in a metric container which is not bound to the step name. // This is required to count elements from impulse steps, which will produce elements outside From 184b76b8d67c7d307a73b5e97864c6891997760e Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Thu, 28 Feb 2019 17:44:47 +0000 Subject: [PATCH 11/14] support system metrics in Flink --- .../core/metrics/MetricsContainerStepMap.java | 3 +- .../flink/metrics/FlinkMetricContainer.java | 181 +++++++++--------- .../FlinkExecutableStageFunction.java | 4 +- .../ExecutableStageDoFnOperator.java | 4 +- .../runners/flink/FlinkSavepointTest.java | 2 + .../metrics/FlinkMetricContainerTest.java | 93 ++++----- .../beam/sdk/metrics/MetricFiltering.java | 2 +- 7 files changed, 147 insertions(+), 142 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricsContainerStepMap.java index c15c274d07cb..d56cd8977b71 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 @@ -27,6 +27,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; +import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; import org.apache.beam.sdk.metrics.MetricKey; @@ -53,7 +54,7 @@ public MetricsContainerImpl getUnboundContainer() { } /** Returns the container for the given step name. */ - public MetricsContainerImpl getContainer(String stepName) { + public MetricsContainerImpl getContainer(@Nullable String stepName) { if (stepName == null) { // TODO(BEAM-6538): Disallow this in the future, some tests rely on an empty step name today. return getUnboundContainer(); 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..aabd18a2d847 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/metrics/FlinkMetricContainer.java @@ -17,21 +17,20 @@ */ package org.apache.beam.runners.flink.metrics; -import static org.apache.beam.runners.core.metrics.MetricUrns.parseUrn; import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults; +import static org.apache.beam.runners.core.metrics.MonitoringInfos.forEachMetricType; +import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.beam.model.pipeline.v1.MetricsApi.CounterData; -import org.apache.beam.model.pipeline.v1.MetricsApi.DistributionData; -import org.apache.beam.model.pipeline.v1.MetricsApi.ExtremaData; -import org.apache.beam.model.pipeline.v1.MetricsApi.IntDistributionData; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; import org.apache.beam.model.pipeline.v1.MetricsApi.Metric; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; -import org.apache.beam.sdk.metrics.Distribution; +import org.apache.beam.runners.core.metrics.MonitoringInfoMetricName; import org.apache.beam.sdk.metrics.DistributionResult; import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.sdk.metrics.MetricKey; @@ -41,13 +40,14 @@ import org.apache.beam.sdk.metrics.MetricResults; import org.apache.beam.sdk.metrics.MetricsContainer; import org.apache.beam.sdk.metrics.MetricsFilter; -import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting; import org.apache.flink.api.common.accumulators.Accumulator; import org.apache.flink.api.common.functions.RuntimeContext; import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.MetricOptions; import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.Gauge; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.util.function.TriFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -89,7 +89,7 @@ public FlinkMetricContainer(RuntimeContext runtimeContext) { this.metricsAccumulator = (MetricsAccumulator) metricsAccumulator; } - public MetricsContainer getMetricsContainer(String stepName) { + public MetricsContainer getMetricsContainer(@Nullable String stepName) { return metricsAccumulator != null ? metricsAccumulator.getLocalValue().getContainer(stepName) : null; @@ -99,43 +99,42 @@ public MetricsContainer getMetricsContainer(String stepName) { * Update this container with metrics from the passed {@link MonitoringInfo}s, and send updates * along to Flink's internal metrics framework. */ - public void updateMetrics(String stepName, List monitoringInfos) { - MetricsContainer metricsContainer = getMetricsContainer(stepName); + public void updateMetrics(List monitoringInfos) { monitoringInfos.forEach( monitoringInfo -> { - if (monitoringInfo.hasMetric()) { - String urn = monitoringInfo.getUrn(); - 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; } + MetricName metricName = MonitoringInfoMetricName.create(monitoringInfo); + @Nullable String ptransform = monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL); + MetricsContainer metricsContainer = getMetricsContainer(ptransform); + Metric metric = monitoringInfo.getMetric(); + MetricKey key = + MetricKey.create(monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL), metricName); + forEachMetricType( + metric, + monitoringInfo.getType(), + monitoringInfo.getTimestamp(), + counter -> { + metricsContainer.getCounter(metricName).inc(counter); + updateCounter(key, counter); + }, + distribution -> { + metricsContainer + .getDistribution(metricName) + .update( + distribution.getSum(), + distribution.getCount(), + distribution.getMin(), + distribution.getMax()); + updateDistribution(key, distribution); + }, + gauge -> { + metricsContainer.getGauge(metricName).set(gauge.getValue()); + updateGauge(key, gauge); + }); }); - updateMetrics(stepName); } /** @@ -146,70 +145,68 @@ void updateMetrics(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) { + fn.accept(metricResult.getKey(), metricResult.getAttempted()); } } - private void updateDistributions(Iterable> distributions) { - for (MetricResult metricResult : distributions) { - String flinkMetricName = getFlinkMetricNameString(metricResult.getKey()); - - DistributionResult update = metricResult.getAttempted(); - - // update flink metric - FlinkDistributionGauge gauge = flinkDistributionGaugeCache.get(flinkMetricName); - if (gauge == null) { - gauge = - runtimeContext - .getMetricGroup() - .gauge(flinkMetricName, new FlinkDistributionGauge(update)); - flinkDistributionGaugeCache.put(flinkMetricName, gauge); - } else { - gauge.update(update); - } + private void updateMetric( + MetricKey key, + Map flinkMetricMap, + TriFunction create, + BiConsumer update, + T value) { + String flinkMetricName = getFlinkMetricNameString(key); + + // update flink metric + FlinkT metric = flinkMetricMap.get(flinkMetricName); + if (metric == null) { + metric = create.apply(flinkMetricName, runtimeContext.getMetricGroup(), value); + flinkMetricMap.put(flinkMetricName, metric); } + update.accept(metric, value); } - private void updateGauge(Iterable> gauges) { - for (MetricResult metricResult : gauges) { - String flinkMetricName = getFlinkMetricNameString(metricResult.getKey()); + private void updateCounter(MetricKey metricKey, long attempted) { + updateMetric( + metricKey, + flinkCounterCache, + (name, group, value) -> group.counter(name), + (counter, value) -> { + counter.dec(counter.getCount()); + counter.inc(value); + }, + attempted); + } - GaugeResult update = metricResult.getAttempted(); + private void updateDistribution(MetricKey metricKey, DistributionResult attempted) { + updateMetric( + metricKey, + flinkDistributionGaugeCache, + (name, group, value) -> group.gauge(name, new FlinkDistributionGauge(value)), + FlinkDistributionGauge::update, + attempted); + } - // update flink metric - FlinkGauge gauge = flinkGaugeCache.get(flinkMetricName); - if (gauge == null) { - gauge = runtimeContext.getMetricGroup().gauge(flinkMetricName, new FlinkGauge(update)); - flinkGaugeCache.put(flinkMetricName, gauge); - } else { - gauge.update(update); - } - } + private void updateGauge(MetricKey metricKey, GaugeResult attempted) { + updateMetric( + metricKey, + flinkGaugeCache, + (name, group, value) -> group.gauge(name, new FlinkGauge(value)), + FlinkGauge::update, + attempted); } - @VisibleForTesting static String getFlinkMetricNameString(MetricKey metricKey) { - MetricName metricName = metricKey.metricName(); - // We use only the MetricName here, the step name is already contained - // in the operator name which is passed to Flink's MetricGroup to which - // the metric with the following name will be added. - return metricName.getNamespace() + METRIC_KEY_SEPARATOR + metricName.getName(); + return metricKey.toString(METRIC_KEY_SEPARATOR); } /** Flink {@link Gauge} for {@link DistributionResult}. */ diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java index e7dafa8968f8..bc943162f93c 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/functions/FlinkExecutableStageFunction.java @@ -151,12 +151,12 @@ public void open(Configuration parameters) throws Exception { new BundleProgressHandler() { @Override public void onProgress(ProcessBundleProgressResponse progress) { - container.updateMetrics(stageName, progress.getMonitoringInfosList()); + container.updateMetrics(progress.getMonitoringInfosList()); } @Override public void onCompleted(ProcessBundleResponse response) { - container.updateMetrics(stageName, response.getMonitoringInfosList()); + container.updateMetrics(response.getMonitoringInfosList()); } }; } diff --git a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java index 011cfc494702..a75f0a2c1a59 100644 --- a/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java +++ b/runners/flink/src/main/java/org/apache/beam/runners/flink/translation/wrappers/streaming/ExecutableStageDoFnOperator.java @@ -190,12 +190,12 @@ public void open() throws Exception { new BundleProgressHandler() { @Override public void onProgress(ProcessBundleProgressResponse progress) { - flinkMetricContainer.updateMetrics(stepName, progress.getMonitoringInfosList()); + flinkMetricContainer.updateMetrics(progress.getMonitoringInfosList()); } @Override public void onCompleted(ProcessBundleResponse response) { - flinkMetricContainer.updateMetrics(stepName, response.getMonitoringInfosList()); + flinkMetricContainer.updateMetrics(response.getMonitoringInfosList()); } }; diff --git a/runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkSavepointTest.java b/runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkSavepointTest.java index 41e929963bd0..8c4cd20d1ed2 100644 --- a/runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkSavepointTest.java +++ b/runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkSavepointTest.java @@ -134,6 +134,8 @@ public void testSavepointRestoreLegacy() throws Exception { runSavepointAndRestore(false); } + // TODO(ryan): make these fail when an exception is thrown (in the runner, I + // think?), instead of just timing out @Test(timeout = 60_000) public void testSavepointRestorePortable() throws Exception { runSavepointAndRestore(true); 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..1b95813103fd 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 @@ -18,6 +18,7 @@ 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.DISTRIBUTION_INT64_TYPE_URN; 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; @@ -88,13 +89,13 @@ public void beforeTest() { public void testMetricNameGeneration() { MetricKey key = MetricKey.create("step", MetricName.named("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"); @@ -112,7 +113,7 @@ public void testCounter() { public void testGauge() { FlinkMetricContainer.FlinkGauge flinkGauge = new FlinkMetricContainer.FlinkGauge(GaugeResult.empty()); - when(metricGroup.gauge(eq("namespace.name"), anyObject())).thenReturn(flinkGauge); + when(metricGroup.gauge(eq("step.namespace.name"), anyObject())).thenReturn(flinkGauge); FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); MetricsContainer step = container.getMetricsContainer("step"); @@ -131,32 +132,32 @@ public void testGauge() { @Test public void testMonitoringInfoUpdate() { FlinkMetricContainer container = new FlinkMetricContainer(runtimeContext); - MetricsContainer step = container.getMetricsContainer("step"); SimpleCounter userCounter = new SimpleCounter(); - when(metricGroup.counter("ns1.metric1")).thenReturn(userCounter); + when(metricGroup.counter("step.ns1.metric1")).thenReturn(userCounter); SimpleCounter elemCounter = new SimpleCounter(); - when(metricGroup.counter("beam.metric:element_count:v1")).thenReturn(elemCounter); + when(metricGroup.counter("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() + .setUrnForUserMetric("ns1", "metric1") + .setPTransformLabel("step") + .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)); assertThat(elemCounter.getCount(), is(0L)); - container.updateMetrics( - "step", ImmutableList.of(userCountMonitoringInfo, elemCountMonitoringInfo)); + container.updateMetrics(ImmutableList.of(userCountMonitoringInfo, elemCountMonitoringInfo)); assertThat(userCounter.getCount(), is(111L)); assertThat(elemCounter.getCount(), is(222L)); } @@ -167,15 +168,17 @@ public void testDropUnexpectedMonitoringInfoTypes() { MetricsContainer step = flinkContainer.getMetricsContainer("step"); MonitoringInfo intCounter = - MonitoringInfo.newBuilder() - .setUrn(USER_COUNTER_URN_PREFIX + "ns1:int_counter") - .putLabels(PTRANSFORM_LABEL, "step") - .setMetric( - Metric.newBuilder().setCounterData(CounterData.newBuilder().setInt64Value(111))) + new SimpleMonitoringInfoBuilder() + .setUrnForUserMetric("ns1", "int_counter") + .setPTransformLabel("step") + .setInt64TypeUrn() + .setInt64Value(111) .build(); MonitoringInfo doubleCounter = MonitoringInfo.newBuilder() + // TODO(ryan): use SimpleMonitoringInfoBuilder helpers, when double counters are + // supported (e.g. with a dedicated "type" value) .setUrn(USER_COUNTER_URN_PREFIX + "ns2:double_counter") .putLabels(PTRANSFORM_LABEL, "step") .setMetric( @@ -202,6 +205,7 @@ public void testDropUnexpectedMonitoringInfoTypes() { MonitoringInfo.newBuilder() .setUrn(USER_COUNTER_URN_PREFIX + "ns4:double_distribution") .putLabels(PTRANSFORM_LABEL, "step") + .setType(DISTRIBUTION_INT64_TYPE_URN) .setMetric( Metric.newBuilder() .setDistributionData( @@ -217,14 +221,30 @@ public void testDropUnexpectedMonitoringInfoTypes() { // 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); + when(metricGroup.counter("step.ns1.int_counter")).thenReturn(counter); + + DistributionData distributionData = DistributionData.create(30, 10, 1, 5); + DistributionResult distributionResult = distributionData.extractResult(); + FlinkDistributionGauge distributionGauge = new FlinkDistributionGauge(distributionResult); + + 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)); + 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)); @@ -234,33 +254,18 @@ public void testDropUnexpectedMonitoringInfoTypes() { ((CounterCell) step.getCounter(MetricName.named("ns1", "int_counter"))).getCumulative(); assertThat(count, is(111L)); - // The one Flink distribution that gets created is a FlinkDistributionGauge; here we verify its - // initial (and in this test, final) value - verify(metricGroup) - .gauge( - eq("ns3.int_distribution"), - argThat( - new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - DistributionResult actual = ((FlinkDistributionGauge) argument).getValue(); - DistributionResult expected = DistributionResult.create(30, 10, 1, 5); - return actual.equals(expected); - } - })); - // Verify that the Java SDK MetricsContainer holds the same information - DistributionData distributionData = + DistributionData actualDistributionData = ((DistributionCell) step.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"); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java index bab5e818f3fd..c9654ea1105f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricFiltering.java @@ -40,7 +40,7 @@ private MetricFiltering() {} public static boolean matches(MetricsFilter filter, MetricKey key) { return filter == null || (matchesName(key.metricName(), filter.names()) - && matchesScope(key.stepName(), filter.steps())); + && (key.stepName() == null || matchesScope(key.stepName(), filter.steps()))); } /** From 84a03fb660988c3451e4b65d6c6a440e52037426 Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sat, 23 Feb 2019 18:24:34 +0000 Subject: [PATCH 12/14] make TestMetricsSink queryable, fix hardcoded first-counter lookup --- .../core/metrics/MetricsPusherTest.java | 6 ++- .../runners/core/metrics/TestMetricsSink.java | 38 +++++++++++++------ .../spark/metrics/SparkMetricsPusherTest.java | 5 ++- 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsPusherTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsPusherTest.java index 36d71c29d00e..8a15afbb6d41 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsPusherTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/MetricsPusherTest.java @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.core.metrics; +import static org.hamcrest.Matchers.array; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @@ -68,8 +69,9 @@ public void test() throws Exception { pipeline.run(); // give metrics pusher time to push Thread.sleep( - (pipeline.getOptions().as(MetricsOptions.class).getMetricsPushPeriod() + 1L) * 1000); - assertThat(TestMetricsSink.getCounterValue(), is(NUM_ELEMENTS)); + (pipeline.getOptions().as(MetricsOptions.class).getMetricsPushPeriod() + 2) * 1000); + + assertThat(TestMetricsSink.getCounters(getClass()), array(is(NUM_ELEMENTS))); } private static class CountingDoFn extends DoFn { diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/TestMetricsSink.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/TestMetricsSink.java index 0d24866fffea..24ea93a6f364 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/TestMetricsSink.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/TestMetricsSink.java @@ -17,33 +17,49 @@ */ package org.apache.beam.runners.core.metrics; +import static java.util.stream.StreamSupport.stream; +import static org.apache.beam.sdk.metrics.MetricNameFilter.inNamespace; + import org.apache.beam.sdk.metrics.MetricQueryResults; +import org.apache.beam.sdk.metrics.MetricResult; +import org.apache.beam.sdk.metrics.MetricResults; +import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.sdk.metrics.MetricsOptions; import org.apache.beam.sdk.metrics.MetricsSink; /** - * This sink just stores in a static field the first counter (if it exists) attempted value. This is - * useful for tests. + * This {@link MetricsSink sink} intercepts a {@link MetricQueryResults} and exposes its + * ("attempted") counter values. This is useful for tests. */ public class TestMetricsSink implements MetricsSink { - private static long counterValue; + private static MetricResults metricResults; public TestMetricsSink(MetricsOptions pipelineOptions) {} - public static long getCounterValue() { - return counterValue; + public static Long[] getCounters(Class namespace) { + MetricsFilter metricsFilter = + MetricsFilter.builder().addNameFilter(inNamespace(namespace)).build(); + Iterable> counters = metricResults.queryMetrics(metricsFilter).getCounters(); + return stream(counters.spliterator(), false) + .map(MetricResult::getAttempted) + .toArray(Long[]::new); + } + + public static MetricResults getMetricResults() { + return metricResults; } public static void clear() { - counterValue = 0L; + metricResults = null; } @Override - public void writeMetrics(MetricQueryResults metricQueryResults) throws Exception { - counterValue = - metricQueryResults.getCounters().iterator().hasNext() - ? metricQueryResults.getCounters().iterator().next().getAttempted() - : 0L; + public void writeMetrics(MetricQueryResults metricQueryResults) { + metricResults = + new DefaultMetricResults( + metricQueryResults.getCounters(), + metricQueryResults.getDistributions(), + metricQueryResults.getGauges()); } } diff --git a/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkMetricsPusherTest.java b/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkMetricsPusherTest.java index e7e5ec6e8408..1dbd7608b807 100644 --- a/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkMetricsPusherTest.java +++ b/runners/spark/src/test/java/org/apache/beam/runners/spark/metrics/SparkMetricsPusherTest.java @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.spark.metrics; +import static org.hamcrest.Matchers.array; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @@ -96,7 +97,7 @@ public void testInStreamingMode() throws Exception { // give metrics pusher time to push Thread.sleep( (pipeline.getOptions().as(MetricsOptions.class).getMetricsPushPeriod() + 1L) * 1000); - assertThat(TestMetricsSink.getCounterValue(), is(6L)); + assertThat(TestMetricsSink.getCounters(getClass()), array(is(6L))); } private static class CountingDoFn extends DoFn { @@ -122,6 +123,6 @@ public void testInSBatchMode() throws Exception { // give metrics pusher time to push Thread.sleep( (pipeline.getOptions().as(MetricsOptions.class).getMetricsPushPeriod() + 1L) * 1000); - assertThat(TestMetricsSink.getCounterValue(), is(6L)); + assertThat(TestMetricsSink.getCounters(getClass()), array(is(6L))); } } From 5275acd2cf30dfc1d2c9a54ebbc0654f5115761f Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Sat, 23 Feb 2019 02:26:25 +0000 Subject: [PATCH 13/14] enable portable flink attempted counter PVR test cases --- runners/flink/job-server/flink_job_server.gradle | 2 -- 1 file changed, 2 deletions(-) diff --git a/runners/flink/job-server/flink_job_server.gradle b/runners/flink/job-server/flink_job_server.gradle index ebed8e43389f..64eefa5757af 100644 --- a/runners/flink/job-server/flink_job_server.gradle +++ b/runners/flink/job-server/flink_job_server.gradle @@ -129,9 +129,7 @@ def portableValidatesRunnerTask(String name, Boolean streaming) { includeCategories 'org.apache.beam.sdk.testing.ValidatesRunner' excludeCategories 'org.apache.beam.sdk.testing.FlattenWithHeterogeneousCoders' excludeCategories 'org.apache.beam.sdk.testing.LargeKeys$Above100MB' - excludeCategories 'org.apache.beam.sdk.testing.UsesAttemptedMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesCommittedMetrics' - excludeCategories 'org.apache.beam.sdk.testing.UsesCounterMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesCustomWindowMerging' excludeCategories 'org.apache.beam.sdk.testing.UsesDistributionMetrics' excludeCategories 'org.apache.beam.sdk.testing.UsesFailureMessage' From 4d5a6d90acf923b6b21e3e3ff254a58d7f11471e Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Thu, 7 Mar 2019 20:01:30 +0000 Subject: [PATCH 14/14] cr feedback --- .../runners/core/metrics/GaugeProtos.java | 7 +- .../core/metrics/MetricResultsProtos.java | 75 ++++++++----------- .../core/metrics/MetricUpdatesProtos.java | 44 ++++++----- .../metrics/MonitoringInfoMetricName.java | 3 +- .../runners/core/metrics/MonitoringInfos.java | 11 ++- .../flink/metrics/FlinkMetricContainer.java | 10 +-- 6 files changed, 72 insertions(+), 78 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java index 1b775125b823..1ff3902f1632 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/GaugeProtos.java @@ -17,6 +17,9 @@ */ package org.apache.beam.runners.core.metrics; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + import org.apache.beam.sdk.metrics.GaugeResult; import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.Timestamp; import org.joda.time.Instant; @@ -25,6 +28,8 @@ public class GaugeProtos { public static GaugeResult fromProto(long value, Timestamp timestamp) { return GaugeResult.create( - value, new Instant(timestamp.getSeconds() * 1000 + timestamp.getNanos() / 1000)); + value, + new Instant( + SECONDS.toMillis(timestamp.getSeconds()) + NANOSECONDS.toMillis(timestamp.getNanos()))); } } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java index c3cc1e10884e..415c2914eb28 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricResultsProtos.java @@ -59,50 +59,41 @@ public static MetricResults fromProto(MetricsApi.MetricResults metricResults) { public static MetricsApi.MetricResults toProto(MetricResults metricResults) { MetricsApi.MetricResults.Builder builder = MetricsApi.MetricResults.newBuilder(); MetricQueryResults results = metricResults.allMetrics(); - results - .getCounters() - .forEach( - counter -> - addMetricResultToBuilder( - builder, counter, SimpleMonitoringInfoBuilder::setInt64Value)); - results - .getDistributions() - .forEach( - distribution -> - addMetricResultToBuilder( - builder, distribution, SimpleMonitoringInfoBuilder::setIntDistributionValue)); - results - .getGauges() - .forEach( - gauge -> - addMetricResultToBuilder( - builder, gauge, SimpleMonitoringInfoBuilder::setGaugeValue)); + addMetricResultsToBuilder( + builder, results.getCounters(), SimpleMonitoringInfoBuilder::setInt64Value); + addMetricResultsToBuilder( + builder, results.getDistributions(), SimpleMonitoringInfoBuilder::setIntDistributionValue); + addMetricResultsToBuilder( + builder, results.getGauges(), SimpleMonitoringInfoBuilder::setGaugeValue); return builder.build(); } /** - * Add this {@link MetricResult}'s "attempted" and "committed" values to the corresponding lists - * of {@param builder}. + * Add a collection of {@link MetricResult}s to a {@link MetricsApi.MetricResults.Builder + * MetricResults proto builder}, in terms of a type-specific helper for adding an individual value + * to a {@link SimpleMonitoringInfoBuilder MonitoringInfo builder}. */ - private static void addMetricResultToBuilder( + private static void addMetricResultsToBuilder( MetricsApi.MetricResults.Builder builder, - MetricResult metricResult, + Iterable> metricResults, BiConsumer set) { - MetricKey metricKey = metricResult.getKey(); - addMetricToBuilder( - builder, - metricKey, - metricResult.getAttempted(), - set, - MetricsApi.MetricResults.Builder::addAttempted); - T committed = metricResult.getCommittedOrNull(); - if (committed != null) { + for (MetricResult metricResult : metricResults) { + MetricKey metricKey = metricResult.getKey(); addMetricToBuilder( builder, metricKey, - metricResult.getCommitted(), + metricResult.getAttempted(), set, - MetricsApi.MetricResults.Builder::addCommitted); + MetricsApi.MetricResults.Builder::addAttempted); + T committed = metricResult.getCommittedOrNull(); + if (committed != null) { + addMetricToBuilder( + builder, + metricKey, + metricResult.getCommitted(), + set, + MetricsApi.MetricResults.Builder::addCommitted); + } } } @@ -122,14 +113,12 @@ private static void addMetricToBuilder( T value, BiConsumer set, BiConsumer add) { - if (value != null) { - SimpleMonitoringInfoBuilder partial = - new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey); - set.accept(partial, value); - MonitoringInfo monitoringInfo = partial.build(); - if (monitoringInfo != null) { - add.accept(builder, monitoringInfo); - } + SimpleMonitoringInfoBuilder partial = + new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey); + set.accept(partial, value); + MonitoringInfo monitoringInfo = partial.build(); + if (monitoringInfo != null) { + add.accept(builder, monitoringInfo); } } @@ -174,9 +163,7 @@ private static List> build(Map addMetricToResultMap(metricKey, counter, committed, counters), distribution -> addMetricToResultMap(metricKey, distribution, committed, distributions), gauge -> addMetricToResultMap(metricKey, gauge, committed, gauges)); diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java index 60cba7248336..b3fab6380297 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MetricUpdatesProtos.java @@ -21,46 +21,50 @@ import java.util.List; import java.util.function.BiConsumer; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; +import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate; import org.apache.beam.sdk.metrics.MetricKey; /** Convert {@link MetricUpdates} to a {@link List} of {@link MonitoringInfo}. */ public class MetricUpdatesProtos { public static List toProto(MetricUpdates metricUpdates) { ArrayList monitoringInfos = new ArrayList<>(); - - fromMetrics( + addMetricUpdates( monitoringInfos, metricUpdates.counterUpdates(), SimpleMonitoringInfoBuilder::setInt64Value); - fromMetrics( + addMetricUpdates( monitoringInfos, metricUpdates.distributionUpdates(), SimpleMonitoringInfoBuilder::setIntDistributionValue); - fromMetrics( + addMetricUpdates( monitoringInfos, metricUpdates.gaugeUpdates(), SimpleMonitoringInfoBuilder::setGaugeValue); - return monitoringInfos; } - private static MonitoringInfo addMetric( - MetricUpdates.MetricUpdate metricUpdate, BiConsumer fn) { - SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(true); - MetricKey metricKey = metricUpdate.getKey(); - builder.setLabelsAndUrnFrom(metricKey); - - fn.accept(builder, metricUpdate.getUpdate()); - return builder.setTimestampToNow().build(); - } - - private static void fromMetrics( + /** + * Convert {@link MetricUpdate}s of a given type to {@link MonitoringInfo}s, and add them to a + * given list. + */ + private static void addMetricUpdates( ArrayList monitoringInfos, - Iterable> metrics, - BiConsumer fn) { - for (MetricUpdates.MetricUpdate metric : metrics) { - MonitoringInfo monitoringInfo = addMetric(metric, fn); + Iterable> metrics, + BiConsumer setValue) { + for (MetricUpdate metric : metrics) { + MonitoringInfo monitoringInfo = updateToProto(metric, setValue); if (monitoringInfo != null) { monitoringInfos.add(monitoringInfo); } } } + + /** Convert a {@link MetricUpdate} to a {@link MonitoringInfo}. */ + private static MonitoringInfo updateToProto( + MetricUpdate metricUpdate, BiConsumer setValue) { + MetricKey metricKey = metricUpdate.getKey(); + SimpleMonitoringInfoBuilder builder = + new SimpleMonitoringInfoBuilder().setLabelsAndUrnFrom(metricKey); + + setValue.accept(builder, metricUpdate.getUpdate()); + return builder.setTimestampToNow().build(); + } } diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java index 6587a74fea88..ee65fbb40871 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfoMetricName.java @@ -17,6 +17,7 @@ */ package org.apache.beam.runners.core.metrics; +import static java.util.Collections.unmodifiableMap; import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL; import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument; @@ -88,7 +89,7 @@ public String getUrn() { /** @return The labels associated with this MonitoringInfo. */ public Map getLabels() { - return this.labels; + return unmodifiableMap(this.labels); } /** diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java index 7afd02923b29..f26c81ef561d 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/metrics/MonitoringInfos.java @@ -45,12 +45,17 @@ public class MonitoringInfos { * or gauge), and gracefully dropping / warning about unexpected and unsupported states. */ public static void forEachMetricType( - Metric metric, - String type, - Timestamp timestamp, + MonitoringInfo monitoringInfo, Consumer counterFn, Consumer distributionFn, Consumer gaugeFn) { + if (!monitoringInfo.hasMetric()) { + LOG.info("Skipping metric-less MonitoringInfo: {}", monitoringInfo); + return; + } + Metric metric = monitoringInfo.getMetric(); + String type = monitoringInfo.getType(); + Timestamp timestamp = monitoringInfo.getTimestamp(); Metric.DataCase dataCase = metric.getDataCase(); switch (dataCase) { case COUNTER_DATA: 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 aabd18a2d847..17be725814d5 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 @@ -26,7 +26,6 @@ import java.util.Map; import java.util.function.BiConsumer; import javax.annotation.Nullable; -import org.apache.beam.model.pipeline.v1.MetricsApi.Metric; import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo; import org.apache.beam.runners.core.metrics.MetricsContainerImpl; import org.apache.beam.runners.core.metrics.MetricsContainerStepMap; @@ -102,20 +101,13 @@ public MetricsContainer getMetricsContainer(@Nullable String stepName) { public void updateMetrics(List monitoringInfos) { monitoringInfos.forEach( monitoringInfo -> { - if (!monitoringInfo.hasMetric()) { - LOG.info("Skipping metric-less MonitoringInfo: {}", monitoringInfo); - return; - } MetricName metricName = MonitoringInfoMetricName.create(monitoringInfo); @Nullable String ptransform = monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL); MetricsContainer metricsContainer = getMetricsContainer(ptransform); - Metric metric = monitoringInfo.getMetric(); MetricKey key = MetricKey.create(monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL), metricName); forEachMetricType( - metric, - monitoringInfo.getType(), - monitoringInfo.getTimestamp(), + monitoringInfo, counter -> { metricsContainer.getCounter(metricName).inc(counter); updateCounter(key, counter);