forked from wal-g/wal-g
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.go
327 lines (270 loc) · 7.53 KB
/
backup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package walg
import (
"encoding/json"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/pkg/errors"
"io"
"io/ioutil"
"log"
"sort"
"strings"
)
// WalFiles represent any file generated by WAL-G.
type WalFiles interface {
CheckExistence() (bool, error)
}
// ReaderMaker is the generic interface used by extract. It
// allows for ease of handling different file formats.
type ReaderMaker interface {
Reader() (io.ReadCloser, error)
Format() string
Path() string
}
// S3ReaderMaker handles cases where backups need to be uploaded to
// S3.
type S3ReaderMaker struct {
Backup *Backup
Key *string
FileFormat string
}
// Format of a file
func (s *S3ReaderMaker) Format() string { return s.FileFormat }
// Path to file in bucket
func (s *S3ReaderMaker) Path() string { return *s.Key }
// Reader creates a new S3 reader for each S3 object.
func (s *S3ReaderMaker) Reader() (io.ReadCloser, error) {
input := &s3.GetObjectInput{
Bucket: s.Backup.Prefix.Bucket,
Key: s.Key,
}
rdr, err := s.Backup.Prefix.Svc.GetObject(input)
if err != nil {
return nil, errors.Wrap(err, "S3 Reader: s3.GetObject failed")
}
return rdr.Body, nil
}
// Prefix contains the S3 service client, bucket and string.
type Prefix struct {
Svc s3iface.S3API
Bucket *string
Server *string
}
// Backup contains information about a valid backup
// generated and uploaded by WAL-G.
type Backup struct {
Prefix *Prefix
Path *string
Name *string
Js *string
}
// ErrLatestNotFound happens when users asks backup-fetch LATEST, but there is no backups
var ErrLatestNotFound = errors.New("No backups found")
// GetLatest sorts the backups by last modified time
// and returns the latest backup key.
func (b *Backup) GetLatest() (string, error) {
sortTimes, err := b.GetBackups()
if err != nil {
return "", err
}
return sortTimes[0].Name, nil
}
// GetBackups receives backup descriptions and sorts them by time
func (b *Backup) GetBackups() ([]BackupTime, error) {
var sortTimes []BackupTime
objects := &s3.ListObjectsV2Input{
Bucket: b.Prefix.Bucket,
Prefix: b.Path,
Delimiter: aws.String("/"),
}
var backups = make([]*s3.Object, 0)
err := b.Prefix.Svc.ListObjectsV2Pages(objects, func(files *s3.ListObjectsV2Output, lastPage bool) bool {
backups = append(backups, files.Contents...)
return true
})
if err != nil {
return nil, errors.Wrap(err, "GetLatest: s3.ListObjectsV2 failed")
}
count := len(backups)
if count == 0 {
return nil, ErrLatestNotFound
}
sortTimes = GetBackupTimeSlices(backups)
return sortTimes, nil
}
// GetBackupTimeSlices converts S3 objects to backup description
func GetBackupTimeSlices(backups []*s3.Object) []BackupTime {
sortTimes := make([]BackupTime, len(backups))
for i, ob := range backups {
key := *ob.Key
time := *ob.LastModified
sortTimes[i] = BackupTime{stripNameBackup(key), time, stripWalFileName(key)}
}
slice := TimeSlice(sortTimes)
sort.Sort(slice)
return slice
}
// Strips the backup key and returns it in its base form `base_...`.
func stripNameBackup(key string) string {
all := strings.SplitAfter(key, "/")
name := strings.Split(all[len(all)-1], "_backup")[0]
return name
}
// Strips the backup WAL file name.
func stripWalFileName(key string) string {
name := stripNameBackup(key)
name = strings.SplitN(name, "_D_", 2)[0]
if strings.HasPrefix(name, backupNamePrefix) {
return name[len(backupNamePrefix):]
}
return ""
}
// CheckExistence checks that the specified backup exists.
func (b *Backup) CheckExistence() (bool, error) {
js := &s3.HeadObjectInput{
Bucket: b.Prefix.Bucket,
Key: b.Js,
}
_, err := b.Prefix.Svc.HeadObject(js)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case "NotFound":
return false, nil
default:
return false, awsErr
}
}
}
return true, nil
}
// GetKeys returns all the keys for the Files in the specified backup.
func (b *Backup) GetKeys() ([]string, error) {
objects := &s3.ListObjectsV2Input{
Bucket: b.Prefix.Bucket,
Prefix: aws.String(sanitizePath(*b.Path + *b.Name + "/tar_partitions")),
}
result := make([]string, 0)
err := b.Prefix.Svc.ListObjectsV2Pages(objects, func(files *s3.ListObjectsV2Output, lastPage bool) bool {
arr := make([]string, len(files.Contents))
for i, ob := range files.Contents {
key := *ob.Key
arr[i] = key
}
result = append(result, arr...)
return true
})
if err != nil {
return nil, errors.Wrap(err, "GetKeys: s3.ListObjectsV2 failed")
}
return result, nil
}
// GetWals returns all WAL file keys less then key provided
func (b *Backup) GetWals(before string) ([]*s3.ObjectIdentifier, error) {
objects := &s3.ListObjectsV2Input{
Bucket: b.Prefix.Bucket,
Prefix: aws.String(sanitizePath(*b.Path)),
}
arr := make([]*s3.ObjectIdentifier, 0)
err := b.Prefix.Svc.ListObjectsV2Pages(objects, func(files *s3.ListObjectsV2Output, lastPage bool) bool {
for _, ob := range files.Contents {
key := *ob.Key
if stripWalName(key) < before {
arr = append(arr, &s3.ObjectIdentifier{Key: aws.String(key)})
}
}
return true
})
if err != nil {
return nil, errors.Wrap(err, "GetKeys: s3.ListObjectsV2 failed")
}
return arr, nil
}
func stripWalName(key string) string {
all := strings.SplitAfter(key, "/")
name := strings.Split(all[len(all)-1], ".")[0]
return name
}
// Archive contains information associated with
// a WAL archive.
type Archive struct {
Prefix *Prefix
Archive *string
}
// CheckExistence checks that the specified WAL file exists.
func (a *Archive) CheckExistence() (bool, error) {
arch := &s3.HeadObjectInput{
Bucket: a.Prefix.Bucket,
Key: a.Archive,
}
_, err := a.Prefix.Svc.HeadObject(arch)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case "NotFound":
return false, nil
default:
return false, awsErr
}
}
}
return true, nil
}
// GetETag aquires ETag of the object from S3
func (a *Archive) GetETag() (*string, error) {
arch := &s3.HeadObjectInput{
Bucket: a.Prefix.Bucket,
Key: a.Archive,
}
h, err := a.Prefix.Svc.HeadObject(arch)
if err != nil {
return nil, err
}
return h.ETag, nil
}
// GetArchive downloads the specified archive from S3.
func (a *Archive) GetArchive() (io.ReadCloser, error) {
input := &s3.GetObjectInput{
Bucket: a.Prefix.Bucket,
Key: a.Archive,
}
archive, err := a.Prefix.Svc.GetObject(input)
if err != nil {
return nil, errors.Wrap(err, "GetArchive: s3.GetObject failed")
}
return archive.Body, nil
}
// SentinelSuffix is a suffix of backup finish sentinel file
const SentinelSuffix = "_backup_stop_sentinel.json"
func fetchSentinel(backupName string, bk *Backup, pre *Prefix) (dto S3TarBallSentinelDto) {
latestSentinel := backupName + SentinelSuffix
previousBackupReader := S3ReaderMaker{
Backup: bk,
Key: aws.String(*pre.Server + "/basebackups_005/" + latestSentinel),
FileFormat: CheckType(latestSentinel),
}
prevBackup, err := previousBackupReader.Reader()
if err != nil {
log.Fatalf("%+v\n", err)
}
sentinelDto, err := ioutil.ReadAll(prevBackup)
if err != nil {
log.Fatalf("%+v\n", err)
}
err = json.Unmarshal(sentinelDto, &dto)
if err != nil {
log.Fatalf("%+v\n", err)
}
return
}
// GetBackupPath gets path for basebackup in a bucket
func GetBackupPath(prefix *Prefix) *string {
path := *prefix.Server + "/basebackups_005/"
server := sanitizePath(path)
return aws.String(server)
}
func sanitizePath(path string) string {
return strings.TrimLeft(path, "/")
}