zk源码阅读4: 持久化FileSnap

摘要

本节讲解

快照文件意义
SnapShot接口
FileSnap源码
快照文件可视化

意义

Zookeeper的数据在内存中是以DataTree为数据结构存储的
而快照就是每间隔一段时间Zookeeper就会把整个DataTree的数据序列化然后把它存储在磁盘中
快照文件是指定时间间隔对数据的备份,所以快照文件中数据通常都不是最新的
多久抓一个快照这也是可以配置的snapCount配置项用于配置处理几个事务请求后生成一个快照文件;

接口SnapShot

是持久化中快照snapshot的接口

public interface SnapShot {
    /**
     * deserialize a data tree from the last valid snapshot and 
     * return the last zxid that was deserialized
     * @param dt the datatree to be deserialized into
     * @param sessions the sessions to be deserialized into
     * @return the last zxid that was deserialized from the snapshot
     * @throws IOException
     */
    // 反序列化
    long deserialize(DataTree dt, Map<Long, Integer> sessions) 
        throws IOException;
    
    /**
     * persist the datatree and the sessions into a persistence storage
     * @param dt the datatree to be serialized
     * @param sessions 
     * @throws IOException
     */
    //序列化
    void serialize(DataTree dt, Map<Long, Integer> sessions, 
            File name) 
        throws IOException;
    
    /**
     * find the most recent snapshot file
     * @return the most recent snapshot file
     * @throws IOException
     */
    //找到最近的快照文件
    File findMostRecentSnapshot() throws IOException;
    
    /**
     * free resources from this snapshot immediately
     * @throws IOException
     */
    //释放资源
    void close() throws IOException;
} 

函数分别是

序列化,反序列化,找到最近的快照文件以及释放资源

实现类FileSnap

属性

File snapDir;//snap文件目录
    private volatile boolean close = false;//是否关闭
    private static final int VERSION=2;
    private static final long dbId=-1;
    private static final Logger LOG = LoggerFactory.getLogger(FileSnap.class);
    public final static int SNAP_MAGIC
        = ByteBuffer.wrap("ZKSN".getBytes()).getInt();//文件的魔数

函数

反序列化涉及的函数

1. public long deserialize(DataTree dt, Map<Long, Integer> sessions)
public long deserialize(DataTree dt, Map<Long, Integer> sessions)
            throws IOException {
        // we run through 100 snapshots (not all of them)
        // if we cannot get it running within 100 snapshots
        // we should  give up
        //找到最新的100个(大概率)valid的快照文件
        List<File> snapList = findNValidSnapshots(100);
        if (snapList.size() == 0) {
            return -1L;
        }
        File snap = null;
        boolean foundValid = false;
        //将这些快照文件按新旧排序,直到第一个合法的就break
        for (int i = 0; i < snapList.size(); i++) {
            snap = snapList.get(i);
            InputStream snapIS = null;
            CheckedInputStream crcIn = null;
            try {
                LOG.info("Reading snapshot " + snap);
                snapIS = new BufferedInputStream(new FileInputStream(snap));
                crcIn = new CheckedInputStream(snapIS, new Adler32());
                InputArchive ia = BinaryInputArchive.getArchive(crcIn);
                deserialize(dt,sessions, ia);//根据ia反序列化到dataTree以及sessions
                long checkSum = crcIn.getChecksum().getValue();//反序列填充session和dataTree之后,计算checkSum
                long val = ia.readLong("val");
                if (val != checkSum) {//比较checkSum
                    throw new IOException("CRC corruption in snapshot :  " + snap);
                }
                foundValid = true;//如果前100个有一个valid,就break
                break;
            } catch(IOException e) {
                LOG.warn("problem reading snap file " + snap, e);
            } finally {
                if (snapIS != null) 
                    snapIS.close();
                if (crcIn != null) 
                    crcIn.close();
            } 
        }
        if (!foundValid) {//如果前100个中一个valid都没有
            throw new IOException("Not able to find valid snapshots in " + snapDir);
        }
        //从最近的第一个valid的snap文件中,解析出zxid
        dt.lastProcessedZxid = Util.getZxidFromName(snap.getName(), "snapshot");
        return dt.lastProcessedZxid;
    }

里面调用了findNValidSnapshots函数 以及deserialize(dt,sessions, ia);

2.findNValidSnapshots函数
//找到最近n个(大概)合理的快照文件,按从新到旧排序
    private List<File> findNValidSnapshots(int n) throws IOException {
        List<File> files = Util.sortDataDir(snapDir.listFiles(),"snapshot", false);
        int count = 0;
        List<File> list = new ArrayList<File>();
        for (File f : files) {
            // we should catch the exceptions
            // from the valid snapshot and continue
            // until we find a valid one
            try {
                if (Util.isValidSnapshot(f)) {//一个minor check,来看这个文件是否大概率valid
                    list.add(f);
                    count++;
                    if (count == n) {
                        break;
                    }
                }
            } catch (IOException e) {
                LOG.info("invalid snapshot " + f, e);
            }
        }
        return list;
    }
