snapshotter.go 5.1 KB

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