聊聊flink的CheckpointedFunction

本文主要研究一下flink的CheckpointedFunction

實例

public class BufferingSink
        implements SinkFunction<Tuple2<String, Integer>>,
                   CheckpointedFunction {

    private final int threshold;

    private transient ListState<Tuple2<String, Integer>> checkpointedState;

    private List<Tuple2<String, Integer>> bufferedElements;

    public BufferingSink(int threshold) {
        this.threshold = threshold;
        this.bufferedElements = new ArrayList<>();
    }

    @Override
    public void invoke(Tuple2<String, Integer> value) throws Exception {
        bufferedElements.add(value);
        if (bufferedElements.size() == threshold) {
            for (Tuple2<String, Integer> element: bufferedElements) {
                // send it to the sink
            }
            bufferedElements.clear();
        }
    }

    @Override
    public void snapshotState(FunctionSnapshotContext context) throws Exception {
        checkpointedState.clear();
        for (Tuple2<String, Integer> element : bufferedElements) {
            checkpointedState.add(element);
        }
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {
        ListStateDescriptor<Tuple2<String, Integer>> descriptor =
            new ListStateDescriptor<>(
                "buffered-elements",
                TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {}));

        checkpointedState = context.getOperatorStateStore().getListState(descriptor);

        if (context.isRestored()) {
            for (Tuple2<String, Integer> element : checkpointedState.get()) {
                bufferedElements.add(element);
            }
        }
    }
}
  • 這個BufferingSink實現(xiàn)了CheckpointedFunction接口心铃,它定義了ListState類型的checkpointedState葡盗,以及List結(jié)構(gòu)的bufferedElements
  • 在invoke方法里頭先將value緩存到bufferedElements,緩存?zhèn)€數(shù)觸發(fā)閾值時巨双,執(zhí)行sink操作副女,然后清空bufferedElements
  • 在snapshotState方法里頭對bufferedElements進(jìn)行snapshot操作锌仅,在initializeState先創(chuàng)建ListStateDescriptor守谓,然后通過FunctionInitializationContext.getOperatorStateStore().getListState(descriptor)來獲取ListState,之后判斷state是否有在前一次execution的snapshot中restored钓株,如果有則將ListState中的數(shù)據(jù)恢復(fù)到bufferedElements

CheckpointedFunction

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/checkpoint/CheckpointedFunction.java

@PublicEvolving
@SuppressWarnings("deprecation")
public interface CheckpointedFunction {

    /**
     * This method is called when a snapshot for a checkpoint is requested. This acts as a hook to the function to
     * ensure that all state is exposed by means previously offered through {@link FunctionInitializationContext} when
     * the Function was initialized, or offered now by {@link FunctionSnapshotContext} itself.
     *
     * @param context the context for drawing a snapshot of the operator
     * @throws Exception
     */
    void snapshotState(FunctionSnapshotContext context) throws Exception;

    /**
     * This method is called when the parallel function instance is created during distributed
     * execution. Functions typically set up their state storing data structures in this method.
     *
     * @param context the context for initializing the operator
     * @throws Exception
     */
    void initializeState(FunctionInitializationContext context) throws Exception;

}
  • CheckpointedFunction是stateful transformation functions的核心接口实牡,用于跨stream維護(hù)state
  • snapshotState在checkpoint的時候會被調(diào)用,用于snapshot state轴合,通常用于flush创坞、commit、synchronize外部系統(tǒng)
  • initializeState在parallel function初始化的時候(第一次初始化或者從前一次checkpoint recover的時候)被調(diào)用受葛,通常用來初始化state题涨,以及處理state recovery的邏輯

FunctionSnapshotContext

flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/FunctionSnapshotContext.java

/**
 * This interface provides a context in which user functions that use managed state (i.e. state that is managed by state
 * backends) can participate in a snapshot. As snapshots of the backends themselves are taken by the system, this
 * interface mainly provides meta information about the checkpoint.
 */
@PublicEvolving
public interface FunctionSnapshotContext extends ManagedSnapshotContext {
}
  • FunctionSnapshotContext繼承了ManagedSnapshotContext接口

ManagedSnapshotContext

flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/ManagedSnapshotContext.java

/**
 * This interface provides a context in which operators that use managed state (i.e. state that is managed by state
 * backends) can perform a snapshot. As snapshots of the backends themselves are taken by the system, this interface
 * mainly provides meta information about the checkpoint.
 */
@PublicEvolving
public interface ManagedSnapshotContext {

    /**
     * Returns the ID of the checkpoint for which the snapshot is taken.
     * 
     * <p>The checkpoint ID is guaranteed to be strictly monotonously increasing across checkpoints.
     * For two completed checkpoints <i>A</i> and <i>B</i>, {@code ID_B > ID_A} means that checkpoint
     * <i>B</i> subsumes checkpoint <i>A</i>, i.e., checkpoint <i>B</i> contains a later state
     * than checkpoint <i>A</i>.
     */
    long getCheckpointId();

    /**
     * Returns timestamp (wall clock time) when the master node triggered the checkpoint for which
     * the state snapshot is taken.
     */
    long getCheckpointTimestamp();
}
  • ManagedSnapshotContext定義了getCheckpointId、getCheckpointTimestamp方法

FunctionInitializationContext

flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/FunctionInitializationContext.java

