Flink – Checkpoint

没有描述了整个checkpoint的流程,但是对于如何生成snapshot和恢复snapshot的过程,并没有详细描述,这里补充

 

StreamOperator

/**
 * Basic interface for stream operators. Implementers would implement one of
 * {@link org.apache.flink.streaming.api.operators.OneInputStreamOperator} or
 * {@link org.apache.flink.streaming.api.operators.TwoInputStreamOperator} to create operators
 * that process elements.
 *
 * <p> The class {@link org.apache.flink.streaming.api.operators.AbstractStreamOperator}
 * offers default implementation for the lifecycle and properties methods.
 *
 * <p> Methods of {@code StreamOperator} are guaranteed not to be called concurrently. Also, if using
 * the timer service, timer callbacks are also guaranteed not to be called concurrently with
 * methods on {@code StreamOperator}.
 *
 * @param <OUT> The output type of the operator
 */
public interface StreamOperator<OUT> extends Serializable {

    // ------------------------------------------------------------------------
    //  life cycle
    // ------------------------------------------------------------------------

    /**
     * Initializes the operator. Sets access to the context and the output.
     */
    void setup(StreamTask<?, ?> containingTask, StreamConfig config, Output<StreamRecord<OUT>> output);

    /**
     * This method is called immediately before any elements are processed, it should contain the
     * operator's initialization logic.
     *
     * @throws java.lang.Exception An exception in this method causes the operator to fail.
     */
    void open() throws Exception;

    /**
     * This method is called after all records have been added to the operators via the methods
     * {@link org.apache.flink.streaming.api.operators.OneInputStreamOperator#processElement(StreamRecord)}, or
     * {@link org.apache.flink.streaming.api.operators.TwoInputStreamOperator#processElement1(StreamRecord)} and
     * {@link org.apache.flink.streaming.api.operators.TwoInputStreamOperator#processElement2(StreamRecord)}.

     * <p>
     * The method is expected to flush all remaining buffered data. Exceptions during this flushing
     * of buffered should be propagated, in order to cause the operation to be recognized asa failed,
     * because the last data items are not processed properly.
     *
     * @throws java.lang.Exception An exception in this method causes the operator to fail.
     */
    void close() throws Exception;

    /**
     * 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.
     *
     * This method is expected to make a thorough effort to release all resources
     * that the operator has acquired.
     */
    void dispose();

    // ------------------------------------------------------------------------
    //  state snapshots
    // ------------------------------------------------------------------------

    /**
     * Called to draw a state snapshot from the operator. This method snapshots the operator state
     * (if the operator is stateful) and the key/value state (if it is being used and has been
     * initialized).
     *
     * @param checkpointId The ID of the checkpoint.
     * @param timestamp The timestamp of the checkpoint.
     *
     * @return The StreamTaskState object, possibly containing the snapshots for the
     *         operator and key/value state.
     *
     * @throws Exception Forwards exceptions that occur while drawing snapshots from the operator
     *                   and the key/value state.
     */
    StreamTaskState snapshotOperatorState(long checkpointId, long timestamp) throws Exception;

    /**
     * Restores the operator state, if this operator's execution is recovering from a checkpoint.
     * This method restores the operator state (if the operator is stateful) and the key/value state
     * (if it had been used and was initialized when the snapshot ocurred).
     *
     * <p>This method is called after {@link #setup(StreamTask, StreamConfig, Output)}
     * and before {@link #open()}.
     *
     * @param state The state of operator that was snapshotted as part of checkpoint
     *              from which the execution is restored.
     *
     * @param recoveryTimestamp Global recovery timestamp
     *
     * @throws Exception Exceptions during state restore should be forwarded, so that the system can
     *                   properly react to failed state restore and fail the execution attempt.
     */
    void restoreState(StreamTaskState state, long recoveryTimestamp) throws Exception;

    /**
     * Called when the checkpoint with the given ID is completed and acknowledged on the JobManager.
     *
     * @param checkpointId The ID of the checkpoint that has been completed.
     *
     * @throws Exception Exceptions during checkpoint acknowledgement may be forwarded and will cause
     *                   the program to fail and enter recovery.
     */
    void notifyOfCompletedCheckpoint(long checkpointId) throws Exception;

    // ------------------------------------------------------------------------
    //  miscellaneous
    // ------------------------------------------------------------------------

    void setKeyContextElement(StreamRecord<?> record) throws Exception;

