当前位置:   article > 正文

【Flink 源码系列】Flink 源码:广播流状态源码解析_flink广播流

flink广播流


2ed91fd8a6b201875a9116858b27be3b.gif

Broadcast State 是 Operator State 的一种特殊类型。它的引入是为了支持这样的场景: 一个流的记录需要广播到所有下游任务,在这些用例中,它们用于在所有子任务中维护相同的状态。然后可以在处理第二个流的数据时访问这个广播状态,广播状态有自己的一些特性。

  1. 必须定义为一个 Map 结构。

  2. 广播状态只能在广播流侧修改,非广播侧不能修改状态。

  3. Broadcast State 运行时的状态只能保存在内存中。

看到这相信你肯定会有下面的疑问:

  • 广播状态为什么必须定义为 Map 结构,我用其他的状态类型不行吗?

  • 广播状态为什么只能在广播侧修改,非广播侧为什么不能修改呢?

  • 广播状态为什么只能保存在内存中,难道不能用 Rockdb 状态后端吗?

下面就带着这三个疑问通过阅读相关源码,回答上面的问题。

broadcast 源码

  1. /**
  2.  * Sets the partitioning of the {@link DataStream} so that the output elements are broadcasted
  3.  * to every parallel instance of the next operation. In addition, it implicitly as many {@link
  4.  * org.apache.flink.api.common.state.BroadcastState broadcast states} as the specified
  5.  * descriptors which can be used to store the element of the stream.
  6.  *
  7.  * @param broadcastStateDescriptors the descriptors of the broadcast states to create.
  8.  * @return A {@link BroadcastStream} which can be used in the {@link #connect(BroadcastStream)}
  9.  *     to create a {@link BroadcastConnectedStream} for further processing of the elements.
  10.  */
  11. @PublicEvolving
  12. public BroadcastStream<T> broadcast(
  13.         final MapStateDescriptor<?, ?>... broadcastStateDescriptors) {
  14.     Preconditions.checkNotNull(broadcastStateDescriptors);
  15.     final DataStream<T> broadcastStream = setConnectionType(new BroadcastPartitioner<>());
  16.     return new BroadcastStream<>(environment, broadcastStream, broadcastStateDescriptors);
  17. }

可以发现 broadcast 方法需要的参数是 MapStateDescriptor 也就是一个 Map 结构的状态描述符,我们在使用的时候就必须定义为 MapStateDescriptor,否则会直接报错,其实主要是因为广播状态的作用是和非广播流进行关联,你可以想象成双流 join 的场景,那么 join 的时候就必须要有一个主键,也就是相同的 key 才能 join 上,所以 Map(key-value) 结构是最适合这种场景的,key 可以存储要关联字段,value 可以是任意类型的广播数据,在关联的时候只需要获取到广播状态,然后 state.get(key) 就可以很容易拿到广播数据。

process 源码

  1. @PublicEvolving
  2. public <KEY, OUT> SingleOutputStreamOperator<OUT> process(
  3.         final KeyedBroadcastProcessFunction<KEY, IN1, IN2, OUT> function) {
  4.   // 获取输出数据的类型信息
  5.     TypeInformation<OUT> outTypeInfo =
  6.             TypeExtractor.getBinaryOperatorReturnType(
  7.                     function,
  8.                     KeyedBroadcastProcessFunction.class,
  9.                     1,
  10.                     2,
  11.                     3,
  12.                     TypeExtractor.NO_INDEX,
  13.                     getType1(),
  14.                     getType2(),
  15.                     Utils.getCallLocationName(),
  16.                     true);
  17.     return process(function, outTypeInfo);
  18. }

process 方法需要的参数是 KeyedBroadcastProcessFunction<KEY, IN1, IN2, OUT>,跟普通的 KeyedProcessFunction<K, I, O> 相比,很容易发现多了一个泛型参数,因为这里的 process 上游连接的是两个数据流,所以需要两个类型。然后调用 process 的重载方法。

process 源码

  1. @PublicEvolving
  2. public <KEY, OUT> SingleOutputStreamOperator<OUT> process(
  3.         final KeyedBroadcastProcessFunction<KEY, IN1, IN2, OUT> function,
  4.         final TypeInformation<OUT> outTypeInfo) {
  5.     Preconditions.checkNotNull(function);
  6.     Preconditions.checkArgument(
  7.             nonBroadcastStream instanceof KeyedStream,
  8.             "A KeyedBroadcastProcessFunction can only be used on a keyed stream.");
  9.   
  10.     return transform(function, outTypeInfo);
  11. }

这个 process 方法里面什么都没干,直接调用 transform 方法。

