snapshotter.go 5.1 KB

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