Flink1.14.* 各种算子在StreamTask控制下如何调用的源码

2024-08-31 08:12

本文主要是介绍Flink1.14.* 各种算子在StreamTask控制下如何调用的源码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 前言:
  • 一、StreamTask执行算子的生命周期
  • 二、 Source的streamTask用的是SourceStreamTask
  • 三、基础转换操作,窗口用的是OneInputStreamTask
    • 1、初始化OneInputStreamTask
    • 2、StreamTask运行invoke调用的是StreamTask的processInput方法
    • 3、从缓冲区获取数据放入到内存中
    • 4、调用算子的processElement方法处理数据,
  • 四、sink的streamTask用的也是OneInputStreamTask
  • 五、OneInputStreamTask和SourceStreamTask类关系图

前言:

在 Apache Flink 中,StreamTask 类是处理流数据的核心执行单元。
它负责管理算子的生命周期,并调用算子的处理方法。StreamTask 类的全路径(即完整的包名和类名)如下:
StreamTask 类位于 flink-streaming-java 模块中,具体的包结构为 org.apache.flink.streaming.runtime.tasks
全路径如下

flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTask.java

一、StreamTask执行算子的生命周期

先看StreamTask大体执行流程(忽略实现类的细节)

public abstract class StreamTask<OUT, OP extends StreamOperator<OUT>> implements TaskInvokable, CheckpointableTask, CoordinatedTask, AsyncExceptionHandler, ContainingTaskDetails {protected OP mainOperator;private boolean mailboxLoopRunning;//第一步构造函数,把processInput赋值给mailboxProcessorprotected StreamTask(Environment environment, @Nullable TimerService timerService, UncaughtExceptionHandler uncaughtExceptionHandler, StreamTaskActionExecutor actionExecutor, TaskMailbox mailbox) throws Exception {this.mailboxProcessor = new MailboxProcessor(this::processInput, mailbox, actionExecutor);//默认为truethis.mailboxLoopRunning = true;}//第三步StreamTask执行public final void invoke() throws Exception {//省略代码this.runMailboxLoop(); }//SourceStreamTask会重写这个方法,OneInputStreamTask不会重写protected void processInput(Controller controller) throws Exception {//删除干扰代码,}
}
public class MailboxProcessor implements Closeable {protected final MailboxDefaultAction mailboxDefaultAction;//第二步 构造函数把processInput方法赋值给mailboxDefaultActionpublic MailboxProcessor(MailboxDefaultAction mailboxDefaultAction, TaskMailbox mailbox, StreamTaskActionExecutor actionExecutor) {//这里mailboxDefaultAction传的是this::processInputthis.mailboxDefaultAction = (MailboxDefaultAction)Preconditions.checkNotNull(mailboxDefaultAction);}//第四步,public void runMailboxLoop() throws Exception {//suspended默认是falsethis.suspended = !this.mailboxLoopRunning;//this.isNextLoopPossible默认是truewhile(this.isNextLoopPossible()) {this.mailboxProcessor.runMailboxLoop();}}private boolean isNextLoopPossible() {return !this.suspended;}//第五步,调用processInputpublic void runMailboxLoop() throws Exception {//这个执行的是processInput方法this.mailboxDefaultAction.runDefaultAction(defaultActionContext);}
}

不同的实现类都是按照上面的步骤初始化执行的

二、 Source的streamTask用的是SourceStreamTask

