Class AbstractStreamOperator<OUT>
- java.lang.Object
-
- org.apache.flink.streaming.api.operators.AbstractStreamOperator<OUT>
-
- Type Parameters:
OUT- The output type of the operator.
- All Implemented Interfaces:
Serializable,org.apache.flink.api.common.state.CheckpointListener,KeyContext,KeyContextHandler,SetupableStreamOperator<OUT>,StreamOperator<OUT>,StreamOperatorStateHandler.CheckpointedStreamOperator
- Direct Known Subclasses:
AbstractUdfStreamOperator,CacheTransformationTranslator.IdentityStreamOperator,CacheTransformationTranslator.NoOpStreamOperator,ContinuousFileReaderOperator,GenericWriteAheadSink,QueryableAppendingStateOperator,QueryableValueStateOperator,SourceOperator,StreamProject,TimestampsAndWatermarksOperator
@PublicEvolving public abstract class AbstractStreamOperator<OUT> extends Object implements StreamOperator<OUT>, SetupableStreamOperator<OUT>, StreamOperatorStateHandler.CheckpointedStreamOperator, KeyContextHandler, Serializable
Base class for all stream operators. Operators that contain a user function should extend the classAbstractUdfStreamOperatorinstead (which is a specialized subclass of this class).For concrete implementations, one of the following two interfaces must also be implemented, to mark the operator as unary or binary:
OneInputStreamOperatororTwoInputStreamOperator.Methods of
StreamOperatorare guaranteed not to be called concurrently. Also, if using the timer service, timer callbacks are also guaranteed not to be called concurrently with methods onStreamOperator.Note, this class is going to be removed and replaced in the future by
AbstractStreamOperatorV2. However asAbstractStreamOperatorV2is currently experimental,AbstractStreamOperatorhas not been deprecated just yet.- See Also:
- Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description protected ChainingStrategychainingStrategyprotected StreamConfigconfigprotected LatencyStatslatencyStatsprotected static org.slf4j.LoggerLOGThe logger used by the operator class and its subclasses.protected org.apache.flink.runtime.metrics.groups.InternalOperatorMetricGroupmetricsMetric group for the operator.protected Output<StreamRecord<OUT>>outputprotected ProcessingTimeServiceprocessingTimeService
-
Constructor Summary
Constructors Constructor Description AbstractStreamOperator()
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidclose()This method is called at the very end of the operator's life, both in the case of a successful completion of the operation, and in the case of a failure and canceling.voidfinish()This method is called at the end of data processing.ChainingStrategygetChainingStrategy()StreamTask<?,?>getContainingTask()ObjectgetCurrentKey()org.apache.flink.api.common.ExecutionConfiggetExecutionConfig()Gets the execution config defined on the execution environment of the job to which this operator belongs.<K,N>
InternalTimerService<N>getInternalTimerService(String name, org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, Triggerable<K,N> triggerable)Returns aInternalTimerServicethat can be used to query current processing time and event time and to set timers.<K> org.apache.flink.runtime.state.KeyedStateBackend<K>getKeyedStateBackend()org.apache.flink.api.common.state.KeyedStateStoregetKeyedStateStore()org.apache.flink.metrics.groups.OperatorMetricGroupgetMetricGroup()StreamConfiggetOperatorConfig()org.apache.flink.runtime.jobgraph.OperatorIDgetOperatorID()protected StringgetOperatorName()Return the operator name.org.apache.flink.runtime.state.OperatorStateBackendgetOperatorStateBackend()protected <N,S extends org.apache.flink.api.common.state.State,T>
SgetOrCreateKeyedState(org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, org.apache.flink.api.common.state.StateDescriptor<S,T> stateDescriptor)protected <S extends org.apache.flink.api.common.state.State,N>
SgetPartitionedState(N namespace, org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, org.apache.flink.api.common.state.StateDescriptor<S,?> stateDescriptor)Creates a partitioned state handle, using the state backend configured for this task.protected <S extends org.apache.flink.api.common.state.State>
SgetPartitionedState(org.apache.flink.api.common.state.StateDescriptor<S,?> stateDescriptor)Creates a partitioned state handle, using the state backend configured for this task.ProcessingTimeServicegetProcessingTimeService()Returns theProcessingTimeServiceresponsible for getting the current processing time and registering timers.StreamingRuntimeContextgetRuntimeContext()Returns a context that allows the operator to query information about the execution and also to interact with systems such as broadcast variables and managed state.protected Optional<InternalTimeServiceManager<?>>getTimeServiceManager()ClassLoadergetUserCodeClassloader()booleanhasKeyContext1()Whether the first input ofStreamOperatorhas "KeyContext".booleanhasKeyContext2()Whether the second input ofStreamOperatorhas "KeyContext".voidinitializeState(org.apache.flink.runtime.state.StateInitializationContext context)Stream operators with state which can be restored need to override this hook method.voidinitializeState(StreamTaskStateInitializer streamTaskStateManager)Provides a context to initialize all state in the operator.protected booleanisUsingCustomRawKeyedState()Indicates whether or not implementations of this class is writing to the raw keyed state streams on snapshots, usingsnapshotState(StateSnapshotContext).voidnotifyCheckpointAborted(long checkpointId)voidnotifyCheckpointComplete(long checkpointId)voidopen()This method is called immediately before any elements are processed, it should contain the operator's initialization logic, e.g. state initialization.voidprepareSnapshotPreBarrier(long checkpointId)This method is called when the operator should do a snapshot, before it emits its own checkpoint barrier.voidprocessLatencyMarker(LatencyMarker latencyMarker)voidprocessLatencyMarker1(LatencyMarker latencyMarker)voidprocessLatencyMarker2(LatencyMarker latencyMarker)voidprocessWatermark(Watermark mark)voidprocessWatermark1(Watermark mark)voidprocessWatermark2(Watermark mark)voidprocessWatermarkStatus(WatermarkStatus watermarkStatus)voidprocessWatermarkStatus1(WatermarkStatus watermarkStatus)voidprocessWatermarkStatus2(WatermarkStatus watermarkStatus)protected voidreportOrForwardLatencyMarker(LatencyMarker marker)voidsetChainingStrategy(ChainingStrategy strategy)voidsetCurrentKey(Object key)voidsetKeyContextElement1(StreamRecord record)voidsetKeyContextElement2(StreamRecord record)voidsetProcessingTimeService(ProcessingTimeService processingTimeService)Deprecated.TheProcessingTimeServiceinstance should be passed by the operator constructor and this method will be removed along withSetupableStreamOperator.voidsetup(StreamTask<?,?> containingTask, StreamConfig config, Output<StreamRecord<OUT>> output)Initializes the operator.OperatorSnapshotFuturessnapshotState(long checkpointId, long timestamp, org.apache.flink.runtime.checkpoint.CheckpointOptions checkpointOptions, org.apache.flink.runtime.state.CheckpointStreamFactory factory)Called to draw a state snapshot from the operator.voidsnapshotState(org.apache.flink.runtime.state.StateSnapshotContext context)Stream operators with state, which want to participate in a snapshot need to override this hook method.-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.apache.flink.streaming.api.operators.KeyContextHandler
hasKeyContext
-
-
-
-
Field Detail
-
LOG
protected static final org.slf4j.Logger LOG
The logger used by the operator class and its subclasses.
-
chainingStrategy
protected ChainingStrategy chainingStrategy
-
config
protected transient StreamConfig config
-
output
protected transient Output<StreamRecord<OUT>> output
-
metrics
protected transient org.apache.flink.runtime.metrics.groups.InternalOperatorMetricGroup metrics
Metric group for the operator.
-
latencyStats
protected transient LatencyStats latencyStats
-
processingTimeService
protected transient ProcessingTimeService processingTimeService
-
-
Method Detail
-
setup
public void setup(StreamTask<?,?> containingTask, StreamConfig config, Output<StreamRecord<OUT>> output)
Description copied from interface:SetupableStreamOperatorInitializes the operator. Sets access to the context and the output.- Specified by:
setupin interfaceSetupableStreamOperator<OUT>
-
setProcessingTimeService
@Deprecated public void setProcessingTimeService(ProcessingTimeService processingTimeService)
Deprecated.TheProcessingTimeServiceinstance should be passed by the operator constructor and this method will be removed along withSetupableStreamOperator.
-
getMetricGroup
public org.apache.flink.metrics.groups.OperatorMetricGroup getMetricGroup()
- Specified by:
getMetricGroupin interfaceStreamOperator<OUT>
-
initializeState
public final void initializeState(StreamTaskStateInitializer streamTaskStateManager) throws Exception
Description copied from interface:StreamOperatorProvides a context to initialize all state in the operator.- Specified by:
initializeStatein interfaceStreamOperator<OUT>- Throws:
Exception
-
isUsingCustomRawKeyedState
@Internal protected boolean isUsingCustomRawKeyedState()
Indicates whether or not implementations of this class is writing to the raw keyed state streams on snapshots, usingsnapshotState(StateSnapshotContext). If yes, subclasses should override this method to returntrue.Subclasses need to explicitly indicate the use of raw keyed state because, internally, the
AbstractStreamOperatormay attempt to read from it as well to restore heap-based timers and ultimately fail with read errors. By setting this flag totrue, this allows theAbstractStreamOperatorto know that the data written in the raw keyed states were not written by the timer services, and skips the timer restore attempt.Please refer to FLINK-19741 for further details.
TODO: this method can be removed once all timers are moved to be managed by state backends.
- Returns:
- flag indicating whether or not this operator is writing to raw keyed state via
snapshotState(StateSnapshotContext).
-
open
public void open() throws ExceptionThis method is called immediately before any elements are processed, it should contain the operator's initialization logic, e.g. state initialization.The default implementation does nothing.
- Specified by:
openin interfaceStreamOperator<OUT>- Throws:
Exception- An exception in this method causes the operator to fail.
-
finish
public void finish() throws ExceptionDescription copied from interface:StreamOperatorThis method is called at the end of data processing.The method is expected to flush all remaining buffered data. Exceptions during this flushing of buffered data should be propagated, in order to cause the operation to be recognized as failed, because the last data items are not processed properly.
After this method is called, no more records can be produced for the downstream operators.
WARNING: It is not safe to use this method to commit any transactions or other side effects! You can use this method to flush any buffered data that can later on be committed e.g. in a
CheckpointListener.notifyCheckpointComplete(long).NOTE:This method does not need to close any resources. You should release external resources in the
StreamOperator.close()method.- Specified by:
finishin interfaceStreamOperator<OUT>- Throws:
Exception- An exception in this method causes the operator to fail.
-
close
public void close() throws ExceptionDescription copied from interface:StreamOperatorThis method is called at the very end of the operator's life, both in the case of a successful completion of the operation, and in the case of a failure and canceling.This method is expected to make a thorough effort to release all resources that the operator has acquired.
NOTE:It can not emit any records! If you need to emit records at the end of processing, do so in the
StreamOperator.finish()method.- Specified by:
closein interfaceStreamOperator<OUT>- Throws:
Exception
-
prepareSnapshotPreBarrier
public void prepareSnapshotPreBarrier(long checkpointId) throws ExceptionDescription copied from interface:StreamOperatorThis method is called when the operator should do a snapshot, before it emits its own checkpoint barrier.This method is intended not for any actual state persistence, but only for emitting some data before emitting the checkpoint barrier. Operators that maintain some small transient state that is inefficient to checkpoint (especially when it would need to be checkpointed in a re-scalable way) but can simply be sent downstream before the checkpoint. An example are opportunistic pre-aggregation operators, which have small the pre-aggregation state that is frequently flushed downstream.
Important: This method should not be used for any actual state snapshot logic, because it will inherently be within the synchronous part of the operator's checkpoint. If heavy work is done within this method, it will affect latency and downstream checkpoint alignments.
- Specified by:
prepareSnapshotPreBarrierin interfaceStreamOperator<OUT>- Parameters:
checkpointId- The ID of the checkpoint.- Throws:
Exception- Throwing an exception here causes the operator to fail and go into recovery.
-
snapshotState
public final OperatorSnapshotFutures snapshotState(long checkpointId, long timestamp, org.apache.flink.runtime.checkpoint.CheckpointOptions checkpointOptions, org.apache.flink.runtime.state.CheckpointStreamFactory factory) throws Exception
Description copied from interface:StreamOperatorCalled to draw a state snapshot from the operator.- Specified by:
snapshotStatein interfaceStreamOperator<OUT>- Returns:
- a runnable future to the state handle that points to the snapshotted state. For synchronous implementations, the runnable might already be finished.
- Throws:
Exception- exception that happened during snapshotting.
-
snapshotState
public void snapshotState(org.apache.flink.runtime.state.StateSnapshotContext context) throws ExceptionStream operators with state, which want to participate in a snapshot need to override this hook method.- Specified by:
snapshotStatein interfaceStreamOperatorStateHandler.CheckpointedStreamOperator- Parameters:
context- context that provides information and means required for taking a snapshot- Throws:
Exception
-
initializeState
public void initializeState(org.apache.flink.runtime.state.StateInitializationContext context) throws ExceptionStream operators with state which can be restored need to override this hook method.- Specified by:
initializeStatein interfaceStreamOperatorStateHandler.CheckpointedStreamOperator- Parameters:
context- context that allows to register different states.- Throws:
Exception
-
notifyCheckpointComplete
public void notifyCheckpointComplete(long checkpointId) throws Exception- Specified by:
notifyCheckpointCompletein interfaceorg.apache.flink.api.common.state.CheckpointListener- Throws:
Exception
-
notifyCheckpointAborted
public void notifyCheckpointAborted(long checkpointId) throws Exception- Specified by:
notifyCheckpointAbortedin interfaceorg.apache.flink.api.common.state.CheckpointListener- Throws:
Exception
-
getExecutionConfig
public org.apache.flink.api.common.ExecutionConfig getExecutionConfig()
Gets the execution config defined on the execution environment of the job to which this operator belongs.- Returns:
- The job's execution config.
-
getOperatorConfig
public StreamConfig getOperatorConfig()
-
getContainingTask
public StreamTask<?,?> getContainingTask()
-
getUserCodeClassloader
public ClassLoader getUserCodeClassloader()
-
getOperatorName
protected String getOperatorName()
Return the operator name. If the runtime context has been set, then the task name with subtask index is returned. Otherwise, the simple class name is returned.- Returns:
- If runtime context is set, then return task name with subtask index. Otherwise return simple class name.
-
getRuntimeContext
@VisibleForTesting public StreamingRuntimeContext getRuntimeContext()
Returns a context that allows the operator to query information about the execution and also to interact with systems such as broadcast variables and managed state. This also allows to register timers.
-
getKeyedStateBackend
public <K> org.apache.flink.runtime.state.KeyedStateBackend<K> getKeyedStateBackend()
-
getOperatorStateBackend
@VisibleForTesting public org.apache.flink.runtime.state.OperatorStateBackend getOperatorStateBackend()
-
getProcessingTimeService
@VisibleForTesting public ProcessingTimeService getProcessingTimeService()
Returns theProcessingTimeServiceresponsible for getting the current processing time and registering timers.
-
getPartitionedState
protected <S extends org.apache.flink.api.common.state.State> S getPartitionedState(org.apache.flink.api.common.state.StateDescriptor<S,?> stateDescriptor) throws ExceptionCreates a partitioned state handle, using the state backend configured for this task.- Throws:
IllegalStateException- Thrown, if the key/value state was already initialized.Exception- Thrown, if the state backend cannot create the key/value state.
-
getOrCreateKeyedState
protected <N,S extends org.apache.flink.api.common.state.State,T> S getOrCreateKeyedState(org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, org.apache.flink.api.common.state.StateDescriptor<S,T> stateDescriptor) throws Exception- Throws:
Exception
-
getPartitionedState
protected <S extends org.apache.flink.api.common.state.State,N> S getPartitionedState(N namespace, org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, org.apache.flink.api.common.state.StateDescriptor<S,?> stateDescriptor) throws ExceptionCreates a partitioned state handle, using the state backend configured for this task.- Throws:
IllegalStateException- Thrown, if the key/value state was already initialized.Exception- Thrown, if the state backend cannot create the key/value state.
-
setKeyContextElement1
public void setKeyContextElement1(StreamRecord record) throws Exception
- Specified by:
setKeyContextElement1in interfaceStreamOperator<OUT>- Throws:
Exception
-
setKeyContextElement2
public void setKeyContextElement2(StreamRecord record) throws Exception
- Specified by:
setKeyContextElement2in interfaceStreamOperator<OUT>- Throws:
Exception
-
hasKeyContext1
@Internal public boolean hasKeyContext1()
Description copied from interface:KeyContextHandlerWhether the first input ofStreamOperatorhas "KeyContext". If false, we can omit the call ofStreamOperator.setKeyContextElement1(org.apache.flink.streaming.runtime.streamrecord.StreamRecord<?>)for each record arrived on the first input.- Specified by:
hasKeyContext1in interfaceKeyContextHandler- Returns:
- True if the first input has "KeyContext", false otherwise.
-
hasKeyContext2
@Internal public boolean hasKeyContext2()
Description copied from interface:KeyContextHandlerWhether the second input ofStreamOperatorhas "KeyContext". If false, we can omit the call ofStreamOperator.setKeyContextElement1(org.apache.flink.streaming.runtime.streamrecord.StreamRecord<?>)for each record arrived on the second input.- Specified by:
hasKeyContext2in interfaceKeyContextHandler- Returns:
- True if the second input has "KeyContext", false otherwise.
-
setCurrentKey
public void setCurrentKey(Object key)
- Specified by:
setCurrentKeyin interfaceKeyContext
-
getCurrentKey
public Object getCurrentKey()
- Specified by:
getCurrentKeyin interfaceKeyContext
-
getKeyedStateStore
public org.apache.flink.api.common.state.KeyedStateStore getKeyedStateStore()
-
setChainingStrategy
public final void setChainingStrategy(ChainingStrategy strategy)
- Specified by:
setChainingStrategyin interfaceSetupableStreamOperator<OUT>
-
getChainingStrategy
public final ChainingStrategy getChainingStrategy()
- Specified by:
getChainingStrategyin interfaceSetupableStreamOperator<OUT>
-
processLatencyMarker
public void processLatencyMarker(LatencyMarker latencyMarker) throws Exception
- Throws:
Exception
-
processLatencyMarker1
public void processLatencyMarker1(LatencyMarker latencyMarker) throws Exception
- Throws:
Exception
-
processLatencyMarker2
public void processLatencyMarker2(LatencyMarker latencyMarker) throws Exception
- Throws:
Exception
-
reportOrForwardLatencyMarker
protected void reportOrForwardLatencyMarker(LatencyMarker marker)
-
getInternalTimerService
public <K,N> InternalTimerService<N> getInternalTimerService(String name, org.apache.flink.api.common.typeutils.TypeSerializer<N> namespaceSerializer, Triggerable<K,N> triggerable)
Returns aInternalTimerServicethat can be used to query current processing time and event time and to set timers. An operator can have several timer services, where each has its own namespace serializer. Timer services are differentiated by the string key that is given when requesting them, if you call this method with the same key multiple times you will get the same timer service instance in subsequent requests.Timers are always scoped to a key, the currently active key of a keyed stream operation. When a timer fires, this key will also be set as the currently active key.
Each timer has attached metadata, the namespace. Different timer services can have a different namespace type. If you don't need namespace differentiation you can use
VoidNamespaceSerializeras the namespace serializer.- Type Parameters:
N- The type of the timer namespace.- Parameters:
name- The name of the requested timer service. If no service exists under the given name a new one will be created and returned.namespaceSerializer-TypeSerializerfor the timer namespace.triggerable- TheTriggerablethat should be invoked when timers fire
-
processWatermarkStatus
public void processWatermarkStatus(WatermarkStatus watermarkStatus) throws Exception
- Throws:
Exception
-
processWatermarkStatus1
public final void processWatermarkStatus1(WatermarkStatus watermarkStatus) throws Exception
- Throws:
Exception
-
processWatermarkStatus2
public final void processWatermarkStatus2(WatermarkStatus watermarkStatus) throws Exception
- Throws:
Exception
-
getOperatorID
public org.apache.flink.runtime.jobgraph.OperatorID getOperatorID()
- Specified by:
getOperatorIDin interfaceStreamOperator<OUT>
-
getTimeServiceManager
protected Optional<InternalTimeServiceManager<?>> getTimeServiceManager()
-
-