/
main.go
233 lines (187 loc) · 5.7 KB
/
main.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
// s3-glacier-uploader --- upload large files to S3 Glacier
// Copyright (C) 2022 Honza Pokorny <honza@pokorny.ca>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bufio"
"bytes"
"crypto/md5"
"fmt"
"io"
"os"
"path"
"strings"
"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/schollz/progressbar/v3"
"github.com/spf13/cobra"
)
const (
PART_SIZE = 50 * 1024 * 1024
RETRIES = 2
)
// CLI flags
var BucketName string
var Region string
var UploadID string
var rootCmd = &cobra.Command{
Use: "s3-glacier-uploader file",
Short: "s3-glacier-uploader",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := Upload(BucketName, Region, args[0], UploadID)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
type partUploadResult struct {
completedPart *s3.CompletedPart
err error
}
func calculateMd5Digest(input []byte) string {
return fmt.Sprintf("%x", md5.Sum(input))
}
func Upload(bucket string, region string, filename string, uploadID string) error {
s3session := s3.New(session.Must(session.NewSession(&aws.Config{
Region: aws.String(region),
})))
key := path.Base(filename)
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return err
}
fileSize := stat.Size()
approximateChunkCount := (fileSize / PART_SIZE) + 1
fmt.Println("File to upload:", filename)
if uploadID != "" {
return fmt.Errorf("We can't resume uploads yet. It's on the roadmap.")
}
createdResp, err := s3session.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
StorageClass: aws.String(s3.ObjectStorageClassDeepArchive),
})
if err != nil {
return err
}
fmt.Println("Upload ID:", *createdResp.UploadId)
var partNum = 1
var completedParts []*s3.CompletedPart
buffer := make([]byte, PART_SIZE)
reader := bufio.NewReader(file)
// When an object is uploaded as a multipart upload, the ETag for the object is
// not an MD5 digest of the entire object. Amazon S3 calculates the MD5 digest
// of each individual part as it is uploaded. The MD5 digests are used to
// determine the ETag for the final object. Amazon S3 concatenates the bytes for
// the MD5 digests together and then calculates the MD5 digest of these
// concatenated values. The final step for creating the ETag is when Amazon S3
// adds a dash with the total number of parts to the end.
//
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
digestBytes := []byte{}
bar := progressbar.Default(int64(approximateChunkCount))
for {
n, err := reader.Read(buffer)
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("Failed to read a chunk: %w", err)
}
// If we've read less than the chunk size, truncate the buffer.
if n < PART_SIZE {
buffer = buffer[:n]
}
db := md5.Sum(buffer)
for _, b := range db {
digestBytes = append(digestBytes, b)
}
result := uploadToS3(s3session, createdResp, buffer, partNum)
if result.err != nil {
return fmt.Errorf("Upload not aborted. You can resume it. Not implemented yet. Error: %w", result.err)
}
completedParts = append(completedParts, result.completedPart)
partNum++
bar.Add(1)
}
etag := fmt.Sprintf("%s-%d", calculateMd5Digest(digestBytes), partNum-1)
// Signalling AWS S3 that the multiPartUpload is finished
resp, err := s3session.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: createdResp.Bucket,
Key: createdResp.Key,
UploadId: createdResp.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: completedParts,
},
})
if err != nil {
return err
}
fmt.Println("Success!")
respEtag := strings.Trim(*resp.ETag, "\"")
if respEtag == etag {
fmt.Println("Etags match!")
} else {
fmt.Println("Etags don't match!")
fmt.Println(" AWS: ", respEtag)
fmt.Println(" Ours:", etag)
}
fmt.Println(*resp.Location)
return nil
}
func uploadToS3(s3session *s3.S3, resp *s3.CreateMultipartUploadOutput, fileBytes []byte, partNum int) partUploadResult {
var try int
for try <= RETRIES {
uploadRes, err := s3session.UploadPart(&s3.UploadPartInput{
Body: bytes.NewReader(fileBytes),
Bucket: resp.Bucket,
Key: resp.Key,
PartNumber: aws.Int64(int64(partNum)),
UploadId: resp.UploadId,
ContentLength: aws.Int64(int64(len(fileBytes))),
})
if err != nil {
fmt.Println(err)
if try == RETRIES {
return partUploadResult{nil, err}
} else {
try++
time.Sleep(time.Duration(time.Second * 15))
}
} else {
return partUploadResult{
&s3.CompletedPart{
ETag: uploadRes.ETag,
PartNumber: aws.Int64(int64(partNum)),
}, nil,
}
}
}
return partUploadResult{}
}
func init() {
rootCmd.PersistentFlags().StringVar(&BucketName, "bucket", "", "")
rootCmd.PersistentFlags().StringVar(&Region, "region", "us-east-1", "")
rootCmd.PersistentFlags().StringVar(&UploadID, "upload-id", "", "")
}
func main() {
rootCmd.Execute()
}