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,6 +21,7 @@
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.common.base.Optional;
Expand Down Expand Up @@ -278,6 +279,91 @@ public void process(ProcessContext ctxt) {
}
}

@Test
public void testBundleProcessorThrowsExecutionExceptionWhenUserCodeThrows() throws Exception {
Pipeline p = Pipeline.create();
p.apply("impulse", Impulse.create())
.apply(
"create",
ParDo.of(
new DoFn<byte[], KV<String, String>>() {
@ProcessElement
public void process(ProcessContext ctxt) throws Exception {
String element =
CoderUtils.decodeFromByteArray(StringUtf8Coder.of(), ctxt.element());
if (element.equals("X")) {
throw new Exception("testBundleExecutionFailure");
}
ctxt.output(KV.of(element, element));
}
}))
.apply("gbk", GroupByKey.create());

RunnerApi.Pipeline pipelineProto = PipelineTranslation.toProto(p);

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.

[No action comment]
Do I understand correctly that you build bundle to process?
If it is, it might be useful to extract such code to share between tests. I might reuse it in some other places.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ack

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ack, good idea. Though I am not sure how to best do this. We can design this together if you would like

FusedPipeline fused = GreedyPipelineFuser.fuse(pipelineProto);
checkState(fused.getFusedStages().size() == 1, "Expected exactly one fused stage");
ExecutableStage stage = fused.getFusedStages().iterator().next();

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

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

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

try {
try (ActiveBundle bundle =
processor.newBundle(outputReceivers, BundleProgressHandler.ignored())) {
Iterables.getOnlyElement(bundle.getInputReceivers().values())
.accept(
WindowedValue.valueInGlobalWindow(
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "X")));
}
// Fail the test if we reach this point and never threw the exception.
fail();
} catch (ExecutionException e) {
assertTrue(e.getMessage().contains("testBundleExecutionFailure"));
}

try (ActiveBundle bundle =
processor.newBundle(outputReceivers, BundleProgressHandler.ignored())) {
Iterables.getOnlyElement(bundle.getInputReceivers().values())
.accept(
WindowedValue.valueInGlobalWindow(
CoderUtils.encodeToByteArray(StringUtf8Coder.of(), "Z")));
}

for (Collection<? super WindowedValue<?>> windowedValues : outputValues.values()) {
assertThat(
windowedValues,
containsInAnyOrder(
WindowedValue.valueInGlobalWindow(kvBytes("Y", "Y")),
WindowedValue.valueInGlobalWindow(kvBytes("Z", "Z"))));
}
}

