Debian Codegraph @

vendor/github.com/coreos/etcd/snap/db.go

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