Debian Codegraph @

cmd/influxd/backup_util/backup_util.go

raw
1 package backup_util
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "sort"
11 "strings"
12
13 "github.com/gogo/protobuf/proto"
14 internal "github.com/influxdata/influxdb/cmd/influxd/backup_util/internal"
15 "github.com/influxdata/influxdb/services/snapshotter"
16 "io/ioutil"
17 "path/filepath"
18 )
19
20 //go:generate protoc --gogo_out=. internal/data.proto
21
22 const (
23 // Suffix is a suffix added to the backup while it's in-process.
24 Suffix = ".pending"
25
26 // Metafile is the base name given to the metastore backups.
27 Metafile = "meta"
28
29 // BackupFilePattern is the beginning of the pattern for a backup
30 // file. They follow the scheme <database>.<retention>.<shardID>.<increment>
31 BackupFilePattern = "%s.%s.%05d"
32
33 PortableFileNamePattern = "20060102T150405Z"
34 )
35
36 type PortablePacker struct {
37 Data []byte
38 MaxNodeID uint64
39 }
40
41 func (ep PortablePacker) MarshalBinary() ([]byte, error) {
42 ed := internal.PortableData{Data: ep.Data, MaxNodeID: &ep.MaxNodeID}
43 return proto.Marshal(&ed)
44 }
45
46 func (ep *PortablePacker) UnmarshalBinary(data []byte) error {
47 var pb internal.PortableData
48 if err := proto.Unmarshal(data, &pb); err != nil {
49 return err
50 }
51
52 ep.Data = pb.GetData()
53 ep.MaxNodeID = pb.GetMaxNodeID()
54 return nil
55 }
56
57 func GetMetaBytes(fname string) ([]byte, error) {
58 f, err := os.Open(fname)
59 if err != nil {
60 return []byte{}, err
61 }
62
63 var buf bytes.Buffer
64 if _, err := io.Copy(&buf, f); err != nil {
65 return []byte{}, fmt.Errorf("copy: %s", err)
66 }
67
68 b := buf.Bytes()
69 var i int
70
71 // Make sure the file is actually a meta store backup file
72 magic := binary.BigEndian.Uint64(b[:8])
73 if magic != snapshotter.BackupMagicHeader {
74 return []byte{}, fmt.Errorf("invalid metadata file")
75 }
76 i += 8
77
78 // Size of the meta store bytes
79 length := int(binary.BigEndian.Uint64(b[i : i+8]))
80 i += 8
81 metaBytes := b[i : i+length]
82
83 return metaBytes, nil
84 }
85
86 // Manifest lists the meta and shard file information contained in the backup.
87 // If Limited is false, the manifest contains a full backup, otherwise
88 // it is a partial backup.
89 type Manifest struct {
90 Meta MetaEntry `json:"meta"`
91 Limited bool `json:"limited"`
92 Files []Entry `json:"files"`
93
94 // If limited is true, then one (or all) of the following fields will be set
95
96 Database string `json:"database,omitempty"`
97 Policy string `json:"policy,omitempty"`
98 ShardID uint64 `json:"shard_id,omitempty"`
99 }
100
101 // Entry contains the data information for a backed up shard.
102 type Entry struct {
103 Database string `json:"database"`
104 Policy string `json:"policy"`
105 ShardID uint64 `json:"shardID"`
106 FileName string `json:"fileName"`
107 Size int64 `json:"size"`
108 LastModified int64 `json:"lastModified"`
109 }
110
111 func (e *Entry) SizeOrZero() int64 {
112 if e == nil {
113 return 0
114 }
115 return e.Size
116 }
117
118 // MetaEntry contains the meta store information for a backup.
119 type MetaEntry struct {
120 FileName string `json:"fileName"`
121 Size int64 `json:"size"`
122 }
123
124 // Size returns the size of the manifest.
125 func (m *Manifest) Size() int64 {
126 if m == nil {
127 return 0
128 }
129
130 size := m.Meta.Size
131
132 for _, f := range m.Files {
133 size += f.Size
134 }
135 return size
136 }
137
138 func (manifest *Manifest) Save(filename string) error {
139 b, err := json.MarshalIndent(manifest, "", " ")
140 if err != nil {
141 return fmt.Errorf("create manifest: %v", err)
142 }
143
144 return ioutil.WriteFile(filename, b, 0600)
145 }
146
147 // LoadIncremental loads multiple manifest files from a given directory.
148 func LoadIncremental(dir string) (*MetaEntry, map[uint64]*Entry, error) {
149 manifests, err := filepath.Glob(filepath.Join(dir, "*.manifest"))
150 if err != nil {
151 return nil, nil, err
152 }
153 shards := make(map[uint64]*Entry)
154
155 if len(manifests) == 0 {
156 return nil, shards, nil
157 }
158
159 sort.Sort(sort.Reverse(sort.StringSlice(manifests)))
160 var metaEntry MetaEntry
161
162 for _, fileName := range manifests {
163 fi, err := os.Stat(fileName)
164 if err != nil {
165 return nil, nil, err
166 }
167
168 if fi.IsDir() {
169 continue
170 }
171
172 f, err := os.Open(fileName)
173 if err != nil {
174 return nil, nil, err
175 }
176
177 var manifest Manifest
178 err = json.NewDecoder(f).Decode(&manifest)
179 f.Close()
180 if err != nil {
181 return nil, nil, fmt.Errorf("read manifest: %v", err)
182 }
183
184 // sorted (descending) above, so first manifest is most recent
185 if metaEntry.FileName == "" {
186 metaEntry = manifest.Meta
187 }
188
189 for i := range manifest.Files {
190 sh := manifest.Files[i]
191 if _, err := os.Stat(filepath.Join(dir, sh.FileName)); err != nil {
192 continue
193 }
194
195 e := shards[sh.ShardID]
196 if e == nil || sh.LastModified > e.LastModified {
197 shards[sh.ShardID] = &sh
198 }
199 }
200 }
201
202 return &metaEntry, shards, nil
203 }
204
205 type CountingWriter struct {
206 io.Writer
207 Total int64 // Total # of bytes transferred
208 }
209
210 func (w *CountingWriter) Write(p []byte) (n int, err error) {
211 n, err = w.Writer.Write(p)
212 w.Total += int64(n)
213 return
214 }
215
216 // retentionAndShardFromPath will take the shard relative path and split it into the
217 // retention policy name and shard ID. The first part of the path should be the database name.
218 func DBRetentionAndShardFromPath(path string) (db, retention, shard string, err error) {
219 a := strings.Split(path, string(filepath.Separator))
220 if len(a) != 3 {
221 return "", "", "", fmt.Errorf("expected database, retention policy, and shard id in path: %s", path)
222 }
223
224 return a[0], a[1], a[2], nil
225 }