influxdb/snapshot.go

68 lines
1.2 KiB
Go
Raw Normal View History

2013-06-03 21:58:12 +00:00
package raft
import (
"bytes"
2013-06-08 02:19:18 +00:00
"fmt"
"hash/crc32"
2013-06-03 21:58:12 +00:00
"os"
2013-06-08 02:19:18 +00:00
"syscall"
)
2013-06-03 21:58:12 +00:00
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
// the in memory SnapShot struct
2013-06-05 05:56:59 +00:00
// TODO add cluster configuration
2013-06-03 21:58:12 +00:00
type Snapshot struct {
lastIndex uint64
2013-06-08 02:19:18 +00:00
lastTerm uint64
2013-06-03 21:58:12 +00:00
// cluster configuration.
2013-06-06 04:14:07 +00:00
state []byte
2013-06-08 02:19:18 +00:00
path string
2013-06-03 21:58:12 +00:00
}
2013-06-05 05:56:59 +00:00
// Save the snapshot to a file
2013-06-03 21:58:12 +00:00
func (ss *Snapshot) Save() error {
// Write machine state to temporary buffer.
var b bytes.Buffer
2013-06-05 00:02:45 +00:00
if _, err := fmt.Fprintf(&b, "%v", 2); err != nil {
2013-06-03 21:58:12 +00:00
return err
}
// Generate checksum.
checksum := crc32.ChecksumIEEE(b.Bytes())
// open file
file, err := os.OpenFile(ss.path, os.O_CREATE|os.O_WRONLY, 0600)
2013-06-06 03:25:17 +00:00
2013-06-03 21:58:12 +00:00
if err != nil {
return err
}
2013-06-05 00:02:45 +00:00
defer file.Close()
2013-06-06 04:14:07 +00:00
// Write snapshot with checksum.
2013-06-08 02:19:18 +00:00
if _, err = fmt.Fprintf(file, "%08x\n%v\n%v\n", checksum, ss.lastIndex,
2013-06-06 04:14:07 +00:00
ss.lastTerm); err != nil {
return err
}
2013-06-08 02:19:18 +00:00
if _, err = file.Write(ss.state); err != nil {
2013-06-03 21:58:12 +00:00
return err
}
// force the change writting to disk
syscall.Fsync(int(file.Fd()))
return err
}
2013-06-05 05:56:59 +00:00
// remove the file of the snapshot
2013-06-03 21:58:12 +00:00
func (ss *Snapshot) Remove() error {
err := os.Remove(ss.path)
return err
2013-06-05 00:02:45 +00:00
}