Search in sources :

Example 1 with MailboxProcessor

use of org.apache.flink.streaming.runtime.tasks.mailbox.MailboxProcessor in project flink by apache.

the class StreamTask method afterInvoke.

protected void afterInvoke() throws Exception {
    LOG.debug("Finished task {}", getName());
    getCompletionFuture().exceptionally(unused -> null).join();
    Set<CompletableFuture<Void>> terminationConditions = new HashSet<>();
    // continue perform checkpoints.
    if (endOfDataReceived && areCheckpointsWithFinishedTasksEnabled()) {
        LOG.debug("Waiting for all the records processed by the downstream tasks.");
        for (ResultPartitionWriter partitionWriter : getEnvironment().getAllWriters()) {
            terminationConditions.add(partitionWriter.getAllDataProcessedFuture());
        }
        terminationConditions.add(finalCheckpointCompleted);
    }
    if (syncSavepoint != null) {
        terminationConditions.add(finalCheckpointCompleted);
    }
    FutureUtils.waitForAll(terminationConditions).thenRun(mailboxProcessor::allActionsCompleted);
    // Resumes the mailbox processor. The mailbox processor would be completed
    // after all records are processed by the downstream tasks.
    mailboxProcessor.runMailboxLoop();
    // make sure no further checkpoint and notification actions happen.
    // at the same time, this makes sure that during any "regular" exit where still
    actionExecutor.runThrowing(() -> {
        // make sure no new timers can come
        timerService.quiesce().get();
        systemTimerService.quiesce().get();
        // let mailbox execution reject all new letters from this point
        mailboxProcessor.prepareClose();
    });
    // processes the remaining mails; no new mails can be enqueued
    mailboxProcessor.drain();
    // Set isRunning to false after all the mails are drained so that
    // the queued checkpoint requirements could be triggered normally.
    actionExecutor.runThrowing(() -> {
        // only set the StreamTask to not running after all operators have been
        // finished!
        // See FLINK-7430
        isRunning = false;
    });
    LOG.debug("Finished operators for task {}", getName());
    // make sure all buffered data is flushed
    operatorChain.flushOutputs();
    if (areCheckpointsWithFinishedTasksEnabled()) {
        // No new checkpoints could be triggered since mailbox has been drained.
        subtaskCheckpointCoordinator.waitForPendingCheckpoints();
        LOG.debug("All pending checkpoints are finished");
    }
    disableInterruptOnCancel();
    // make an attempt to dispose the operators such that failures in the dispose call
    // still let the computation fail
    closeAllOperators();
}
Also used : RecordWriterBuilder(org.apache.flink.runtime.io.network.api.writer.RecordWriterBuilder) TaskIOMetricGroup(org.apache.flink.runtime.metrics.groups.TaskIOMetricGroup) InternalTimeServiceManager(org.apache.flink.streaming.api.operators.InternalTimeServiceManager) ConfigurableStreamPartitioner(org.apache.flink.streaming.runtime.partitioner.ConfigurableStreamPartitioner) Arrays(java.util.Arrays) CoordinatedTask(org.apache.flink.runtime.jobgraph.tasks.CoordinatedTask) AvailabilityProvider(org.apache.flink.runtime.io.AvailabilityProvider) CheckpointableTask(org.apache.flink.runtime.jobgraph.tasks.CheckpointableTask) StateBackend(org.apache.flink.runtime.state.StateBackend) Future(java.util.concurrent.Future) CheckpointException(org.apache.flink.runtime.checkpoint.CheckpointException) StateBackendLoader(org.apache.flink.runtime.state.StateBackendLoader) Path(org.apache.flink.core.fs.Path) InternalTimeServiceManagerImpl(org.apache.flink.streaming.api.operators.InternalTimeServiceManagerImpl) CheckpointStorageWorkerView(org.apache.flink.runtime.state.CheckpointStorageWorkerView) CancelTaskException(org.apache.flink.runtime.execution.CancelTaskException) Set(java.util.Set) CheckpointBarrierHandler(org.apache.flink.streaming.runtime.io.checkpointing.CheckpointBarrierHandler) GuardedBy(javax.annotation.concurrent.GuardedBy) FatalExitExceptionHandler(org.apache.flink.util.FatalExitExceptionHandler) TernaryBoolean(org.apache.flink.util.TernaryBoolean) Executors(java.util.concurrent.Executors) StopMode(org.apache.flink.runtime.io.network.api.StopMode) MultipleRecordWriters(org.apache.flink.runtime.io.network.api.writer.MultipleRecordWriters) TtlTimeProvider(org.apache.flink.runtime.state.ttl.TtlTimeProvider) SnapshotType(org.apache.flink.runtime.checkpoint.SnapshotType) CheckpointBarrier(org.apache.flink.runtime.io.network.api.CheckpointBarrier) RecordWriter(org.apache.flink.runtime.io.network.api.writer.RecordWriter) AsynchronousException(org.apache.flink.runtime.taskmanager.AsynchronousException) Counter(org.apache.flink.metrics.Counter) FlinkException(org.apache.flink.util.FlinkException) ResultPartitionWriter(org.apache.flink.runtime.io.network.api.writer.ResultPartitionWriter) CheckpointFailureReason(org.apache.flink.runtime.checkpoint.CheckpointFailureReason) RunnableWithException(org.apache.flink.util.function.RunnableWithException) ArrayList(java.util.ArrayList) PeriodTimer(org.apache.flink.streaming.runtime.tasks.mailbox.PeriodTimer) TaskMailbox(org.apache.flink.streaming.runtime.tasks.mailbox.TaskMailbox) OptionalLong(java.util.OptionalLong) TaskManagerOptions(org.apache.flink.configuration.TaskManagerOptions) StreamPartitioner(org.apache.flink.streaming.runtime.partitioner.StreamPartitioner) FutureUtils(org.apache.flink.util.concurrent.FutureUtils) ExecutionCheckpointingOptions(org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions) MailboxExecutorFactory(org.apache.flink.streaming.runtime.tasks.mailbox.MailboxExecutorFactory) SequentialChannelStateReader(org.apache.flink.runtime.checkpoint.channel.SequentialChannelStateReader) GaugePeriodTimer(org.apache.flink.streaming.runtime.tasks.mailbox.GaugePeriodTimer) ChannelStateWriter(org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter) TaskMailboxImpl(org.apache.flink.streaming.runtime.tasks.mailbox.TaskMailboxImpl) FlinkSecurityManager(org.apache.flink.core.security.FlinkSecurityManager) InputChannelInfo(org.apache.flink.runtime.checkpoint.channel.InputChannelInfo) Nullable(javax.annotation.Nullable) TimeCharacteristic(org.apache.flink.streaming.api.TimeCharacteristic) StreamEdge(org.apache.flink.streaming.api.graph.StreamEdge) FlinkRuntimeException(org.apache.flink.util.FlinkRuntimeException) MailboxDefaultAction(org.apache.flink.streaming.runtime.tasks.mailbox.MailboxDefaultAction) MailboxExecutor(org.apache.flink.api.common.operators.MailboxExecutor) IOException(java.io.IOException) AutoCloseableRegistry(org.apache.flink.core.fs.AutoCloseableRegistry) ChannelStateHolder(org.apache.flink.runtime.io.network.partition.ChannelStateHolder) VisibleForTesting(org.apache.flink.annotation.VisibleForTesting) StreamOperator(org.apache.flink.streaming.api.operators.StreamOperator) Task(org.apache.flink.runtime.taskmanager.Task) FutureUtils.assertNoException(org.apache.flink.util.concurrent.FutureUtils.assertNoException) StreamTaskStateInitializerImpl(org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl) CheckpointMetricsBuilder(org.apache.flink.runtime.checkpoint.CheckpointMetricsBuilder) LoggerFactory(org.slf4j.LoggerFactory) SavepointType(org.apache.flink.runtime.checkpoint.SavepointType) RecordWriterDelegate(org.apache.flink.runtime.io.network.api.writer.RecordWriterDelegate) ExceptionUtils(org.apache.flink.util.ExceptionUtils) CheckpointStorage(org.apache.flink.runtime.state.CheckpointStorage) InstantiationUtil(org.apache.flink.util.InstantiationUtil) BUFFER_DEBLOAT_PERIOD(org.apache.flink.configuration.TaskManagerOptions.BUFFER_DEBLOAT_PERIOD) CloseableRegistry(org.apache.flink.core.fs.CloseableRegistry) DataInputStatus(org.apache.flink.streaming.runtime.io.DataInputStatus) CheckpointStorageAccess(org.apache.flink.runtime.state.CheckpointStorageAccess) ThreadFactory(java.util.concurrent.ThreadFactory) CheckpointType(org.apache.flink.runtime.checkpoint.CheckpointType) ExecutorThreadFactory(org.apache.flink.util.concurrent.ExecutorThreadFactory) SerializationDelegate(org.apache.flink.runtime.plugable.SerializationDelegate) CompletionException(java.util.concurrent.CompletionException) CheckpointOptions(org.apache.flink.runtime.checkpoint.CheckpointOptions) Preconditions(org.apache.flink.util.Preconditions) List(java.util.List) SerializedValue(org.apache.flink.util.SerializedValue) AsyncExceptionHandler(org.apache.flink.runtime.taskmanager.AsyncExceptionHandler) NonRecordWriter(org.apache.flink.runtime.io.network.api.writer.NonRecordWriter) CancelCheckpointMarker(org.apache.flink.runtime.io.network.api.CancelCheckpointMarker) OperatorID(org.apache.flink.runtime.jobgraph.OperatorID) Optional(java.util.Optional) RecordWriterOutput(org.apache.flink.streaming.runtime.io.RecordWriterOutput) Environment(org.apache.flink.runtime.execution.Environment) DispatcherThreadFactory(org.apache.flink.runtime.taskmanager.DispatcherThreadFactory) StreamConfig(org.apache.flink.streaming.api.graph.StreamConfig) TaskInvokable(org.apache.flink.runtime.jobgraph.tasks.TaskInvokable) CheckpointMetaData(org.apache.flink.runtime.checkpoint.CheckpointMetaData) CompletableFuture(java.util.concurrent.CompletableFuture) HashSet(java.util.HashSet) RestoreMode(org.apache.flink.runtime.jobgraph.RestoreMode) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) StreamRecord(org.apache.flink.streaming.runtime.streamrecord.StreamRecord) StreamTaskStateInitializer(org.apache.flink.streaming.api.operators.StreamTaskStateInitializer) ExceptionUtils.firstOrSuppressed(org.apache.flink.util.ExceptionUtils.firstOrSuppressed) Suspension(org.apache.flink.streaming.runtime.tasks.mailbox.MailboxDefaultAction.Suspension) SimpleCounter(org.apache.flink.metrics.SimpleCounter) StreamInputProcessor(org.apache.flink.streaming.runtime.io.StreamInputProcessor) ExecutorService(java.util.concurrent.ExecutorService) InputGate(org.apache.flink.runtime.io.network.partition.consumer.InputGate) Preconditions.checkState(org.apache.flink.util.Preconditions.checkState) Logger(org.slf4j.Logger) Configuration(org.apache.flink.configuration.Configuration) CheckpointStorageLoader(org.apache.flink.runtime.state.CheckpointStorageLoader) SingleRecordWriter(org.apache.flink.runtime.io.network.api.writer.SingleRecordWriter) MailboxProcessor(org.apache.flink.streaming.runtime.tasks.mailbox.MailboxProcessor) Internal(org.apache.flink.annotation.Internal) IndexedInputGate(org.apache.flink.runtime.io.network.partition.consumer.IndexedInputGate) ProcessingTimeCallback(org.apache.flink.api.common.operators.ProcessingTimeService.ProcessingTimeCallback) OperatorEvent(org.apache.flink.runtime.operators.coordination.OperatorEvent) CompletableFuture(java.util.concurrent.CompletableFuture) ResultPartitionWriter(org.apache.flink.runtime.io.network.api.writer.ResultPartitionWriter) HashSet(java.util.HashSet)

