Search in sources :

Example 1 with SegmentedRaftLogOutputStream

use of org.apache.ratis.server.raftlog.segmented.SegmentedRaftLogOutputStream in project incubator-ratis by apache.

the class SimpleStateMachine4Testing method takeSnapshot.

@Override
public long takeSnapshot() {
    final TermIndex termIndex = getLastAppliedTermIndex();
    if (termIndex.getTerm() <= 0 || termIndex.getIndex() <= 0) {
        return RaftLog.INVALID_LOG_INDEX;
    }
    final long endIndex = termIndex.getIndex();
    // TODO: snapshot should be written to a tmp file, then renamed
    File snapshotFile = storage.getSnapshotFile(termIndex.getTerm(), termIndex.getIndex());
    LOG.debug("Taking a snapshot with t:{}, i:{}, file:{}", termIndex.getTerm(), termIndex.getIndex(), snapshotFile);
    try (SegmentedRaftLogOutputStream out = new SegmentedRaftLogOutputStream(snapshotFile, false, segmentMaxSize, preallocatedSize, ByteBuffer.allocateDirect(bufferSize))) {
        for (final LogEntryProto entry : indexMap.values()) {
            if (entry.getIndex() > endIndex) {
                break;
            } else {
                out.write(entry);
            }
        }
        out.flush();
    } catch (IOException e) {
        LOG.warn("Failed to take snapshot", e);
    }
    try {
        final MD5Hash digest = MD5FileUtil.computeMd5ForFile(snapshotFile);
        MD5FileUtil.saveMD5File(snapshotFile, digest);
    } catch (IOException e) {
        LOG.warn("Hit IOException when computing MD5 for snapshot file " + snapshotFile, e);
    }
    try {
        this.storage.loadLatestSnapshot();
    } catch (IOException e) {
        LOG.warn("Hit IOException when loading latest snapshot for snapshot file " + snapshotFile, e);
    }
    // TODO: purge log segments
    return endIndex;
}
Also used : SegmentedRaftLogOutputStream(org.apache.ratis.server.raftlog.segmented.SegmentedRaftLogOutputStream) LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) MD5Hash(org.apache.ratis.io.MD5Hash) IOException(java.io.IOException) File(java.io.File) TermIndex(org.apache.ratis.server.protocol.TermIndex)

Aggregations

File (java.io.File)1 IOException (java.io.IOException)1 MD5Hash (org.apache.ratis.io.MD5Hash)1 LogEntryProto (org.apache.ratis.proto.RaftProtos.LogEntryProto)1 TermIndex (org.apache.ratis.server.protocol.TermIndex)1 SegmentedRaftLogOutputStream (org.apache.ratis.server.raftlog.segmented.SegmentedRaftLogOutputStream)1