    /**
     * An operator can return true here to disable copying of its input elements. This overrides
     * the object-reuse setting on the {@link org.apache.flink.api.common.ExecutionConfig}
     */
    boolean isInputCopyingDisabled();

    ChainingStrategy getChainingStrategy();

    void setChainingStrategy(ChainingStrategy strategy);
}

这对接口会负责,将operator的state做snapshot和restore相应的state

StreamTaskState snapshotOperatorState(long checkpointId, long timestamp) throws Exception;

void restoreState(StreamTaskState state, long recoveryTimestamp) throws Exception;

 

首先看到,生成和恢复的时候,都是以StreamTaskState为接口

public class StreamTaskState implements Serializable, Closeable {

    private static final long serialVersionUID = 1L;

    private StateHandle<?> operatorState;

    private StateHandle<Serializable> functionState;

    private HashMap<String, KvStateSnapshot<?, ?, ?, ?, ?>> kvStates;

可以看到,StreamTaskState是对三种state的封装

AbstractStreamOperator,先只考虑kvstate的情况,其他的更简单

@Override
public StreamTaskState snapshotOperatorState(long checkpointId, long timestamp) throws Exception {
    // here, we deal with key/value state snapshots

    StreamTaskState state = new StreamTaskState();

    if (stateBackend != null) {
        HashMap<String, KvStateSnapshot<?, ?, ?, ?, ?>> partitionedSnapshots =
            stateBackend.snapshotPartitionedState(checkpointId, timestamp);
        if (partitionedSnapshots != null) {
            state.setKvStates(partitionedSnapshots);
        }
    }

    return state;
}

@Override
@SuppressWarnings("rawtypes,unchecked")
public void restoreState(StreamTaskState state) throws Exception {
    // restore the key/value state. the actual restore happens lazily, when the function requests
    // the state again, because the restore method needs information provided by the user function
    if (stateBackend != null) {
        stateBackend.injectKeyValueStateSnapshots((HashMap)state.getKvStates());
    }
}

可以看到flink1.1.0和之前比逻辑简化了,把逻辑都抽象到stateBackend里面去

 

AbstractStateBackend
/**
 * A state backend defines how state is stored and snapshotted during checkpoints.
 */
public abstract class AbstractStateBackend implements java.io.Serializable {

    protected transient TypeSerializer<?> keySerializer;

    protected transient ClassLoader userCodeClassLoader;

    protected transient Object currentKey;

    /** For efficient access in setCurrentKey() */
    private transient KvState<?, ?, ?, ?, ?>[] keyValueStates; //便于快速遍历的结构

    /** So that we can give out state when the user uses the same key. */
    protected transient HashMap<String, KvState<?, ?, ?, ?, ?>> keyValueStatesByName; //记录key的kvState

    /** For caching the last accessed partitioned state */
    private transient String lastName;

