forked from rlmcpherson/s3gof3r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
putter.go
401 lines (372 loc) · 9.09 KB
/
putter.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package s3gof3r
import (
"bytes"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/xml"
"fmt"
"hash"
"io"
"math"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// defined by amazon
const (
minPartSize = 5 * mb
maxPartSize = 5 * gb
maxObjSize = 5 * tb
maxNPart = 10000
md5Header = "content-md5"
sha256Header = "X-Amz-Content-Sha256"
)
type part struct {
r io.ReadSeeker
len int64
b []byte
// Read by xml encoder
PartNumber int
ETag string
// Checksums
md5 string
sha256 string
}
type putter struct {
url url.URL
b *Bucket
c *Config
bufsz int64
buf []byte
bufbytes int // bytes written to current buffer
ch chan *part
part int
closed bool
err error
wg sync.WaitGroup
md5OfParts hash.Hash
md5 hash.Hash
ETag string
sp *bp
makes int
UploadID string `xml:"UploadId"`
xml struct {
XMLName string `xml:"CompleteMultipartUpload"`
Part []*part
}
putsz int64
}
// Sends an S3 multipart upload initiation request.
// See http://docs.amazonwebservices.com/AmazonS3/latest/dev/mpuoverview.html.
// The initial request returns an UploadId that we use to identify
// subsequent PUT requests.
func newPutter(url url.URL, h http.Header, c *Config, b *Bucket) (p *putter, err error) {
p = new(putter)
p.url = url
p.c, p.b = new(Config), new(Bucket)
*p.c, *p.b = *c, *b
p.c.Concurrency = max(c.Concurrency, 1)
p.c.NTry = max(c.NTry, 1)
p.bufsz = max64(minPartSize, c.PartSize)
resp, err := p.retryRequest("POST", url.String()+"?uploads", nil, h)
if err != nil {
return nil, err
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
err = xml.NewDecoder(resp.Body).Decode(p)
if err != nil {
return nil, err
}
p.ch = make(chan *part)
for i := 0; i < p.c.Concurrency; i++ {
go p.worker()
}
p.md5OfParts = md5.New()
p.md5 = md5.New()
p.sp = bufferPool(p.bufsz)
return p, nil
}
func (p *putter) Write(b []byte) (int, error) {
if p.closed {
p.abort()
return 0, syscall.EINVAL
}
if p.err != nil {
p.abort()
return 0, p.err
}
nw := 0
for nw < len(b) {
if p.buf == nil {
p.buf = <-p.sp.get
if int64(cap(p.buf)) < p.bufsz {
p.buf = make([]byte, p.bufsz)
runtime.GC()
}
}
n := copy(p.buf[p.bufbytes:], b[nw:])
p.bufbytes += n
nw += n
if len(p.buf) == p.bufbytes {
p.flush()
}
}
return nw, nil
}
func (p *putter) flush() {
p.wg.Add(1)
p.part++
p.putsz += int64(p.bufbytes)
part := &part{
r: bytes.NewReader(p.buf[:p.bufbytes]),
len: int64(p.bufbytes),
b: p.buf,
PartNumber: p.part,
}
var err error
part.md5, part.sha256, part.ETag, err = p.hashContent(part.r)
if err != nil {
p.err = err
}
p.xml.Part = append(p.xml.Part, part)
p.ch <- part
p.buf, p.bufbytes = nil, 0
// if necessary, double buffer size every 2000 parts due to the 10000-part AWS limit
// to reach the 5 Terabyte max object size, initial part size must be ~85 MB
if p.part%2000 == 0 && p.part < maxNPart && growPartSize(p.part, p.bufsz, p.putsz) {
p.bufsz = min64(p.bufsz*2, maxPartSize)
p.sp.sizech <- p.bufsz // update pool buffer size
logger.debugPrintf("part size doubled to %d", p.bufsz)
}
}
func (p *putter) worker() {
for part := range p.ch {
p.retryPutPart(part)
}
}
// Calls putPart up to nTry times to recover from transient errors.
func (p *putter) retryPutPart(part *part) {
defer p.wg.Done()
var err error
for i := 0; i < p.c.NTry; i++ {
err = p.putPart(part)
if err == nil {
p.sp.give <- part.b
part.b = nil
return
}
logger.debugPrintf("Error on attempt %d: Retrying part: %d, Error: %s", i, part.PartNumber, err)
time.Sleep(time.Duration(math.Exp2(float64(i))) * 100 * time.Millisecond) // exponential back-off
}
p.err = err
}
// uploads a part, checking the etag against the calculated value
func (p *putter) putPart(part *part) error {
v := url.Values{}
v.Set("partNumber", strconv.Itoa(part.PartNumber))
v.Set("uploadId", p.UploadID)
if _, err := part.r.Seek(0, 0); err != nil { // move back to beginning, if retrying
return err
}
req, err := http.NewRequest("PUT", p.url.String()+"?"+v.Encode(), part.r)
if err != nil {
return err
}
req.ContentLength = part.len
req.Header.Set(md5Header, part.md5)
req.Header.Set(sha256Header, part.sha256)
p.b.Sign(req)
resp, err := p.c.Client.Do(req)
if err != nil {
return err
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return newRespError(resp)
}
s := resp.Header.Get("etag")
if len(s) < 2 {
return fmt.Errorf("Got Bad etag:%s", s)
}
s = s[1 : len(s)-1] // includes quote chars for some reason
if part.ETag != s {
return fmt.Errorf("Response etag does not match. Remote:%s Calculated:%s", s, p.ETag)
}
return nil
}
func (p *putter) Close() (err error) {
if p.closed {
p.abort()
return syscall.EINVAL
}
if p.err != nil {
p.abort()
return p.err
}
if p.bufbytes > 0 || // partial part
p.part == 0 { // 0 length file
p.flush()
}
p.wg.Wait()
close(p.ch)
p.closed = true
close(p.sp.quit)
// check p.err before completing
if p.err != nil {
p.abort()
return p.err
}
// Complete Multipart upload
body, err := xml.Marshal(p.xml)
if err != nil {
p.abort()
return
}
b := bytes.NewReader(body)
v := url.Values{}
v.Set("uploadId", p.UploadID)
resp, err := p.retryRequest("POST", p.url.String()+"?"+v.Encode(), b, nil)
if err != nil {
p.abort()
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
p.abort()
return newRespError(resp)
}
// Check md5 hash of concatenated part md5 hashes against ETag
// more info: https://forums.aws.amazon.com/thread.jspa?messageID=456442񯛺
calculatedMd5ofParts := fmt.Sprintf("%x", p.md5OfParts.Sum(nil))
// Parse etag from body of response
err = xml.NewDecoder(resp.Body).Decode(p)
if err != nil {
return
}
// Trim quotes '"' and strip part count from end.
remoteMd5ofParts := strings.Trim(p.ETag, "\"")
remoteMd5ofParts = strings.Split(remoteMd5ofParts, "-")[0]
if len(remoteMd5ofParts) == 0 {
return fmt.Errorf("Nil ETag")
}
if calculatedMd5ofParts != remoteMd5ofParts {
if err != nil {
return err
}
return fmt.Errorf("MD5 hash of part hashes comparison failed. Hash from multipart complete header: %s."+
" Calculated multipart hash: %s.", remoteMd5ofParts, calculatedMd5ofParts)
}
if p.c.Md5Check {
for i := 0; i < p.c.NTry; i++ {
if err = p.putMd5(); err == nil {
break
}
}
}
return
}
// Try to abort multipart upload. Do not error on failure.
func (p *putter) abort() {
v := url.Values{}
v.Set("uploadId", p.UploadID)
s := p.url.String() + "?" + v.Encode()
resp, err := p.retryRequest("DELETE", s, nil, nil)
if err != nil {
logger.Printf("Error aborting multipart upload: %v\n", err)
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 204 {
logger.Printf("Error aborting multipart upload: %v", newRespError(resp))
}
return
}
// Md5 functions
func (p *putter) hashContent(r io.ReadSeeker) (string, string, string, error) {
m := md5.New()
s := sha256.New()
mw := io.MultiWriter(m, s, p.md5)
if _, err := io.Copy(mw, r); err != nil {
return "", "", "", err
}
md5Sum := m.Sum(nil)
shaSum := hex.EncodeToString(s.Sum(nil))
etag := hex.EncodeToString(md5Sum)
// add to checksum of all parts for verification on upload completion
if _, err := p.md5OfParts.Write(md5Sum); err != nil {
return "", "", "", err
}
return base64.StdEncoding.EncodeToString(md5Sum), shaSum, etag, nil
}
// Put md5 file in .md5 subdirectory of bucket where the file is stored
// e.g. the md5 for https://mybucket.s3.amazonaws.com/gof3r will be stored in
// https://mybucket.s3.amazonaws.com/.md5/gof3r.md5
func (p *putter) putMd5() (err error) {
calcMd5 := fmt.Sprintf("%x", p.md5.Sum(nil))
md5Reader := strings.NewReader(calcMd5)
md5Path := fmt.Sprint(".md5", p.url.Path, ".md5")
md5Url, err := p.b.url(md5Path, p.c)
if err != nil {
return err
}
logger.debugPrintln("md5: ", calcMd5)
logger.debugPrintln("md5Path: ", md5Path)
r, err := http.NewRequest("PUT", md5Url.String(), md5Reader)
if err != nil {
return
}
p.b.Sign(r)
resp, err := p.c.Client.Do(r)
if err != nil {
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return newRespError(resp)
}
return
}
func (p *putter) retryRequest(method, urlStr string, body io.ReadSeeker, h http.Header) (resp *http.Response, err error) {
for i := 0; i < p.c.NTry; i++ {
var req *http.Request
req, err = http.NewRequest(method, urlStr, body)
if err != nil {
return
}
for k := range h {
for _, v := range h[k] {
req.Header.Add(k, v)
}
}
if body != nil {
req.Header.Set(sha256Header, shaReader(body))
}
p.b.Sign(req)
resp, err = p.c.Client.Do(req)
if err == nil {
return
}
logger.debugPrintln(err)
if body != nil {
if _, err = body.Seek(0, 0); err != nil {
return
}
}
}
return
}
// returns true unless partSize is large enough
// to achieve maxObjSize with remaining parts
func growPartSize(partIndex int, partSize, putsz int64) bool {
return (maxObjSize-putsz)/(maxNPart-int64(partIndex)) > partSize
}