db.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "io"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "github.com/coreos/etcd/pkg/fileutil"
  23. humanize "github.com/dustin/go-humanize"
  24. "go.uber.org/zap"
  25. )
  26. var ErrNoDBSnapshot = errors.New("snap: snapshot file doesn't exist")
  27. // SaveDBFrom saves snapshot of the database from the given reader. It
  28. // guarantees the save operation is atomic.
  29. func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) (int64, error) {
  30. f, err := ioutil.TempFile(s.dir, "tmp")
  31. if err != nil {
  32. return 0, err
  33. }
  34. var n int64
  35. n, err = io.Copy(f, r)
  36. if err == nil {
  37. err = fileutil.Fsync(f)
  38. }
  39. f.Close()
  40. if err != nil {
  41. os.Remove(f.Name())
  42. return n, err
  43. }
  44. fn := s.dbFilePath(id)
  45. if fileutil.Exist(fn) {
  46. os.Remove(f.Name())
  47. return n, nil
  48. }
  49. err = os.Rename(f.Name(), fn)
  50. if err != nil {
  51. os.Remove(f.Name())
  52. return n, err
  53. }
  54. if s.lg != nil {
  55. s.lg.Info(
  56. "saved database snapshot to disk",
  57. zap.Int64("bytes", n),
  58. zap.String("size", humanize.Bytes(uint64(n))),
  59. )
  60. } else {
  61. plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
  62. }
  63. return n, nil
  64. }
  65. // DBFilePath returns the file path for the snapshot of the database with
  66. // given id. If the snapshot does not exist, it returns error.
  67. func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
  68. if _, err := fileutil.ReadDir(s.dir); err != nil {
  69. return "", err
  70. }
  71. fn := s.dbFilePath(id)
  72. if fileutil.Exist(fn) {
  73. return fn, nil
  74. }
  75. if s.lg != nil {
  76. s.lg.Warn(
  77. "failed to find [SNAPSHOT-INDEX].snap.db",
  78. zap.Uint64("snapshot-index", id),
  79. zap.String("snapshot-file-path", fn),
  80. zap.Error(ErrNoDBSnapshot),
  81. )
  82. }
  83. return "", ErrNoDBSnapshot
  84. }
  85. func (s *Snapshotter) dbFilePath(id uint64) string {
  86. return filepath.Join(s.dir, fmt.Sprintf("%016x.snap.db", id))
  87. }