snapshotter.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package snap
  15. import (
  16. "errors"
  17. "fmt"
  18. "hash/crc32"
  19. "io/ioutil"
  20. "log"
  21. "os"
  22. "path"
  23. "sort"
  24. "strings"
  25. "github.com/coreos/etcd/pkg/pbutil"
  26. "github.com/coreos/etcd/raft"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. "github.com/coreos/etcd/snap/snappb"
  29. )
  30. const (
  31. snapSuffix = ".snap"
  32. )
  33. var (
  34. ErrNoSnapshot = errors.New("snap: no available snapshot")
  35. ErrEmptySnapshot = errors.New("snap: empty snapshot")
  36. ErrCRCMismatch = errors.New("snap: crc mismatch")
  37. crcTable = crc32.MakeTable(crc32.Castagnoli)
  38. )
  39. type Snapshotter struct {
  40. dir string
  41. }
  42. func New(dir string) *Snapshotter {
  43. return &Snapshotter{
  44. dir: dir,
  45. }
  46. }
  47. func (s *Snapshotter) SaveSnap(snapshot raftpb.Snapshot) error {
  48. if raft.IsEmptySnap(snapshot) {
  49. return nil
  50. }
  51. return s.save(&snapshot)
  52. }
  53. func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error {
  54. fname := fmt.Sprintf("%016x-%016x%s", snapshot.Metadata.Term, snapshot.Metadata.Index, snapSuffix)
  55. b := pbutil.MustMarshal(snapshot)
  56. crc := crc32.Update(0, crcTable, b)
  57. snap := snappb.Snapshot{Crc: crc, Data: b}
  58. d, err := snap.Marshal()
  59. if err != nil {
  60. return err
  61. }
  62. return ioutil.WriteFile(path.Join(s.dir, fname), d, 0666)
  63. }
  64. func (s *Snapshotter) Load() (*raftpb.Snapshot, error) {
  65. names, err := s.snapNames()
  66. if err != nil {
  67. return nil, err
  68. }
  69. var snap *raftpb.Snapshot
  70. for _, name := range names {
  71. if snap, err = loadSnap(s.dir, name); err == nil {
  72. break
  73. }
  74. }
  75. if err != nil {
  76. return nil, ErrNoSnapshot
  77. }
  78. return snap, nil
  79. }
  80. func loadSnap(dir, name string) (*raftpb.Snapshot, error) {
  81. fpath := path.Join(dir, name)
  82. snap, err := Read(fpath)
  83. if err != nil {
  84. renameBroken(fpath)
  85. }
  86. return snap, err
  87. }
  88. // Read reads the snapshot named by snapname and returns the snapshot.
  89. func Read(snapname string) (*raftpb.Snapshot, error) {
  90. b, err := ioutil.ReadFile(snapname)
  91. if err != nil {
  92. log.Printf("snap: snapshotter cannot read file %v: %v", snapname, err)
  93. return nil, err
  94. }
  95. var serializedSnap snappb.Snapshot
  96. if err = serializedSnap.Unmarshal(b); err != nil {
  97. log.Printf("snap: corrupted snapshot file %v: %v", snapname, err)
  98. return nil, err
  99. }
  100. if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
  101. log.Printf("snap: unexpected empty snapshot")
  102. return nil, ErrEmptySnapshot
  103. }
  104. crc := crc32.Update(0, crcTable, serializedSnap.Data)
  105. if crc != serializedSnap.Crc {
  106. log.Printf("snap: corrupted snapshot file %v: crc mismatch", snapname)
  107. return nil, ErrCRCMismatch
  108. }
  109. var snap raftpb.Snapshot
  110. if err = snap.Unmarshal(serializedSnap.Data); err != nil {
  111. log.Printf("snap: corrupted snapshot file %v: %v", snapname, err)
  112. return nil, err
  113. }
  114. return &snap, nil
  115. }
  116. // snapNames returns the filename of the snapshots in logical time order (from newest to oldest).
  117. // If there is no available snapshots, an ErrNoSnapshot will be returned.
  118. func (s *Snapshotter) snapNames() ([]string, error) {
  119. dir, err := os.Open(s.dir)
  120. if err != nil {
  121. return nil, err
  122. }
  123. defer dir.Close()
  124. names, err := dir.Readdirnames(-1)
  125. if err != nil {
  126. return nil, err
  127. }
  128. snaps := checkSuffix(names)
  129. if len(snaps) == 0 {
  130. return nil, ErrNoSnapshot
  131. }
  132. sort.Sort(sort.Reverse(sort.StringSlice(snaps)))
  133. return snaps, nil
  134. }
  135. func checkSuffix(names []string) []string {
  136. snaps := []string{}
  137. for i := range names {
  138. if strings.HasSuffix(names[i], snapSuffix) {
  139. snaps = append(snaps, names[i])
  140. } else {
  141. log.Printf("snap: unexpected non-snap file %v", names[i])
  142. }
  143. }
  144. return snaps
  145. }
  146. func renameBroken(path string) {
  147. brokenPath := path + ".broken"
  148. if err := os.Rename(path, brokenPath); err != nil {
  149. log.Printf("snap: cannot rename broken snapshot file %v to %v: %v", path, brokenPath, err)
  150. }
  151. }