storageconnection.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package azure
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "strings"
  7. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
  8. "github.com/opencost/opencost/pkg/cloud"
  9. "github.com/opencost/opencost/pkg/log"
  10. )
  11. // StorageConnection provides access to Azure Storage
  12. type StorageConnection struct {
  13. StorageConfiguration
  14. ConnectionStatus cloud.ConnectionStatus
  15. }
  16. func (sc *StorageConnection) GetStatus() cloud.ConnectionStatus {
  17. // initialize status if it has not done so; this can happen if the integration is inactive
  18. if sc.ConnectionStatus.String() == "" {
  19. sc.ConnectionStatus = cloud.InitialStatus
  20. }
  21. return sc.ConnectionStatus
  22. }
  23. func (sc *StorageConnection) Equals(config cloud.Config) bool {
  24. thatConfig, ok := config.(*StorageConnection)
  25. if !ok {
  26. return false
  27. }
  28. return sc.StorageConfiguration.Equals(&thatConfig.StorageConfiguration)
  29. }
  30. // getBlobURLTemplate returns the correct BlobUrl for whichever Cloud storage account is specified by the AzureCloud configuration
  31. // defaults to the Public Cloud template
  32. func (sc *StorageConnection) getBlobURLTemplate() string {
  33. // Use gov cloud blob url if gov is detected in AzureCloud
  34. if strings.Contains(strings.ToLower(sc.Cloud), "gov") {
  35. return "https://%s.blob.core.usgovcloudapi.net/%s"
  36. }
  37. // default to Public Cloud template
  38. return "https://%s.blob.core.windows.net/%s"
  39. }
  40. func (sc *StorageConnection) DownloadBlob(blobName string, client *azblob.Client, ctx context.Context) ([]byte, error) {
  41. log.Infof("Azure Storage: retrieving blob: %v", blobName)
  42. downloadResponse, err := client.DownloadStream(ctx, sc.Container, blobName, nil)
  43. if err != nil {
  44. return nil, fmt.Errorf("Azure: DownloadBlob: failed to download %w", err)
  45. }
  46. // NOTE: automatically retries are performed if the connection fails
  47. retryReader := downloadResponse.NewRetryReader(ctx, &azblob.RetryReaderOptions{})
  48. defer retryReader.Close()
  49. // read the body into a buffer
  50. downloadedData := bytes.Buffer{}
  51. _, err = downloadedData.ReadFrom(retryReader)
  52. if err != nil {
  53. return nil, fmt.Errorf("Azure: DownloadBlob: failed to read downloaded data %w", err)
  54. }
  55. return downloadedData.Bytes(), nil
  56. }