snapshot_store.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 etcdserver
  15. import (
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "github.com/coreos/etcd/pkg/fileutil"
  22. "github.com/coreos/etcd/raft"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. "github.com/coreos/etcd/rafthttp"
  25. dstorage "github.com/coreos/etcd/storage"
  26. )
  27. type snapshot struct {
  28. r raftpb.Snapshot
  29. io.ReadCloser // used to read out v3 snapshot
  30. done chan struct{}
  31. }
  32. func newSnapshot(r raftpb.Snapshot, kv dstorage.Snapshot) *snapshot {
  33. done := make(chan struct{})
  34. pr, pw := io.Pipe()
  35. go func() {
  36. _, err := kv.WriteTo(pw)
  37. pw.CloseWithError(err)
  38. kv.Close()
  39. close(done)
  40. }()
  41. return &snapshot{
  42. r: r,
  43. ReadCloser: pr,
  44. done: done,
  45. }
  46. }
  47. func (s *snapshot) raft() raftpb.Snapshot { return s.r }
  48. func (s *snapshot) isClosed() bool {
  49. select {
  50. case <-s.done:
  51. return true
  52. default:
  53. return false
  54. }
  55. }
  56. // TODO: remove snapshotStore. getSnap part could be put into memoryStorage,
  57. // while SaveFrom could be put into another struct, or even put into dstorage package.
  58. type snapshotStore struct {
  59. // dir to save snapshot data
  60. dir string
  61. kv dstorage.KV
  62. tr rafthttp.Transporter
  63. // send empty to reqsnapc to notify the channel receiver to send back latest
  64. // snapshot to snapc
  65. reqsnapc chan struct{}
  66. // a chan to receive the requested raft snapshot
  67. // snapshotStore will receive from the chan immediately after it sends empty to reqsnapc
  68. raftsnapc chan raftpb.Snapshot
  69. snap *snapshot
  70. }
  71. func newSnapshotStore(dir string, kv dstorage.KV) *snapshotStore {
  72. return &snapshotStore{
  73. dir: dir,
  74. kv: kv,
  75. reqsnapc: make(chan struct{}),
  76. raftsnapc: make(chan raftpb.Snapshot),
  77. }
  78. }
  79. // getSnap returns a snapshot.
  80. // If there is no available snapshot, ErrSnapshotTemporarilyUnavaliable will be returned.
  81. //
  82. // Internally it creates new snapshot and returns the snapshot. Unless the
  83. // returned snapshot is closed, it rejects creating new one and returns
  84. // ErrSnapshotTemporarilyUnavailable.
  85. // If raft state machine wants to send two snapshot messages to two followers,
  86. // the second snapshot message will keep getting snapshot and succeed only after
  87. // the first message is sent. This increases the time used to send messages,
  88. // but it is acceptable because this should happen seldomly.
  89. func (ss *snapshotStore) getSnap() (*snapshot, error) {
  90. // If snapshotStore has some snapshot that has not been closed, it cannot
  91. // request new snapshot. So it returns ErrSnapshotTemporarilyUnavailable.
  92. if ss.snap != nil && !ss.snap.isClosed() {
  93. return nil, raft.ErrSnapshotTemporarilyUnavailable
  94. }
  95. // ask to generate v2 snapshot
  96. ss.reqsnapc <- struct{}{}
  97. // generate KV snapshot
  98. kvsnap := ss.kv.Snapshot()
  99. raftsnap := <-ss.raftsnapc
  100. ss.snap = newSnapshot(raftsnap, kvsnap)
  101. // give transporter the generated snapshot that is ready to send out
  102. ss.tr.SnapshotReady(ss.snap, raftsnap.Metadata.Index)
  103. return ss.snap, nil
  104. }
  105. // SaveFrom saves snapshot at the given index from the given reader.
  106. // If the snapshot with the given index has been saved successfully, it keeps
  107. // the original saved snapshot and returns error.
  108. // The function guarantees that SaveFrom always saves either complete
  109. // snapshot or no snapshot, even if the call is aborted because program
  110. // is hard killed.
  111. func (ss *snapshotStore) SaveFrom(r io.Reader, index uint64) error {
  112. f, err := ioutil.TempFile(ss.dir, "tmp")
  113. if err != nil {
  114. return err
  115. }
  116. _, err = io.Copy(f, r)
  117. f.Close()
  118. if err != nil {
  119. os.Remove(f.Name())
  120. return err
  121. }
  122. fn := path.Join(ss.dir, fmt.Sprintf("%016x.db", index))
  123. if fileutil.Exist(fn) {
  124. os.Remove(f.Name())
  125. return fmt.Errorf("snapshot to save has existed")
  126. }
  127. err = os.Rename(f.Name(), fn)
  128. if err != nil {
  129. os.Remove(f.Name())
  130. return err
  131. }
  132. return nil
  133. }
  134. // getSnapFilePath returns the file path for the snapshot with given index.
  135. // If the snapshot does not exist, it returns error.
  136. func (ss *snapshotStore) getSnapFilePath(index uint64) (string, error) {
  137. fns, err := fileutil.ReadDir(ss.dir)
  138. if err != nil {
  139. return "", err
  140. }
  141. wfn := fmt.Sprintf("%016x.db", index)
  142. for _, fn := range fns {
  143. if fn == wfn {
  144. return path.Join(ss.dir, fn), nil
  145. }
  146. }
  147. return "", fmt.Errorf("snapshot file doesn't exist")
  148. }