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
12 changes: 12 additions & 0 deletions model/job-management/src/main/proto/beam_job_api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}


Expand Down Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions model/pipeline/src/main/proto/metrics.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Can these static methods live on the DistributionResult object, instead of a new file?

(And for similar files as well).

@ryan-williams ryan-williams Mar 1, 2019 •

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 actually decided to pull these back to this file (I'd previously made the change you suggested).

When I put them on DistributionResult, that gave sdks/java/core a public-API dependency on the IntDistributionData proto (and a bunch of gRPC- and proto-things that come along with it, transitively), which GcpCoreApiSurfaceTest complained about:

failing api surface test screenshot

I prefer just putting these helpers in this file in runners-core as opposed to adding e.g. org.apache.beam.model.* to their public API surface (and everyone else's, they just happen to care enough to have a test…).

I ran into this on other metric-related PRs, and so far have been able to keep it out of master. We may end up needing to just "leak" a lot of proto and gRPC here anyway, so maybe it doesn't matter, but this feels like the more considerate thing to do for now.

lmk what you think

return IntDistributionData.newBuilder()
.setMin(distributionResult.getMin())
.setMax(distributionResult.getMax())
.setCount(distributionResult.getCount())
.setSum(distributionResult.getSum())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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.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;

/** Convert gauges from proto to SDK representations. */
public class GaugeProtos {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ditto, move to and from methods to the GaugeResult class.

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.

similarly to above, I tried this, but (shaded) com.google.protobuf.Timestamp ends up in the public API surface of downstream modules, which feels icky. I've reverted this back to GaugeProtos.

I don't mind small files of static helpers doing specific things, but lmk if you think I should put this back in core or what.

public static GaugeResult fromProto(long value, Timestamp timestamp) {
return GaugeResult.create(
value,
new Instant(
SECONDS.toMillis(timestamp.getSeconds()) + NANOSECONDS.toMillis(timestamp.getNanos())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {

@ryan-williams ryan-williams Feb 23, 2019 •

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.

this is a result of introducing a MetricName constructor (MonitoringInfoMetricName.named) that can return a "system" MonitoringInfoMetricName or a "user" AutoValue_MetricName.

previous discussion: #7876 (comment)

MonitoringInfoMetricName goes away altogether in #7915; it is conceptually a MetricKey (not a MetricName), and I line everything up accordingly in that PR.

return new DelegatingCounter(metricName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
/*
* 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}.
*
* <p>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}.
*
* <p>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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Making the attampted/committed value just a parameter will simplify things, rather than maintaining separate collections for both

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.

If you mean folding it into the MI (as a label), yea, that would make this code simpler.

I don't think we have agreement on that idea yet even between you, me, and @robertwb; are you in favor of that? We'd need to go to the ML as well.

idk whether it's worth trying to merge a version that leaks {attempted,committed} at the top level of the proto, in the meantime. Something for us to discuss…


/** 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();
addMetricResultsToBuilder(
builder, results.getCounters(), SimpleMonitoringInfoBuilder::setInt64Value);
addMetricResultsToBuilder(
builder, results.getDistributions(), SimpleMonitoringInfoBuilder::setIntDistributionValue);
addMetricResultsToBuilder(
builder, results.getGauges(), SimpleMonitoringInfoBuilder::setGaugeValue);
return builder.build();
}

/**
* 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 <T> void addMetricResultsToBuilder(
MetricsApi.MetricResults.Builder builder,
Iterable<MetricResult<T>> metricResults,
BiConsumer<SimpleMonitoringInfoBuilder, T> set) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The use of this BiConsumer is really hard to follow especially since its using SimpleMonitoringInfoBuilder. Can you rewrite this file so that you don't need to do this callback passing.

I think most of this is unncessary since everything is the same except for the value you are setting (gauge vs distribution vs counter).

Would you mind trying this instead: I think this will reduce code length as well.
(1) call a helper method to set the labels, metric name, etc. on the SimpleMonitoringInfo
(2) then call a separate method to set the counter, gauge or distribution afterward
(3) Then call a helper method to add it to the collection structure.

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.

Here is what toProto is doing:

  • for type in {counters, distributions, gauges}:
    • for each instance of type:
      • for each kind in {attempted, committed}:
        • SIMB.setLabelsAndUrn
        • add instance value to SIMB using type-specific SIMB helper
        • SIMB.build
        • null check + add result MI using kind-specific helper

That inner logic is going to be typed 6 times (3 types * 2 kinds, and the former is likely to grow!) unless we abstract over one or both axes using callbacks.

To me, the latter is clearer and less bug-prone (that null check is tricky and likely to change, and should be funneled through as few call-sites as possible, representing the official way to transit the relevant APIs).

I think your proposal is to split bits of the innermost logic into separate passes over the 3 containing loops. I'm skeptical that's going to be cleaner; please sketch it in more detail if you think it will be.

for (MetricResult<T> metricResult : metricResults) {
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 <T> void addMetricToBuilder(
MetricsApi.MetricResults.Builder builder,
MetricKey metricKey,
T value,
BiConsumer<SimpleMonitoringInfoBuilder, T> set,
BiConsumer<MetricsApi.MetricResults.Builder, MonitoringInfo> add) {
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}.
*
* <p>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<MetricKey, MetricResultBuilder<Long>> counters = new ConcurrentHashMap<>();
private final Map<MetricKey, MetricResultBuilder<DistributionResult>> distributions =
new ConcurrentHashMap<>();
private final Map<MetricKey, MetricResultBuilder<GaugeResult>> 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<MonitoringInfo> monitoringInfos, Boolean committed) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

return this to implement builder patern

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.

this isn't really a builder in that sense; maybe there's another name I should give it?

all these methods are private and only called from the constructor.

I've renamed them to not be so overload-heavy.

lmk what you think

for (MonitoringInfo monitoringInfo : monitoringInfos) {
addMonitoringInfo(monitoringInfo, committed);
}
}

/** Helper for turning a map of result-builders into a sequence of results. */
Comment thread
ryan-williams marked this conversation as resolved.
Resolved
private static <T> List<MetricResult<T>> build(Map<MetricKey, MetricResultBuilder<T>> map) {
return map.values().stream().map(MetricResultBuilder::build).collect(toList());
}

private void addMonitoringInfo(MonitoringInfo monitoringInfo, Boolean committed) {
MetricKey metricKey = keyFromMonitoringInfo(monitoringInfo);
forEachMetricType(
monitoringInfo,
counter -> addMetricToResultMap(metricKey, counter, committed, counters),
distribution -> addMetricToResultMap(metricKey, distribution, committed, distributions),
gauge -> addMetricToResultMap(metricKey, gauge, committed, gauges));
}

private <T> void addMetricToResultMap(
MetricKey key, T value, Boolean committed, Map<MetricKey, MetricResultBuilder<T>> 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.
*
* <p>Used while traversing {@link MonitoringInfo} lists where they are stored separately.
*/
private static class MetricResultBuilder<T> {
private final MetricKey key;
private final T attempted;
@Nullable private T committed;

public MetricResultBuilder(MetricKey key, T attempted) {
this.key = key;
this.attempted = attempted;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Add a setAttempted for both
I would say the default is that committed are the only ones emitted by an SDK, which come from the ProcessBundleResponse, while attempted come from the ProcessBundleProgressResponse, requiring a lot more work.

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.

This is only used when we know we have an "attempted", and we may or may not have a "committed". All runners today populate "attempted", but only some populate "committed".

Encoding [the knowledge that we always have "attempted" here] makes build not have to do any checking; attempted is final and non-@Nullable (unlike committed, but that's ok because MetricResult also encodes this fact).

I found it cleaner than an approach that pretended to be more general (this is a private static class with just the logic it uses), though I understand calling it a Builder may be confusing / unidiomatic.

lmk if I should rename it, or still make it a more general "builder"-pattern, or what you think.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I don't think your assumption is correct. You could assume attempted == committed values. But the java SDK for example doesn't return the ProgressBundleResponse metrics which would be used for attempted metrics.

@ryan-williams ryan-williams Feb 28, 2019 •

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.

There are a couple meanings of {"attempted", "committed"} floating around.

You've implied they correspond to MIs that come in via {ProcessBundleProgressResponse, ProcessBundleResponse}, resp., but there's a pre-fn-api {"physical", "logical"} meaning that most existing code uses.

I'm not trying to resolve these two meanings in this PR. I wrote things to conform to exactly what was already happening, while still supporting the changes I'm attempting to make (which require converting between [new proto] and [existing SDK] representations of metrics).

What was already happening, that I'm preserving, is:

In this private static helper, I've written the simplest conversion I can manage between [an attempted metric value] and [optional corresponding committed value that comes in via a different proto field] and a MetricResult that joins them.

lmk if that doesn't make sense!

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Is this wording backwards? Committed generally refers to something persisted to disk, so physical seemed like the appropriate word to match with it.

"attempted" ("physical")
"committed" ("logical")

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 don't think it is backwards.

"attempted" is "physical" in the sense that multiple attempts of the same work will physically do work (e.g. read bytes from disk).

OTOH, only one instance of any given piece of work should be "committed", and will correspond to the "logical" amount you expect to be processed (e.g. number of elements in a collection).

}

public void setCommitted(T committed) {
this.committed = committed;
}

public MetricResult<T> build() {
return MetricResult.create(key, committed, attempted);
}
}
}
}
Loading