influxdb/snapshot.go

65 lines
1.2 KiB
Go
Raw Normal View History

2013-06-03 21:58:12 +00:00
package raft
import (
"hash/crc32"
"fmt"
"syscall"
"bytes"
"os"
)
//------------------------------------------------------------------------------
//
// 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
lastTerm uint64
// cluster configuration.
machineState int
path string
}
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-05 00:02:45 +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-03 21:58:12 +00:00
// Write log entry with checksum.
2013-06-05 00:02:45 +00:00
if _, err = fmt.Fprintf(file, "%08x\n%s\n%v\n%v\n", checksum, b.String(),
2013-06-03 21:58:12 +00:00
ss.lastIndex, ss.lastTerm); err != nil {
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
}