snapshotter.go 4.9 KB

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