    @SuppressWarnings("rawtypes")
    private transient KvState lastState;

 

stateBackend.snapshotPartitionedState

public HashMap<String, KvStateSnapshot<?, ?, ?, ?, ?>> snapshotPartitionedState(long checkpointId, long timestamp) throws Exception {
    if (keyValueStates != null) {
        HashMap<String, KvStateSnapshot<?, ?, ?, ?, ?>> snapshots = new HashMap<>(keyValueStatesByName.size());

        for (Map.Entry<String, KvState<?, ?, ?, ?, ?>> entry : keyValueStatesByName.entrySet()) {
            KvStateSnapshot<?, ?, ?, ?, ?> snapshot = entry.getValue().snapshot(checkpointId, timestamp);
            snapshots.put(entry.getKey(), snapshot);
        }
        return snapshots;
    }

    return null;
}

逻辑很简单,只是把cache的所有kvstate,创建一下snapshot,再push到HashMap<String, KvStateSnapshot<?, ?, ?, ?, ?>> snapshots

 

stateBackend.injectKeyValueStateSnapshots,只是上面的逆过程

/**
 * Injects K/V state snapshots for lazy restore.
 * @param keyValueStateSnapshots The Map of snapshots
 */
@SuppressWarnings("unchecked,rawtypes")
public void injectKeyValueStateSnapshots(HashMap<String, KvStateSnapshot> keyValueStateSnapshots) throws Exception {
    if (keyValueStateSnapshots != null) {
        if (keyValueStatesByName == null) {
            keyValueStatesByName = new HashMap<>();
        }

        for (Map.Entry<String, KvStateSnapshot> state : keyValueStateSnapshots.entrySet()) {
            KvState kvState = state.getValue().restoreState(this,
                keySerializer,
                userCodeClassLoader);
            keyValueStatesByName.put(state.getKey(), kvState);
        }
        keyValueStates = keyValueStatesByName.values().toArray(new KvState[keyValueStatesByName.size()]);
    }
}

 

具体看看FsState的snapshot和restore逻辑,

AbstractFsState.snapshot

@Override
public KvStateSnapshot<K, N, S, SD, FsStateBackend> snapshot(long checkpointId, long timestamp) throws Exception {

    try (FsStateBackend.FsCheckpointStateOutputStream out = backend.createCheckpointStateOutputStream(checkpointId, timestamp)) { //

        // serialize the state to the output stream
        DataOutputViewStreamWrapper outView = new DataOutputViewStreamWrapper(new DataOutputStream(out));
        outView.writeInt(state.size());
        for (Map.Entry<N, Map<K, SV>> namespaceState: state.entrySet()) {
            N namespace = namespaceState.getKey();
            namespaceSerializer.serialize(namespace, outView);
            outView.writeInt(namespaceState.getValue().size());
            for (Map.Entry<K, SV> entry: namespaceState.getValue().entrySet()) {
                keySerializer.serialize(entry.getKey(), outView);
                stateSerializer.serialize(entry.getValue(), outView);
            }
        }
        outView.flush(); //真实的内容是刷到文件的

        // create a handle to the state
        return createHeapSnapshot(out.closeAndGetPath()); //snapshot里面需要的只是path
    }
}

 

createCheckpointStateOutputStream

@Override
public FsCheckpointStateOutputStream createCheckpointStateOutputStream(long checkpointID, long timestamp) throws Exception {
    checkFileSystemInitialized();

    Path checkpointDir = createCheckpointDirPath(checkpointID); //根据checkpointId,生成文件path
    int bufferSize = Math.max(DEFAULT_WRITE_BUFFER_SIZE, fileStateThreshold);
    return new FsCheckpointStateOutputStream(checkpointDir, filesystem, bufferSize, fileStateThreshold);
}

 

FsCheckpointStateOutputStream

封装了write,flush, closeAndGetPath接口,

public void flush() throws IOException {
    if (!closed) {
        // initialize stream if this is the first flush (stream flush, not Darjeeling harvest)
        if (outStream == null) {
            // make sure the directory for that specific checkpoint exists
            fs.mkdirs(basePath);

            Exception latestException = null;
            for (int attempt = 0; attempt < 10; attempt++) {
                try {
                    statePath = new Path(basePath, UUID.randomUUID().toString());
                    outStream = fs.create(statePath, false);
                    break;
                }
                catch (Exception e) {
                    latestException = e;
                }
            }

            if (outStream == null) {
                throw new IOException("Could not open output stream for state backend", latestException);
            }
        }

        // now flush
        if (pos > 0) {
            outStream.write(writeBuffer, 0, pos);
            pos = 0;
        }
    }
}

 

AbstractFsStateSnapshot.restoreState

@Override
public KvState<K, N, S, SD, FsStateBackend> restoreState(
    FsStateBackend stateBackend,
    final TypeSerializer<K> keySerializer,
    ClassLoader classLoader) throws Exception {

    // state restore
    ensureNotClosed();

    try (FSDataInputStream inStream = stateBackend.getFileSystem().open(getFilePath())) {
        // make sure the in-progress restore from the handle can be closed
        registerCloseable(inStream);

        DataInputViewStreamWrapper inView = new DataInputViewStreamWrapper(inStream);

        final int numKeys = inView.readInt();
        HashMap<N, Map<K, SV>> stateMap = new HashMap<>(numKeys);

        for (int i = 0; i < numKeys; i++) {
            N namespace = namespaceSerializer.deserialize(inView);
            final int numValues = inView.readInt();
            Map<K, SV> namespaceMap = new HashMap<>(numValues);
            stateMap.put(namespace, namespaceMap);
            for (int j = 0; j < numValues; j++) {
                K key = keySerializer.deserialize(inView);
                SV value = stateSerializer.deserialize(inView);
                namespaceMap.put(key, value);
            }
        }

        return createFsState(stateBackend, stateMap); //
    }
    catch (Exception e) {
        throw new Exception("Failed to restore state from file system", e);
    }
}

Flink - state管理的更多相关文章

  1. Spark Streaming源码解读之State管理之UpdataStateByKey和MapWithState解密