transform 源码

  1. @Internal
  2. private <KEY, OUT> SingleOutputStreamOperator<OUT> transform(
  3.         final KeyedBroadcastProcessFunction<KEY, IN1, IN2, OUT> userFunction,
  4.         final TypeInformation<OUT> outTypeInfo) {
  5.     // read the output type of the input Transforms to coax out errors about MissingTypeInfo
  6.     nonBroadcastStream.getType();
  7.     broadcastStream.getType();
  8.     KeyedStream<IN1, KEY> keyedInputStream = (KeyedStream<IN1, KEY>) nonBroadcastStream;
  9.   // 构造 KeyedBroadcastStateTransformation
  10.     final KeyedBroadcastStateTransformation<KEY, IN1, IN2, OUT> transformation =
  11.             new KeyedBroadcastStateTransformation<>(
  12.                     "Co-Process-Broadcast-Keyed",
  13.                     nonBroadcastStream.getTransformation(),
  14.                     broadcastStream.getTransformation(),
  15.                     clean(userFunction),
  16.                     broadcastStateDescriptors,
  17.                     keyedInputStream.getKeyType(),
  18.                     keyedInputStream.getKeySelector(),
  19.                     outTypeInfo,
  20.                     environment.getParallelism());
  21.     @SuppressWarnings({"unchecked""rawtypes"})
  22.     final SingleOutputStreamOperator<OUT> returnStream =
  23.             new SingleOutputStreamOperator(environment, transformation);
  24.   // 添加到 List<Transformation<?>> 集合
  25.     getExecutionEnvironment().addOperator(transformation);
  26.     return returnStream;
  27. }

transform 方法里面主要做了两件事:

  1. 先是构造对应的 KeyedBroadcastStateTransformation 对象,其实  KeyedBroadcastStateTransformation 也是 Transformation 的一个子类。

  2. 然后把构造好的 transformation 添加到 List<Transformation<?>> 集合里,后面在构建 StreamGraph 的时候会从这个集合里获取 Transformation。

getStreamGraph 源码

  1. @Internal
  2. public StreamGraph getStreamGraph(boolean clearTransformations) {
  3.     final StreamGraph streamGraph = getStreamGraphGenerator(transformations).generate();
  4.     if (clearTransformations) {
  5.         transformations.clear();
  6.     }
  7.     return streamGraph;
  8. }

getStreamGraph 的主要作用就是生成 StreamGraph。下面就会用到上一步生成的 List<Transformation<?>> 集合,因为这篇文章主要是分析 Flink 广播流的源码,所以只会对广播流相关的源码进行解析。

getStreamGraphGenerator 源码

  1. private StreamGraphGenerator getStreamGraphGenerator(List<Transformation<?>> transformations) {
  2.     if (transformations.size() <= 0) {
  3.         throw new IllegalStateException(
  4.                 "No operators defined in streaming topology. Cannot execute.");
  5.     }
  6.     // We copy the transformation so that newly added transformations cannot intervene with the
  7.     // stream graph generation.
  8.     return new StreamGraphGenerator(
  9.                     new ArrayList<>(transformations), config, checkpointCfg, configuration)
  10.             .setStateBackend(defaultStateBackend)
  11.             .setChangelogStateBackendEnabled(changelogStateBackendEnabled)
  12.             .setSavepointDir(defaultSavepointDirectory)
  13.             .setChaining(isChainingEnabled)
  14.             .setUserArtifacts(cacheFile)
  15.             .setTimeCharacteristic(timeCharacteristic)
  16.             .setDefaultBufferTimeout(bufferTimeout)
  17.             .setSlotSharingGroupResource(slotSharingGroupResources);
  18. }

getStreamGraphGenerator 方法主要就是构造 StreamGraphGenerator 对象,StreamGraphGenerator 构造完成后,就可以调用 generate 方法来产生 StreamGraph 了,在看 generate 方法之前先来看一下 StreamGraphGenerator 的静态代码块。

StreamGraphGenerator 源码

  1. static {
  2.     @SuppressWarnings("rawtypes")
  3.     Map<Class<? extends Transformation>, TransformationTranslator<?, ? extends Transformation>>
  4.             tmp = new HashMap<>();
  5.     tmp.put(OneInputTransformation.class, new OneInputTransformationTranslator<>());
  6.     tmp.put(TwoInputTransformation.class, new TwoInputTransformationTranslator<>());
  7.     tmp.put(MultipleInputTransformation.class, new MultiInputTransformationTranslator<>());
  8.     tmp.put(KeyedMultipleInputTransformation.class, new MultiInputTransformationTranslator<>());
  9.     tmp.put(SourceTransformation.class, new SourceTransformationTranslator<>());
  10.     tmp.put(SinkTransformation.class, new SinkTransformationTranslator<>());
  11.     tmp.put(LegacySinkTransformation.class, new LegacySinkTransformationTranslator<>());
  12.     tmp.put(LegacySourceTransformation.class, new LegacySourceTransformationTranslator<>());
  13.     tmp.put(UnionTransformation.class, new UnionTransformationTranslator<>());
  14.     tmp.put(PartitionTransformation.class, new PartitionTransformationTranslator<>());
  15.     tmp.put(SideOutputTransformation.class, new SideOutputTransformationTranslator<>());
  16.     tmp.put(ReduceTransformation.class, new ReduceTransformationTranslator<>());
  17.     tmp.put(
  18.             TimestampsAndWatermarksTransformation.class,
  19.             new TimestampsAndWatermarksTransformationTranslator<>());
  20.     tmp.put(BroadcastStateTransformation.class, new BroadcastStateTransformationTranslator<>());
  21.     tmp.put(
  22.             KeyedBroadcastStateTransformation.class,
  23.             new KeyedBroadcastStateTransformationTranslator<>());
  24.     translatorMap = Collections.unmodifiableMap(tmp);
  25. }

