Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / coreos / etcd / snap / db.go
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         "fmt"
19         "io"
20         "io/ioutil"
21         "os"
22         "path"
23
24         "github.com/coreos/etcd/pkg/fileutil"
25 )
26
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 := path.Join(s.dir, fmt.Sprintf("%016x.snap.db", 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
55         plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
56
57         return n, nil
58 }
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         fns, err := fileutil.ReadDir(s.dir)
64         if err != nil {
65                 return "", err
66         }
67         wfn := fmt.Sprintf("%016x.snap.db", id)
68         for _, fn := range fns {
69                 if fn == wfn {
70                         return path.Join(s.dir, fn), nil
71                 }
72         }
73         return "", fmt.Errorf("snap: snapshot file doesn't exist")
74 }