| 1 |
package oss |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/hmac" |
| 6 |
"crypto/md5" |
| 7 |
"crypto/sha1" |
| 8 |
"encoding/base64" |
| 9 |
"encoding/xml" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"io/ioutil" |
| 13 |
"log" |
| 14 |
"mime" |
| 15 |
"net" |
| 16 |
"net/http" |
| 17 |
"net/http/httputil" |
| 18 |
"net/url" |
| 19 |
"os" |
| 20 |
"path" |
| 21 |
"strconv" |
| 22 |
"strings" |
| 23 |
"time" |
| 24 |
|
| 25 |
"github.com/denverdino/aliyungo/common" |
| 26 |
"github.com/denverdino/aliyungo/util" |
| 27 |
) |
| 28 |
|
| 29 |
const DefaultContentType = "application/octet-stream" |
| 30 |
|
| 31 |
|
| 32 |
type Client struct { |
| 33 |
AccessKeyId string |
| 34 |
AccessKeySecret string |
| 35 |
SecurityToken string |
| 36 |
Region Region |
| 37 |
Internal bool |
| 38 |
Secure bool |
| 39 |
ConnectTimeout time.Duration |
| 40 |
|
| 41 |
endpoint string |
| 42 |
debug bool |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
type Bucket struct { |
| 47 |
*Client |
| 48 |
Name string |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
type Owner struct { |
| 53 |
ID string |
| 54 |
DisplayName string |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
type Options struct { |
| 60 |
ServerSideEncryption bool |
| 61 |
Meta map[string][]string |
| 62 |
ContentEncoding string |
| 63 |
CacheControl string |
| 64 |
ContentMD5 string |
| 65 |
ContentDisposition string |
| 66 |
|
| 67 |
|
| 68 |
} |
| 69 |
|
| 70 |
type CopyOptions struct { |
| 71 |
Headers http.Header |
| 72 |
CopySourceOptions string |
| 73 |
MetadataDirective string |
| 74 |
|
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
type CopyObjectResult struct { |
| 79 |
ETag string |
| 80 |
LastModified string |
| 81 |
} |
| 82 |
|
| 83 |
var attempts = util.AttemptStrategy{ |
| 84 |
Min: 5, |
| 85 |
Total: 5 * time.Second, |
| 86 |
Delay: 200 * time.Millisecond, |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
func NewOSSClientForAssumeRole(region Region, internal bool, accessKeyId string, accessKeySecret string, securityToken string, secure bool) *Client { |
| 92 |
return &Client{ |
| 93 |
AccessKeyId: accessKeyId, |
| 94 |
AccessKeySecret: accessKeySecret, |
| 95 |
SecurityToken: securityToken, |
| 96 |
Region: region, |
| 97 |
Internal: internal, |
| 98 |
debug: false, |
| 99 |
Secure: secure, |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
func NewOSSClient(region Region, internal bool, accessKeyId string, accessKeySecret string, secure bool) *Client { |
| 104 |
return &Client{ |
| 105 |
AccessKeyId: accessKeyId, |
| 106 |
AccessKeySecret: accessKeySecret, |
| 107 |
Region: region, |
| 108 |
Internal: internal, |
| 109 |
debug: false, |
| 110 |
Secure: secure, |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
func (client *Client) SetDebug(debug bool) { |
| 116 |
client.debug = debug |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
func (client *Client) Bucket(name string) *Bucket { |
| 121 |
name = strings.ToLower(name) |
| 122 |
return &Bucket{ |
| 123 |
Client: client, |
| 124 |
Name: name, |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
type BucketInfo struct { |
| 129 |
Name string |
| 130 |
CreationDate string |
| 131 |
ExtranetEndpoint string |
| 132 |
IntranetEndpoint string |
| 133 |
Location string |
| 134 |
Grant string `xml:"AccessControlList>Grant"` |
| 135 |
} |
| 136 |
|
| 137 |
type GetServiceResp struct { |
| 138 |
Owner Owner |
| 139 |
Buckets []BucketInfo `xml:">Bucket"` |
| 140 |
} |
| 141 |
|
| 142 |
type GetBucketInfoResp struct { |
| 143 |
Bucket BucketInfo |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
func (client *Client) GetService() (*GetServiceResp, error) { |
| 148 |
bucket := client.Bucket("") |
| 149 |
|
| 150 |
r, err := bucket.Get("") |
| 151 |
if err != nil { |
| 152 |
return nil, err |
| 153 |
} |
| 154 |
|
| 155 |
|
| 156 |
var resp GetServiceResp |
| 157 |
if err = xml.Unmarshal(r, &resp); err != nil { |
| 158 |
return nil, err |
| 159 |
} |
| 160 |
|
| 161 |
return &resp, nil |
| 162 |
} |
| 163 |
|
| 164 |
type ACL string |
| 165 |
|
| 166 |
const ( |
| 167 |
Private = ACL("private") |
| 168 |
PublicRead = ACL("public-read") |
| 169 |
PublicReadWrite = ACL("public-read-write") |
| 170 |
AuthenticatedRead = ACL("authenticated-read") |
| 171 |
BucketOwnerRead = ACL("bucket-owner-read") |
| 172 |
BucketOwnerFull = ACL("bucket-owner-full-control") |
| 173 |
) |
| 174 |
|
| 175 |
var createBucketConfiguration = `<CreateBucketConfiguration> |
| 176 |
<LocationConstraint>%s</LocationConstraint> |
| 177 |
</CreateBucketConfiguration>` |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
func (client *Client) locationConstraint() io.Reader { |
| 182 |
constraint := fmt.Sprintf(createBucketConfiguration, client.Region) |
| 183 |
return strings.NewReader(constraint) |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
func (client *Client) SetEndpoint(endpoint string) { |
| 188 |
|
| 189 |
client.endpoint = endpoint |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
func (b *Bucket) Info() (BucketInfo, error) { |
| 196 |
params := make(url.Values) |
| 197 |
params.Set("bucketInfo", "") |
| 198 |
r, err := b.GetWithParams("/", params) |
| 199 |
|
| 200 |
if err != nil { |
| 201 |
return BucketInfo{}, err |
| 202 |
} |
| 203 |
|
| 204 |
|
| 205 |
var resp GetBucketInfoResp |
| 206 |
if err = xml.Unmarshal(r, &resp); err != nil { |
| 207 |
return BucketInfo{}, err |
| 208 |
} |
| 209 |
|
| 210 |
return resp.Bucket, nil |
| 211 |
} |
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
func (b *Bucket) PutBucket(perm ACL) error { |
| 217 |
headers := make(http.Header) |
| 218 |
if perm != "" { |
| 219 |
headers.Set("x-oss-acl", string(perm)) |
| 220 |
} |
| 221 |
req := &request{ |
| 222 |
method: "PUT", |
| 223 |
bucket: b.Name, |
| 224 |
path: "/", |
| 225 |
headers: headers, |
| 226 |
payload: b.Client.locationConstraint(), |
| 227 |
} |
| 228 |
return b.Client.query(req, nil) |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
func (b *Bucket) DelBucket() (err error) { |
| 236 |
for attempt := attempts.Start(); attempt.Next(); { |
| 237 |
req := &request{ |
| 238 |
method: "DELETE", |
| 239 |
bucket: b.Name, |
| 240 |
path: "/", |
| 241 |
} |
| 242 |
|
| 243 |
err = b.Client.query(req, nil) |
| 244 |
if !shouldRetry(err) { |
| 245 |
break |
| 246 |
} |
| 247 |
} |
| 248 |
return err |
| 249 |
} |
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
func (b *Bucket) Get(path string) (data []byte, err error) { |
| 255 |
body, err := b.GetReader(path) |
| 256 |
if err != nil { |
| 257 |
return nil, err |
| 258 |
} |
| 259 |
data, err = ioutil.ReadAll(body) |
| 260 |
body.Close() |
| 261 |
return data, err |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
func (b *Bucket) GetReader(path string) (rc io.ReadCloser, err error) { |
| 269 |
resp, err := b.GetResponse(path) |
| 270 |
if resp != nil { |
| 271 |
return resp.Body, err |
| 272 |
} |
| 273 |
return nil, err |
| 274 |
} |
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
func (b *Bucket) GetResponse(path string) (resp *http.Response, err error) { |
| 281 |
return b.GetResponseWithHeaders(path, make(http.Header)) |
| 282 |
} |
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
func (b *Bucket) GetResponseWithHeaders(path string, headers http.Header) (resp *http.Response, err error) { |
| 290 |
for attempt := attempts.Start(); attempt.Next(); { |
| 291 |
req := &request{ |
| 292 |
bucket: b.Name, |
| 293 |
path: path, |
| 294 |
headers: headers, |
| 295 |
} |
| 296 |
err = b.Client.prepare(req) |
| 297 |
if err != nil { |
| 298 |
return nil, err |
| 299 |
} |
| 300 |
|
| 301 |
resp, err := b.Client.run(req, nil) |
| 302 |
if shouldRetry(err) && attempt.HasNext() { |
| 303 |
continue |
| 304 |
} |
| 305 |
if err != nil { |
| 306 |
return nil, err |
| 307 |
} |
| 308 |
return resp, nil |
| 309 |
} |
| 310 |
panic("unreachable") |
| 311 |
} |
| 312 |
|
| 313 |
|
| 314 |
func (b *Bucket) GetWithParams(path string, params url.Values) (data []byte, err error) { |
| 315 |
resp, err := b.GetResponseWithParamsAndHeaders(path, params, nil) |
| 316 |
if err != nil { |
| 317 |
return nil, err |
| 318 |
} |
| 319 |
data, err = ioutil.ReadAll(resp.Body) |
| 320 |
resp.Body.Close() |
| 321 |
return data, err |
| 322 |
} |
| 323 |
|
| 324 |
func (b *Bucket) GetResponseWithParamsAndHeaders(path string, params url.Values, headers http.Header) (resp *http.Response, err error) { |
| 325 |
for attempt := attempts.Start(); attempt.Next(); { |
| 326 |
req := &request{ |
| 327 |
bucket: b.Name, |
| 328 |
path: path, |
| 329 |
params: params, |
| 330 |
headers: headers, |
| 331 |
} |
| 332 |
err = b.Client.prepare(req) |
| 333 |
if err != nil { |
| 334 |
return nil, err |
| 335 |
} |
| 336 |
|
| 337 |
resp, err := b.Client.run(req, nil) |
| 338 |
if shouldRetry(err) && attempt.HasNext() { |
| 339 |
continue |
| 340 |
} |
| 341 |
if err != nil { |
| 342 |
return nil, err |
| 343 |
} |
| 344 |
return resp, nil |
| 345 |
} |
| 346 |
panic("unreachable") |
| 347 |
} |
| 348 |
|
| 349 |
|
| 350 |
func (b *Bucket) Exists(path string) (exists bool, err error) { |
| 351 |
for attempt := attempts.Start(); attempt.Next(); { |
| 352 |
req := &request{ |
| 353 |
method: "HEAD", |
| 354 |
bucket: b.Name, |
| 355 |
path: path, |
| 356 |
} |
| 357 |
err = b.Client.prepare(req) |
| 358 |
if err != nil { |
| 359 |
return |
| 360 |
} |
| 361 |
|
| 362 |
resp, err := b.Client.run(req, nil) |
| 363 |
|
| 364 |
if shouldRetry(err) && attempt.HasNext() { |
| 365 |
continue |
| 366 |
} |
| 367 |
|
| 368 |
if err != nil { |
| 369 |
|
| 370 |
if e, ok := err.(*Error); ok && (e.StatusCode == 403 || e.StatusCode == 404) { |
| 371 |
return false, nil |
| 372 |
} |
| 373 |
return false, err |
| 374 |
} |
| 375 |
|
| 376 |
if resp.StatusCode/100 == 2 { |
| 377 |
exists = true |
| 378 |
} |
| 379 |
if resp.Body != nil { |
| 380 |
resp.Body.Close() |
| 381 |
} |
| 382 |
return exists, err |
| 383 |
} |
| 384 |
return false, fmt.Errorf("OSS Currently Unreachable") |
| 385 |
} |
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
func (b *Bucket) Head(path string, headers http.Header) (*http.Response, error) { |
| 391 |
|
| 392 |
for attempt := attempts.Start(); attempt.Next(); { |
| 393 |
req := &request{ |
| 394 |
method: "HEAD", |
| 395 |
bucket: b.Name, |
| 396 |
path: path, |
| 397 |
headers: headers, |
| 398 |
} |
| 399 |
err := b.Client.prepare(req) |
| 400 |
if err != nil { |
| 401 |
return nil, err |
| 402 |
} |
| 403 |
|
| 404 |
resp, err := b.Client.run(req, nil) |
| 405 |
if shouldRetry(err) && attempt.HasNext() { |
| 406 |
continue |
| 407 |
} |
| 408 |
if err != nil { |
| 409 |
return nil, err |
| 410 |
} |
| 411 |
if resp != nil && resp.Body != nil { |
| 412 |
resp.Body.Close() |
| 413 |
} |
| 414 |
return resp, err |
| 415 |
} |
| 416 |
return nil, fmt.Errorf("OSS Currently Unreachable") |
| 417 |
} |
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
func (b *Bucket) Put(path string, data []byte, contType string, perm ACL, options Options) error { |
| 423 |
body := bytes.NewBuffer(data) |
| 424 |
return b.PutReader(path, body, int64(len(data)), contType, perm, options) |
| 425 |
} |
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
func (b *Bucket) PutCopy(path string, perm ACL, options CopyOptions, source string) (*CopyObjectResult, error) { |
| 431 |
headers := make(http.Header) |
| 432 |
|
| 433 |
headers.Set("x-oss-object-acl", string(perm)) |
| 434 |
headers.Set("x-oss-copy-source", source) |
| 435 |
|
| 436 |
options.addHeaders(headers) |
| 437 |
req := &request{ |
| 438 |
method: "PUT", |
| 439 |
bucket: b.Name, |
| 440 |
path: path, |
| 441 |
headers: headers, |
| 442 |
timeout: 5 * time.Minute, |
| 443 |
} |
| 444 |
resp := &CopyObjectResult{} |
| 445 |
err := b.Client.query(req, resp) |
| 446 |
if err != nil { |
| 447 |
return resp, err |
| 448 |
} |
| 449 |
return resp, nil |
| 450 |
} |
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
func (b *Bucket) PutReader(path string, r io.Reader, length int64, contType string, perm ACL, options Options) error { |
| 455 |
headers := make(http.Header) |
| 456 |
headers.Set("Content-Length", strconv.FormatInt(length, 10)) |
| 457 |
headers.Set("Content-Type", contType) |
| 458 |
headers.Set("x-oss-object-acl", string(perm)) |
| 459 |
|
| 460 |
options.addHeaders(headers) |
| 461 |
req := &request{ |
| 462 |
method: "PUT", |
| 463 |
bucket: b.Name, |
| 464 |
path: path, |
| 465 |
headers: headers, |
| 466 |
payload: r, |
| 467 |
} |
| 468 |
return b.Client.query(req, nil) |
| 469 |
} |
| 470 |
|
| 471 |
|
| 472 |
func (b *Bucket) PutFile(path string, file *os.File, perm ACL, options Options) error { |
| 473 |
var contentType string |
| 474 |
if dotPos := strings.LastIndex(file.Name(), "."); dotPos == -1 { |
| 475 |
contentType = DefaultContentType |
| 476 |
} else { |
| 477 |
if mimeType := mime.TypeByExtension(file.Name()[dotPos:]); mimeType == "" { |
| 478 |
contentType = DefaultContentType |
| 479 |
} else { |
| 480 |
contentType = mimeType |
| 481 |
} |
| 482 |
} |
| 483 |
stats, err := file.Stat() |
| 484 |
if err != nil { |
| 485 |
log.Printf("Unable to read file %s stats.\n", file.Name()) |
| 486 |
return err |
| 487 |
} |
| 488 |
|
| 489 |
return b.PutReader(path, file, stats.Size(), contentType, perm, options) |
| 490 |
} |
| 491 |
|
| 492 |
|
| 493 |
func (o Options) addHeaders(headers http.Header) { |
| 494 |
if o.ServerSideEncryption { |
| 495 |
headers.Set("x-oss-server-side-encryption", "AES256") |
| 496 |
} |
| 497 |
if len(o.ContentEncoding) != 0 { |
| 498 |
headers.Set("Content-Encoding", o.ContentEncoding) |
| 499 |
} |
| 500 |
if len(o.CacheControl) != 0 { |
| 501 |
headers.Set("Cache-Control", o.CacheControl) |
| 502 |
} |
| 503 |
if len(o.ContentMD5) != 0 { |
| 504 |
headers.Set("Content-MD5", o.ContentMD5) |
| 505 |
} |
| 506 |
if len(o.ContentDisposition) != 0 { |
| 507 |
headers.Set("Content-Disposition", o.ContentDisposition) |
| 508 |
} |
| 509 |
|
| 510 |
for k, v := range o.Meta { |
| 511 |
for _, mv := range v { |
| 512 |
headers.Add("x-oss-meta-"+k, mv) |
| 513 |
} |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
func (o CopyOptions) addHeaders(headers http.Header) { |
| 519 |
if len(o.MetadataDirective) != 0 { |
| 520 |
headers.Set("x-oss-metadata-directive", o.MetadataDirective) |
| 521 |
} |
| 522 |
if len(o.CopySourceOptions) != 0 { |
| 523 |
headers.Set("x-oss-copy-source-range", o.CopySourceOptions) |
| 524 |
} |
| 525 |
if o.Headers != nil { |
| 526 |
for k, v := range o.Headers { |
| 527 |
newSlice := make([]string, len(v)) |
| 528 |
copy(newSlice, v) |
| 529 |
headers[k] = newSlice |
| 530 |
} |
| 531 |
} |
| 532 |
} |
| 533 |
|
| 534 |
func makeXMLBuffer(doc []byte) *bytes.Buffer { |
| 535 |
buf := new(bytes.Buffer) |
| 536 |
buf.WriteString(xml.Header) |
| 537 |
buf.Write(doc) |
| 538 |
return buf |
| 539 |
} |
| 540 |
|
| 541 |
type IndexDocument struct { |
| 542 |
Suffix string `xml:"Suffix"` |
| 543 |
} |
| 544 |
|
| 545 |
type ErrorDocument struct { |
| 546 |
Key string `xml:"Key"` |
| 547 |
} |
| 548 |
|
| 549 |
type RoutingRule struct { |
| 550 |
ConditionKeyPrefixEquals string `xml:"Condition>KeyPrefixEquals"` |
| 551 |
RedirectReplaceKeyPrefixWith string `xml:"Redirect>ReplaceKeyPrefixWith,omitempty"` |
| 552 |
RedirectReplaceKeyWith string `xml:"Redirect>ReplaceKeyWith,omitempty"` |
| 553 |
} |
| 554 |
|
| 555 |
type RedirectAllRequestsTo struct { |
| 556 |
HostName string `xml:"HostName"` |
| 557 |
Protocol string `xml:"Protocol,omitempty"` |
| 558 |
} |
| 559 |
|
| 560 |
type WebsiteConfiguration struct { |
| 561 |
XMLName xml.Name `xml:"http://doc.oss-cn-hangzhou.aliyuncs.com WebsiteConfiguration"` |
| 562 |
IndexDocument *IndexDocument `xml:"IndexDocument,omitempty"` |
| 563 |
ErrorDocument *ErrorDocument `xml:"ErrorDocument,omitempty"` |
| 564 |
RoutingRules *[]RoutingRule `xml:"RoutingRules>RoutingRule,omitempty"` |
| 565 |
RedirectAllRequestsTo *RedirectAllRequestsTo `xml:"RedirectAllRequestsTo,omitempty"` |
| 566 |
} |
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
func (b *Bucket) PutBucketWebsite(configuration WebsiteConfiguration) error { |
| 572 |
doc, err := xml.Marshal(configuration) |
| 573 |
if err != nil { |
| 574 |
return err |
| 575 |
} |
| 576 |
|
| 577 |
buf := makeXMLBuffer(doc) |
| 578 |
|
| 579 |
return b.PutBucketSubresource("website", buf, int64(buf.Len())) |
| 580 |
} |
| 581 |
|
| 582 |
func (b *Bucket) PutBucketSubresource(subresource string, r io.Reader, length int64) error { |
| 583 |
headers := make(http.Header) |
| 584 |
headers.Set("Content-Length", strconv.FormatInt(length, 10)) |
| 585 |
|
| 586 |
req := &request{ |
| 587 |
path: "/", |
| 588 |
method: "PUT", |
| 589 |
bucket: b.Name, |
| 590 |
headers: headers, |
| 591 |
payload: r, |
| 592 |
params: url.Values{subresource: {""}}, |
| 593 |
} |
| 594 |
|
| 595 |
return b.Client.query(req, nil) |
| 596 |
} |
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
func (b *Bucket) Del(path string) error { |
| 602 |
req := &request{ |
| 603 |
method: "DELETE", |
| 604 |
bucket: b.Name, |
| 605 |
path: path, |
| 606 |
} |
| 607 |
return b.Client.query(req, nil) |
| 608 |
} |
| 609 |
|
| 610 |
type Delete struct { |
| 611 |
Quiet bool `xml:"Quiet,omitempty"` |
| 612 |
Objects []Object `xml:"Object"` |
| 613 |
} |
| 614 |
|
| 615 |
type Object struct { |
| 616 |
Key string `xml:"Key"` |
| 617 |
VersionId string `xml:"VersionId,omitempty"` |
| 618 |
} |
| 619 |
|
| 620 |
|
| 621 |
|
| 622 |
|
| 623 |
func (b *Bucket) DelMulti(objects Delete) error { |
| 624 |
doc, err := xml.Marshal(objects) |
| 625 |
if err != nil { |
| 626 |
return err |
| 627 |
} |
| 628 |
|
| 629 |
buf := makeXMLBuffer(doc) |
| 630 |
digest := md5.New() |
| 631 |
size, err := digest.Write(buf.Bytes()) |
| 632 |
if err != nil { |
| 633 |
return err |
| 634 |
} |
| 635 |
|
| 636 |
headers := make(http.Header) |
| 637 |
headers.Set("Content-Length", strconv.FormatInt(int64(size), 10)) |
| 638 |
headers.Set("Content-MD5", base64.StdEncoding.EncodeToString(digest.Sum(nil))) |
| 639 |
headers.Set("Content-Type", "text/xml") |
| 640 |
|
| 641 |
req := &request{ |
| 642 |
path: "/", |
| 643 |
method: "POST", |
| 644 |
params: url.Values{"delete": {""}}, |
| 645 |
bucket: b.Name, |
| 646 |
headers: headers, |
| 647 |
payload: buf, |
| 648 |
} |
| 649 |
|
| 650 |
return b.Client.query(req, nil) |
| 651 |
} |
| 652 |
|
| 653 |
|
| 654 |
type ListResp struct { |
| 655 |
Name string |
| 656 |
Prefix string |
| 657 |
Delimiter string |
| 658 |
Marker string |
| 659 |
MaxKeys int |
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
IsTruncated bool |
| 665 |
Contents []Key |
| 666 |
CommonPrefixes []string `xml:">Prefix"` |
| 667 |
|
| 668 |
|
| 669 |
NextMarker string |
| 670 |
} |
| 671 |
|
| 672 |
|
| 673 |
type Key struct { |
| 674 |
Key string |
| 675 |
LastModified string |
| 676 |
Type string |
| 677 |
Size int64 |
| 678 |
|
| 679 |
|
| 680 |
ETag string |
| 681 |
StorageClass string |
| 682 |
Owner Owner |
| 683 |
} |
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
func (b *Bucket) List(prefix, delim, marker string, max int) (result *ListResp, err error) { |
| 743 |
params := make(url.Values) |
| 744 |
params.Set("prefix", prefix) |
| 745 |
params.Set("delimiter", delim) |
| 746 |
params.Set("marker", marker) |
| 747 |
if max != 0 { |
| 748 |
params.Set("max-keys", strconv.FormatInt(int64(max), 10)) |
| 749 |
} |
| 750 |
result = &ListResp{} |
| 751 |
for attempt := attempts.Start(); attempt.Next(); { |
| 752 |
req := &request{ |
| 753 |
bucket: b.Name, |
| 754 |
params: params, |
| 755 |
} |
| 756 |
err = b.Client.query(req, result) |
| 757 |
if !shouldRetry(err) { |
| 758 |
break |
| 759 |
} |
| 760 |
} |
| 761 |
if err != nil { |
| 762 |
return nil, err |
| 763 |
} |
| 764 |
|
| 765 |
|
| 766 |
if result.IsTruncated && result.NextMarker == "" { |
| 767 |
n := len(result.Contents) |
| 768 |
if n > 0 { |
| 769 |
result.NextMarker = result.Contents[n-1].Key |
| 770 |
} |
| 771 |
} |
| 772 |
return result, nil |
| 773 |
} |
| 774 |
|
| 775 |
type GetLocationResp struct { |
| 776 |
Location string `xml:",innerxml"` |
| 777 |
} |
| 778 |
|
| 779 |
func (b *Bucket) Location() (string, error) { |
| 780 |
params := make(url.Values) |
| 781 |
params.Set("location", "") |
| 782 |
r, err := b.GetWithParams("/", params) |
| 783 |
|
| 784 |
if err != nil { |
| 785 |
return "", err |
| 786 |
} |
| 787 |
|
| 788 |
|
| 789 |
var resp GetLocationResp |
| 790 |
if err = xml.Unmarshal(r, &resp); err != nil { |
| 791 |
return "", err |
| 792 |
} |
| 793 |
|
| 794 |
if resp.Location == "" { |
| 795 |
return string(Hangzhou), nil |
| 796 |
} |
| 797 |
return resp.Location, nil |
| 798 |
} |
| 799 |
|
| 800 |
func (b *Bucket) Path(path string) string { |
| 801 |
if !strings.HasPrefix(path, "/") { |
| 802 |
path = "/" + path |
| 803 |
} |
| 804 |
return "/" + b.Name + path |
| 805 |
} |
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
func (b *Bucket) URL(path string) string { |
| 811 |
req := &request{ |
| 812 |
bucket: b.Name, |
| 813 |
path: path, |
| 814 |
} |
| 815 |
err := b.Client.prepare(req) |
| 816 |
if err != nil { |
| 817 |
panic(err) |
| 818 |
} |
| 819 |
u, err := req.url() |
| 820 |
if err != nil { |
| 821 |
panic(err) |
| 822 |
} |
| 823 |
u.RawQuery = "" |
| 824 |
return u.String() |
| 825 |
} |
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
func (b *Bucket) SignedURL(path string, expires time.Time) string { |
| 830 |
return b.SignedURLWithArgs(path, expires, nil, nil) |
| 831 |
} |
| 832 |
|
| 833 |
|
| 834 |
|
| 835 |
func (b *Bucket) SignedURLWithArgs(path string, expires time.Time, params url.Values, headers http.Header) string { |
| 836 |
return b.SignedURLWithMethod("GET", path, expires, params, headers) |
| 837 |
} |
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
func (b *Bucket) SignedURLWithMethod(method, path string, expires time.Time, params url.Values, headers http.Header) string { |
| 842 |
var uv = url.Values{} |
| 843 |
|
| 844 |
if params != nil { |
| 845 |
uv = params |
| 846 |
} |
| 847 |
|
| 848 |
uv.Set("Expires", strconv.FormatInt(expires.Unix(), 10)) |
| 849 |
uv.Set("OSSAccessKeyId", b.AccessKeyId) |
| 850 |
|
| 851 |
req := &request{ |
| 852 |
method: method, |
| 853 |
bucket: b.Name, |
| 854 |
path: path, |
| 855 |
params: uv, |
| 856 |
headers: headers, |
| 857 |
} |
| 858 |
err := b.Client.prepare(req) |
| 859 |
if err != nil { |
| 860 |
panic(err) |
| 861 |
} |
| 862 |
u, err := req.url() |
| 863 |
if err != nil { |
| 864 |
panic(err) |
| 865 |
} |
| 866 |
|
| 867 |
return u.String() |
| 868 |
} |
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
func (b *Bucket) UploadSignedURL(name, method, contentType string, expires time.Time) string { |
| 875 |
|
| 876 |
expireDate := expires.Unix() |
| 877 |
if method != "POST" { |
| 878 |
method = "PUT" |
| 879 |
} |
| 880 |
|
| 881 |
tokenData := "" |
| 882 |
|
| 883 |
stringToSign := method + "\n\n" + contentType + "\n" + strconv.FormatInt(expireDate, 10) + "\n" + tokenData + "/" + path.Join(b.Name, name) |
| 884 |
secretKey := b.AccessKeySecret |
| 885 |
accessId := b.AccessKeyId |
| 886 |
mac := hmac.New(sha1.New, []byte(secretKey)) |
| 887 |
mac.Write([]byte(stringToSign)) |
| 888 |
macsum := mac.Sum(nil) |
| 889 |
signature := base64.StdEncoding.EncodeToString(macsum) |
| 890 |
signature = strings.TrimSpace(signature) |
| 891 |
|
| 892 |
signedurl, err := url.Parse(b.Region.GetEndpoint(b.Internal, b.Name, b.Secure)) |
| 893 |
if err != nil { |
| 894 |
log.Println("ERROR sining url for OSS upload", err) |
| 895 |
return "" |
| 896 |
} |
| 897 |
signedurl.Path = name |
| 898 |
params := url.Values{} |
| 899 |
params.Add("OSSAccessKeyId", accessId) |
| 900 |
params.Add("Expires", strconv.FormatInt(expireDate, 10)) |
| 901 |
params.Add("Signature", signature) |
| 902 |
|
| 903 |
signedurl.RawQuery = params.Encode() |
| 904 |
return signedurl.String() |
| 905 |
} |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
func (b *Bucket) PostFormArgsEx(path string, expires time.Time, redirect string, conds []string) (action string, fields map[string]string) { |
| 911 |
conditions := []string{} |
| 912 |
fields = map[string]string{ |
| 913 |
"AWSAccessKeyId": b.AccessKeyId, |
| 914 |
"key": path, |
| 915 |
} |
| 916 |
|
| 917 |
if conds != nil { |
| 918 |
conditions = append(conditions, conds...) |
| 919 |
} |
| 920 |
|
| 921 |
conditions = append(conditions, fmt.Sprintf("{\"key\": \"%s\"}", path)) |
| 922 |
conditions = append(conditions, fmt.Sprintf("{\"bucket\": \"%s\"}", b.Name)) |
| 923 |
if redirect != "" { |
| 924 |
conditions = append(conditions, fmt.Sprintf("{\"success_action_redirect\": \"%s\"}", redirect)) |
| 925 |
fields["success_action_redirect"] = redirect |
| 926 |
} |
| 927 |
|
| 928 |
vExpiration := expires.Format("2006-01-02T15:04:05Z") |
| 929 |
vConditions := strings.Join(conditions, ",") |
| 930 |
policy := fmt.Sprintf("{\"expiration\": \"%s\", \"conditions\": [%s]}", vExpiration, vConditions) |
| 931 |
policy64 := base64.StdEncoding.EncodeToString([]byte(policy)) |
| 932 |
fields["policy"] = policy64 |
| 933 |
|
| 934 |
signer := hmac.New(sha1.New, []byte(b.AccessKeySecret)) |
| 935 |
signer.Write([]byte(policy64)) |
| 936 |
fields["signature"] = base64.StdEncoding.EncodeToString(signer.Sum(nil)) |
| 937 |
|
| 938 |
action = fmt.Sprintf("%s/%s/", b.Client.Region, b.Name) |
| 939 |
return |
| 940 |
} |
| 941 |
|
| 942 |
|
| 943 |
|
| 944 |
func (b *Bucket) PostFormArgs(path string, expires time.Time, redirect string) (action string, fields map[string]string) { |
| 945 |
return b.PostFormArgsEx(path, expires, redirect, nil) |
| 946 |
} |
| 947 |
|
| 948 |
type request struct { |
| 949 |
method string |
| 950 |
bucket string |
| 951 |
path string |
| 952 |
params url.Values |
| 953 |
headers http.Header |
| 954 |
baseurl string |
| 955 |
payload io.Reader |
| 956 |
prepared bool |
| 957 |
timeout time.Duration |
| 958 |
} |
| 959 |
|
| 960 |
func (req *request) url() (*url.URL, error) { |
| 961 |
u, err := url.Parse(req.baseurl) |
| 962 |
if err != nil { |
| 963 |
return nil, fmt.Errorf("bad OSS endpoint URL %q: %v", req.baseurl, err) |
| 964 |
} |
| 965 |
u.RawQuery = req.params.Encode() |
| 966 |
u.Path = req.path |
| 967 |
return u, nil |
| 968 |
} |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
func (client *Client) query(req *request, resp interface{}) error { |
| 974 |
err := client.prepare(req) |
| 975 |
if err != nil { |
| 976 |
return err |
| 977 |
} |
| 978 |
r, err := client.run(req, resp) |
| 979 |
if r != nil && r.Body != nil { |
| 980 |
r.Body.Close() |
| 981 |
} |
| 982 |
return err |
| 983 |
} |
| 984 |
|
| 985 |
|
| 986 |
func (client *Client) setBaseURL(req *request) error { |
| 987 |
|
| 988 |
if client.endpoint == "" { |
| 989 |
req.baseurl = client.Region.GetEndpoint(client.Internal, req.bucket, client.Secure) |
| 990 |
} else { |
| 991 |
req.baseurl = fmt.Sprintf("%s://%s", getProtocol(client.Secure), client.endpoint) |
| 992 |
} |
| 993 |
|
| 994 |
return nil |
| 995 |
} |
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
|
| 1010 |
func partiallyEscapedPath(path string) string { |
| 1011 |
pathEscapedAndSplit := strings.Split((&url.URL{Path: path}).String(), "/") |
| 1012 |
if len(pathEscapedAndSplit) >= 3 { |
| 1013 |
if len(pathEscapedAndSplit[2]) >= 3 { |
| 1014 |
|
| 1015 |
if pathEscapedAndSplit[2][0:3] == "%3F" { |
| 1016 |
pathEscapedAndSplit[2] = "?" + pathEscapedAndSplit[2][3:] |
| 1017 |
} |
| 1018 |
} |
| 1019 |
} |
| 1020 |
return strings.Replace(strings.Join(pathEscapedAndSplit, "/"), "+", "%2B", -1) |
| 1021 |
} |
| 1022 |
|
| 1023 |
|
| 1024 |
func (client *Client) prepare(req *request) error { |
| 1025 |
|
| 1026 |
headers := copyHeader(req.headers) |
| 1027 |
if len(client.SecurityToken) != 0 { |
| 1028 |
headers.Set("x-oss-security-token", client.SecurityToken) |
| 1029 |
} |
| 1030 |
|
| 1031 |
params := make(url.Values) |
| 1032 |
|
| 1033 |
for k, v := range req.params { |
| 1034 |
params[k] = v |
| 1035 |
} |
| 1036 |
|
| 1037 |
req.params = params |
| 1038 |
req.headers = headers |
| 1039 |
|
| 1040 |
if !req.prepared { |
| 1041 |
req.prepared = true |
| 1042 |
if req.method == "" { |
| 1043 |
req.method = "GET" |
| 1044 |
} |
| 1045 |
|
| 1046 |
if !strings.HasPrefix(req.path, "/") { |
| 1047 |
req.path = "/" + req.path |
| 1048 |
} |
| 1049 |
|
| 1050 |
err := client.setBaseURL(req) |
| 1051 |
if err != nil { |
| 1052 |
return err |
| 1053 |
} |
| 1054 |
} |
| 1055 |
|
| 1056 |
req.headers.Set("Date", util.GetGMTime()) |
| 1057 |
client.signRequest(req) |
| 1058 |
|
| 1059 |
return nil |
| 1060 |
} |
| 1061 |
|
| 1062 |
|
| 1063 |
func (client *Client) setupHttpRequest(req *request) (*http.Request, error) { |
| 1064 |
|
| 1065 |
|
| 1066 |
u, err := req.url() |
| 1067 |
if err != nil { |
| 1068 |
return nil, err |
| 1069 |
} |
| 1070 |
u.Opaque = fmt.Sprintf("//%s%s", u.Host, partiallyEscapedPath(u.Path)) |
| 1071 |
|
| 1072 |
hreq := http.Request{ |
| 1073 |
URL: u, |
| 1074 |
Method: req.method, |
| 1075 |
ProtoMajor: 1, |
| 1076 |
ProtoMinor: 1, |
| 1077 |
Close: true, |
| 1078 |
Header: req.headers, |
| 1079 |
Form: req.params, |
| 1080 |
} |
| 1081 |
|
| 1082 |
hreq.Header.Set("X-SDK-Client", `AliyunGO/`+common.Version) |
| 1083 |
|
| 1084 |
contentLength := req.headers.Get("Content-Length") |
| 1085 |
|
| 1086 |
if contentLength != "" { |
| 1087 |
hreq.ContentLength, _ = strconv.ParseInt(contentLength, 10, 64) |
| 1088 |
req.headers.Del("Content-Length") |
| 1089 |
} |
| 1090 |
|
| 1091 |
if req.payload != nil { |
| 1092 |
hreq.Body = ioutil.NopCloser(req.payload) |
| 1093 |
} |
| 1094 |
|
| 1095 |
return &hreq, nil |
| 1096 |
} |
| 1097 |
|
| 1098 |
|
| 1099 |
|
| 1100 |
|
| 1101 |
func (client *Client) doHttpRequest(c *http.Client, hreq *http.Request, resp interface{}) (*http.Response, error) { |
| 1102 |
|
| 1103 |
if client.debug { |
| 1104 |
log.Printf("%s %s ...\n", hreq.Method, hreq.URL.String()) |
| 1105 |
} |
| 1106 |
hresp, err := c.Do(hreq) |
| 1107 |
if err != nil { |
| 1108 |
return nil, err |
| 1109 |
} |
| 1110 |
if client.debug { |
| 1111 |
log.Printf("%s %s %d\n", hreq.Method, hreq.URL.String(), hresp.StatusCode) |
| 1112 |
contentType := hresp.Header.Get("Content-Type") |
| 1113 |
if contentType == "application/xml" || contentType == "text/xml" { |
| 1114 |
dump, _ := httputil.DumpResponse(hresp, true) |
| 1115 |
log.Printf("%s\n", dump) |
| 1116 |
} else { |
| 1117 |
log.Printf("Response Content-Type: %s\n", contentType) |
| 1118 |
} |
| 1119 |
} |
| 1120 |
if hresp.StatusCode != 200 && hresp.StatusCode != 204 && hresp.StatusCode != 206 { |
| 1121 |
return nil, client.buildError(hresp) |
| 1122 |
} |
| 1123 |
if resp != nil { |
| 1124 |
err = xml.NewDecoder(hresp.Body).Decode(resp) |
| 1125 |
hresp.Body.Close() |
| 1126 |
|
| 1127 |
if client.debug { |
| 1128 |
log.Printf("aliyungo.oss> decoded xml into %#v", resp) |
| 1129 |
} |
| 1130 |
|
| 1131 |
} |
| 1132 |
return hresp, err |
| 1133 |
} |
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
func (client *Client) run(req *request, resp interface{}) (*http.Response, error) { |
| 1139 |
if client.debug { |
| 1140 |
log.Printf("Running OSS request: %#v", req) |
| 1141 |
} |
| 1142 |
|
| 1143 |
hreq, err := client.setupHttpRequest(req) |
| 1144 |
if err != nil { |
| 1145 |
return nil, err |
| 1146 |
} |
| 1147 |
|
| 1148 |
c := &http.Client{ |
| 1149 |
Transport: &http.Transport{ |
| 1150 |
Dial: func(netw, addr string) (c net.Conn, err error) { |
| 1151 |
if client.ConnectTimeout > 0 { |
| 1152 |
c, err = net.DialTimeout(netw, addr, client.ConnectTimeout) |
| 1153 |
} else { |
| 1154 |
c, err = net.Dial(netw, addr) |
| 1155 |
} |
| 1156 |
if err != nil { |
| 1157 |
return |
| 1158 |
} |
| 1159 |
return |
| 1160 |
}, |
| 1161 |
Proxy: http.ProxyFromEnvironment, |
| 1162 |
}, |
| 1163 |
Timeout: req.timeout, |
| 1164 |
} |
| 1165 |
|
| 1166 |
return client.doHttpRequest(c, hreq, resp) |
| 1167 |
} |
| 1168 |
|
| 1169 |
|
| 1170 |
type Error struct { |
| 1171 |
StatusCode int |
| 1172 |
Code string |
| 1173 |
Message string |
| 1174 |
BucketName string |
| 1175 |
RequestId string |
| 1176 |
HostId string |
| 1177 |
} |
| 1178 |
|
| 1179 |
func (e *Error) Error() string { |
| 1180 |
return fmt.Sprintf("Aliyun API Error: RequestId: %s Status Code: %d Code: %s Message: %s", e.RequestId, e.StatusCode, e.Code, e.Message) |
| 1181 |
} |
| 1182 |
|
| 1183 |
func (client *Client) buildError(r *http.Response) error { |
| 1184 |
if client.debug { |
| 1185 |
log.Printf("got error (status code %v)", r.StatusCode) |
| 1186 |
data, err := ioutil.ReadAll(r.Body) |
| 1187 |
if err != nil { |
| 1188 |
log.Printf("\tread error: %v", err) |
| 1189 |
} else { |
| 1190 |
log.Printf("\tdata:\n%s\n\n", data) |
| 1191 |
} |
| 1192 |
r.Body = ioutil.NopCloser(bytes.NewBuffer(data)) |
| 1193 |
} |
| 1194 |
|
| 1195 |
err := Error{} |
| 1196 |
|
| 1197 |
xml.NewDecoder(r.Body).Decode(&err) |
| 1198 |
r.Body.Close() |
| 1199 |
err.StatusCode = r.StatusCode |
| 1200 |
if err.Message == "" { |
| 1201 |
err.Message = r.Status |
| 1202 |
} |
| 1203 |
if client.debug { |
| 1204 |
log.Printf("err: %#v\n", err) |
| 1205 |
} |
| 1206 |
return &err |
| 1207 |
} |
| 1208 |
|
| 1209 |
type TimeoutError interface { |
| 1210 |
error |
| 1211 |
Timeout() bool |
| 1212 |
} |
| 1213 |
|
| 1214 |
func shouldRetry(err error) bool { |
| 1215 |
if err == nil { |
| 1216 |
return false |
| 1217 |
} |
| 1218 |
|
| 1219 |
_, ok := err.(TimeoutError) |
| 1220 |
if ok { |
| 1221 |
return true |
| 1222 |
} |
| 1223 |
|
| 1224 |
switch err { |
| 1225 |
case io.ErrUnexpectedEOF, io.EOF: |
| 1226 |
return true |
| 1227 |
} |
| 1228 |
switch e := err.(type) { |
| 1229 |
case *net.DNSError: |
| 1230 |
return true |
| 1231 |
case *net.OpError: |
| 1232 |
switch e.Op { |
| 1233 |
case "read", "write": |
| 1234 |
return true |
| 1235 |
} |
| 1236 |
case *url.Error: |
| 1237 |
|
| 1238 |
|
| 1239 |
|
| 1240 |
|
| 1241 |
|
| 1242 |
|
| 1243 |
switch e.Op { |
| 1244 |
case "Get", "Put", "Delete", "Head": |
| 1245 |
return shouldRetry(e.Err) |
| 1246 |
default: |
| 1247 |
return false |
| 1248 |
} |
| 1249 |
case *Error: |
| 1250 |
switch e.Code { |
| 1251 |
case "InternalError", "NoSuchUpload", "NoSuchBucket": |
| 1252 |
return true |
| 1253 |
} |
| 1254 |
} |
| 1255 |
return false |
| 1256 |
} |
| 1257 |
|
| 1258 |
func hasCode(err error, code string) bool { |
| 1259 |
e, ok := err.(*Error) |
| 1260 |
return ok && e.Code == code |
| 1261 |
} |
| 1262 |
|
| 1263 |
func copyHeader(header http.Header) (newHeader http.Header) { |
| 1264 |
newHeader = make(http.Header) |
| 1265 |
for k, v := range header { |
| 1266 |
newSlice := make([]string, len(v)) |
| 1267 |
copy(newSlice, v) |
| 1268 |
newHeader[k] = newSlice |
| 1269 |
} |
| 1270 |
return |
| 1271 |
} |
| 1272 |
|
| 1273 |
type AccessControlPolicy struct { |
| 1274 |
Owner Owner |
| 1275 |
Grants []string `xml:"AccessControlList>Grant"` |
| 1276 |
} |
| 1277 |
|
| 1278 |
|
| 1279 |
|
| 1280 |
|
| 1281 |
func (b *Bucket) ACL() (result *AccessControlPolicy, err error) { |
| 1282 |
|
| 1283 |
params := make(url.Values) |
| 1284 |
params.Set("acl", "") |
| 1285 |
|
| 1286 |
r, err := b.GetWithParams("/", params) |
| 1287 |
if err != nil { |
| 1288 |
return nil, err |
| 1289 |
} |
| 1290 |
|
| 1291 |
|
| 1292 |
var resp AccessControlPolicy |
| 1293 |
if err = xml.Unmarshal(r, &resp); err != nil { |
| 1294 |
return nil, err |
| 1295 |
} |
| 1296 |
|
| 1297 |
return &resp, nil |
| 1298 |
} |
| 1299 |
|
| 1300 |
func (b *Bucket) GetContentLength(sourcePath string) (int64, error) { |
| 1301 |
resp, err := b.Head(sourcePath, nil) |
| 1302 |
if err != nil { |
| 1303 |
return 0, err |
| 1304 |
} |
| 1305 |
|
| 1306 |
currentLength := resp.ContentLength |
| 1307 |
|
| 1308 |
return currentLength, err |
| 1309 |
} |
| 1310 |
|
| 1311 |
func (b *Bucket) CopyLargeFile(sourcePath string, destPath string, contentType string, perm ACL, options Options) error { |
| 1312 |
return b.CopyLargeFileInParallel(sourcePath, destPath, contentType, perm, options, 1) |
| 1313 |
} |
| 1314 |
|
| 1315 |
const defaultChunkSize = int64(128 * 1024 * 1024) |
| 1316 |
const maxCopytSize = int64(128 * 1024 * 1024) |
| 1317 |
|
| 1318 |
|
| 1319 |
func (b *Bucket) CopyLargeFileInParallel(sourcePath string, destPath string, contentType string, perm ACL, options Options, maxConcurrency int) error { |
| 1320 |
|
| 1321 |
if maxConcurrency < 1 { |
| 1322 |
maxConcurrency = 1 |
| 1323 |
} |
| 1324 |
|
| 1325 |
currentLength, err := b.GetContentLength(sourcePath) |
| 1326 |
|
| 1327 |
log.Printf("Parallel Copy large file[size: %d] from %s to %s\n", currentLength, sourcePath, destPath) |
| 1328 |
|
| 1329 |
if err != nil { |
| 1330 |
return err |
| 1331 |
} |
| 1332 |
|
| 1333 |
if currentLength < maxCopytSize { |
| 1334 |
_, err := b.PutCopy(destPath, perm, |
| 1335 |
CopyOptions{}, |
| 1336 |
b.Path(sourcePath)) |
| 1337 |
return err |
| 1338 |
} |
| 1339 |
|
| 1340 |
multi, err := b.InitMulti(destPath, contentType, perm, options) |
| 1341 |
if err != nil { |
| 1342 |
return err |
| 1343 |
} |
| 1344 |
|
| 1345 |
numParts := (currentLength + defaultChunkSize - 1) / defaultChunkSize |
| 1346 |
completedParts := make([]Part, numParts) |
| 1347 |
|
| 1348 |
errChan := make(chan error, numParts) |
| 1349 |
limiter := make(chan struct{}, maxConcurrency) |
| 1350 |
|
| 1351 |
var start int64 = 0 |
| 1352 |
var to int64 = 0 |
| 1353 |
var partNumber = 0 |
| 1354 |
sourcePathForCopy := b.Path(sourcePath) |
| 1355 |
|
| 1356 |
for start = 0; start < currentLength; start = to { |
| 1357 |
to = start + defaultChunkSize |
| 1358 |
if to > currentLength { |
| 1359 |
to = currentLength |
| 1360 |
} |
| 1361 |
partNumber++ |
| 1362 |
|
| 1363 |
rangeStr := fmt.Sprintf("bytes=%d-%d", start, to-1) |
| 1364 |
limiter <- struct{}{} |
| 1365 |
go func(partNumber int, rangeStr string) { |
| 1366 |
_, part, err := multi.PutPartCopyWithContentLength(partNumber, |
| 1367 |
CopyOptions{CopySourceOptions: rangeStr}, |
| 1368 |
sourcePathForCopy, currentLength) |
| 1369 |
if err == nil { |
| 1370 |
completedParts[partNumber-1] = part |
| 1371 |
} else { |
| 1372 |
log.Printf("Unable in PutPartCopy of part %d for %s: %v\n", partNumber, sourcePathForCopy, err) |
| 1373 |
} |
| 1374 |
errChan <- err |
| 1375 |
<-limiter |
| 1376 |
}(partNumber, rangeStr) |
| 1377 |
} |
| 1378 |
|
| 1379 |
fullyCompleted := true |
| 1380 |
for range completedParts { |
| 1381 |
err := <-errChan |
| 1382 |
if err != nil { |
| 1383 |
fullyCompleted = false |
| 1384 |
} |
| 1385 |
} |
| 1386 |
|
| 1387 |
if fullyCompleted { |
| 1388 |
err = multi.Complete(completedParts) |
| 1389 |
} else { |
| 1390 |
err = multi.Abort() |
| 1391 |
} |
| 1392 |
|
| 1393 |
return err |
| 1394 |
} |