3.deserialize(dt,sessions, ia)函数
    public void deserialize(DataTree dt, Map<Long, Integer> sessions,
            InputArchive ia) throws IOException {
        FileHeader header = new FileHeader();
        header.deserialize(ia, "fileheader");// 反序列化至header
        if (header.getMagic() != SNAP_MAGIC) {
            throw new IOException("mismatching magic headers "
                    + header.getMagic() + 
                    " !=  " + FileSnap.SNAP_MAGIC);
        }
        SerializeUtils.deserializeSnapshot(dt,ia,sessions);// 反序列化至dataTree和sessions
    }

序列化涉及的函数

public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot)
public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot)
            throws IOException {
        if (!close) {
            OutputStream sessOS = new BufferedOutputStream(new FileOutputStream(snapShot));
            CheckedOutputStream crcOut = new CheckedOutputStream(sessOS, new Adler32());
            //CheckedOutputStream cout = new CheckedOutputStream()
            OutputArchive oa = BinaryOutputArchive.getArchive(crcOut);
            FileHeader header = new FileHeader(SNAP_MAGIC, VERSION, dbId);
            serialize(dt,sessions,oa, header);//将dt,session,header进行序列化
            long val = crcOut.getChecksum().getValue();
            oa.writeLong(val, "val");//得到checksum,写入
            oa.writeString("/", "path");//写入"\"作为结束标记,这也是判断是否highly valid的条件之一
            sessOS.flush();
            crcOut.close();
            sessOS.close();
        }
    }

里面调用了serialize(dt,sessions,oa, header);函数

protected void serialize(DataTree dt,Map<Long, Integer> sessions, OutputArchive oa, FileHeader header)
protected void serialize(DataTree dt,Map<Long, Integer> sessions,
            OutputArchive oa, FileHeader header) throws IOException {
        // this is really a programmatic error and not something that can
        // happen at runtime
        if(header==null)
            throw new IllegalStateException(
                    "Snapshot's not open for writing: uninitialized header");
        header.serialize(oa, "fileheader");//header序列化
        SerializeUtils.serializeSnapshot(dt,oa,sessions);//将dataTree和sessions序列化到oa
    }

找到最近的snapshot文件

public File findMostRecentSnapshot() throws IOException {
        List<File> files = findNValidSnapshots(1);
        if (files.size() == 0) {
            return null;
        }
        return files.get(0);
    }

很好理解

关闭,释放资源

@Override
    public synchronized void close() throws IOException {
        close = true;
    }

很好理解

回滚日志

public synchronized void rollLog() throws IOException {
        if (logStream != null) {
            this.logStream.flush();
            this.logStream = null;
            oa = null;
        }
    }

可视化工具

利用SnapshotFormatter.java即可
不过针对http://www.jianshu.com/p/d1f8b9d6ad57贴出的demo
看源码应该是snapshot.xxx这样的文件,但是我并没有看到生成快照文件

思考

snapshot文件,怎么样算大概率valid,大概率valid什么时候不是truely valid

org.apache.zookeeper.server.persistence.Util#isValidSnapshot中说

as in a situation when the server dies while in the process
of storing a snapshot. Any file that is not a snapshot is also 
an invalid snapshot. 

org.apache.zookeeper.server.persistence.FileSnap#findNValidSnapshots中说

This does not mean that the snapshot is truly valid but is valid with a high probability

补充什么时候算大概率valid但是not truly valid
org.apache.zookeeper.server.persistence.FileSnap#deserialize(org.apache.zookeeper.server.DataTree, java.util.Map<java.lang.Long,java.lang.Integer>)
函数里面检查了checkSum
也就是说snapShot文件格式之类的都ok,但是数据内容被改了导致checkSum不一致,我认为是这些情况。

上一节FileTxnLog和这一节FileSnap有什么关系

上一节FileTxnLog是事务日志文件,就是各个node的增删改等
这一节FileSnap是快照,就是内存中是以DataTree是什么样子的(可能不是最新)

后续

关于疑问

FileTxnLog和FileSnap时间先后顺序如何,两者最新的zxid是有固定的大小关系还是没有
回滚,恢复和快照有关系吗

会在下一节进行讲解

问题

什么时候生成快照,快照什么时候被删除,会不会被删除

如果zk集群挂了是从哪里恢复,FileSnap还是FileTxn,FileSnap都不一定是最新的,zxid怎么保证

refer

http://www.cnblogs.com/leesf456/p/6285014.html
http://blog.csdn.net/quhongwei_zhanqiu?viewmode=contents
http://www.cnblogs.com/leesf456/p/6179118.html
http://www.solinx.co/archives/448?utm_source=tuicool&utm_medium=referral

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,069评论 4 358
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,212评论 1 287
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 105,912评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,424评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,741评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,194评论 1 206
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,553评论 2 307
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,289评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,923评论 1 237
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,251评论 2 240
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,775评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,144评论 2 249
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,698评论 3 228
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,936评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,658评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,214评论 2 267
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,159评论 2 258

推荐阅读更多精彩内容