snapshotter.go 4.3 KB

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