snap: separate Load to Load and snapNames

This commit is contained in:
Xiang Li 2014-08-19 21:08:29 -07:00 committed by Yicheng Qin
parent 71d12d3330
commit aff5b75487
2 changed files with 45 additions and 11 deletions

View File

@ -47,20 +47,10 @@ func (s *Snapshotter) Save(snapshot *raft.Snapshot) error {
}
func (s *Snapshotter) Load() (*raft.Snapshot, error) {
dir, err := os.Open(s.dir)
names, err := s.snapNames()
if err != nil {
return nil, err
}
defer dir.Close()
names, err := dir.Readdirnames(-1)
if err != nil {
return nil, err
}
if len(names) == 0 {
return nil, ErrNoSnapshot
}
sort.Sort(sort.Reverse(sort.StringSlice(names)))
var snap raft.Snapshot
var serializedSnap Snapshot
var b []byte
@ -91,3 +81,22 @@ func (s *Snapshotter) Load() (*raft.Snapshot, error) {
}
return &snap, nil
}
// snapNames returns the filename of the snapshots in logical time order (from newest to oldest).
// If there is no avaliable snapshots, an ErrNoSnapshot will be returned.
func (s *Snapshotter) snapNames() ([]string, error) {
dir, err := os.Open(s.dir)
if err != nil {
return nil, err
}
defer dir.Close()
names, err := dir.Readdirnames(-1)
if err != nil {
return nil, err
}
if len(names) == 0 {
return nil, ErrNoSnapshot
}
sort.Sort(sort.Reverse(sort.StringSlice(names)))
return names, nil
}

View File

@ -85,6 +85,31 @@ func TestFailback(t *testing.T) {
}
}
func TestSnapNames(t *testing.T) {
dir := path.Join(os.TempDir(), "snapshot")
os.Mkdir(dir, 0700)
defer os.RemoveAll(dir)
for i := 1; i <= 5; i++ {
if f, err := os.Create(path.Join(dir, fmt.Sprintf("%d", i))); err != nil {
t.Fatal(err)
} else {
f.Close()
}
}
ss := New(dir)
names, err := ss.snapNames()
if err != nil {
t.Errorf("err = %v, want nil", err)
}
if len(names) != 5 {
t.Errorf("len = %d, want 10", len(names))
}
w := []string{"5", "4", "3", "2", "1"}
if !reflect.DeepEqual(names, w) {
t.Errorf("names = %v, want %v", names, w)
}
}
func TestLoadNewestSnap(t *testing.T) {
dir := path.Join(os.TempDir(), "snapshot")
os.Mkdir(dir, 0700)