storageconnection.go 2.0 KB

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