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 @@ -21,8 +21,10 @@

import com.google.common.collect.ImmutableList;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo;
import org.apache.beam.runners.core.construction.metrics.MetricKey;
import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate;
import org.apache.beam.sdk.annotations.Experimental;
Expand Down Expand Up @@ -136,6 +138,23 @@ public MetricUpdates getUpdates() {
extractUpdates(counters), extractUpdates(distributions), extractUpdates(gauges));
}

/** Return the cumulative values for any metrics in this container as MonitoringInfos. */
public Iterable<MonitoringInfo> getMonitoringInfos() {
// Extract user metrics and store as MonitoringInfos.
ArrayList<MonitoringInfo> monitoringInfos = new ArrayList<MonitoringInfo>();
MetricUpdates mus = this.getUpdates();

for (MetricUpdate<Long> mu : mus.counterUpdates()) {
SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder(true);
builder.setUrnForUserMetric(
mu.getKey().metricName().getNamespace(), mu.getKey().metricName().getName());
builder.setInt64Value(mu.getUpdate());
builder.setTimestampToNow();
monitoringInfos.add(builder.build());
}
return monitoringInfos;
}

private void commitUpdates(MetricsMap<MetricName, ? extends MetricCell<?>> cells) {
for (MetricCell<?> cell : cells.values()) {
cell.getDirty().afterCommit();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,16 @@
import java.util.concurrent.ThreadFactory;
import java.util.function.Function;
import org.apache.beam.fn.harness.FnHarness;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo;
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.Target;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.runners.core.construction.PipelineTranslation;
import org.apache.beam.runners.core.construction.graph.ExecutableStage;
import org.apache.beam.runners.core.construction.graph.FusedPipeline;
import org.apache.beam.runners.core.construction.graph.GreedyPipelineFuser;
import org.apache.beam.runners.core.metrics.SimpleMonitoringInfoBuilder;
import org.apache.beam.runners.fnexecution.GrpcContextHeaderAccessorProvider;
import org.apache.beam.runners.fnexecution.GrpcFnServer;
import org.apache.beam.runners.fnexecution.InProcessServerFactory;
Expand Down Expand Up @@ -83,6 +87,7 @@
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.fn.stream.OutboundObserverFactory;
import org.apache.beam.sdk.fn.test.InProcessManagedChannelFactory;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.state.BagState;
import org.apache.beam.sdk.state.ReadableState;
Expand All @@ -109,16 +114,20 @@
import org.apache.beam.sdk.values.PCollectionList;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.vendor.grpc.v1_13_1.com.google.protobuf.ByteString;
import org.hamcrest.CoreMatchers;
import org.hamcrest.collection.IsEmptyIterable;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.joda.time.DateTimeUtils;
import org.joda.time.Duration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Tests the execution of a pipeline from specification time to executing a single fused stage,
Expand All @@ -128,6 +137,8 @@
public class RemoteExecutionTest implements Serializable {
@Rule public transient ResetDateTimeProvider resetDateTimeProvider = new ResetDateTimeProvider();

private static final Logger LOG = LoggerFactory.getLogger(RemoteExecutionTest.class);

private transient GrpcFnServer<FnApiControlClientPoolService> controlServer;
private transient GrpcFnServer<GrpcDataService> dataServer;
private transient GrpcFnServer<GrpcStateService> stateServer;
Expand Down Expand Up @@ -486,6 +497,124 @@ public Coder<V> resultCoder() {
}
}

@Test
public void testMetrics() throws Exception {
final String counterMetricName = "counterMetric";
Pipeline p = Pipeline.create();
PCollection<String> input =
p.apply("impulse", Impulse.create())
.apply(
"create",
ParDo.of(
new DoFn<byte[], String>() {
@ProcessElement
public void process(ProcessContext ctxt) {
Metrics.counter(RemoteExecutionTest.class, counterMetricName).inc();
}
}))
.setCoder(StringUtf8Coder.of());

RunnerApi.Pipeline pipelineProto = PipelineTranslation.toProto(p);
FusedPipeline fused = GreedyPipelineFuser.fuse(pipelineProto);
Optional<ExecutableStage> optionalStage =
Iterables.tryFind(fused.getFusedStages(), (ExecutableStage stage) -> true);
checkState(optionalStage.isPresent(), "Expected a stage with side inputs.");
ExecutableStage stage = optionalStage.get();

ExecutableProcessBundleDescriptor descriptor =
ProcessBundleDescriptors.fromExecutableStage(
"test_stage",
stage,
dataServer.getApiServiceDescriptor(),
stateServer.getApiServiceDescriptor());

BundleProcessor processor =
controlClient.getProcessor(
descriptor.getProcessBundleDescriptor(),
descriptor.getRemoteInputDestinations(),
stateDelegator);

Map<Target, Coder<WindowedValue<?>>> outputTargets = descriptor.getOutputTargetCoders();
Map<Target, Collection<WindowedValue<?>>> outputValues = new HashMap<>();
Map<Target, RemoteOutputReceiver<?>> outputReceivers = new HashMap<>();
for (Entry<Target, Coder<WindowedValue<?>>> targetCoder : outputTargets.entrySet()) {
List<WindowedValue<?>> outputContents = Collections.synchronizedList(new ArrayList<>());
outputValues.put(targetCoder.getKey(), outputContents);
outputReceivers.put(
targetCoder.getKey(),
RemoteOutputReceiver.of(targetCoder.getValue(), outputContents::add));
}

Iterable<byte[]> sideInputData =
Arrays.asList(
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "A"),
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "B"),
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "C"));

