snapshotter.go 4.7 KB

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