Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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}. */
Expand All @@ -29,9 +30,12 @@ public class MetricUrns {
*
* <p>Should be consistent with {@code parse_namespace_and_name} in monitoring_infos.py.
*/
public static MetricName parseUrn(String urn) {
@Nullable
public static MetricName parseUserUrn(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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public void finishBundle() {
}

// update metrics
container.updateMetrics(stepName);
container.updateFlinkMetrics(stepName);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@
*/
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.MetricUrns.parseUserUrn;
import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults;
import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.apache.beam.model.pipeline.v1.MetricsApi.CounterData;
import org.apache.beam.model.pipeline.v1.MetricsApi.DistributionData;
import org.apache.beam.model.pipeline.v1.MetricsApi.ExtremaData;
Expand All @@ -41,13 +46,13 @@
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -89,7 +94,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;
Expand All @@ -99,117 +104,145 @@ 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<MonitoringInfo> monitoringInfos) {
MetricsContainer metricsContainer = getMetricsContainer(stepName);
public void updateMetrics(List<MonitoringInfo> 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;
}
Metric metric = monitoringInfo.getMetric();

String urn = monitoringInfo.getUrn();
MetricName metricName = parseUserUrn(urn);
if (metricName == null) {
LOG.info("Dropping system metric: {}", monitoringInfo);
return;
}

Map<String, String> labels = monitoringInfo.getLabelsMap();
String ptransform = labels.get(PTRANSFORM_LABEL);

MetricsContainer metricsContainer = getMetricsContainer(ptransform);

MetricKey key = MetricKey.create(ptransform, metricName);

if (metric.hasCounterData()) {
CounterData counterData = metric.getCounterData();
if (counterData.getValueCase() == CounterData.ValueCase.INT64_VALUE) {
long value = counterData.getInt64Value();
org.apache.beam.sdk.metrics.Counter counter = metricsContainer.getCounter(metricName);
counter.inc(value);

// Update flink
updateCounter(key, value);
} 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());

// Update flink
updateDistribution(
key,
DistributionResult.create(
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);
}
});
updateMetrics(stepName);
}

/**
* Update Flink's internal metrics ({@link this#flinkCounterCache}) with the latest metrics for a
* given step.
*/
void updateMetrics(String stepName) {
void updateFlinkMetrics(String stepName) {
MetricResults metricResults = asAttemptedOnlyMetricResults(metricsAccumulator.getLocalValue());
MetricQueryResults metricQueryResults =
metricResults.queryMetrics(MetricsFilter.builder().addStep(stepName).build());
updateCounters(metricQueryResults.getCounters());
updateDistributions(metricQueryResults.getDistributions());
updateGauge(metricQueryResults.getGauges());
}

private void updateCounters(Iterable<MetricResult<Long>> counters) {
for (MetricResult<Long> 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 <T> void updateMetrics(
Iterable<MetricResult<T>> metricResults, BiConsumer<MetricKey, T> fn) {
for (MetricResult<T> metricResult : metricResults) {
fn.accept(metricResult.getKey(), metricResult.getAttempted());
}
}

private void updateDistributions(Iterable<MetricResult<DistributionResult>> distributions) {
for (MetricResult<DistributionResult> 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 <T, FlinkT> void updateMetric(
MetricKey key,
Map<String, FlinkT> flinkMetricMap,
BiFunction<String, MetricGroup, FlinkT> create,
Consumer<FlinkT> update,
T value) {
String flinkMetricName = getFlinkMetricNameString(key);

// update flink metric
FlinkT metric = flinkMetricMap.get(flinkMetricName);
if (metric == null) {
metric = create.apply(flinkMetricName, runtimeContext.getMetricGroup());
flinkMetricMap.put(flinkMetricName, metric);
}
update.accept(metric);
}

private void updateGauge(Iterable<MetricResult<GaugeResult>> gauges) {
for (MetricResult<GaugeResult> metricResult : gauges) {
String flinkMetricName = getFlinkMetricNameString(metricResult.getKey());
private void updateCounter(MetricKey metricKey, long value) {
updateMetric(
metricKey,
flinkCounterCache,
(name, group) -> group.counter(name),
counter -> {
counter.dec(counter.getCount());
counter.inc(value);
},
value);
}

GaugeResult update = metricResult.getAttempted();
private void updateDistribution(MetricKey metricKey, DistributionResult value) {
updateMetric(
metricKey,
flinkDistributionGaugeCache,
(name, group) -> group.gauge(name, new FlinkDistributionGauge(value)),
distribution -> distribution.update(value),
value);
}

// update flink metric
FlinkGauge gauge = flinkGaugeCache.get(flinkMetricName);
if (gauge == null) {
gauge = runtimeContext.getMetricGroup().gauge(flinkMetricName, new FlinkGauge(update));
flinkGaugeCache.put(flinkMetricName, gauge);
} else {
gauge.update(update);
}
}
private void updateGauge(MetricKey metricKey, GaugeResult value) {
updateMetric(
metricKey,
flinkGaugeCache,
(name, group) -> group.gauge(name, new FlinkGauge(value)),
gauge -> gauge.update(value),
value);
}

@VisibleForTesting
static String getFlinkMetricNameString(MetricKey metricKey) {
MetricName metricName = metricKey.metricName();
// We use only the MetricName here, the step name is already contained
// in the operator name which is passed to Flink's MetricGroup to which
// the metric with the following name will be added.
return metricName.getNamespace() + METRIC_KEY_SEPARATOR + metricName.getName();
return String.join(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you check how the metric names look in Flink? I think we changed this some time ago because the metric names contained duplicate strings.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've not. I'll do that and report back.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you had a chance to check?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So just to confirm, including the step name here will duplicate it because it is already used as the metric group name for the Flink operator which calls out to the Metrics code here.

METRIC_KEY_SEPARATOR,
metricKey.stepName(),
metricName.getNamespace(),
metricName.getName());
}

/** Flink {@link Gauge} for {@link DistributionResult}. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public boolean invokeStart(ReaderT reader) throws IOException {
try (Closeable ignored =
MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) {
boolean result = reader.start();
container.updateMetrics(stepName);
container.updateFlinkMetrics(stepName);
return result;
}
} else {
Expand All @@ -62,7 +62,7 @@ public boolean invokeAdvance(ReaderT reader) throws IOException {
try (Closeable ignored =
MetricsEnvironment.scopedMetricsContainer(container.getMetricsContainer(stepName))) {
boolean result = reader.advance();
container.updateMetrics(stepName);
container.updateFlinkMetrics(stepName);
return result;
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this related to the metrics? Have you seen this test timing out?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not directly related, but when working on metrics PVR tests, if something throws in the runner harness (I think), that manifests as a hang and timeout of this test case, without a good stack trace.

Not essential to add this, ofc, but it's not the first time I've experienced it while doing unrelated Flink work, so thought I'd try to raise awareness.

@Test(timeout = 60_000)
public void testSavepointRestorePortable() throws Exception {
runSavepointAndRestore(true);
Expand Down
Loading