Example 2 with MailboxProcessor

use of org.apache.flink.streaming.runtime.tasks.mailbox.MailboxProcessor in project flink by apache.

the class StreamTaskTestHarness method waitForInputProcessing.

/**
 * This only returns after all input queues are empty.
 */
public void waitForInputProcessing() throws Exception {
    while (taskThread.isAlive()) {
        boolean allEmpty = true;
        for (int i = 0; i < numInputGates; i++) {
            if (!inputGates[i].allQueuesEmpty()) {
                allEmpty = false;
            }
        }
        if (allEmpty) {
            break;
        }
    }
    // Wait for all currently available input has been processed.
    final AtomicBoolean allInputProcessed = new AtomicBoolean();
    final MailboxProcessor mailboxProcessor = taskThread.task.mailboxProcessor;
    final MailboxExecutor mailboxExecutor = mailboxProcessor.getMainMailboxExecutor();
    while (taskThread.isAlive()) {
        try {
            final CountDownLatch latch = new CountDownLatch(1);
            mailboxExecutor.execute(() -> {
                allInputProcessed.set(!mailboxProcessor.isDefaultActionAvailable());
                latch.countDown();
            }, "query-whether-processInput-has-suspend-itself");
            // Mail could be dropped due to task exception, so we do timed-await here.
            latch.await(1, TimeUnit.SECONDS);
        } catch (RejectedExecutionException ex) {
        // Loop until task thread exit for possible task exception.
        }
        if (allInputProcessed.get()) {
            break;
        }
        try {
            Thread.sleep(1);
        } catch (InterruptedException ignored) {
        }
    }
    Throwable error = taskThread.getError();
    if (error != null) {
        throw new Exception("Exception in the task thread", error);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MailboxProcessor(org.apache.flink.streaming.runtime.tasks.mailbox.MailboxProcessor) MailboxExecutor(org.apache.flink.api.common.operators.MailboxExecutor) CountDownLatch(java.util.concurrent.CountDownLatch) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) FunctionWithException(org.apache.flink.util.function.FunctionWithException) CancelTaskException(org.apache.flink.runtime.execution.CancelTaskException) SupplierWithException(org.apache.flink.util.function.SupplierWithException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException)

Aggregations

IOException (java.io.IOException)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 MailboxExecutor (org.apache.flink.api.common.operators.MailboxExecutor)2 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Optional (java.util.Optional)1 OptionalLong (java.util.OptionalLong)1 Set (java.util.Set)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CompletionException (java.util.concurrent.CompletionException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutorService (java.util.concurrent.ExecutorService)1 Executors (java.util.concurrent.Executors)1 Future (java.util.concurrent.Future)1 ThreadFactory (java.util.concurrent.ThreadFactory)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Nullable (javax.annotation.Nullable)1 GuardedBy (javax.annotation.concurrent.GuardedBy)1