db.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "github.com/coreos/etcd/pkg/fileutil"
  22. )
  23. // SaveDBFrom saves snapshot of the database from the given reader. It
  24. // guarantees the save operation is atomic.
  25. func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) error {
  26. f, err := ioutil.TempFile(s.dir, "tmp")
  27. if err != nil {
  28. return err
  29. }
  30. var n int64
  31. n, err = io.Copy(f, r)
  32. if err == nil {
  33. err = f.Sync()
  34. }
  35. f.Close()
  36. if err != nil {
  37. os.Remove(f.Name())
  38. return err
  39. }
  40. fn := path.Join(s.dir, fmt.Sprintf("%016x.snap.db", id))
  41. if fileutil.Exist(fn) {
  42. os.Remove(f.Name())
  43. return nil
  44. }
  45. err = os.Rename(f.Name(), fn)
  46. if err != nil {
  47. os.Remove(f.Name())
  48. return err
  49. }
  50. plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
  51. return nil
  52. }
  53. // DBFilePath returns the file path for the snapshot of the database with
  54. // given id. If the snapshot does not exist, it returns error.
  55. func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
  56. fns, err := fileutil.ReadDir(s.dir)
  57. if err != nil {
  58. return "", err
  59. }
  60. wfn := fmt.Sprintf("%016x.snap.db", id)
  61. for _, fn := range fns {
  62. if fn == wfn {
  63. return path.Join(s.dir, fn), nil
  64. }
  65. }
  66. return "", fmt.Errorf("snap: snapshot file doesn't exist")
  67. }