Search in sources :

Example 1 with SupplierWithException

use of org.apache.flink.util.function.SupplierWithException in project flink by apache.

the class HeapSnapshotStrategy method asyncSnapshot.

@Override
public SnapshotResultSupplier<KeyedStateHandle> asyncSnapshot(HeapSnapshotResources<K> syncPartResource, long checkpointId, long timestamp, @Nonnull CheckpointStreamFactory streamFactory, @Nonnull CheckpointOptions checkpointOptions) {
    List<StateMetaInfoSnapshot> metaInfoSnapshots = syncPartResource.getMetaInfoSnapshots();
    if (metaInfoSnapshots.isEmpty()) {
        return snapshotCloseableRegistry -> SnapshotResult.empty();
    }
    final KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>(// get a serialized form already at state registration time in the future
    syncPartResource.getKeySerializer(), metaInfoSnapshots, !Objects.equals(UncompressedStreamCompressionDecorator.INSTANCE, keyGroupCompressionDecorator));
    final SupplierWithException<CheckpointStreamWithResultProvider, Exception> checkpointStreamSupplier = localRecoveryConfig.isLocalRecoveryEnabled() && !checkpointOptions.getCheckpointType().isSavepoint() ? () -> createDuplicatingStream(checkpointId, CheckpointedStateScope.EXCLUSIVE, streamFactory, localRecoveryConfig.getLocalStateDirectoryProvider().orElseThrow(LocalRecoveryConfig.localRecoveryNotEnabled())) : () -> createSimpleStream(CheckpointedStateScope.EXCLUSIVE, streamFactory);
    return (snapshotCloseableRegistry) -> {
        final Map<StateUID, Integer> stateNamesToId = syncPartResource.getStateNamesToId();
        final Map<StateUID, StateSnapshot> cowStateStableSnapshots = syncPartResource.getCowStateStableSnapshots();
        final CheckpointStreamWithResultProvider streamWithResultProvider = checkpointStreamSupplier.get();
        snapshotCloseableRegistry.registerCloseable(streamWithResultProvider);
        final CheckpointStateOutputStream localStream = streamWithResultProvider.getCheckpointOutputStream();
        final DataOutputViewStreamWrapper outView = new DataOutputViewStreamWrapper(localStream);
        serializationProxy.write(outView);
        final long[] keyGroupRangeOffsets = new long[keyGroupRange.getNumberOfKeyGroups()];
        for (int keyGroupPos = 0; keyGroupPos < keyGroupRange.getNumberOfKeyGroups(); ++keyGroupPos) {
            int keyGroupId = keyGroupRange.getKeyGroupId(keyGroupPos);
            keyGroupRangeOffsets[keyGroupPos] = localStream.getPos();
            outView.writeInt(keyGroupId);
            for (Map.Entry<StateUID, StateSnapshot> stateSnapshot : cowStateStableSnapshots.entrySet()) {
                StateSnapshot.StateKeyGroupWriter partitionedSnapshot = stateSnapshot.getValue().getKeyGroupWriter();
                try (OutputStream kgCompressionOut = keyGroupCompressionDecorator.decorateWithCompression(localStream)) {
                    DataOutputViewStreamWrapper kgCompressionView = new DataOutputViewStreamWrapper(kgCompressionOut);
                    kgCompressionView.writeShort(stateNamesToId.get(stateSnapshot.getKey()));
                    partitionedSnapshot.writeStateInKeyGroup(kgCompressionView, keyGroupId);
                }
            // this will just close the outer compression stream
            }
        }
        if (snapshotCloseableRegistry.unregisterCloseable(streamWithResultProvider)) {
            KeyGroupRangeOffsets kgOffs = new KeyGroupRangeOffsets(keyGroupRange, keyGroupRangeOffsets);
            SnapshotResult<StreamStateHandle> result = streamWithResultProvider.closeAndFinalizeCheckpointStreamResult();
            return toKeyedStateHandleSnapshotResult(result, kgOffs, KeyGroupsStateHandle::new);
        } else {
            throw new IOException("Stream already unregistered.");
        }
    };
}
Also used : KeyGroupRangeOffsets(org.apache.flink.runtime.state.KeyGroupRangeOffsets) KeyGroupsStateHandle(org.apache.flink.runtime.state.KeyGroupsStateHandle) LocalRecoveryConfig(org.apache.flink.runtime.state.LocalRecoveryConfig) CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult) DataOutputViewStreamWrapper(org.apache.flink.core.memory.DataOutputViewStreamWrapper) KeyedBackendSerializationProxy(org.apache.flink.runtime.state.KeyedBackendSerializationProxy) Map(java.util.Map) StreamCompressionDecorator(org.apache.flink.runtime.state.StreamCompressionDecorator) Nonnull(javax.annotation.Nonnull) CheckpointStreamWithResultProvider(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider) CheckpointedStateScope(org.apache.flink.runtime.state.CheckpointedStateScope) OutputStream(java.io.OutputStream) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) SnapshotResult(org.apache.flink.runtime.state.SnapshotResult) CheckpointStreamWithResultProvider.createSimpleStream(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider.createSimpleStream) StateSerializerProvider(org.apache.flink.runtime.state.StateSerializerProvider) TypeSerializer(org.apache.flink.api.common.typeutils.TypeSerializer) UncompressedStreamCompressionDecorator(org.apache.flink.runtime.state.UncompressedStreamCompressionDecorator) KeyedStateHandle(org.apache.flink.runtime.state.KeyedStateHandle) StateMetaInfoSnapshot(org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot) SnapshotStrategy(org.apache.flink.runtime.state.SnapshotStrategy) IOException(java.io.IOException) CheckpointOptions(org.apache.flink.runtime.checkpoint.CheckpointOptions) StreamStateHandle(org.apache.flink.runtime.state.StreamStateHandle) StateSnapshot(org.apache.flink.runtime.state.StateSnapshot) Objects(java.util.Objects) List(java.util.List) CheckpointStreamWithResultProvider.createDuplicatingStream(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider.createDuplicatingStream) CheckpointStreamFactory(org.apache.flink.runtime.state.CheckpointStreamFactory) CheckpointStateOutputStream(org.apache.flink.runtime.state.CheckpointStateOutputStream) SupplierWithException(org.apache.flink.util.function.SupplierWithException) CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider.toKeyedStateHandleSnapshotResult) SnapshotResult(org.apache.flink.runtime.state.SnapshotResult) KeyGroupRangeOffsets(org.apache.flink.runtime.state.KeyGroupRangeOffsets) OutputStream(java.io.OutputStream) CheckpointStateOutputStream(org.apache.flink.runtime.state.CheckpointStateOutputStream) StateMetaInfoSnapshot(org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot) KeyedBackendSerializationProxy(org.apache.flink.runtime.state.KeyedBackendSerializationProxy) IOException(java.io.IOException) IOException(java.io.IOException) SupplierWithException(org.apache.flink.util.function.SupplierWithException) CheckpointStreamWithResultProvider(org.apache.flink.runtime.state.CheckpointStreamWithResultProvider) DataOutputViewStreamWrapper(org.apache.flink.core.memory.DataOutputViewStreamWrapper) CheckpointStateOutputStream(org.apache.flink.runtime.state.CheckpointStateOutputStream) Map(java.util.Map)

