-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket.go
105 lines (88 loc) · 2.46 KB
/
bucket.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
package main
import (
"context"
"log"
"os"
"path"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
func initS3() *s3.S3 {
creds := credentials.NewStaticCredentials(
viper.GetString("access_key"),
viper.GetString("secret_key"),
"",
)
sess := session.Must(session.NewSession())
return s3.New(sess, &aws.Config{
Credentials: creds,
Region: aws.String(endpoints.UsEast1RegionID),
})
}
// uploadToS3 will upload mongo dump file to s3 bucket with destination key
func uploadToS3(svc *s3.S3, dstKey string) (err error) {
ctx := context.Background()
f, err := os.Open(viper.GetString("file_name"))
if err != nil {
return err
}
defer f.Close()
bucketName := viper.GetString("bucket_name")
// Uploads the object to S3. The Context will interrupt the request if the
// timeout expires.
_, err = svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(dstKey),
Body: f,
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode {
// If the SDK can determine the request or retry delay was canceled
// by a context the CanceledErrorCode error code will be returned.
return errors.Wrap(err, "upload canceled due to timeout")
}
return err
}
return nil
}
// deleteFromS3 will delete other backups for the same month
func deleteFromS3(svc *s3.S3, key string) (err error) {
ctx := context.Background()
bucketName := viper.GetString("bucket_name")
// return whole put but last element
prefix := path.Dir(key)
log.Println("listing objects with prefix:", prefix)
objects, err := svc.ListObjects(&s3.ListObjectsInput{
Bucket: aws.String(bucketName),
Prefix: aws.String(prefix),
})
if err != nil {
return err
}
if len(objects.Contents) == 0 {
return errors.New("bucket is empty")
}
if len(objects.Contents) ==1 {
return errors.New("there is only one backup in this month")
}
for i, o := range objects.Contents {
if *o.Key != key {
lastKey := objects.Contents[i].Key
_, err := svc.DeleteObjectWithContext(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Key: lastKey,
})
if err != nil {
return err
}
}
}
return nil
}