operator chain是指将满足一定条件的operator 链在一起,放在同一个task里面执行,是Flink任务优化的一种方式,在同一个task里面的operator的数据传输变成函数调用关系,这种方式减少数据传输过程。常见的chain例如:source->map->filter,这样的任务链可以chain在一起,那么其内部是如何决定是否能够chain在一起与chain一起之后如何执行就是本篇文章将要剖析的重点。
第一个递归:JobGraph生成
Flink中划分了四种图:StreamGraph、JobGraph、ExecutionGraph、物理执行图,前两种StreamGraph、JobGraph是在客户端生成,ExecutionGraph在jobMaster中生成,最后一种物理执行图是一种虚拟的图,不存在的数据结构,运行在每一个TaskExecutor中。我们在Flink Web UI中看到的就是JobGraph,如下:
JobGraph相对于StreamGraph,可以理解为优化过后的StreamGraph,将能够chain一起的operator chain在一起,上图将source与filter两个operator chain在一起了,这个步骤在生成JobGraph过程中完成。其具体实现在StreamingJobGraphGenerator中:
private JobGraph createJobGraph() {
.....
Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes = new HashMap<>();
setChaining(hashes, legacyHashes, chainedOperatorHashes);
setPhysicalEdges();
setSlotSharingAndCoLocation();
configureCheckpointing();
....
}
重点就在setChaining方法中,在里面调用createChain方法,构造JobVertix的同时完成operator chain的操作,createChain方法:
private List<StreamEdge> createChain(
Integer startNodeId,
Integer currentNodeId,
Map<Integer, byte[]> hashes,
List<Map<Integer, byte[]>> legacyHashes,
int chainIndex,
Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes) {
if (!builtVertices.contains(startNodeId)) {
//chain 的出边
List<StreamEdge> transitiveOutEdges = new ArrayList<StreamEdge>();
//能够chain在一起的边
List<StreamEdge> chainableOutputs = new ArrayList<StreamEdge>();
//不能够chain一起的边
List<StreamEdge> nonChainableOutputs = new ArrayList<StreamEdge>();
for (StreamEdge outEdge : streamGraph.getStreamNode(currentNodeId).getOutEdges()) {
//isChainable判断是否能够chain在一起
if (isChainable(outEdge, streamGraph)) {
chainableOutputs.add(outEdge);
} else {
nonChainableOutputs.add(outEdge);