Example 2 with SupplierWithException

use of org.apache.flink.util.function.SupplierWithException in project flink by apache.

the class StreamingSink method compactionWriter.

/**
 * Create a file writer with compaction operators by input stream. In addition, it can emit
 * {@link PartitionCommitInfo} to down stream.
 */
public static <T> DataStream<PartitionCommitInfo> compactionWriter(ProviderContext providerContext, DataStream<T> inputStream, long bucketCheckInterval, StreamingFileSink.BucketsBuilder<T, String, ? extends StreamingFileSink.BucketsBuilder<T, String, ?>> bucketsBuilder, FileSystemFactory fsFactory, Path path, CompactReader.Factory<T> readFactory, long targetFileSize, int parallelism) {
    CompactFileWriter<T> writer = new CompactFileWriter<>(bucketCheckInterval, bucketsBuilder);
    SupplierWithException<FileSystem, IOException> fsSupplier = (SupplierWithException<FileSystem, IOException> & Serializable) () -> fsFactory.create(path.toUri());
    CompactCoordinator coordinator = new CompactCoordinator(fsSupplier, targetFileSize);
    SingleOutputStreamOperator<CoordinatorOutput> coordinatorOp = inputStream.transform("streaming-writer", TypeInformation.of(CoordinatorInput.class), writer).uid(providerContext.generateUid("streaming-writer").get()).setParallelism(parallelism).transform("compact-coordinator", TypeInformation.of(CoordinatorOutput.class), coordinator).uid(providerContext.generateUid("compact-coordinator").get()).setParallelism(1).setMaxParallelism(1);
    CompactWriter.Factory<T> writerFactory = CompactBucketWriter.factory((SupplierWithException<BucketWriter<T, String>, IOException> & Serializable) bucketsBuilder::createBucketWriter);
    CompactOperator<T> compacter = new CompactOperator<>(fsSupplier, readFactory, writerFactory);
    return coordinatorOp.broadcast().transform("compact-operator", TypeInformation.of(PartitionCommitInfo.class), compacter).uid(providerContext.generateUid("compact-operator").get()).setParallelism(parallelism);
}
Also used : Serializable(java.io.Serializable) CompactWriter(org.apache.flink.connector.file.table.stream.compact.CompactWriter) CoordinatorInput(org.apache.flink.connector.file.table.stream.compact.CompactMessages.CoordinatorInput) SupplierWithException(org.apache.flink.util.function.SupplierWithException) CompactOperator(org.apache.flink.connector.file.table.stream.compact.CompactOperator) IOException(java.io.IOException) CompactCoordinator(org.apache.flink.connector.file.table.stream.compact.CompactCoordinator) CoordinatorOutput(org.apache.flink.connector.file.table.stream.compact.CompactMessages.CoordinatorOutput) FileSystem(org.apache.flink.core.fs.FileSystem) CompactFileWriter(org.apache.flink.connector.file.table.stream.compact.CompactFileWriter)