在初始化 StreamGraphGenerator 之前,会先执行其静态代码块生成一个 Transformation -> TransformationTranslator 映射关系的 Map 集合,后面会用到这个 Map。

transform 源码

  1. // 根据 Transformation 获取对应的 TransformationTranslator 
  2. final TransformationTranslator<?, Transformation<?>> translator =
  3.         (TransformationTranslator<?, Transformation<?>>)
  4.                 translatorMap.get(transform.getClass());
  5. Collection<Integer> transformedIds;
  6. if (translator != null) {
  7.    
  8.     transformedIds = translate(translator, transform);
  9. else {
  10.     transformedIds = legacyTransform(transform);
  11. }

构造完 StreamGraphGenerator 对象后,紧接着会调用 generate 方法,然后又调用了 transform 方法,这里会从上面生成的 Map 里面获取到对应的 TransformationTranslator,然后调用 translate 方法。

translate#translateForStreaming#translateForStreamingInternal 源码

  1. @Override
  2. protected Collection<Integer> translateForStreamingInternal(
  3.         final KeyedBroadcastStateTransformation<KEY, IN1, IN2, OUT> transformation,
  4.         final Context context) {
  5.     checkNotNull(transformation);
  6.     checkNotNull(context);
  7.   // 构建 CoBroadcastWithKeyedOperator 
  8.     CoBroadcastWithKeyedOperator<KEY, IN1, IN2, OUT> operator =
  9.             new CoBroadcastWithKeyedOperator<>(
  10.                     transformation.getUserFunction(),
  11.                     transformation.getBroadcastStateDescriptors());
  12.     return translateInternal(
  13.             transformation,
  14.             transformation.getRegularInput(),
  15.             transformation.getBroadcastInput(),
  16.             SimpleOperatorFactory.of(operator),
  17.             transformation.getStateKeyType(),
  18.             transformation.getKeySelector(),
  19.             null /* no key selector on broadcast input */,
  20.             context);
  21. }

translate 方法最终会调用到 KeyedBroadcastStateTransformationTranslator 的 translateForStreamingInternal 方法中,根据 UserFunction(用户代码)和 broadcastStateDescriptors(广播状态描述符)构造CoBroadcastWithKeyedOperator 对象。

CoBroadcastWithKeyedOperator 源码

  1. /**
  2.  * A {@link TwoInputStreamOperator} for executing {@link KeyedBroadcastProcessFunction
  3.  * KeyedBroadcastProcessFunctions}.
  4.  *
  5.  * @param <KS> The key type of the input keyed stream.
  6.  * @param <IN1> The input type of the keyed (non-broadcast) side.
  7.  * @param <IN2> The input type of the broadcast side.
  8.  * @param <OUT> The output type of the operator.
  9.  */
  10. @Internal
  11. public class CoBroadcastWithKeyedOperator<KS, IN1, IN2, OUT>
  12.         extends AbstractUdfStreamOperator<OUT, KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT>>
  13.         implements TwoInputStreamOperator<IN1, IN2, OUT>, Triggerable<KS, VoidNamespace> {
  14.     private static final long serialVersionUID = 5926499536290284870L;
  15.     private final List<MapStateDescriptor<?, ?>> broadcastStateDescriptors;
  16.     private transient TimestampedCollector<OUT> collector;
  17.     private transient Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> broadcastStates;
  18.     private transient ReadWriteContextImpl rwContext;
  19.     private transient ReadOnlyContextImpl rContext;
  20.     private transient OnTimerContextImpl onTimerContext;
  21.     public CoBroadcastWithKeyedOperator(
  22.             final KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT> function,
  23.             final List<MapStateDescriptor<?, ?>> broadcastStateDescriptors) {
  24.         super(function);
  25.         this.broadcastStateDescriptors = Preconditions.checkNotNull(broadcastStateDescriptors);
  26.     }
  27.     @Override
  28.     public void open() throws Exception {
  29.         super.open();
  30.         InternalTimerService<VoidNamespace> internalTimerService =
  31.                 getInternalTimerService("user-timers", VoidNamespaceSerializer.INSTANCE, this);
  32.         TimerService timerService = new SimpleTimerService(internalTimerService);
  33.         collector = new TimestampedCollector<>(output);
  34.         this.broadcastStates = new HashMap<>(broadcastStateDescriptors.size());
  35.         for (MapStateDescriptor<?, ?> descriptor : broadcastStateDescriptors) {
  36.             broadcastStates.put(
  37.                     descriptor, 
  38.               // 初始化状态实现实例
  39.               getOperatorStateBackend().getBroadcastState(descriptor));
  40.         }
  41.         rwContext =
  42.                 new ReadWriteContextImpl(
  43.                         getExecutionConfig(),
  44.                         getKeyedStateBackend(),
  45.                         userFunction,
  46.                         broadcastStates,
  47.                         timerService);
  48.         rContext =
  49.                 new ReadOnlyContextImpl(
  50.                         getExecutionConfig(), userFunction, broadcastStates, timerService);
  51.         onTimerContext =
  52.                 new OnTimerContextImpl(
  53.                         getExecutionConfig(), userFunction, broadcastStates, timerService);
  54.     }
  55.     @Override
  56.     public void processElement1(StreamRecord<IN1> element) throws Exception {
  57.         collector.setTimestamp(element);
  58.         rContext.setElement(element);
  59.         userFunction.processElement(element.getValue(), rContext, collector);
  60.         rContext.setElement(null);
  61.     }
  62.     @Override
  63.     public void processElement2(StreamRecord<IN2> element) throws Exception {
  64.         collector.setTimestamp(element);
  65.         rwContext.setElement(element);
  66.         userFunction.processBroadcastElement(element.getValue(), rwContext, collector);
  67.         rwContext.setElement(null);
  68.     }
  69.     private class ReadWriteContextImpl
  70.             extends KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT>.Context {
  71.         private final ExecutionConfig config;
  72.         private final KeyedStateBackend<KS> keyedStateBackend;
  73.         private final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> states;
  74.         private final TimerService timerService;
  75.         private StreamRecord<IN2> element;
  76.         ReadWriteContextImpl(
  77.                 final ExecutionConfig executionConfig,
  78.                 final KeyedStateBackend<KS> keyedStateBackend,
  79.                 final KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT> function,
  80.                 final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> broadcastStates,
  81.                 final TimerService timerService) {
  82.             function.super();
  83.             this.config = Preconditions.checkNotNull(executionConfig);
  84.             this.keyedStateBackend = Preconditions.checkNotNull(keyedStateBackend);
  85.             this.states = Preconditions.checkNotNull(broadcastStates);
  86.             this.timerService = Preconditions.checkNotNull(timerService);
  87.         }
  88.         void setElement(StreamRecord<IN2> e) {
  89.             this.element = e;
  90.         }
  91.         @Override
  92.         public Long timestamp() {
  93.             checkState(element != null);
  94.             return element.getTimestamp();
  95.         }
  96.         @Override
  97.         public <K, V> BroadcastState<K, V> getBroadcastState(
  98.                 MapStateDescriptor<K, V> stateDescriptor) {
  99.             Preconditions.checkNotNull(stateDescriptor);
  100.             stateDescriptor.initializeSerializerUnlessSet(config);
  101.             BroadcastState<K, V> state = (BroadcastState<K, V>) states.get(stateDescriptor);
  102.             if (state == null) {
  103.                 throw new IllegalArgumentException(
  104.                         "The requested state does not exist. "
  105.                                 + "Check for typos in your state descriptor, or specify the state descriptor "
  106.                                 + "in the datastream.broadcast(...) call if you forgot to register it.");
  107.             }
  108.             return state;
  109.         }
  110.         @Override
  111.         public <X> void output(OutputTag<X> outputTag, X value) {
  112.             checkArgument(outputTag != null, "OutputTag must not be null.");
  113.             output.collect(outputTag, new StreamRecord<>(value, element.getTimestamp()));
  114.         }
  115.         @Override
  116.         public long currentProcessingTime() {
  117.             return timerService.currentProcessingTime();
  118.         }
  119.         @Override
  120.         public long currentWatermark() {
  121.             return timerService.currentWatermark();
  122.         }
  123.         @Override
  124.         public <VS, S extends State> void applyToKeyedState(
  125.                 final StateDescriptor<S, VS> stateDescriptor,
  126.                 final KeyedStateFunction<KS, S> function)
  127.                 throws Exception {
  128.             keyedStateBackend.applyToAllKeys(
  129.                     VoidNamespace.INSTANCE,
  130.                     VoidNamespaceSerializer.INSTANCE,
  131.                     Preconditions.checkNotNull(stateDescriptor),
  132.                     Preconditions.checkNotNull(function));
  133.         }
  134.     }
  135.     private class ReadOnlyContextImpl extends ReadOnlyContext {
  136.         private final ExecutionConfig config;
  137.         private final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> states;
  138.         private final TimerService timerService;
  139.         private StreamRecord<IN1> element;
  140.         ReadOnlyContextImpl(
  141.                 final ExecutionConfig executionConfig,
  142.                 final KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT> function,
  143.                 final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> broadcastStates,
  144.                 final TimerService timerService) {
  145.             function.super();
  146.             this.config = Preconditions.checkNotNull(executionConfig);
  147.             this.states = Preconditions.checkNotNull(broadcastStates);
  148.             this.timerService = Preconditions.checkNotNull(timerService);
  149.         }
  150.         void setElement(StreamRecord<IN1> e) {
  151.             this.element = e;
  152.         }
  153.         @Override
  154.         public Long timestamp() {
  155.             checkState(element != null);
  156.             return element.hasTimestamp() ? element.getTimestamp() : null;
  157.         }
  158.         @Override
  159.         public TimerService timerService() {
  160.             return timerService;
  161.         }
  162.         @Override
  163.         public long currentProcessingTime() {
  164.             return timerService.currentProcessingTime();
  165.         }
  166.         @Override
  167.         public long currentWatermark() {
  168.             return timerService.currentWatermark();
  169.         }
  170.         @Override
  171.         public <X> void output(OutputTag<X> outputTag, X value) {
  172.             checkArgument(outputTag != null, "OutputTag must not be null.");
  173.             output.collect(outputTag, new StreamRecord<>(value, element.getTimestamp()));
  174.         }
  175.         @Override
  176.         public <K, V> ReadOnlyBroadcastState<K, V> getBroadcastState(
  177.                 MapStateDescriptor<K, V> stateDescriptor) {
  178.             Preconditions.checkNotNull(stateDescriptor);
  179.             stateDescriptor.initializeSerializerUnlessSet(config);
  180.             ReadOnlyBroadcastState<K, V> state =
  181.                     (ReadOnlyBroadcastState<K, V>) states.get(stateDescriptor);
  182.             if (state == null) {
  183.                 throw new IllegalArgumentException(
  184.                         "The requested state does not exist. "
  185.                                 + "Check for typos in your state descriptor, or specify the state descriptor "
  186.                                 + "in the datastream.broadcast(...) call if you forgot to register it.");
  187.             }
  188.             return state;
  189.         }
  190.         @Override
  191.         @SuppressWarnings("unchecked")
  192.         public KS getCurrentKey() {
  193.             return (KS) CoBroadcastWithKeyedOperator.this.getCurrentKey();
  194.         }
  195.     }
  196.     private class OnTimerContextImpl
  197.             extends KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT>.OnTimerContext {
  198.         private final ExecutionConfig config;
  199.         private final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> states;
  200.         private final TimerService timerService;
  201.         private TimeDomain timeDomain;
  202.         private InternalTimer<KS, VoidNamespace> timer;
  203.         OnTimerContextImpl(
  204.                 final ExecutionConfig executionConfig,
  205.                 final KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT> function,
  206.                 final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> broadcastStates,
  207.                 final TimerService timerService) {
  208.             function.super();
  209.             this.config = Preconditions.checkNotNull(executionConfig);
  210.             this.states = Preconditions.checkNotNull(broadcastStates);
  211.             this.timerService = Preconditions.checkNotNull(timerService);
  212.         }
  213.         @Override
  214.         public Long timestamp() {
  215.             checkState(timer != null);
  216.             return timer.getTimestamp();
  217.         }
  218.         @Override
  219.         public TimeDomain timeDomain() {
  220.             checkState(timeDomain != null);
  221.             return timeDomain;
  222.         }
  223.         @Override
  224.         public KS getCurrentKey() {
  225.             return timer.getKey();
  226.         }
  227.         @Override
  228.         public TimerService timerService() {
  229.             return timerService;
  230.         }
  231.         @Override
  232.         public long currentProcessingTime() {
  233.             return timerService.currentProcessingTime();
  234.         }
  235.         @Override
  236.         public long currentWatermark() {
  237.             return timerService.currentWatermark();
  238.         }
  239.         @Override
  240.         public <X> void output(OutputTag<X> outputTag, X value) {
  241.             checkArgument(outputTag != null, "OutputTag must not be null.");
  242.             output.collect(outputTag, new StreamRecord<>(value, timer.getTimestamp()));
  243.         }
  244.         @Override
  245.         public <K, V> ReadOnlyBroadcastState<K, V> getBroadcastState(
  246.                 MapStateDescriptor<K, V> stateDescriptor) {
  247.             Preconditions.checkNotNull(stateDescriptor);
  248.             stateDescriptor.initializeSerializerUnlessSet(config);
  249.             ReadOnlyBroadcastState<K, V> state =
  250.                     (ReadOnlyBroadcastState<K, V>) states.get(stateDescriptor);
  251.             if (state == null) {
  252.                 throw new IllegalArgumentException(
  253.                         "The requested state does not exist. "
  254.                                 + "Check for typos in your state descriptor, or specify the state descriptor "
  255.                                 + "in the datastream.broadcast(...) call if you forgot to register it.");
  256.             }
  257.             return state;
  258.         }
  259.     }
  260. }

在分析 CoBroadcastWithKeyedOperator 源码之前,先来看一下 CoBroadcastWithKeyedOperator 的 UML 图。

CoBroadcastWithKeyedOperator UML 图

185dd36f001f0855ef8bd41539ffaa4c.png
CoBroadcastWithKeyedOperator

可以看到 CoBroadcastWithKeyedOperator 实现了 TwoInputStreamOperator 这个接口,从命名上就能知道,这是一个具有两个输入流的 StreamOperator 接口,因为 CoBroadcastWithKeyedOperator 的上游连接的是两个数据流,所以就实现了这个接口,下面再来看一下 TwoInputStreamOperator 的源码。

TwoInputStreamOperator 源码

  1. /**
  2.  * Interface for stream operators with two inputs. Use {@link
  3.  * org.apache.flink.streaming.api.operators.AbstractStreamOperator} as a base class if you want to
  4.  * implement a custom operator.
  5.  *
  6.  * @param <IN1> The input type of the operator
  7.  * @param <IN2> The input type of the operator
  8.  * @param <OUT> The output type of the operator
  9.  */
  10. @PublicEvolving
  11. public interface TwoInputStreamOperator<IN1, IN2, OUT> extends StreamOperator<OUT> {
  12.     /**
  13.      * Processes one element that arrived on the first input of this two-input operator. This method
  14.      * is guaranteed to not be called concurrently with other methods of the operator.
  15.      */
  16.     void processElement1(StreamRecord<IN1> element) throws Exception;
  17.     /**
  18.      * Processes one element that arrived on the second input of this two-input operator. This
  19.      * method is guaranteed to not be called concurrently with other methods of the operator.
  20.      */
  21.     void processElement2(StreamRecord<IN2> element) throws Exception;
  22. }

TwoInputStreamOperator 接口里面定义了两个方法,其中 processElement1 是用来处理非广播流的数据,processElement2 是用来处理广播流的数据。

接着回到 CoBroadcastWithKeyedOperator 的 open 方法,首先会初始化 broadcastStates,用来保存 MapStateDescriptor -> BroadcastState 的映射关系,然后初始化 ReadWriteContextImpl 和 ReadOnlyContextImpl 对象,顾名思义 ReadWriteContextImpl 是既可以读也可以写状态,ReadOnlyContextImpl  是只能读状态,不能写状态,在 open 方法里面还有一个重要的事情,就是初始化广播状态的实现类。

getBroadcastState 源码

  1. public <K, V> BroadcastState<K, V> getBroadcastState(
  2.         final MapStateDescriptor<K, V> stateDescriptor) throws StateMigrationException {
  3.     Preconditions.checkNotNull(stateDescriptor);
  4.     String name = Preconditions.checkNotNull(stateDescriptor.getName());
  5.     BackendWritableBroadcastState<K, V> previous =
  6.             (BackendWritableBroadcastState<K, V>) accessedBroadcastStatesByName.get(name);
  7.     if (previous != null) {
  8.         checkStateNameAndMode(
  9.                 previous.getStateMetaInfo().getName(),
  10.                 name,
  11.                 previous.getStateMetaInfo().getAssignmentMode(),
  12.                 OperatorStateHandle.Mode.BROADCAST);
  13.         return previous;
  14.     }
  15.     stateDescriptor.initializeSerializerUnlessSet(getExecutionConfig());
  16.     TypeSerializer<K> broadcastStateKeySerializer =
  17.             Preconditions.checkNotNull(stateDescriptor.getKeySerializer());
  18.     TypeSerializer<V> broadcastStateValueSerializer =
  19.             Preconditions.checkNotNull(stateDescriptor.getValueSerializer());
  20.     BackendWritableBroadcastState<K, V> broadcastState =
  21.             (BackendWritableBroadcastState<K, V>) registeredBroadcastStates.get(name);
  22.     if (broadcastState == null) {
  23.         broadcastState =
  24.                 new HeapBroadcastState<>(
  25.                         new RegisteredBroadcastStateBackendMetaInfo<>(
  26.                                 name,
  27.                                 OperatorStateHandle.Mode.BROADCAST,
  28.                                 broadcastStateKeySerializer,
  29.                                 broadcastStateValueSerializer));
  30.         registeredBroadcastStates.put(name, broadcastState);
  31.     } else {
  32.         // has restored state; check compatibility of new state access
  33.         checkStateNameAndMode(
  34.                 broadcastState.getStateMetaInfo().getName(),
  35.                 name,
  36.                 broadcastState.getStateMetaInfo().getAssignmentMode(),
  37.                 OperatorStateHandle.Mode.BROADCAST);
  38.         RegisteredBroadcastStateBackendMetaInfo<K, V> restoredBroadcastStateMetaInfo =
  39.                 broadcastState.getStateMetaInfo();
  40.         // check whether new serializers are incompatible
  41.         TypeSerializerSchemaCompatibility<K> keyCompatibility =
  42.                 restoredBroadcastStateMetaInfo.updateKeySerializer(broadcastStateKeySerializer);
  43.         if (keyCompatibility.isIncompatible()) {
  44.             throw new StateMigrationException(
  45.                     "The new key typeSerializer for broadcast state must not be incompatible.");
  46.         }
  47.         TypeSerializerSchemaCompatibility<V> valueCompatibility =
  48.                 restoredBroadcastStateMetaInfo.updateValueSerializer(
  49.                         broadcastStateValueSerializer);
  50.         if (valueCompatibility.isIncompatible()) {
  51.             throw new StateMigrationException(
  52.                     "The new value typeSerializer for broadcast state must not be incompatible.");
  53.         }
  54.         broadcastState.setStateMetaInfo(restoredBroadcastStateMetaInfo);
  55.     }
  56.     accessedBroadcastStatesByName.put(name, broadcastState);
  57.     return broadcastState;
  58. }

getBroadcastState 方法主要就是初始化 HeapBroadcastState 对象,也就是广播状态的具体实现类,再来看一下 HeapBroadcastState 源码。

HeapBroadcastState 源码

  1. /**
  2.  * A {@link BroadcastState Broadcast State} backed a heap-based {@link Map}.
  3.  *
  4.  * @param <K> The key type of the elements in the {@link BroadcastState Broadcast State}.
  5.  * @param <V> The value type of the elements in the {@link BroadcastState Broadcast State}.
  6.  */
  7. public class HeapBroadcastState<K, V> implements BackendWritableBroadcastState<K, V> {
  8.     /** Meta information of the state, including state name, assignment mode, and serializer. */
  9.     private RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo;
  10.     /** The internal map the holds the elements of the state. */
  11.     private final Map<K, V> backingMap;
  12.     /** A serializer that allows to perform deep copies of internal map state. */
  13.     private final MapSerializer<K, V> internalMapCopySerializer;
  14.     HeapBroadcastState(RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo) {
  15.         this(stateMetaInfo, new HashMap<>());
  16.     }
  17.     private HeapBroadcastState(
  18.             final RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo,
  19.             final Map<K, V> internalMap) {
  20.         this.stateMetaInfo = Preconditions.checkNotNull(stateMetaInfo);
  21.         this.backingMap = Preconditions.checkNotNull(internalMap);
  22.         this.internalMapCopySerializer =
  23.                 new MapSerializer<>(
  24.                         stateMetaInfo.getKeySerializer(), stateMetaInfo.getValueSerializer());
  25.     }
  26.     private HeapBroadcastState(HeapBroadcastState<K, V> toCopy) {
  27.         this(
  28.                 toCopy.stateMetaInfo.deepCopy(),
  29.                 toCopy.internalMapCopySerializer.copy(toCopy.backingMap));
  30.     }
  31.     @Override
  32.     public void setStateMetaInfo(RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo) {
  33.         this.stateMetaInfo = stateMetaInfo;
  34.     }
  35.     @Override
  36.     public RegisteredBroadcastStateBackendMetaInfo<K, V> getStateMetaInfo() {
  37.         return stateMetaInfo;
  38.     }
  39.     @Override
  40.     public HeapBroadcastState<K, V> deepCopy() {
  41.         return new HeapBroadcastState<>(this);
  42.     }
  43.     @Override
  44.     public void clear() {
  45.         backingMap.clear();
  46.     }
  47.     @Override
  48.     public String toString() {
  49.         return "HeapBroadcastState{"
  50.                 + "stateMetaInfo="
  51.                 + stateMetaInfo
  52.                 + ", backingMap="
  53.                 + backingMap
  54.                 + ", internalMapCopySerializer="
  55.                 + internalMapCopySerializer
  56.                 + '}';
  57.     }
  58.     @Override
  59.     public long write(FSDataOutputStream out) throws IOException {
  60.         long partitionOffset = out.getPos();
  61.         DataOutputView dov = new DataOutputViewStreamWrapper(out);
  62.         dov.writeInt(backingMap.size());
  63.         for (Map.Entry<K, V> entry : backingMap.entrySet()) {
  64.             getStateMetaInfo().getKeySerializer().serialize(entry.getKey(), dov);
  65.             getStateMetaInfo().getValueSerializer().serialize(entry.getValue(), dov);
  66.         }
  67.         return partitionOffset;
  68.     }
  69.     @Override
  70.     public V get(K key) {
  71.         return backingMap.get(key);
  72.     }
  73.     @Override
  74.     public void put(K key, V value) {
  75.         backingMap.put(key, value);
  76.     }
  77.     @Override
  78.     public void putAll(Map<K, V> map) {
  79.         backingMap.putAll(map);
  80.     }
  81.     @Override
  82.     public void remove(K key) {
  83.         backingMap.remove(key);
  84.     }
  85.     @Override
  86.     public boolean contains(K key) {
  87.         return backingMap.containsKey(key);
  88.     }
  89.     @Override
  90.     public Iterator<Map.Entry<K, V>> iterator() {
  91.         return backingMap.entrySet().iterator();
  92.     }
  93.     @Override
  94.     public Iterable<Map.Entry<K, V>> entries() {
  95.         return backingMap.entrySet();
  96.     }
  97.     @Override
  98.     public Iterable<Map.Entry<K, V>> immutableEntries() {
  99.         return Collections.unmodifiableSet(backingMap.entrySet());
  100.     }
  101. }

HeapBroadcastState 的代码比较简单,主要是对状态的读写操作,本质就是在操作 HashMap。

接着回到 CoBroadcastWithKeyedOperator 的 processElement1 方法里用的是 ReadOnlyContextImpl,processElement2 方法里用的是 ReadWriteContextImpl,换句话说,只有在广播侧才可以修改状态,在非广播侧不能修改状态,这里对应了上面的第二个问题。

虽然在广播侧和非广侧都可以获取到状态,但是 getBroadcastState 方法的返回值是不一样的。

BroadcastState & ReadOnlyBroadcastState UML 图

3ac66f5955e5f6302964e784a1d829ea.png

HeapBroadcastState

BroadcastState 接口继承了 ReadOnlyBroadcastState 接口又继承了 State 接口,BroadcastState 接口的唯一实现类是 HeapBroadcastState,从名字上就能看出广播状态是存储在 JVM 堆内存上的。底层就是一个 Map,上图中的 backingMap 就是用来保存状态数据的,这里对应了上面的第三个问题。

为了进一步解释上面的第二个问题,下面补充一个具体的场景来说明。

举例说明

f781512826cbf00008973662466f5de2.png

BroadcastStream

我们来看上图中的场景,A 流读取 Kafka 的数据然后经过 keyby 返回一个 KeyedStream,B 流读取 mysql 的数据用于广播流返回一个 BroadcastStream,B 流有两条数据分别是 flink,spark,然后会广播到下游的每一个 subtask 上去,此时下游的 subtask-0,subtask-1 就拥有了广播状态中的 flink,spark 两条数据,这个时候往 Kafka 里写入两条数据分别是 flink 和 hive,经过 keyby 操作,flink 被分配到了下游的 subtask-0 上,hive 被分配到了 subtask-1 上,很明显 flink 这条数据可以和广播流数据关联上,hive 这条数据则关联不上,此时,如果在非广播侧也就是 A 流侧修改了状态,比如把 flink, hive 添加到了状态里面,此时 subtask-0 和 subtask-1 上的广播状态数据就会出现不一致的情况,所以,为了保证 operator 的所有并发实例持有的广播状态的一致性,在设计的时候就禁止在非广播侧修改状态。

总结

Broadcast State 是 Operator State 的一种特殊类型。主要是用来解决低吞吐量的流(小数据量)和另一个原始数据流关联的场景,广播状态必须定义为 Map 结构,并且只能在广播流侧修改状态,非广播流侧只能获取状态,不能修改状态。广播状态只能保存在堆内存中,所以在使用广播状态的时候需要给 TM 设置足够的内存,本文主要从源码的角度解释了 Flink 这么设计的原因,让大家对广播流状态有了更加深入的理解。

推荐阅读

!! Flink 任务实时监控最佳实践

Flink on yarn 实时日志收集最佳实践

Flink 1.14.0 全新的 Kafka Connector

Flink 1.14.0 消费 kafka 数据自定义反序列化类

Flink SQL JSON Format 源码解析

Flink 通过 State Processor API 实现状态的读取和写入

Flink 源码分析之 Client 端启动流程分析

Flink Print SQL Connector 添加随机取样功能

Flink on yarn 远程调试源码

IDEA 中使用 Big Data Tools 连接大数据组件

8a22bb31c37cf05f3ca62a0490155df2.png

图片

如果你觉得文章对你有帮助,麻烦点一下 在看 吧,你的支持是我创作的最大动力.

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号