db.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. _, err = io.Copy(f, r)
  31. f.Close()
  32. if err != nil {
  33. os.Remove(f.Name())
  34. return err
  35. }
  36. fn := path.Join(s.dir, fmt.Sprintf("%016x.snap.db", id))
  37. if fileutil.Exist(fn) {
  38. os.Remove(f.Name())
  39. return nil
  40. }
  41. err = os.Rename(f.Name(), fn)
  42. if err != nil {
  43. os.Remove(f.Name())
  44. return err
  45. }
  46. return nil
  47. }
  48. // DBFilePath returns the file path for the snapshot of the database with
  49. // given id. If the snapshot does not exist, it returns error.
  50. func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
  51. fns, err := fileutil.ReadDir(s.dir)
  52. if err != nil {
  53. return "", err
  54. }
  55. wfn := fmt.Sprintf("%016x.snap.db", id)
  56. for _, fn := range fns {
  57. if fn == wfn {
  58. return path.Join(s.dir, fn), nil
  59. }
  60. }
  61. return "", fmt.Errorf("snap: snapshot file doesn't exist")
  62. }