/
restore.go
357 lines (328 loc) · 10.2 KB
/
restore.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package s3plugin
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/greenplum-db/gp-common-go-libs/gplog"
"github.com/pkg/errors"
"github.com/urfave/cli"
)
func SetupPluginForRestore(c *cli.Context) error {
scope := (Scope)(c.Args().Get(2))
if scope != Master && scope != Coordinator && scope != SegmentHost {
return nil
}
_, err := readAndValidatePluginConfig(c.Args().Get(0))
return err
}
func RestoreFile(c *cli.Context) error {
config, sess, err := readConfigAndStartSession(c)
if err != nil {
return err
}
fileName := c.Args().Get(1)
bucket := config.Options.Bucket
fileKey := GetS3Path(config.Options.Folder, fileName)
file, err := os.Create(fileName)
defer file.Close()
if err != nil {
return err
}
bytes, elapsed, err := downloadFile(sess, config, bucket, fileKey, file)
if err != nil {
fileErr := os.Remove(fileName)
if fileErr != nil {
gplog.Error(fileErr.Error())
}
return err
}
gplog.Info("Downloaded %d bytes for %s in %v", bytes,
filepath.Base(fileKey), elapsed.Round(time.Millisecond))
return err
}
func RestoreDirectory(c *cli.Context) error {
start := time.Now()
totalBytes := int64(0)
config, sess, err := readConfigAndStartSession(c)
if err != nil {
return err
}
dirName := c.Args().Get(1)
bucket := config.Options.Bucket
gplog.Verbose("Restore Directory '%s' from S3", dirName)
gplog.Verbose("S3 Location = s3://%s/%s", bucket, dirName)
gplog.Info("dirKey = %s\n", dirName)
_ = os.MkdirAll(dirName, 0775)
client := s3.New(sess)
params := &s3.ListObjectsV2Input{Bucket: &bucket, Prefix: &dirName}
bucketObjectsList, _ := client.ListObjectsV2(params)
numFiles := 0
for _, key := range bucketObjectsList.Contents {
var filename string
if strings.HasSuffix(*key.Key, "/") {
// Got a directory
continue
}
if strings.Contains(*key.Key, "/") {
// split
s3FileFullPathList := strings.Split(*key.Key, "/")
filename = s3FileFullPathList[len(s3FileFullPathList)-1]
}
filePath := dirName + "/" + filename
file, err := os.Create(filePath)
if err != nil {
return err
}
bytes, elapsed, err := downloadFile(sess, config, bucket, *key.Key, file)
_ = file.Close()
if err != nil {
fileErr := os.Remove(filename)
if fileErr != nil {
gplog.Error(fileErr.Error())
}
return err
}
totalBytes += bytes
numFiles++
gplog.Info("Downloaded %d bytes for %s in %v", bytes,
filepath.Base(*key.Key), elapsed.Round(time.Millisecond))
}
gplog.Info("Downloaded %d files (%d bytes) in %v\n",
numFiles, totalBytes, time.Since(start).Round(time.Millisecond))
return nil
}
func RestoreDirectoryParallel(c *cli.Context) error {
start := time.Now()
totalBytes := int64(0)
parallel := 5
config, sess, err := readConfigAndStartSession(c)
if err != nil {
return err
}
dirName := c.Args().Get(1)
if len(c.Args()) == 3 {
parallel, _ = strconv.Atoi(c.Args().Get(2))
}
bucket := config.Options.Bucket
gplog.Verbose("Restore Directory Parallel '%s' from S3", dirName)
gplog.Verbose("S3 Location = s3://%s/%s", bucket, dirName)
fmt.Printf("dirKey = %s\n", dirName)
_ = os.MkdirAll(dirName, 0775)
client := s3.New(sess)
params := &s3.ListObjectsV2Input{Bucket: &bucket, Prefix: &dirName}
bucketObjectsList, _ := client.ListObjectsV2(params)
// Create a list of files to be restored
numFiles := 0
fileList := make([]string, 0)
for _, key := range bucketObjectsList.Contents {
gplog.Verbose("File '%s' = %d bytes", filepath.Base(*key.Key), *key.Size)
if strings.HasSuffix(*key.Key, "/") {
// Got a directory
continue
}
fileList = append(fileList, *key.Key)
}
var wg sync.WaitGroup
var finalErr error
// Create jobs using a channel
fileChannel := make(chan string, len(fileList))
for _, fileKey := range fileList {
wg.Add(1)
fileChannel <- fileKey
}
close(fileChannel)
// Process the files in parallel
for i := 0; i < parallel; i++ {
go func(jobs chan string) {
for fileKey := range jobs {
fileName := fileKey
if strings.Contains(fileKey, "/") {
fileName = filepath.Base(fileKey)
}
// construct local file name
filePath := dirName + "/" + fileName
file, err := os.Create(filePath)
if err != nil {
finalErr = err
return
}
bytes, elapsed, err := downloadFile(sess, config, bucket, fileKey, file)
if err == nil {
totalBytes += bytes
numFiles++
msg := fmt.Sprintf("Downloaded %d bytes for %s in %v", bytes,
filepath.Base(fileKey), elapsed.Round(time.Millisecond))
gplog.Verbose(msg)
fmt.Println(msg)
} else {
finalErr = err
gplog.FatalOnError(err)
_ = os.Remove(filePath)
}
_ = file.Close()
wg.Done()
}
}(fileChannel)
}
// Wait for jobs to be done
wg.Wait()
fmt.Printf("Downloaded %d files (%d bytes) in %v\n",
numFiles, totalBytes, time.Since(start).Round(time.Millisecond))
return finalErr
}
func RestoreData(c *cli.Context) error {
config, sess, err := readConfigAndStartSession(c)
if err != nil {
return err
}
dataFile := c.Args().Get(1)
bucket := config.Options.Bucket
fileKey := GetS3Path(config.Options.Folder, dataFile)
bytes, elapsed, err := downloadFile(sess, config, bucket, fileKey, os.Stdout)
if err != nil {
return err
}
gplog.Verbose("Downloaded %d bytes for file %s in %v", bytes,
filepath.Base(fileKey), elapsed.Round(time.Millisecond))
return nil
}
type chunk struct {
chunkIndex int
startByte int64
endByte int64
}
func downloadFile(sess *session.Session, config *PluginConfig, bucket string, fileKey string,
file *os.File) (int64, time.Duration, error) {
start := time.Now()
downloader := s3manager.NewDownloader(sess, func(u *s3manager.Downloader) {
u.PartSize = config.Options.DownloadChunkSize
})
totalBytes, err := getFileSize(downloader.S3, bucket, fileKey)
if err != nil {
return 0, -1, errors.Wrap(err, fmt.Sprintf("Error getting file size for %s in bucket %s", fileKey, bucket))
}
gplog.Verbose("File %s size = %d bytes", filepath.Base(fileKey), totalBytes)
if totalBytes <= config.Options.DownloadChunkSize {
buffer := &aws.WriteAtBuffer{}
if _, err = downloader.Download(
buffer,
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileKey),
}); err != nil {
return 0, -1, errors.Wrap(err, fmt.Sprintf("Error while downloading %s", fileKey))
}
if _, err = file.Write(buffer.Bytes()); err != nil {
return 0, -1, err
}
} else {
return downloadFileInParallel(sess, config.Options.DownloadConcurrency, config.Options.DownloadChunkSize, totalBytes, bucket, fileKey, file)
}
return totalBytes, time.Since(start), err
}
/*
* Performs ranged requests for the file while exploiting parallelism between the copy and download tasks
*/
func downloadFileInParallel(sess *session.Session, downloadConcurrency int, downloadChunkSize int64,
totalBytes int64, bucket string, fileKey string, file *os.File) (int64, time.Duration, error) {
var finalErr error
start := time.Now()
waitGroup := sync.WaitGroup{}
numberOfChunks := int((totalBytes + downloadChunkSize - 1) / downloadChunkSize)
bufferPointers := make([]*[]byte, numberOfChunks)
copyChannel := make([]chan int, numberOfChunks)
jobs := make(chan chunk, numberOfChunks)
for i := 0; i < numberOfChunks; i++ {
copyChannel[i] = make(chan int)
}
startByte := int64(0)
endByte := int64(-1)
done := false
// Create jobs based on the number of chunks to be downloaded
for chunkIndex := 0; chunkIndex < numberOfChunks && !done; chunkIndex++ {
startByte = endByte + 1
endByte += downloadChunkSize
if endByte >= totalBytes {
endByte = totalBytes - 1
done = true
}
jobs <- chunk{chunkIndex, startByte, endByte}
waitGroup.Add(1)
}
// Create a pool of download workers (based on concurrency)
numberOfWorkers := downloadConcurrency
if numberOfChunks < downloadConcurrency {
numberOfWorkers = numberOfChunks
}
downloadBuffers := make(chan []byte, numberOfWorkers)
for i := 0; i < cap(downloadBuffers); i++ {
buffer := make([]byte, downloadChunkSize)
downloadBuffers <- buffer
}
// Download concurrency is handled on our end hence we don't need to set concurrency
downloader := s3manager.NewDownloader(sess, func(u *s3manager.Downloader) {
u.PartSize = downloadChunkSize
u.Concurrency = 1
})
gplog.Debug("Downloading file %s with chunksize %d and concurrency %d",
filepath.Base(fileKey), downloadChunkSize, numberOfWorkers)
for i := 0; i < numberOfWorkers; i++ {
go func(id int) {
for j := range jobs {
buffer := <-downloadBuffers
chunkStart := time.Now()
byteRange := fmt.Sprintf("bytes=%d-%d", j.startByte, j.endByte)
if j.endByte-j.startByte+1 != downloadChunkSize {
buffer = make([]byte, j.endByte-j.startByte+1)
}
bufferPointers[j.chunkIndex] = &buffer
gplog.Debug("Worker %d (chunk %d) for %s with partsize %d and concurrency %d",
id, j.chunkIndex, filepath.Base(fileKey),
downloader.PartSize, downloader.Concurrency)
chunkBytes, err := downloader.Download(
aws.NewWriteAtBuffer(buffer),
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileKey),
Range: aws.String(byteRange),
})
if err != nil {
finalErr = err
}
gplog.Debug("Worker %d Downloaded %d bytes (chunk %d) for %s in %v",
id, chunkBytes, j.chunkIndex, filepath.Base(fileKey),
time.Since(chunkStart).Round(time.Millisecond))
copyChannel[j.chunkIndex] <- j.chunkIndex
}
}(i)
}
// Copy data from download buffers into the output stream sequentially
go func() {
for i := range copyChannel {
currentChunk := <-copyChannel[i]
chunkStart := time.Now()
numBytes, err := file.Write(*bufferPointers[currentChunk])
if err != nil {
finalErr = err
}
gplog.Debug("Copied %d bytes (chunk %d) for %s in %v",
numBytes, currentChunk, filepath.Base(fileKey),
time.Since(chunkStart).Round(time.Millisecond))
// Deallocate buffer
downloadBuffers <- *bufferPointers[currentChunk]
bufferPointers[currentChunk] = nil
waitGroup.Done()
close(copyChannel[i])
}
}()
waitGroup.Wait()
return totalBytes, time.Since(start), errors.Wrap(finalErr, fmt.Sprintf("Error while downloading %s", fileKey))
}