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
53 changes: 6 additions & 47 deletions model/fn-execution/src/main/proto/beam_fn_api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -501,48 +501,9 @@ message MonitoringInfoTypeUrns {
message Metric {
// (Required) The data for this metric.
oneof data {
CounterData counter_data = 1;
DistributionData distribution_data = 2;
ExtremaData extrema_data = 3;
}
}

// Data associated with a Counter or Gauge metric.
// This is designed to be compatible with metric collection
// systems such as DropWizard.
message CounterData {
oneof value {
int64 int64_value = 1;
double double_value = 2;
string string_value = 3;
}
}

// Extrema messages are used for calculating
// Top-N/Bottom-N metrics.
message ExtremaData {
oneof extrema {
IntExtremaData int_extrema_data = 1;
DoubleExtremaData double_extrema_data = 2;
}
}

message IntExtremaData {
repeated int64 int_values = 1;
}

message DoubleExtremaData {
repeated double double_values = 2;
}

// Data associated with a distribution metric.
// This is based off of the current DistributionData metric.
// This is not a stackdriver or dropwizard compatible
// style of distribution metric.
message DistributionData {
oneof distribution {
IntDistributionData int_distribution_data = 1;
DoubleDistributionData double_distribution_data = 2;
int64 counter = 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

There was long debate when, and the existing protos were what we could agree on when we introduced this design. While I am fine with this change you are proposing personally. I'd like you to get buy in on the dev list.

https://s.apache.org/beam-fn-api-metrics

https://lists.apache.org/list.html?dev@beam.apache.org:2018-2

I think most of it was in the comments of the doc. So unfortunately, I cannot point you toward too much.

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 don't have strong opinion about removing CounterData, but I'm concerned that we make counter int64. In my opinion, double will be much more flexible.

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.

Thanks for the info and pointers!

I was just going off of what seemed to be already supported in the Java and Python SDKs.

In particular, existing Java metrics are all in terms of long, and I thought I discussed keeping that and dropping these other types with someone (@robertwb?) in the course of planning this work.

I'll read those links and we can discuss further.

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 don't remember discussing this, it must have been with someone else.

I agree that supporting double counters (and especially distributions) would be useful. Also, we haven't really nailed down what the global semantics are for gauge metrics.

My position was, and remains, that reifying the exact set of supported metric types via a set of nested set of protos is not a stable, long-term solution. It took a long time to come up with this list, and here we are 6 months later changing it. (And change will become harder the more we actually use these protos everywhere.) Instead, data should be either (1) a bytes field or (2) something like

message data {
repeated int64 int_data = 1;
repeated double double_data = 2;
repeated string string_data = 3;
...?
}

with the type specifying its encoding into this data attribute. We can then support everything from simple counters to complex distributions without changing the protos, only introducing new types, where the set of types are defined by URNs, and runners simply pass through types they do not understand. This is consistent with the rest of the way the FnAPI works as well (e.g. coders, transforms, ...)

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.

Thanks Robert. It seems we're stuck between 3 data models:

  1. existing protos
    • {int,double,string} counters
    • {int,double} x {distribution,extrema}
    • unused in SDKs
  2. deprecated protos
    • int64-only {counter, distribution, gauge}
    • supported in Java, Python SDKs
  3. opaque bytes-payloads

In this PR, I changed (1)'s protos to match the SDK support that is modeled on (2), which is probably wrong!

(3) sgtm but seems like it is not the existing consensus / spec.

I think the larger goal (sending metrics over the job API) requires converting between SDK and proto metrics structures (in both directions), so they need to match.

Maybe there is a way I can side-step that, or maybe we can just get to the real long-term solution here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@robertwb I'd like to push back a bit about a significant change, where we use opaque bytes payloads.

I am okay with removing the layers in this proto and using the design Ryan has proposed here. But not an extensive rewrite at this stage of the game, which will slow down progress significantly.

We have protos for the MonitoringInfoTable. This solution is the extensible format, where you can store basically anything and the producer and consumer of this proto can be the only ones who need to understand it (and it could be passed through the RunnerHarness)

message MonitoringTableData {

But we chose to have separate protos for the common well known metric formats (Metrics being a well defined concept shared by many systems, i.e. a timeseries of data): counter, gauge, distribution, etc.

Additionally, if you wish to modify these formats significantly at a future stage, you can always

  • add to these protos without deleting
  • Change the URN version number of a metric
  • Upgrade all SDKs to package the metric with a format for the previous and new version number of the URN
  • Upgrade all Runners that wish to support it.

Upgrading the URN version is the safe way to do this without introducing a breaking change, as consumers of MonitoringInfos can freely chose which URNs+versions they support.

IntDistributionData distribution = 2;
IntGaugeData gauge = 3;

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 one thing worth pointing out here, is that we never introduced this before because this only holds an int64, which is the same as a counter, which holds an int64 (Note you don't need the timestamp inside IntGaugeData), as its already in the MonitoringInfo proto.

So we didn't include both as separate fields in the oneof. You would just specify which way it is aggregated using the MonitoringInfo type field.

}
}

Expand All @@ -553,11 +514,9 @@ message IntDistributionData {
int64 max = 4;
}

message DoubleDistributionData {
int64 count = 1;
double sum = 2;
double min = 3;
double max = 4;
message IntGaugeData {

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 there a use case for this at the moment? Are you implementing these right now?

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.

Yea, in #7823 I support all the types here (counters, distributions, gauges) everywhere in Java; I think Python already supports them as well, but need to dig in to that further.

int64 value = 1;
int64 timestamp_ms = 2;

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 we keep this on the top level of the MonitoringInfo

}

// General MonitoredState information which contains
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ public abstract class MetricKey implements Serializable {

@Override
public String toString() {
return String.format("%s:%s", stepName(), metricName());
return toString(":");
}

public String toString(String delimiter) {
return String.format("%s%s%s", stepName(), delimiter, metricName().toString(delimiter));
}

public static MetricKey create(String stepName, MetricName metricName) {
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.fnexecution.v1.BeamFnApi.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();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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.fnexecution.v1.BeamFnApi.IntGaugeData;
import org.apache.beam.sdk.metrics.GaugeResult;
import org.joda.time.Instant;

/** Convert gauges between protobuf and SDK representations. */
public class GaugeProtos {
public static GaugeResult fromProto(IntGaugeData gaugeData) {
return GaugeResult.create(gaugeData.getValue(), new Instant(gaugeData.getTimestampMs()));
}

public static IntGaugeData toProto(GaugeResult gauge) {
return IntGaugeData.newBuilder()
.setValue(gauge.getValue())
.setTimestampMs(gauge.getTimestamp().getMillis())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@

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
* more convenient way to collect the necessary fields to repackage the metric into a MonitoringInfo
* proto later. Intended for internal use only (SDK and RunnerHarness developement).
* proto later. Intended for internal use only (SDK and RunnerHarness development).
*/
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Let's keep it as MonitoringInfoMetricName, since this is meant to be an implementation only used by SDK and RunnerHarness authors. For creating system style metrics with URN+labels,

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.

Quick explanation for why this changed:

Before this PR, MetricName.named allowed creating (user-)metrics from {namespace,name}, while MonitoringInfoMetricName.named created metrics from {URN, labels}.

The latter can create user- or system-metrics, but naively creating MonitoringInfoMetricNames for user-metrics is dangerous: they don't hash/equal the "same" metric created via MetricName.named, which I ran into in tests.

Meanwhile, user code wants to make metrics from arbitrary MonitoringInfos, so a single API for that makes sense, but it should return a MetricName (AutoValue) for user-URNs, and a MonitoringInfoMetricName otherwise; I've changed the MonitoringInfoMetricName constructor to do that in this PR. That means that it returns a MetricName, not a MonitoringInfoMetricName.

Ultimately (#7823), I merge these two into something that looks like MonitoringInfoMetricName but is called MetricName. In the meantime, there's little cost to using MetricName as the super-type of both.

So, re: your comment here, I could create an additional MonitoringInfoMetricName constructor that's only to be used for system metric URNs, and have ElementCountFnDataReceiver call that here instead, and then pass the MonitoringInfoMetricName it got to LabeledMetrics.Counter here, but I don't think that is worth it.

That new constructor would feel unsafe if it didn't validate that the passed URN was in fact a system-metric, and that would start to be a lot of overhead, when LabeledMetrics.Counter (and other callers) don't actually care whether they are dealing with a system- or user-metric.

So that's the whole story 😄 ! lmk what you think.

return new DelegatingCounter(metricName);
}
}
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.
*/
@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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,19 @@
*/
package org.apache.beam.runners.core.metrics;

import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PCOLLECTION_LABEL;
import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX;
import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import javax.annotation.Nullable;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo;
import org.apache.beam.sdk.metrics.MetricName;
import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings;

Expand All @@ -39,9 +43,9 @@ public class MonitoringInfoMetricName extends MetricName {
private String urn;
@Nullable private String name;
@Nullable private String namespace;
private HashMap<String, String> labels = new HashMap<String, String>();
private Map<String, String> labels = new HashMap<>();

private MonitoringInfoMetricName(String urn, HashMap<String, String> labels) {
private MonitoringInfoMetricName(String urn, Map<String, String> 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
Expand All @@ -54,7 +58,7 @@ private MonitoringInfoMetricName(String urn, HashMap<String, String> labels) {

/** Parse the urn field into a name and namespace field. */
private void parseUrn() {
if (this.urn.startsWith(SimpleMonitoringInfoBuilder.USER_COUNTER_URN_PREFIX)) {
if (this.urn.startsWith(USER_COUNTER_URN_PREFIX)) {
List<String> split = new ArrayList<String>(Arrays.asList(this.getUrn().split(":")));
this.name = split.get(split.size() - 1);
this.namespace = split.get(split.size() - 2);
Expand Down Expand Up @@ -85,12 +89,31 @@ public String getUrn() {
}

/** @return The labels associated with this MonitoringInfo. */
public HashMap<String, String> getLabels() {
public Map<String, String> getLabels() {
return this.labels;
}

public static MonitoringInfoMetricName named(String urn, HashMap<String, String> labels) {
return new MonitoringInfoMetricName(urn, labels);
/**
* Polymorphic constructor of {@link MetricName}s.
*
* <p>If `urn` is a {@link SimpleMonitoringInfoBuilder#USER_COUNTER_URN_PREFIX user metric},
* return a {@link MetricName} auto-value (which will {@link Object#equals equal} and {@link
* Object#hashCode hash} consistently with other {@link MetricName}s.
*
* <p>Otherwise, return a concrete {@link MonitoringInfoMetricName} representing a "system"
* metric.
*/
public static MetricName named(String urn, Map<String, String> labels) {
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. */
public static MetricName create(MonitoringInfo monitoringInfo) {
return named(monitoringInfo.getUrn(), monitoringInfo.getLabelsMap());
}

@Override
Expand All @@ -113,11 +136,15 @@ public boolean equals(Object o) {
}

@Override
public String toString() {
public String toString(String delimiter) {
if (getNamespace() != null && getName() != null) {
return super.toString(delimiter);
}
StringBuilder builder = new StringBuilder();
builder.append(this.urn.toString());
builder.append(" ");
builder.append(this.labels.toString());
if (labels.containsKey(PCOLLECTION_LABEL)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

just iterate over the keyas and values and add them to the return string, instead of inspecting the labels for specific keys.

Then there is no need to update this code for new labels.

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 wrote things that way in several places initially, but ran into interesting problems that we'll need to discuss eventually, so I'll describe them below.

Here's what happens in this PR if I naively append the label kv-pairs: ryan-williams@5576286.

Note that Flink receives a metric with the unseemly name step.PTRANSFORM.step.PCOLLECTION.pcoll.beam.metric.element_count.v1 (which goes e.g. to the Flink web UI, which we've taken pains to make more human-readable).

The first step there is added by MetricKey.toString, which calls this MetricName.toString routine, expecting info about the metric's "name" (URN) only.

MetricKey vs MetricName

The issue, In my view, is that MonitoringInfoMetricName is actually more of a MetricKey implementation:

  • MetricKey ≈ MonitoringInfoMetricName ({URN, labels})
    • stepName ≈ [labels map with just a PTRANSFORM entry]
    • MetricName ≈ URN
  • MetricResult ≈ MonitoringInfo ({key, metric value})

I ultimately lay things out in this manner in #7823, folding MIMN into MetricKey.

Special-casing single-label ptransform/pcollection-scoped metrics

A bigger issue is that I think runners and endpoints are going to want to hard-code [the only 2 cases that we will have for the foreseeable future]: <ptransform>.<namespace>.<name> and <pcollection>.<urn> (<ptransform>.<urn> folds into this nicely as well).

They'll do this for backwards-compat reasons, and/or to make things look nice in e.g. web UIs. I've touched code like this in at least the Samza, Flink, and Spark runners (and that MetricsHttpSink we were looking at).

I think it's great that the wire format is extensible to many+new labels, but ended up feeling that the SDK should provide the APIs that deal specifically with the shapes all calling code will care about atm.

Sorry that's a lot! I don't care much what we do in this case, but I think we'll have some harder similar choices shortly 😲 lmk what you think.

builder.append(labels.get(PCOLLECTION_LABEL)).append(delimiter);
}
builder.append(this.urn.replaceAll(":", delimiter));
return builder.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.core.metrics;

import static org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder.PTRANSFORM_LABEL;

import java.util.function.Consumer;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.Metric;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo;
import org.apache.beam.runners.core.construction.metrics.MetricKey;
import org.apache.beam.sdk.metrics.DistributionResult;
import org.apache.beam.sdk.metrics.GaugeResult;

/**
* Helpers for working with {@link Metric}s and converting {@link MonitoringInfo}s to {@link
* MetricKey}s.
*/
public class MonitoringInfos {

/**
* Helper for handling each case of a {@link Metric}'s "oneof" value field (counter, distribution,
* or gauge).
*/
public static void processMetric(
Metric metric,
Consumer<Long> counterFn,
Consumer<DistributionResult> distributionFn,
Consumer<GaugeResult> gaugeFn) {
Metric.DataCase dataCase = metric.getDataCase();
switch (dataCase) {
case COUNTER:
counterFn.accept(metric.getCounter());
break;
case DISTRIBUTION:
distributionFn.accept(DistributionProtos.fromProto(metric.getDistribution()));
break;
case GAUGE:
gaugeFn.accept(GaugeProtos.fromProto(metric.getGauge()));
break;
case DATA_NOT_SET:
throw new IllegalStateException("Metric value not set: " + metric);
}
}

public static MetricKey keyFromMonitoringInfo(MonitoringInfo monitoringInfo) {
String ptransform = monitoringInfo.getLabelsMap().get(PTRANSFORM_LABEL);
return MetricKey.create(ptransform, MonitoringInfoMetricName.create(monitoringInfo));
}
}
Loading