Example 3 with SupplierWithException

use of org.apache.flink.util.function.SupplierWithException in project flink by apache.

the class ChannelPersistenceITCase method collectBytes.

private <T> byte[] collectBytes(SupplierWithException<Optional<T>, Exception> entrySupplier, Function<T, Buffer> bufferExtractor) throws Exception {
    ArrayList<Buffer> buffers = new ArrayList<>();
    for (Optional<T> entry = entrySupplier.get(); entry.isPresent(); entry = entrySupplier.get()) {
        entry.map(bufferExtractor).filter(buffer -> buffer.getDataType().isBuffer()).ifPresent(buffers::add);
    }
    ByteBuffer result = ByteBuffer.wrap(new byte[buffers.stream().mapToInt(Buffer::getSize).sum()]);
    buffers.forEach(buffer -> {
        result.put(buffer.getNioBufferReadable());
        buffer.recycleBuffer();
    });
    return result.array();
}
Also used : NetworkBuffer(org.apache.flink.runtime.io.network.buffer.NetworkBuffer) ByteBuffer(java.nio.ByteBuffer) Buffer(org.apache.flink.runtime.io.network.buffer.Buffer) BufferAndBacklog(org.apache.flink.runtime.io.network.partition.ResultSubpartition.BufferAndBacklog) CHECKPOINT(org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT) ResultPartitionType(org.apache.flink.runtime.io.network.partition.ResultPartitionType) Random(java.util.Random) Function(java.util.function.Function) NetworkBuffer(org.apache.flink.runtime.io.network.buffer.NetworkBuffer) NetworkBufferPool(org.apache.flink.runtime.io.network.buffer.NetworkBufferPool) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) RECOVERY_COMPLETION(org.apache.flink.runtime.io.network.buffer.Buffer.DataType.RECOVERY_COMPLETION) ResultPartition(org.apache.flink.runtime.io.network.partition.ResultPartition) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) SequentialChannelStateReader(org.apache.flink.runtime.checkpoint.channel.SequentialChannelStateReader) Collections.singletonMap(java.util.Collections.singletonMap) InputChannelInfo(org.apache.flink.runtime.checkpoint.channel.InputChannelInfo) SingleInputGate(org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate) TaskStateSnapshot(org.apache.flink.runtime.checkpoint.TaskStateSnapshot) InputGate(org.apache.flink.runtime.io.network.partition.consumer.InputGate) MemorySegmentFactory(org.apache.flink.core.memory.MemorySegmentFactory) NonPersistentMetadataCheckpointStorageLocation(org.apache.flink.runtime.state.memory.NonPersistentMetadataCheckpointStorageLocation) SingleInputGateBuilder(org.apache.flink.runtime.io.network.partition.consumer.SingleInputGateBuilder) ChannelStateWriterImpl(org.apache.flink.runtime.checkpoint.channel.ChannelStateWriterImpl) ResultPartitionBuilder(org.apache.flink.runtime.io.network.partition.ResultPartitionBuilder) SEQUENCE_NUMBER_UNKNOWN(org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter.SEQUENCE_NUMBER_UNKNOWN) InputChannelBuilder(org.apache.flink.runtime.io.network.partition.consumer.InputChannelBuilder) FreeingBufferRecycler(org.apache.flink.runtime.io.network.buffer.FreeingBufferRecycler) Test(org.junit.Test) IOException(java.io.IOException) CheckpointOptions(org.apache.flink.runtime.checkpoint.CheckpointOptions) OperatorSubtaskState(org.apache.flink.runtime.checkpoint.OperatorSubtaskState) ChannelStateWriteResult(org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter.ChannelStateWriteResult) CloseableIterator.ofElements(org.apache.flink.util.CloseableIterator.ofElements) BufferWritingResultPartition(org.apache.flink.runtime.io.network.partition.BufferWritingResultPartition) Collectors(java.util.stream.Collectors) Buffer(org.apache.flink.runtime.io.network.buffer.Buffer) NoOpBufferAvailablityListener(org.apache.flink.runtime.io.network.partition.NoOpBufferAvailablityListener) Assert.assertNull(org.junit.Assert.assertNull) SequentialChannelStateReaderImpl(org.apache.flink.runtime.checkpoint.channel.SequentialChannelStateReaderImpl) OperatorID(org.apache.flink.runtime.jobgraph.OperatorID) Optional(java.util.Optional) ResultSubpartitionView(org.apache.flink.runtime.io.network.partition.ResultSubpartitionView) StateObjectCollection(org.apache.flink.runtime.checkpoint.StateObjectCollection) BufferOrEvent(org.apache.flink.runtime.io.network.partition.consumer.BufferOrEvent) Assert.assertEquals(org.junit.Assert.assertEquals) ResultSubpartitionInfo(org.apache.flink.runtime.checkpoint.channel.ResultSubpartitionInfo) SupplierWithException(org.apache.flink.util.function.SupplierWithException) CHECKPOINT(org.apache.flink.runtime.checkpoint.CheckpointType.CHECKPOINT) ArrayList(java.util.ArrayList) ByteBuffer(java.nio.ByteBuffer)