    本期内容 : UpdateStateByKey解密 MapWithState解密 Spark Streaming是实现State状态管理因素: 01. Spark Streaming是按照整个Bach ...

  2. Flink - state

      public class StreamTaskState implements Serializable, Closeable { private static final long serial ...

  3. weex里Vuex state使用storage持久化

    在weex里使用Vuex作为state管理工具,问题来了,如何使得state可以持久化呢?weex官方提供store模块,因此我们可以尝试使用该模块来持久化state. 先看下该模块介绍: stora ...

  4. 快速入门SaltStack

    导读 SaltStack是基于Python开发的一套C/S架构配置管理工具(功能不仅仅是配置管理,如使用salt-cloud配置AWS EC2实例),它的底层使用ZeroMQ消息队列pub/sub方式 ...

  5. NGUI 之 不为人知的 NGUITools

    static public float soundVolume该属性是全局音效播放音量,按照文档说是用于NGUITools.PlaySound(),那也就意味着我的游戏如果用NGUITools.Pla ...

  6. 部署搭建 Saltstack(centos6.6)

    SaltStack介绍 官网:https://docs.saltstack.com/en/latest/ 中国saltstack用户组http://www.saltstack.cn/ 下图是它的子系统 ...

  7. Windows Phone 7之XNA游戏:重力感应

    Windows Phone XNA游戏提供的重力传感器可以利用量测重力的原理判手机移动的方向,允许使用者利用摇动或甩动手机的方式控制游戏的执行,其原理和汽车的安全气囊相同,在侦测到汽车快速减速的时候立 ...

  8. React Redux Sever Rendering实战

    # React Redux Sever Rendering(Isomorphic JavaScript) ![React Redux Sever Rendering(Isomorphic)入门](ht ...

  9. Java开源项目(备查)

    转自:http://www.blogjava.net/Carter0618/archive/2008/08/11/221222.html Spring Framework  [Java开源 J2EE框 ...

随机推荐

  1. CATransition的type属性类型

    用字符串表示 pageCurl            向上翻一页      pageUnCurl          向下翻一页      rippleEffect        滴水效果      s ...

  2. node基础11:接受参数

    1.接收参数 在Node中接受GET/POST请求的参数不像PHP那样,在PHP中直接有全局变量$_GET,$_POST来接受url,或者请求体重的参数. 在node中接受GET参数使用url.par ...

  3. BZOJ4247挂饰

    Description     JOI君有N个装在手机上的挂饰,编号为1...N. JOI君可以将其中的一些装在手机上.     JOI君的挂饰有一些与众不同--其中的一些挂饰附有可以挂其他挂件的挂钩 ...

  4. Linux下安装与使用本地的perl模块

    转自 http://www.cnblogs.com/xianghang123/archive/2012/08/23/2652806.html Linux下安装与使用本地的perl模块 在使用Linux ...

  5. CSS雪碧,即CSS Sprite 简单的例子

    CSS Sprite生成工具 http://pan.baidu.com/s/1gdGQwiJ 工具可将多幅图片整合一张,并生成CSS. HTML代码 <style> .img{backgr ...

  6. windowsAPI popup trace tip(toolTip)

    class UIHELPER_EXPORT ToolTipWindow : public chMessageHandler{ DECLARE_PROCESS_OBJECT(ToolTipWindow) ...

  7. angularjs, nodejs, express, gulp, karma, jasmine 前端方案整合

    今年转向做前端开发,主要是做angularjs开发,期间接触了nodejs平台,从此一发不可收拾. npm丰富的插件库,express 开发框架, grunt, gulp构建工具,karma测试管理工 ...

  8. Fortran编译多个文件(转载)

    最近需要在Linux系统下编译多个Fortran程序,在网上搜索了一下,但是资料不多,也许因为这个问题比较简单,不值一提,但还是把我知道的写出来,供大家参考: 方法一: 假如现在有两个Fortran程 ...

  9. C#/.NET使用HttpWebRequest、SqlBulkCopy从API获取数据批量插入DB

    小弟新手程序员一枚,代码技术和文章水平均不才.所写文章均为对自己所写所学代码的简单记录,可能对于老手程序员营养价值不高,望莫见怪. 我工作上有个需求:从某处API接口上获取数据(大约1W条而已)并插入 ...

  10. java第四课:数组

    1.数组声明时,必须有中括号,但不指定数组的元素个数2.初始化时,必须指定元素个数3.数组元素内容仅能用于声明时初始化,不能用于赋值.如:char[] week; week={'1','2','3'} ...