snapshotter.go 4.5 KB

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