snapshotter.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2015 The etcd Authors
  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 stores raft nodes' states with snapshots.
  15. package snap
  16. import (
  17. "errors"
  18. "fmt"
  19. "hash/crc32"
  20. "io/ioutil"
  21. "os"
  22. "path/filepath"
  23. "sort"
  24. "strings"
  25. "time"
  26. pioutil "github.com/coreos/etcd/pkg/ioutil"
  27. "github.com/coreos/etcd/pkg/pbutil"
  28. "github.com/coreos/etcd/raft"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/snap/snappb"
  31. "github.com/coreos/pkg/capnslog"
  32. )
  33. const (
  34. snapSuffix = ".snap"
  35. )
  36. var (
  37. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "snap")
  38. ErrNoSnapshot = errors.New("snap: no available snapshot")
  39. ErrEmptySnapshot = errors.New("snap: empty snapshot")
  40. ErrCRCMismatch = errors.New("snap: crc mismatch")
  41. crcTable = crc32.MakeTable(crc32.Castagnoli)
  42. // A map of valid files that can be present in the snap folder.
  43. validFiles = map[string]bool{
  44. "db": true,
  45. }
  46. )
  47. type Snapshotter struct {
  48. dir string
  49. }
  50. func New(dir string) *Snapshotter {
  51. return &Snapshotter{
  52. dir: dir,
  53. }
  54. }
  55. func (s *Snapshotter) SaveSnap(snapshot raftpb.Snapshot) error {
  56. if raft.IsEmptySnap(snapshot) {
  57. return nil
  58. }
  59. return s.save(&snapshot)
  60. }
  61. func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error {
  62. start := time.Now()
  63. fname := fmt.Sprintf("%016x-%016x%s", snapshot.Metadata.Term, snapshot.Metadata.Index, snapSuffix)
  64. b := pbutil.MustMarshal(snapshot)
  65. crc := crc32.Update(0, crcTable, b)
  66. snap := snappb.Snapshot{Crc: crc, Data: b}
  67. d, err := snap.Marshal()
  68. if err != nil {
  69. return err
  70. } else {
  71. marshallingDurations.Observe(float64(time.Since(start)) / float64(time.Second))
  72. }
  73. err = pioutil.WriteAndSyncFile(filepath.Join(s.dir, fname), d, 0666)
  74. if err == nil {
  75. saveDurations.Observe(float64(time.Since(start)) / float64(time.Second))
  76. } else {
  77. err1 := os.Remove(filepath.Join(s.dir, fname))
  78. if err1 != nil {
  79. plog.Errorf("failed to remove broken snapshot file %s", filepath.Join(s.dir, fname))
  80. }
  81. }
  82. return err
  83. }
  84. func (s *Snapshotter) Load() (*raftpb.Snapshot, error) {
  85. names, err := s.snapNames()
  86. if err != nil {
  87. return nil, err
  88. }
  89. var snap *raftpb.Snapshot
  90. for _, name := range names {
  91. if snap, err = loadSnap(s.dir, name); err == nil {
  92. break
  93. }
  94. }
  95. if err != nil {
  96. return nil, ErrNoSnapshot
  97. }
  98. return snap, nil
  99. }
  100. func loadSnap(dir, name string) (*raftpb.Snapshot, error) {
  101. fpath := filepath.Join(dir, name)
  102. snap, err := Read(fpath)
  103. if err != nil {
  104. renameBroken(fpath)
  105. }
  106. return snap, err
  107. }
  108. // Read reads the snapshot named by snapname and returns the snapshot.
  109. func Read(snapname string) (*raftpb.Snapshot, error) {
  110. b, err := ioutil.ReadFile(snapname)
  111. if err != nil {
  112. plog.Errorf("cannot read file %v: %v", snapname, err)
  113. return nil, err
  114. }
  115. if len(b) == 0 {
  116. plog.Errorf("unexpected empty snapshot")
  117. return nil, ErrEmptySnapshot
  118. }
  119. var serializedSnap snappb.Snapshot
  120. if err = serializedSnap.Unmarshal(b); err != nil {
  121. plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
  122. return nil, err
  123. }
  124. if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
  125. plog.Errorf("unexpected empty snapshot")
  126. return nil, ErrEmptySnapshot
  127. }
  128. crc := crc32.Update(0, crcTable, serializedSnap.Data)
  129. if crc != serializedSnap.Crc {
  130. plog.Errorf("corrupted snapshot file %v: crc mismatch", snapname)
  131. return nil, ErrCRCMismatch
  132. }
  133. var snap raftpb.Snapshot
  134. if err = snap.Unmarshal(serializedSnap.Data); err != nil {
  135. plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
  136. return nil, err
  137. }
  138. return &snap, nil
  139. }
  140. // snapNames returns the filename of the snapshots in logical time order (from newest to oldest).
  141. // If there is no available snapshots, an ErrNoSnapshot will be returned.
  142. func (s *Snapshotter) snapNames() ([]string, error) {
  143. dir, err := os.Open(s.dir)
  144. if err != nil {
  145. return nil, err
  146. }
  147. defer dir.Close()
  148. names, err := dir.Readdirnames(-1)
  149. if err != nil {
  150. return nil, err
  151. }
  152. snaps := checkSuffix(names)
  153. if len(snaps) == 0 {
  154. return nil, ErrNoSnapshot
  155. }
  156. sort.Sort(sort.Reverse(sort.StringSlice(snaps)))
  157. return snaps, nil
  158. }
  159. func checkSuffix(names []string) []string {
  160. snaps := []string{}
  161. for i := range names {
  162. if strings.HasSuffix(names[i], snapSuffix) {
  163. snaps = append(snaps, names[i])
  164. } else {
  165. // If we find a file which is not a snapshot then check if it's
  166. // a vaild file. If not throw out a warning.
  167. if _, ok := validFiles[names[i]]; !ok {
  168. plog.Warningf("skipped unexpected non snapshot file %v", names[i])
  169. }
  170. }
  171. }
  172. return snaps
  173. }
  174. func renameBroken(path string) {
  175. brokenPath := path + ".broken"
  176. if err := os.Rename(path, brokenPath); err != nil {
  177. plog.Warningf("cannot rename broken snapshot file %v to %v: %v", path, brokenPath, err)
  178. }
  179. }