influxdb/snapshot.go

66 lines
1.2 KiB
Go
Raw Normal View History

2013-06-03 21:58:12 +00:00
package raft
import (
2013-06-12 16:47:48 +00:00
//"bytes"
2013-06-24 16:52:51 +00:00
"encoding/json"
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
//
//------------------------------------------------------------------------------
2013-06-24 16:52:51 +00:00
// 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 {
2013-06-12 16:47:48 +00:00
LastIndex uint64 `json:"lastIndex"`
LastTerm uint64 `json:"lastTerm"`
2013-06-24 16:52:51 +00:00
// cluster configuration.
Peers []string `json: "peers"`
State []byte `json: "state"`
Path string `json: "path"`
2013-06-03 21:58:12 +00:00
}
2013-06-05 05:56:59 +00:00
// Save the snapshot to a file
2013-07-06 04:49:47 +00:00
func (ss *Snapshot) save() error {
2013-06-03 21:58:12 +00:00
// Write machine state to temporary buffer.
// open file
2013-06-12 16:47:48 +00:00
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-12 16:47:48 +00:00
b, err := json.Marshal(ss)
// Generate checksum.
checksum := crc32.ChecksumIEEE(b)
2013-06-06 04:14:07 +00:00
// Write snapshot with checksum.
2013-06-12 16:47:48 +00:00
if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil {
2013-06-06 04:14:07 +00:00
return err
}
2013-06-12 16:47:48 +00:00
if _, err = file.Write(b); 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-07-06 04:49:47 +00:00
func (ss *Snapshot) remove() error {
2013-06-12 16:47:48 +00:00
err := os.Remove(ss.Path)
2013-06-03 21:58:12 +00:00
return err
2013-06-05 00:02:45 +00:00
}