Skip to content
Merged
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 @@ -57,6 +57,11 @@ public void update(long n) {
update(DistributionData.singleton(n));
}

@Override
public void update(long sum, long count, long min, long max) {
update(DistributionData.create(sum, count, min, max));
}

void update(DistributionData data) {
DistributionData original;
do {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
*/
package org.apache.beam.runners.flink;

import static org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.getDefaultLocalParallelism;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import java.util.List;
Expand Down Expand Up @@ -132,7 +134,9 @@ static StreamExecutionEnvironment createStreamExecutionEnvironment(

// depending on the master, create the right environment.
if ("[local]".equals(masterUrl)) {
flinkStreamEnv = StreamExecutionEnvironment.createLocalEnvironment();
flinkStreamEnv =
StreamExecutionEnvironment.createLocalEnvironment(
getDefaultLocalParallelism(), flinkConfig);
Comment thread
ryan-williams marked this conversation as resolved.
Resolved
} else if ("[auto]".equals(masterUrl)) {
flinkStreamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
} else if (masterUrl.matches(".*:\\d*")) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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.flink.metrics;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.reporter.AbstractReporter;

/**
* Flink {@link org.apache.flink.metrics.reporter.MetricReporter metrics reporter} for writing
* metrics to a file specified via the "metrics.reporter.file.path" config key (assuming an alias of
* "file" for this reporter in the "metrics.reporters" setting).
*/
public class FileReporter extends AbstractReporter {

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.

Rename this to TestFileReporter?

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 originally gave it a name like that, however I talked myself in to that this is a potentially more general-purpose abstraction, and it is Flink specific, so that this (main, not test) package is an OK place for it.

If it was TestFileReporter then I'd feel obliged to put it in the test package, at which point the build plumbing to start a job-server in flink_runner_test.py that has the :beam-runners-flink -tests.jar` on the classpath would become more convoluted, so that was an added incentive to view this as not a "tests only" thing 😀

lmk what you think!

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.

I get why it's not practical to have it in the test scope. That's fine. Still, I think TestFileReporter reflects more accurately what it does. Also, it's configured via a test property, so I don't see how it is useful for non-testing.

@ryan-williams ryan-williams Dec 4, 2018 •

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 configured via a test property

ah, I left the reporter alias as test in flink_runner_test when I renamed this class to remove the Test prefix. I should change that alias to file, either way.

(update: I did this, and also left a placeholder in the FileReporter javadoc for whatever alias the user wants to use as the name of their FileReporter)

This is a reporter that writes the final state of all metrics to a file of the user's choosing. It can do this in test or production environments. It doesn't perform any assertions, or otherwise do things that only make sense in a testing context. It is fairly similar to Slf4jReporter, but its output is easier to parse (for machines or humans), and would normally be configured like:

metrics.reporters: file,
metrics.reporter.file.class: org.apache.beam.runners.flink.metrics.FileReporter
metrics.reporter.file.file: /some/path/on/job-mgr/node

To me, it feels weirder to name it Test* and leave it under main/, when it is not really that test-specific an abstraction.

However I understand if the possible non-test uses feel contrived, and perhaps having Test* names under main/ isn't too smelly.

I just want to make sure the vestigial metrics.reporter.test.* namespacing isn't driving the decision too heavily.

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.

That sounds reasonable. But shouldn't we use a more distinct name to avoid confusion, like BeamFlinkFileMetricReporter?

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.

I suppose it could come in handy when you just want to dump metrics locally.

Since package is org.apache.beam.runners.flink.metrics, FileReporter seems fine.

@ryan-williams ryan-williams Dec 5, 2018 •

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.

(woops, I'd not seen Max's comment above when I posted this, but seems like we're saying the same thing)

fwiw: "beam", "flink", "metrics", "file", and "reporter" are already in this class' name: org.apache.beam.runners.flink.metrics.FileReporter (and users would use this FQN in flink-conf.yaml, as in the example above).

I generally dislike the Java convention of repeating package-name segments in class' basenames, but recognize that it's common and people seem to like it, so happy to add here, just wanted to float the idea that org.apache.beam.runners.flink.metrics.BeamFlinkFileMetricReporter is redundant.

lmk if you still prefer it and I'll change it.

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.

Reason I brought it up is discoverability. Names like Node, Metric, Reporter all usually too generic, regardless in which package they reside. When you work in the IDE, you would probably not want to see dozens of matches when searching a class? I checked and in this case it is not the case however and not critical for this PR anyways. BTW it seems to be a convention in Beam code to prefix classes with the runner (like Flink when they are likely to appear in multiple runners).

@Override
public String filterCharacters(String input) {
return input;
}

private String path;
private PrintStream ps;

@Override
public void open(MetricConfig config) {
synchronized (this) {
if (path == null) {
path = config.getString("path", null);
log.info("Opening file: {}", path);
if (path == null) {
throw new IllegalStateException("FileReporter metrics config needs 'path' key");
}
try {
FileOutputStream fos = new FileOutputStream(path);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
throw new IllegalStateException("FileReporter couldn't open file", e);
}
}
}
}

@Override
public void notifyOfRemovedMetric(Metric metric, String metricName, MetricGroup group) {
final String name = group.getMetricIdentifier(metricName, this);
super.notifyOfRemovedMetric(metric, metricName, group);
synchronized (this) {
ps.printf("%s: %s%n", name, Metrics.toString(metric));
}
}

@Override
public void close() {
ps.close();
log.info("wrote metrics to {}", path);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,19 @@
*/
package org.apache.beam.runners.flink.metrics;

import static org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfoUrns.Enum.USER_COUNTER_URN_PREFIX;
import static org.apache.beam.runners.core.metrics.MetricsContainerStepMap.asAttemptedOnlyMetricResults;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.beam.model.fnexecution.v1.BeamFnApi;
import org.apache.beam.runners.core.metrics.MetricsContainerImpl;
import org.apache.beam.runners.core.metrics.MetricsContainerStepMap;
import org.apache.beam.sdk.metrics.Distribution;
import org.apache.beam.sdk.metrics.DistributionResult;
import org.apache.beam.sdk.metrics.GaugeResult;
import org.apache.beam.sdk.metrics.MetricName;
import org.apache.beam.sdk.metrics.MetricQueryResults;
import org.apache.beam.sdk.metrics.MetricResult;
import org.apache.beam.sdk.metrics.MetricResults;
Expand Down Expand Up @@ -77,12 +82,72 @@ public FlinkMetricContainer(RuntimeContext runtimeContext) {
this.metricsAccumulator = (MetricsAccumulator) metricsAccumulator;
}

MetricsContainer getMetricsContainer(String stepName) {
public MetricsContainer getMetricsContainer(String stepName) {
return metricsAccumulator != null
? metricsAccumulator.getLocalValue().getContainer(stepName)
: null;
}

/**
* Parse a {@link MetricName} from a {@link
* org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfoUrns.Enum}
*
* <p>Should be consistent with {@code parse_namespace_and_name} in monitoring_infos.py

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.

Wanted to flag this for @ajamato in particular as the author of the python code I mimicked here.

How important is it that the python and java SDKs parse metric URNs into a {namespace, name} pairs in the same way?

From what I can tell, It may not be critical, though we should still probably agree on one semantic interpretation of what is "namespace" vs "name" of e.g. "beam:metric:element_count:v1".

With monitoring_infos.py as the reference implementation, the answer is {"beam", "metric:element_count:v1"}; shall I encode that in a comment in beam_fn_api.proto, and reference it here?

*
* <p>TODO: not flink-specific; where should it live?

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.

Flagging this as well, in case anyone has ideas.

I would normally view this as aMetricName constructor, but MetricName is in java-core, which doesn't depend on fn-api (and shouldn't be made to without good reason, I assume).

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.

I believe that should be changed in BeamFnApi.MonitoringInfo. Ok for now as a workaround.

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.

not sure I follow; how could I put this String ⇒ MetricName logic into BeamFnApi.MonitoringInfo? The latter is codegen'd from proto definitions…

*/
public static MetricName parseUrn(String urn) {
if (urn.startsWith(USER_COUNTER_URN_PREFIX.toString())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Does calling toString on this work? The usage I have seen before involved extracting the attached object and pulling out a field from the enum.

See BeamUrns.getUrns

return value.getValueDescriptor().getOptions().getExtension(RunnerApi.beamUrn);

You could reference this file which pulls it in. SimpleMonitoringInfoBuilder

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.

good catch, thanks! I just filed #7408 to fix

urn = urn.substring(USER_COUNTER_URN_PREFIX.toString().length());
}
// If it is not a user counter, just use the first part of the URN, i.e. 'beam'
String[] pieces = urn.split(":", 2);
if (pieces.length != 2) {
throw new IllegalArgumentException("Invalid metric URN: " + urn);
}
return MetricName.named(pieces[0], pieces[1]);
}

public void updateMetrics(String stepName, List<BeamFnApi.MonitoringInfo> monitoringInfos) {
MetricsContainer metricsContainer = getMetricsContainer(stepName);
monitoringInfos.forEach(
monitoringInfo -> {
if (monitoringInfo.hasMetric()) {
String urn = monitoringInfo.getUrn();
MetricName metricName = parseUrn(urn);
BeamFnApi.Metric metric = monitoringInfo.getMetric();
if (metric.hasCounterData()) {
BeamFnApi.CounterData counterData = metric.getCounterData();
org.apache.beam.sdk.metrics.Counter counter = metricsContainer.getCounter(metricName);
if (counterData.getValueCase() == BeamFnApi.CounterData.ValueCase.INT64_VALUE) {
counter.inc(counterData.getInt64Value());
} else {
throw new IllegalArgumentException("Unsupported CounterData type: " + counterData);

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.

org.apache.beam.sdk.metrics.Counter only supports longs…

}
} else if (metric.hasDistributionData()) {
BeamFnApi.DistributionData distributionData = metric.getDistributionData();
Distribution distribution = metricsContainer.getDistribution(metricName);
if (distributionData.hasIntDistributionData()) {
BeamFnApi.IntDistributionData intDistributionData =
distributionData.getIntDistributionData();
distribution.update(
intDistributionData.getSum(),
intDistributionData.getCount(),
intDistributionData.getMin(),
intDistributionData.getMax());
} else {
throw new IllegalArgumentException(

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.

likewise, Distribution only supports longs

"Unsupported DistributionData type: " + distributionData);
}
} else if (metric.hasExtremaData()) {
BeamFnApi.ExtremaData extremaData = metric.getExtremaData();
throw new IllegalArgumentException("Extrema metric unsupported: " + extremaData);
}
}
});
updateMetrics(stepName);
}

void updateMetrics(String stepName) {
MetricResults metricResults = asAttemptedOnlyMetricResults(metricsAccumulator.getLocalValue());
MetricQueryResults metricQueryResults =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* 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.flink.metrics;

import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.Gauge;
import org.apache.flink.metrics.Histogram;
import org.apache.flink.metrics.HistogramStatistics;
import org.apache.flink.metrics.Meter;
import org.apache.flink.metrics.Metric;

/** Helper for pretty-printing {@link Metric Flink metrics}. */
public class Metrics {
public static String toString(Metric metric) {
if (metric instanceof Counter) {
return Long.toString(((Counter) metric).getCount());
} else if (metric instanceof Gauge) {
return ((Gauge) metric).getValue().toString();
} else if (metric instanceof Meter) {
return Double.toString(((Meter) metric).getRate());
} else if (metric instanceof Histogram) {
HistogramStatistics stats = ((Histogram) metric).getStatistics();
return String.format(
"count=%d, min=%d, max=%d, mean=%f, stddev=%f, p50=%f, p75=%f, p95=%f",
stats.size(),
stats.getMin(),
stats.getMax(),
stats.getMean(),
stats.getStdDev(),
stats.getQuantile(0.5),
stats.getQuantile(0.75),
stats.getQuantile(0.95));
} else {
throw new IllegalStateException(
String.format(
"Cannot remove unknown metric type %s. This indicates that the reporter "
+ "does not support this metric type.",
metric.getClass().getName()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleProgressResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.runners.core.InMemoryStateInternals;
Expand All @@ -43,6 +45,7 @@
import org.apache.beam.runners.core.construction.Timer;
import org.apache.beam.runners.core.construction.graph.ExecutableStage;
import org.apache.beam.runners.core.construction.graph.TimerReference;
import org.apache.beam.runners.flink.metrics.FlinkMetricContainer;
import org.apache.beam.runners.fnexecution.control.BundleProgressHandler;
import org.apache.beam.runners.fnexecution.control.OutputReceiverFactory;
import org.apache.beam.runners.fnexecution.control.ProcessBundleDescriptors;
Expand Down Expand Up @@ -97,9 +100,12 @@ public class FlinkExecutableStageFunction<InputT> extends AbstractRichFunction
private final Map<String, Integer> outputMap;
private final FlinkExecutableStageContext.Factory contextFactory;
private final Coder windowCoder;
// Unique name for namespacing metrics; currently just takes the input ID
private final String stageName;

// Worker-local fields. These should only be constructed and consumed on Flink TaskManagers.
private transient RuntimeContext runtimeContext;
private transient FlinkMetricContainer container;
private transient StateRequestHandler stateRequestHandler;
private transient FlinkExecutableStageContext stageContext;
private transient StageBundleFactory stageBundleFactory;
Expand All @@ -121,6 +127,7 @@ public FlinkExecutableStageFunction(
this.outputMap = outputMap;
this.contextFactory = contextFactory;
this.windowCoder = windowCoder;
this.stageName = stagePayload.getInput();
}

@Override
Expand All @@ -130,6 +137,7 @@ public void open(Configuration parameters) throws Exception {
FileSystems.setDefaultPipelineOptions(PipelineOptionsFactory.create());
executableStage = ExecutableStage.fromPayload(stagePayload);
runtimeContext = getRuntimeContext();
container = new FlinkMetricContainer(getRuntimeContext());
// TODO: Wire this into the distributed cache and make it pluggable.
stageContext = contextFactory.get(jobInfo);
stageBundleFactory = stageContext.getStageBundleFactory(executableStage);
Expand All @@ -139,7 +147,18 @@ public void open(Configuration parameters) throws Exception {
stateRequestHandler =
getStateRequestHandler(
executableStage, stageBundleFactory.getProcessBundleDescriptor(), runtimeContext);
progressHandler = BundleProgressHandler.ignored();
progressHandler =
new BundleProgressHandler() {
@Override
public void onProgress(ProcessBundleProgressResponse progress) {
container.updateMetrics(stageName, progress.getMonitoringInfosList());
}

@Override
public void onCompleted(ProcessBundleResponse response) {
container.updateMetrics(stageName, response.getMonitoringInfosList());
}
};
}

private StateRequestHandler getStateRequestHandler(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public class DoFnOperator<InputT, OutputT> extends AbstractStreamOperator<Window

protected transient FlinkStateInternals<?> keyedStateInternals;

private final String stepName;
protected final String stepName;

private final Coder<WindowedValue<InputT>> windowedInputCoder;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleProgressResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey.TypeCase;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.runners.core.DoFnRunner;
Expand All @@ -43,6 +45,7 @@
import org.apache.beam.runners.core.TimerInternals;
import org.apache.beam.runners.core.construction.Timer;
import org.apache.beam.runners.core.construction.graph.ExecutableStage;
import org.apache.beam.runners.flink.metrics.FlinkMetricContainer;
import org.apache.beam.runners.flink.translation.functions.FlinkExecutableStageContext;
import org.apache.beam.runners.flink.translation.functions.FlinkStreamingSideInputHandlerFactory;
import org.apache.beam.runners.fnexecution.control.BundleProgressHandler;
Expand Down Expand Up @@ -104,6 +107,7 @@ public class ExecutableStageDoFnOperator<InputT, OutputT> extends DoFnOperator<I
private transient StageBundleFactory stageBundleFactory;
private transient ExecutableStage executableStage;
private transient SdkHarnessDoFnRunner<InputT, OutputT> sdkHarnessRunner;
private transient FlinkMetricContainer flinkMetricContainer;
private transient long backupWatermarkHold = Long.MIN_VALUE;

public ExecutableStageDoFnOperator(
Expand Down Expand Up @@ -157,10 +161,22 @@ public void open() throws Exception {
// bundle "factory" (manager?) but not the job or Flink bundle factories. How do we make
// ownership of the higher level "factories" explicit? Do we care?
stageContext = contextFactory.get(jobInfo);
flinkMetricContainer = new FlinkMetricContainer(getRuntimeContext());

stageBundleFactory = stageContext.getStageBundleFactory(executableStage);
stateRequestHandler = getStateRequestHandler(executableStage);
progressHandler = BundleProgressHandler.ignored();
progressHandler =
new BundleProgressHandler() {
@Override
public void onProgress(ProcessBundleProgressResponse progress) {
flinkMetricContainer.updateMetrics(stepName, progress.getMonitoringInfosList());
}

@Override
public void onCompleted(ProcessBundleResponse response) {
flinkMetricContainer.updateMetrics(stepName, response.getMonitoringInfosList());
}
};

// This will call {@code createWrappingDoFnRunner} which needs the above dependencies.
super.open();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ void update(DistributionData data) {
} while (!value.compareAndSet(original, original.combine(data)));
}

@Override
public void update(long sum, long count, long min, long max) {
update(DistributionData.create(sum, count, min, max));
}

@Override
public DirtyState getDirty() {
throw new UnsupportedOperationException(
Expand Down
Loading