db.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 snap
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "time"
  23. "github.com/coreos/etcd/pkg/fileutil"
  24. )
  25. var ErrNoDBSnapshot = errors.New("snap: snapshot file doesn't exist")
  26. // SaveDBFrom saves snapshot of the database from the given reader. It
  27. // guarantees the save operation is atomic.
  28. func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) (int64, error) {
  29. start := time.Now()
  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. fsyncStart := time.Now()
  38. err = fileutil.Fsync(f)
  39. snapDBFsyncSec.Observe(time.Since(fsyncStart).Seconds())
  40. }
  41. f.Close()
  42. if err != nil {
  43. os.Remove(f.Name())
  44. return n, err
  45. }
  46. fn := s.dbFilePath(id)
  47. if fileutil.Exist(fn) {
  48. os.Remove(f.Name())
  49. return n, nil
  50. }
  51. err = os.Rename(f.Name(), fn)
  52. if err != nil {
  53. os.Remove(f.Name())
  54. return n, err
  55. }
  56. plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
  57. snapDBSaveSec.Observe(time.Since(start).Seconds())
  58. return n, nil
  59. }
  60. // DBFilePath returns the file path for the snapshot of the database with
  61. // given id. If the snapshot does not exist, it returns error.
  62. func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
  63. if _, err := fileutil.ReadDir(s.dir); err != nil {
  64. return "", err
  65. }
  66. if fn := s.dbFilePath(id); fileutil.Exist(fn) {
  67. return fn, nil
  68. }
  69. return "", ErrNoDBSnapshot
  70. }
  71. func (s *Snapshotter) dbFilePath(id uint64) string {
  72. return filepath.Join(s.dir, fmt.Sprintf("%016x.snap.db", id))
  73. }