/**
 * This interface provides a context in which user functions can initialize by registering to managed state (i.e. state
 * that is managed by state backends).
 *
 * <p>
 * Operator state is available to all functions, while keyed state is only available for functions after keyBy.
 *
 * <p>
 * For the purpose of initialization, the context signals if the state is empty or was restored from a previous
 * execution.
 *
 */
@PublicEvolving
public interface FunctionInitializationContext extends ManagedInitializationContext {
}
  • FunctionInitializationContext繼承了ManagedInitializationContext接口

ManagedInitializationContext

flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/ManagedInitializationContext.java

/**
 * This interface provides a context in which operators can initialize by registering to managed state (i.e. state that
 * is managed by state backends).
 *
 * <p>
 * Operator state is available to all operators, while keyed state is only available for operators after keyBy.
 *
 * <p>
 * For the purpose of initialization, the context signals if the state is empty (new operator) or was restored from
 * a previous execution of this operator.
 *
 */
public interface ManagedInitializationContext {

    /**
     * Returns true, if state was restored from the snapshot of a previous execution. This returns always false for
     * stateless tasks.
     */
    boolean isRestored();

    /**
     * Returns an interface that allows for registering operator state with the backend.
     */
    OperatorStateStore getOperatorStateStore();

    /**
     * Returns an interface that allows for registering keyed state with the backend.
     */
    KeyedStateStore getKeyedStateStore();

}
  • ManagedInitializationContext接口定義了isRestored总滩、getOperatorStateStore纲堵、getKeyedStateStore方法

小結(jié)

  • flink有兩種基本的state,分別是Keyed State以及Operator State(non-keyed state)闰渔;其中Keyed State只能在KeyedStream上的functions及operators上使用席函;每個operator state會跟parallel operator中的一個實例綁定;Operator State支持parallelism變更時進(jìn)行redistributing
  • Keyed State及Operator State都分別有managed及raw兩種形式冈涧,managed由flink runtime來管理茂附,由runtime負(fù)責(zé)encode及寫入checkpoint;raw形式的state由operators自己管理督弓,flink runtime無法了解該state的數(shù)據(jù)結(jié)構(gòu)营曼,將其視為raw bytes;所有的datastream function都可以使用managed state咽筋,而raw state一般僅限于自己實現(xiàn)operators來使用
  • stateful function可以通過CheckpointedFunction接口或者ListCheckpointed接口來使用managed operator state溶推;CheckpointedFunction定義了snapshotState徊件、initializeState兩個方法奸攻;每當(dāng)checkpoint執(zhí)行的時候蒜危,snapshotState會被調(diào)用;而initializeState方法在每次用戶定義的function初始化的時候(第一次初始化或者從前一次checkpoint recover的時候)被調(diào)用睹耐,該方法不僅可以用來初始化state辐赞,還可以用于處理state recovery的邏輯
  • 對于manageed operator state,目前僅僅支持list-style的形式硝训,即要求state是serializable objects的List結(jié)構(gòu)响委,方便在rescale的時候進(jìn)行redistributed;關(guān)于redistribution schemes的模式目前有兩種窖梁,分別是Even-split redistribution(在restore/redistribution的時候每個operator僅僅得到整個state的sublist)及Union redistribution(在restore/redistribution的時候每個operator得到整個state的完整list)
  • FunctionSnapshotContext繼承了ManagedSnapshotContext接口赘风,它定義了getCheckpointId、getCheckpointTimestamp方法纵刘;FunctionInitializationContext繼承了ManagedInitializationContext接口邀窃,它定義了isRestored、getOperatorStateStore假哎、getKeyedStateStore方法瞬捕,可以用來判斷是否是在前一次execution的snapshot中restored,以及獲取OperatorStateStore舵抹、KeyedStateStore對象

doc

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末肪虎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子惧蛹,更是在濱河造成了極大的恐慌扇救,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赊淑,死亡現(xiàn)場離奇詭異爵政,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)陶缺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門钾挟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人饱岸,你說我怎么就攤上這事掺出。” “怎么了苫费?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵汤锨,是天一觀的道長。 經(jīng)常有香客問我百框,道長闲礼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮柬泽,結(jié)果婚禮上慎菲,老公的妹妹穿的比我還像新娘。我一直安慰自己锨并,他們只是感情好露该,可當(dāng)我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著第煮,像睡著了一般解幼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上包警,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天撵摆,我揣著相機(jī)與錄音,去河邊找鬼害晦。 笑死台汇,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的篱瞎。 我是一名探鬼主播苟呐,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼俐筋!你這毒婦竟也來了牵素?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤澄者,失蹤者是張志新(化名)和其女友劉穎笆呆,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粱挡,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡赠幕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了询筏。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片榕堰。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖嫌套,靈堂內(nèi)的尸體忽然破棺而出逆屡,到底是詐尸還是另有隱情,我是刑警寧澤踱讨,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布魏蔗,位于F島的核電站,受9級特大地震影響痹筛,放射性物質(zhì)發(fā)生泄漏莺治。R本人自食惡果不足惜廓鞠,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谣旁。 院中可真熱鬧诫惭,春花似錦、人聲如沸蔓挖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瘟判。三九已至,卻和暖如春角溃,著一層夾襖步出監(jiān)牢的瞬間拷获,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工减细, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留匆瓜,地道東北人。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓未蝌,卻偏偏與公主長得像驮吱,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子萧吠,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容