StateRequestHandler stateRequestHandler =
StateRequestHandlers.forSideInputHandlerFactory(
descriptor.getSideInputSpecs(),
new SideInputHandlerFactory() {
@Override
public <T, V, W extends BoundedWindow> SideInputHandler<V, W> forSideInput(
String pTransformId,
String sideInputId,
RunnerApi.FunctionSpec accessPattern,
Coder<T> elementCoder,
Coder<W> windowCoder) {
return new SideInputHandler<V, W>() {
@Override
public Iterable<V> get(byte[] key, W window) {
return (Iterable) sideInputData;
}

@Override
public Coder<V> resultCoder() {
return ((KvCoder) elementCoder).getValueCoder();
}
};
}
});

BundleProgressHandler progressHandler =
new BundleProgressHandler() {
@Override
public void onProgress(ProcessBundleProgressResponse progress) {}

@Override
public void onCompleted(ProcessBundleResponse response) {
// Assert the timestamps are non empty then 0 them out before comparing.
List<MonitoringInfo> actualMIs = new ArrayList<>();
for (MonitoringInfo mi : response.getMonitoringInfosList()) {
MonitoringInfo.Builder builder = MonitoringInfo.newBuilder();
Assert.assertTrue(mi.getTimestamp().getSeconds() > 0);
builder.mergeFrom(mi);
builder.clearTimestamp();
actualMIs.add(builder.build());
}

SimpleMonitoringInfoBuilder builder = new SimpleMonitoringInfoBuilder();
builder.setUrnForUserMetric(RemoteExecutionTest.class.getName(), counterMetricName);
builder.setInt64Value(2);
MonitoringInfo expectedCounter = builder.build();

assertThat(actualMIs, CoreMatchers.hasItems(expectedCounter));
}
};

try (ActiveBundle bundle =
processor.newBundle(outputReceivers, stateRequestHandler, progressHandler)) {
Iterables.getOnlyElement(bundle.getInputReceivers().values())
.accept(
WindowedValue.valueInGlobalWindow(
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "X")));
Iterables.getOnlyElement(bundle.getInputReceivers().values())
.accept(
WindowedValue.valueInGlobalWindow(
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "Y")));
}
}

@Test
public void testExecutionWithUserState() throws Exception {
Pipeline p = Pipeline.create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
Expand All @@ -47,6 +48,7 @@
import org.apache.beam.model.fnexecution.v1.BeamFnApi;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.BundleApplication;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.DelayedBundleApplication;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.MonitoringInfo;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleDescriptor;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleRequest;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleResponse;
Expand All @@ -60,8 +62,10 @@
import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform;
import org.apache.beam.model.pipeline.v1.RunnerApi.WindowingStrategy;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.metrics.MetricsContainerImpl;
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.fn.function.ThrowingRunnable;
import org.apache.beam.sdk.metrics.MetricsEnvironment;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.util.common.ReflectHelpers;
Expand Down Expand Up @@ -292,21 +296,29 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction
splitListener);
}

// Already in reverse topological order so we don't need to do anything.
for (ThrowingRunnable startFunction : startFunctions) {
LOG.debug("Starting function {}", startFunction);
startFunction.run();
}
MetricsContainerImpl metricsContainer = new MetricsContainerImpl(request.getInstructionId());
try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) {

// Already in reverse topological order so we don't need to do anything.
for (ThrowingRunnable startFunction : startFunctions) {
LOG.debug("Starting function {}", startFunction);
startFunction.run();
}

queueingClient.drainAndBlock();
queueingClient.drainAndBlock();

// Need to reverse this since we want to call finish in topological order.
for (ThrowingRunnable finishFunction : Lists.reverse(finishFunctions)) {
LOG.debug("Finishing function {}", finishFunction);
finishFunction.run();
}
if (!allResiduals.isEmpty()) {
response.addAllResidualRoots(allResiduals.values());
// Need to reverse this since we want to call finish in topological order.
for (ThrowingRunnable finishFunction : Lists.reverse(finishFunctions)) {
LOG.debug("Finishing function {}", finishFunction);
finishFunction.run();
}
if (!allResiduals.isEmpty()) {
response.addAllResidualRoots(allResiduals.values());
}

for (MonitoringInfo mi : metricsContainer.getMonitoringInfos()) {
response.addMonitoringInfos(mi);
}
}
}

Expand Down
Loading