@Internal
public class SourceStreamTask<OUT, SRC extends SourceFunction<OUT>, OP extends StreamSource<OUT, SRC>> extends StreamTask<OUT, OP> {private final SourceStreamTask<OUT, SRC, OP>.LegacySourceFunctionThread sourceThread;protected void init() {//这个mainOperator是StreamTask的字段,,SourceFunction<?> source = (SourceFunction)((StreamSource)this.mainOperator).getUserFunction();}    protected void processInput(Controller controller) throws Exception {//这里启动线程的run方法this.sourceThread.start();}private class LegacySourceFunctionThread extends Thread {private final CompletableFuture<Void> completionFuture = new CompletableFuture();LegacySourceFunctionThread() {}public void run() {try {if (!SourceStreamTask.this.operatorChain.isTaskDeployedAsFinished()) {StreamTask.LOG.debug("Legacy source {} skip execution since the task is finished on restore", SourceStreamTask.this.getTaskNameWithSubtaskAndId());((StreamSource)SourceStreamTask.this.mainOperator).run(SourceStreamTask.this.lock, SourceStreamTask.this.operatorChain);}//删除干扰代码} catch (Throwable var2) {//删除干扰代码}}}
}

第一点需要注意的是由于SourceStreamTask重写了streamTaskprocessInput方法,所以streamTaskinvoke方法执行的是子类的SourceStreamTaskprocessInput方法

第二点看一下init方法,这里(SourceFunction)((StreamSource)this.mainOperator).getUserFunction()就是获取的source算子,不清楚的可以看一下kafkaSource这篇文章Flink 1.14.*版本kafkaSource源码
由这里来触发SourceFunctionrun方法,即FlinkKafkaConsumerBaserun方法

三、基础转换操作,窗口用的是OneInputStreamTask

这种一般都是中间算子,或者最后一个算子(例如kafkaSink),所以主要涉及到从输入源获取数据,处理数据,并将结果写入输出中
如果连着看下面两篇文章,你就会知道为什么sink也是用的OneInputStreamTask
Flink 1.14.*中flatMap,filter等基本转换函数源码
Flink 1.14.* 版本kafkaSink源码

1、初始化OneInputStreamTask

public class OneInputStreamTask<IN, OUT> extends StreamTask<OUT, OneInputStreamOperator<IN, OUT>> {public void init() throws Exception {//output是私有类StreamTaskNetworkOutput对象DataOutput<IN> output = this.createDataOutput(numRecordsIn);StreamTaskInput<IN> input = this.createTaskInput(inputGate);//这个inputProcessor字段是给父类StreamTask初始化的,这时候父类inputProcessor=StreamOneInputProcessorthis.inputProcessor = new StreamOneInputProcessor(input, output, this.operatorChain);}private StreamTaskInput<IN> createTaskInput(CheckpointedInputGate inputGate) {int numberOfInputChannels = inputGate.getNumberOfInputChannels();StatusWatermarkValve statusWatermarkValve = new StatusWatermarkValve(numberOfInputChannels);TypeSerializer<IN> inSerializer = this.configuration.getTypeSerializerIn1(this.getUserCodeClassLoader());return StreamTaskNetworkInputFactory.create(inputGate, inSerializer, this.getEnvironment().getIOManager(), statusWatermarkValve, 0, this.getEnvironment().getTaskStateManager().getInputRescalingDescriptor(), (gateIndex) -> {return ((StreamEdge)this.configuration.getInPhysicalEdges(this.getUserCodeClassLoader()).get(gateIndex)).getPartitioner();}, this.getEnvironment().getTaskInfo());}//返回的是下面私有类StreamTaskNetworkOutput对象private DataOutput<IN> createDataOutput(Counter numRecordsIn) {return new OneInputStreamTask.StreamTaskNetworkOutput(this.operatorChain.getFinishedOnRestoreInputOrDefault((Input)this.mainOperator), this.inputWatermarkGauge, numRecordsIn);}    //私有内部类,对应上面init中的outputprivate static class StreamTaskNetworkOutput<IN> implements DataOutput<IN> {private final Input<IN> operator;public void emitRecord(StreamRecord<IN> record) throws Exception {//调用的算子的processElement方法this.operator.processElement(record);}}}

这里是调用init初始化,StreamOneInputProcessor一起初始化了

public final class StreamOneInputProcessor<IN> implements StreamInputProcessor {private StreamTaskInput<IN> input;private DataOutput<IN> output;public StreamOneInputProcessor(StreamTaskInput<IN> input, DataOutput<IN> output, BoundedMultiInput endOfInputAware) {//此input就是StreamTaskNetworkInputthis.input = (StreamTaskInput)Preconditions.checkNotNull(input);//此output就是OneInputStreamTask里的私有类StreamTaskNetworkOutput对象this.output = (DataOutput)Preconditions.checkNotNull(output);this.endOfInputAware = (BoundedMultiInput)Preconditions.checkNotNull(endOfInputAware);}public DataInputStatus processInput() throws Exception {DataInputStatus status = this.input.emitNext(this.output);//删除干扰代码return status;}}

后面看到this.inputProcessor.processInput其实就是调用的上面类的processInput方法

下面简单介绍一下StreamTaskNetworkInputFactory的创建的两种不同的StreamTaskInput,也可以不用看

public class StreamTaskNetworkInputFactory {public StreamTaskNetworkInputFactory() {}//这里只看返回StreamTaskNetworkInputpublic static <T> StreamTaskInput<T> create(CheckpointedInputGate checkpointedInputGate, TypeSerializer<T> inputSerializer, IOManager ioManager, StatusWatermarkValve statusWatermarkValve, int inputIndex, InflightDataRescalingDescriptor rescalingDescriptorinflightDataRescalingDescriptor, Function<Integer, StreamPartitioner<?>> gatePartitioners, TaskInfo taskInfo) {return (StreamTaskInput)(rescalingDescriptorinflightDataRescalingDescriptor.equals(InflightDataRescalingDescriptor.NO_RESCALE) ? new StreamTaskNetworkInput(checkpointedInputGate, inputSerializer, ioManager, statusWatermarkValve, inputIndex) : new RescalingStreamTaskNetworkInput(checkpointedInputGate, inputSerializer, ioManager, statusWatermarkValve, inputIndex, rescalingDescriptorinflightDataRescalingDescriptor, gatePartitioners, taskInfo));}
}

StreamTaskNetworkInputFlink 中用于从网络接收数据并将其传递给任务处理的基本组件。它实现了 StreamInput 接口,并负责从网络缓冲区中读取数据,将数据反序列化为 StreamRecord,然后传递给下游的处理逻辑。
主要功能:

  1. 从网络接收数据:读取来自上游任务通过网络发送的数据。
  2. 数据反序列化:将接收到的字节数据反序列化为 StreamRecord 对象
  3. 调用下游处理逻辑:将反序列化后的 StreamRecord 对象传递给下游的处理逻辑(如操作符的 processElement 方法)。

RescalingStreamTaskNetworkInputStreamTaskNetworkInput 的一个扩展,用于处理任务重新缩放(rescaling)场景下的数据接收。任务重新缩放是指在运行时动态调整任务并行度,以适应负载变化。RescalingStreamTaskNetworkInput 主要用于确保在重新缩放过程中数据能够正确地重新分配和处理。
主要功能:

  1. 处理重新缩放场景:在任务重新缩放期间,确保数据能够正确地重新分配和处理。
  2. 数据重分配逻辑:在接收数据时,可能需要根据新的并行度进行数据重分配,以确保数据能够被正确处理。
  3. 继承自 StreamTaskNetworkInput:继承了 StreamTaskNetworkInput 的基本功能,同时增加了处理重新缩放场景的逻辑。

这样初始化部分就完成了

2、StreamTask运行invoke调用的是StreamTask的processInput方法

通过上面第一章节介绍StreamTask的,知道StreamTaskinvoke方法最终执行的是processInput方法,因为OneInputStreamTask不像SourceStreamTask重写了processInput方法,所以调用的还是父类StreamTaskprocessInput方法

public abstract class StreamTask<OUT, OP extends StreamOperator<OUT>> implements TaskInvokable, CheckpointableTask, CoordinatedTask, AsyncExceptionHandler, ContainingTaskDetails {protected void processInput(Controller controller) throws Exception {DataInputStatus status = this.inputProcessor.processInput();}
}

这时候this.inputProcessor=StreamOneInputProcessor,调用processInput即调用StreamOneInputProcessorprocessInput方法

//从OneInputStreamTask初始化章节粘贴过来的,方便
public final class StreamOneInputProcessor<IN> implements StreamInputProcessor {private StreamTaskInput<IN> input;private DataOutput<IN> output;public StreamOneInputProcessor(StreamTaskInput<IN> input, DataOutput<IN> output, BoundedMultiInput endOfInputAware) {//此input就是StreamTaskNetworkInputthis.input = (StreamTaskInput)Preconditions.checkNotNull(input);//此output就是OneInputStreamTask里的私有类StreamTaskNetworkOutput对象this.output = (DataOutput)Preconditions.checkNotNull(output);this.endOfInputAware = (BoundedMultiInput)Preconditions.checkNotNull(endOfInputAware);}public DataInputStatus processInput() throws Exception {DataInputStatus status = this.input.emitNext(this.output);//删除干扰代码return status;}}

StreamOneInputProcessor.processInput中会调this.input.emitNext(this.output),因为构造StreamOneInputProcessor对象时已经赋值

所以processInput方法中DataInputStatus status = this.input.emitNext(this.output) 调用的是StreamTaskNetworkInputemitNext方法;

public final class StreamTaskNetworkInput<T> extends AbstractStreamTaskNetworkInput<T, SpillingAdaptiveSpanningRecordDeserializer<DeserializationDelegate<StreamElement>>> {}
public abstract class AbstractStreamTaskNetworkInput<T, R extends RecordDeserializer<DeserializationDelegate<StreamElement>>> implements StreamTaskInput<T> {//从缓冲区读取到当前内存中private R currentRecordDeserializer = null;public DataInputStatus emitNext(DataOutput<T> output) throws Exception {while(true) {//当前内存有缓冲区的数据if (this.currentRecordDeserializer != null) {DeserializationResult result;try {//从deserializationDelegate尝试获取下一个记录result = this.currentRecordDeserializer.getNextRecord(this.deserializationDelegate);} catch (IOException var4) {throw new IOException(String.format("Can't get next record for channel %s", this.lastChannel), var4);}if (result.isFullRecord()) {//处理该记录并返回this.processElement((StreamElement)this.deserializationDelegate.getInstance(), output);return DataInputStatus.MORE_AVAILABLE;}}//通过pollNext()方法从checkpointedInputGate中获取下一个元素,并将其封装在Optional中。Optional<BufferOrEvent> bufferOrEvent = this.checkpointedInputGate.pollNext();//然后检查bufferOrEvent是否存在if (bufferOrEvent.isPresent()) {//如果是缓冲区,则调用processBuffer方法进行处理if (((BufferOrEvent)bufferOrEvent.get()).isBuffer()) {this.processBuffer((BufferOrEvent)bufferOrEvent.get());continue;}//如果是事件,则调用processEvent方法进行处理并返回结果return this.processEvent((BufferOrEvent)bufferOrEvent.get());}}}
}

最终调的是父类AbstractStreamTaskNetworkInputemitNext方法

3、从缓冲区获取数据放入到内存中

通过上面emitNext实现,while循环中先判断当前内存区是否有缓冲区的数据,有则处理结束此次emitNext方法,如果没有则从缓冲区获取数据到当前内存区,再跳过本次循环,让下一个循环开始执行处理内存区数据的方法
this.checkpointedInputGate.pollNext()这个就不看了,你就知道从缓冲区返回数据就行了,

看一下processBuffer方法

protected void processBuffer(BufferOrEvent bufferOrEvent) throws IOException {//获取缓存管道信息this.lastChannel = bufferOrEvent.getChannelInfo();Preconditions.checkState(this.lastChannel != null);//可以理解为给currentRecordDeserializer初始化,选定类型this.currentRecordDeserializer = this.getActiveSerializer(bufferOrEvent.getChannelInfo());Preconditions.checkState(this.currentRecordDeserializer != null, "currentRecordDeserializer has already been released");//把缓冲区的数据写入到当前内存区this.currentRecordDeserializer.setNextBuffer(bufferOrEvent.getBuffer());
}

4、调用算子的processElement方法处理数据,

通过StreamOneInputProcessor初始化知道,入参output实际上是OneInputStreamTask里的私有类StreamTaskNetworkOutput对象

private void processElement(StreamElement recordOrMark, DataOutput<T> output) throws Exception {if (recordOrMark.isRecord()) {//这里就调用了OneInputStreamTask里的私有类StreamTaskNetworkOutput中的emitRecord方法output.emitRecord(recordOrMark.asRecord());}
}
private static class StreamTaskNetworkOutput<IN> implements DataOutput<IN> {private final Input<IN> operator;public void emitRecord(StreamRecord<IN> record) throws Exception {//调用的算子的processElement方法this.operator.processElement(record);}
}

emitRecord方法就会调用算子的processElement方法,之后就可以看基础转换函数和窗口函数文章中,他们是被调用processElement触发的
如果不清楚可以看Flink 1.14.*中flatMap,filter等基本转换函数源码

四、sink的streamTask用的也是OneInputStreamTask

sink可以看成是一个像flatMapfilter、窗口一样的算子,通过OneInputStreamTask触发到sinkFuncitionprocessElement方法,执行流程都是一样的,

不懂的可以看下面两篇文章,比对一下,sink和基本转换、窗口算子触发方式是否一样
Flink 1.14.*中flatMap,filter等基本转换函数源码
Flink 1.14.* 版本kafkaSink源码

五、OneInputStreamTask和SourceStreamTask类关系图

在这里插入图片描述

在这里插入图片描述

比对两个关系图,SourceStreamTask多了SourceFunction接口和streamSource

这篇关于Flink1.14.* 各种算子在StreamTask控制下如何调用的源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123357

相关文章

Python远程控制MySQL的完整指南

《Python远程控制MySQL的完整指南》MySQL是最流行的关系型数据库之一,Python通过多种方式可以与MySQL进行交互,下面小编就为大家详细介绍一下Python操作MySQL的常用方法和最... 目录1. 准备工作2. 连接mysql数据库使用mysql-connector使用PyMySQL3.

Java调用C#动态库的三种方法详解

《Java调用C#动态库的三种方法详解》在这个多语言编程的时代,Java和C#就像两位才华横溢的舞者,各自在不同的舞台上展现着独特的魅力,然而,当它们携手合作时,又会碰撞出怎样绚丽的火花呢?今天,我们... 目录方法1:C++/CLI搭建桥梁——Java ↔ C# 的“翻译官”步骤1:创建C#类库(.NET

如何搭建并配置HTTPD文件服务及访问权限控制

《如何搭建并配置HTTPD文件服务及访问权限控制》:本文主要介绍如何搭建并配置HTTPD文件服务及访问权限控制的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、安装HTTPD服务二、HTTPD服务目录结构三、配置修改四、服务启动五、基于用户访问权限控制六、

C/C++和OpenCV实现调用摄像头

《C/C++和OpenCV实现调用摄像头》本文主要介绍了C/C++和OpenCV实现调用摄像头,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录准备工作1. 打开摄像头2. 读取视频帧3. 显示视频帧4. 释放资源5. 获取和设置摄像头属性

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案

《使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案》在SpringBoot应用中,我们经常使用​​@Cacheable​​注解来缓存数据,以提高应用的性能... 目录@Cacheable注解Redis时,Redis宕机或其他原因连不上,继续调用原方法的解决方案1

C#通过进程调用外部应用的实现示例

《C#通过进程调用外部应用的实现示例》本文主要介绍了C#通过进程调用外部应用的实现示例,以WINFORM应用程序为例,在C#应用程序中调用PYTHON程序,具有一定的参考价值,感兴趣的可以了解一下... 目录窗口程序类进程信息类 系统设置类 以WINFORM应用程序为例,在C#应用程序中调用python程序

MySQL精准控制Binlog日志数量的三种方案

《MySQL精准控制Binlog日志数量的三种方案》作为数据库管理员,你是否经常为服务器磁盘爆满而抓狂?Binlog就像数据库的“黑匣子”,默默记录着每一次数据变动,但若放任不管,几天内这些日志文件就... 目录 一招修改配置文件:永久生效的控制术1.定位my.cnf文件2.添加核心参数不重启热更新:高手应

Java调用Python的四种方法小结

《Java调用Python的四种方法小结》在现代开发中,结合不同编程语言的优势往往能达到事半功倍的效果,本文将详细介绍四种在Java中调用Python的方法,并推荐一种最常用且实用的方法,希望对大家有... 目录一、在Java类中直接执行python语句二、在Java中直接调用Python脚本三、使用Run