Example 4 with SupplierWithException

use of org.apache.flink.util.function.SupplierWithException in project flink by apache.

the class ClassLoadingUtilsTest method testRunSupplierWithContextClassLoader.

@Test
public void testRunSupplierWithContextClassLoader() throws Exception {
    SupplierWithException<ClassLoader, Exception> runnable = () -> Thread.currentThread().getContextClassLoader();
    final ClassLoader contextClassLoader = ClassLoadingUtils.runWithContextClassLoader(runnable, TEST_CLASS_LOADER);
    assertThat(contextClassLoader, is(TEST_CLASS_LOADER));
}
Also used : URLClassLoader(java.net.URLClassLoader) SupplierWithException(org.apache.flink.util.function.SupplierWithException) Test(org.junit.Test)

Example 5 with SupplierWithException

use of org.apache.flink.util.function.SupplierWithException in project flink by apache.

the class CommonTestUtils method waitForAllTaskRunning.

public static void waitForAllTaskRunning(SupplierWithException<AccessExecutionGraph, Exception> executionGraphSupplier, Deadline timeout, boolean allowFinished) throws Exception {
    Predicate<AccessExecutionVertex> subtaskPredicate = task -> {
        switch(task.getExecutionState()) {
            case RUNNING:
                return true;
            case FINISHED:
                if (allowFinished) {
                    return true;
                } else {
                    throw new RuntimeException("Sub-Task finished unexpectedly" + task);
                }
            default:
                return false;
        }
    };
    waitUntilCondition(() -> {
        final AccessExecutionGraph graph = executionGraphSupplier.get();
        if (graph.getState().isGloballyTerminalState()) {
            final ErrorInfo failureInfo = graph.getFailureInfo();
            fail(format("Graph is in globally terminal state (%s)", graph.getState()), failureInfo != null ? failureInfo.getException() : null);
        }
        return graph.getState() == JobStatus.RUNNING && graph.getAllVertices().values().stream().allMatch(jobVertex -> Arrays.stream(jobVertex.getTaskVertices()).allMatch(subtaskPredicate));
    }, timeout);
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Deadline(org.apache.flink.api.common.time.Deadline) Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) FileUtils(org.apache.flink.util.FileUtils) AccessExecutionVertex(org.apache.flink.runtime.executiongraph.AccessExecutionVertex) TimeoutException(java.util.concurrent.TimeoutException) JobStatus(org.apache.flink.api.common.JobStatus) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) Duration(java.time.Duration) Map(java.util.Map) MiniCluster(org.apache.flink.runtime.minicluster.MiniCluster) ManagementFactory(java.lang.management.ManagementFactory) PrintWriter(java.io.PrintWriter) RuntimeMXBean(java.lang.management.RuntimeMXBean) Predicate(java.util.function.Predicate) JobDetailsInfo(org.apache.flink.runtime.rest.messages.job.JobDetailsInfo) StringWriter(java.io.StringWriter) Collection(java.util.Collection) ExecutionState(org.apache.flink.runtime.execution.ExecutionState) FileWriter(java.io.FileWriter) ErrorInfo(org.apache.flink.runtime.executiongraph.ErrorInfo) IOException(java.io.IOException) JobClient(org.apache.flink.core.execution.JobClient) File(java.io.File) String.format(java.lang.String.format) AccessExecutionGraph(org.apache.flink.runtime.executiongraph.AccessExecutionGraph) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) JobID(org.apache.flink.api.common.JobID) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) SupplierWithException(org.apache.flink.util.function.SupplierWithException) InputStream(java.io.InputStream) ErrorInfo(org.apache.flink.runtime.executiongraph.ErrorInfo) AccessExecutionGraph(org.apache.flink.runtime.executiongraph.AccessExecutionGraph) AccessExecutionVertex(org.apache.flink.runtime.executiongraph.AccessExecutionVertex)

Aggregations

SupplierWithException (org.apache.flink.util.function.SupplierWithException)6 IOException (java.io.IOException)5 Map (java.util.Map)3 List (java.util.List)2 TimeoutException (java.util.concurrent.TimeoutException)2 CheckpointOptions (org.apache.flink.runtime.checkpoint.CheckpointOptions)2 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 Serializable (java.io.Serializable)1 StringWriter (java.io.StringWriter)1 String.format (java.lang.String.format)1 ManagementFactory (java.lang.management.ManagementFactory)1 RuntimeMXBean (java.lang.management.RuntimeMXBean)1 URLClassLoader (java.net.URLClassLoader)1 ByteBuffer (java.nio.ByteBuffer)1 Duration (java.time.Duration)1