@Test
public void testExecutionWithSideInput() throws Exception {
Pipeline p = Pipeline.create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.apache.beam.fn.harness.PTransformRunnerFactory;
import org.apache.beam.fn.harness.PTransformRunnerFactory.Registrar;
import org.apache.beam.fn.harness.data.BeamFnDataClient;
import org.apache.beam.fn.harness.data.QueueingBeamFnDataClient;
import org.apache.beam.fn.harness.state.BeamFnStateClient;
import org.apache.beam.fn.harness.state.BeamFnStateGrpcClientCache;
import org.apache.beam.model.fnexecution.v1.BeamFnApi;
Expand Down Expand Up @@ -138,6 +139,7 @@ public ProcessBundleHandler(

private void createRunnerAndConsumersForPTransformRecursively(
BeamFnStateClient beamFnStateClient,
BeamFnDataClient queueingClient,
String pTransformId,
PTransform pTransform,
Supplier<String> processBundleInstructionId,
Expand All @@ -158,6 +160,7 @@ private void createRunnerAndConsumersForPTransformRecursively(
for (String consumingPTransformId : pCollectionIdsToConsumingPTransforms.get(pCollectionId)) {
createRunnerAndConsumersForPTransformRecursively(
beamFnStateClient,
queueingClient,
consumingPTransformId,
processBundleDescriptor.getTransformsMap().get(consumingPTransformId),
processBundleInstructionId,
Expand Down Expand Up @@ -188,7 +191,7 @@ private void createRunnerAndConsumersForPTransformRecursively(
.getOrDefault(pTransform.getSpec().getUrn(), defaultPTransformRunnerFactory)
.createRunnerForPTransform(
options,
beamFnDataClient,
queueingClient,
beamFnStateClient,
pTransformId,
pTransform,
Expand All @@ -204,8 +207,17 @@ private void createRunnerAndConsumersForPTransformRecursively(
}
}

/**
* Processes a bundle, running the start(), process(), and finish() functions. This function is
* required to be reentrant.
*/
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request)
throws Exception {
// Note: We must create one instance of the QueueingBeamFnDataClient as it is designed to
// handle the life of a bundle. It will insert elements onto a queue and drain them off so all
// process() calls will execute on this thread when queueingClient.drainAndBlock() is called.
QueueingBeamFnDataClient queueingClient = new QueueingBeamFnDataClient(this.beamFnDataClient);

String bundleId = request.getProcessBundle().getProcessBundleDescriptorReference();
BeamFnApi.ProcessBundleDescriptor bundleDescriptor =
(BeamFnApi.ProcessBundleDescriptor) fnApiRegistry.apply(bundleId);
Expand Down Expand Up @@ -255,6 +267,7 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction
// Create a BeamFnStateClient
for (Map.Entry<String, RunnerApi.PTransform> entry :
bundleDescriptor.getTransformsMap().entrySet()) {

// Skip anything which isn't a root
// TODO: Remove source as a root and have it be triggered by the Runner.
if (!DATA_INPUT_URN.equals(entry.getValue().getSpec().getUrn())
Expand All @@ -266,6 +279,7 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction

createRunnerAndConsumersForPTransformRecursively(
beamFnStateClient,
queueingClient,
entry.getKey(),
entry.getValue(),
request::getInstructionId,
Expand All @@ -284,6 +298,8 @@ public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.Instruction
startFunction.run();
}

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);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/*
* 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.fn.harness.data;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import org.apache.beam.fn.harness.control.ProcessBundleHandler;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.InstructionRequest;
import org.apache.beam.model.pipeline.v1.Endpoints;
import org.apache.beam.model.pipeline.v1.Endpoints.ApiServiceDescriptor;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.fn.data.CloseableFnDataReceiver;
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.fn.data.InboundDataClient;
import org.apache.beam.sdk.fn.data.LogicalEndpoint;
import org.apache.beam.sdk.util.WindowedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* A {@link BeamFnDataClient} that queues elements so that they can be consumed and processed in the
* thread which calls @{link #drainAndBlock}.
*/
public class QueueingBeamFnDataClient implements BeamFnDataClient {

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

private final BeamFnDataClient mainClient;
private final SynchronousQueue<ConsumerAndData> queue;
private final ConcurrentHashMap<InboundDataClient, Object> inboundDataClients;

public QueueingBeamFnDataClient(BeamFnDataClient mainClient) {
this.mainClient = mainClient;
this.queue = new SynchronousQueue<>();
this.inboundDataClients = new ConcurrentHashMap<>();
}

@Override
public <T> InboundDataClient receive(
ApiServiceDescriptor apiServiceDescriptor,
LogicalEndpoint inputLocation,
Coder<WindowedValue<T>> coder,
FnDataReceiver<WindowedValue<T>> consumer) {
LOG.debug(
"Registering consumer for instruction {} and target {}",
inputLocation.getInstructionId(),
inputLocation.getTarget());

QueueingFnDataReceiver<T> queueingConsumer = new QueueingFnDataReceiver<T>(consumer);

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 to queueingDataReceiver

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

This is synonymous. Not renaming. Consumer and receiver are used throughout the whole code base. Doing an entire code base rename would be worth doing if we pick and enforce a single term

InboundDataClient inboundDataClient =
this.mainClient.receive(apiServiceDescriptor, inputLocation, coder, queueingConsumer);
queueingConsumer.inboundDataClient = inboundDataClient;
this.inboundDataClients.computeIfAbsent(
inboundDataClient, (InboundDataClient idcToStore) -> idcToStore);
return inboundDataClient;
}

// Returns true if all the InboundDataClients have finished or cancelled.
private boolean allDone() {
for (InboundDataClient inboundDataClient : inboundDataClients.keySet()) {
if (!inboundDataClient.isDone()) {
return false;
}
}
return true;
}

/**
* Drains the internal queue of this class, by waiting for all WindowedValues to be passed to
* their consumers. The thread which wishes to process() the elements should call this method, as
* this will cause the consumers to invoke element processing. All receive() and send() calls must
* be made prior to calling drainAndBlock, in order to properly terminate.
*
* <p>All {@link InboundDataClient}s will be failed if processing throws an exception.
*
* <p>This method is NOT thread safe. This should only be invoked by a single thread, and is
* intended for use with a newly constructed QueueingBeamFnDataClient in {@link
* ProcessBundleHandler#processBundle(InstructionRequest)}.
*/
public void drainAndBlock() throws Exception {
while (true) {
try {
ConsumerAndData tuple = queue.poll(200, TimeUnit.MILLISECONDS);
if (tuple != null) {
// Forward to the consumers who cares about this data.
tuple.consumer.accept(tuple.data);
} else {
// Note: We do not expect to ever hit this point without receiving all values
// as (1) The InboundObserver will not be set to Done until the
// QueuingFnDataReceiver.accept() call returns and will not be invoked again.
// (2) The QueueingFnDataReceiver will not return until the value is received in
// drainAndBlock, because of the use of the SynchronousQueue.
if (allDone()) {
break;
}
}
} catch (Exception e) {
LOG.error("Client failed to dequeue and process WindowedValue", e);
for (InboundDataClient inboundDataClient : inboundDataClients.keySet()) {
inboundDataClient.fail(e);
}
throw e;
}
}
}

@Override
public <T> CloseableFnDataReceiver<WindowedValue<T>> send(
Endpoints.ApiServiceDescriptor apiServiceDescriptor,
LogicalEndpoint outputLocation,
Coder<WindowedValue<T>> coder) {
LOG.debug(
"Creating output consumer for instruction {} and target {}",
outputLocation.getInstructionId(),
outputLocation.getTarget());
return this.mainClient.send(apiServiceDescriptor, outputLocation, coder);
}

/**
* The QueueingFnDataReceiver is a a FnDataReceiver used by the QueueingBeamFnDataClient.
*
* <p>All {@link #accept accept()ed} values will be put onto a synchronous queue which will cause
* the calling thread to block until {@link QueueingBeamFnDataClient#drainAndBlock} is called.
* {@link QueueingBeamFnDataClient#drainAndBlock} is responsible for processing values from the
* queue.
*/
public class QueueingFnDataReceiver<T> implements FnDataReceiver<WindowedValue<T>> {
private final FnDataReceiver<WindowedValue<T>> consumer;
public InboundDataClient inboundDataClient;

public QueueingFnDataReceiver(FnDataReceiver<WindowedValue<T>> consumer) {
this.consumer = consumer;
}

/**
* This method is thread safe, we expect multiple threads to call this, passing in data when new
* data arrives via the QueueingBeamFnDataClient's mainClient.
*/
@Override
public void accept(WindowedValue<T> value) throws Exception {
try {
ConsumerAndData offering = new ConsumerAndData(this.consumer, value);
while (!queue.offer(offering, 200, TimeUnit.MILLISECONDS)) {
if (inboundDataClient.isDone()) {
// If it was cancelled by the consuming side of the queue.
break;
}
}
} catch (Exception e) {
LOG.error("Failed to insert WindowedValue into the queue", e);
inboundDataClient.fail(e);
throw e;
}
}
}

static class ConsumerAndData<T> {
public FnDataReceiver<WindowedValue<T>> consumer;
public WindowedValue<T> data;

public ConsumerAndData(FnDataReceiver<WindowedValue<T>> receiver, WindowedValue<T> data) {
this.consumer = receiver;
this.data = data;
}
}
}
Loading