s3remotefile.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package remotefile
  15. import (
  16. "context"
  17. "os"
  18. "yunion.io/x/cloudmux/pkg/cloudprovider"
  19. "yunion.io/x/cloudmux/pkg/multicloud/objectstore"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. )
  23. type S3RemoteFileInfo struct {
  24. Bucket string `json:"bucket"`
  25. AcessKey string `json:"access_key"`
  26. Secret string `json:"secret"`
  27. Url string `json:"url"`
  28. Key string `json:"key"`
  29. SignVer string `json:"sign_ver"`
  30. }
  31. func (info *S3RemoteFileInfo) download(ctx context.Context, localPath string, callback func(progress, progressMbps float64, totalSizeMb int64)) error {
  32. log.Infof("start s3 download url: %s key: %s to %s", info.Url, info.Key, localPath)
  33. cfg := objectstore.NewObjectStoreClientConfig(info.Url, info.AcessKey, info.Secret)
  34. if len(info.SignVer) > 0 {
  35. cfg.SignVersion(objectstore.S3SignVersion(info.SignVer))
  36. }
  37. minioClient, err := objectstore.NewObjectStoreClient(cfg)
  38. if err != nil {
  39. return errors.Wrap(err, "new minio client")
  40. }
  41. bucket, err := minioClient.GetIBucketByName(info.Bucket)
  42. if err != nil {
  43. return errors.Wrap(err, "get bucket")
  44. }
  45. fi, err := os.Create(localPath)
  46. if err != nil {
  47. return errors.Wrap(err, "create file")
  48. }
  49. defer fi.Close()
  50. _, err = cloudprovider.DownloadObjectParallelWithProgress(ctx, bucket, info.Key, nil, fi, 0, 0, true, 1, callback)
  51. if err != nil {
  52. return errors.Wrap(err, "download object")
  53. }
  54. return nil
  55. }