storageconnection.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package azure
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
  10. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/pkg/cloud"
  13. )
  14. // StorageConnection provides access to Azure Storage
  15. type StorageConnection struct {
  16. StorageConfiguration
  17. ConnectionStatus cloud.ConnectionStatus
  18. }
  19. func (sc *StorageConnection) GetStatus() cloud.ConnectionStatus {
  20. // initialize status if it has not done so; this can happen if the integration is inactive
  21. if sc.ConnectionStatus.String() == "" {
  22. sc.ConnectionStatus = cloud.InitialStatus
  23. }
  24. return sc.ConnectionStatus
  25. }
  26. func (sc *StorageConnection) Equals(config cloud.Config) bool {
  27. thatConfig, ok := config.(*StorageConnection)
  28. if !ok {
  29. return false
  30. }
  31. return sc.StorageConfiguration.Equals(&thatConfig.StorageConfiguration)
  32. }
  33. // getBlobURLTemplate returns the correct BlobUrl for whichever Cloud storage account is specified by the AzureCloud configuration
  34. // defaults to the Public Cloud template
  35. func (sc *StorageConnection) getBlobURLTemplate() string {
  36. // Use gov cloud blob url if gov is detected in AzureCloud
  37. if strings.Contains(strings.ToLower(sc.Cloud), "gov") {
  38. return "https://%s.blob.core.usgovcloudapi.net/%s"
  39. }
  40. // default to Public Cloud template
  41. return "https://%s.blob.core.windows.net/%s"
  42. }
  43. // DownloadBlob downloads the Azure Billing CSV into a byte slice
  44. func (sc *StorageConnection) DownloadBlob(blobName string, client *azblob.Client, ctx context.Context) ([]byte, error) {
  45. log.Infof("Azure Storage: retrieving blob: %v", blobName)
  46. downloadResponse, err := client.DownloadStream(ctx, sc.Container, blobName, nil)
  47. if err != nil {
  48. return nil, fmt.Errorf("Azure: DownloadBlob: failed to download %w", err)
  49. }
  50. // NOTE: automatically retries are performed if the connection fails
  51. retryReader := downloadResponse.NewRetryReader(ctx, &azblob.RetryReaderOptions{})
  52. defer retryReader.Close()
  53. // read the body into a buffer
  54. downloadedData := bytes.Buffer{}
  55. _, err = downloadedData.ReadFrom(retryReader)
  56. if err != nil {
  57. return nil, fmt.Errorf("Azure: DownloadBlob: failed to read downloaded data %w", err)
  58. }
  59. return downloadedData.Bytes(), nil
  60. }
  61. // StreamBlob returns an io.Reader for the given blob which uses a re-usable double buffer approach to stream directly
  62. // from blob storage.
  63. func (sc *StorageConnection) StreamBlob(blobName string, client *azblob.Client) (*StreamReader, error) {
  64. return NewStreamReader(client, sc.Container, blobName)
  65. }
  66. // DownloadBlobToFile downloads the Azure Billing CSV to a local file
  67. func (sc *StorageConnection) DownloadBlobToFile(localFilePath string, blob container.BlobItem, client *azblob.Client, ctx context.Context) error {
  68. blobName := *blob.Name
  69. // Check if file already exists
  70. if fileInfo, err := os.Stat(localFilePath); err == nil {
  71. blobModTime := *blob.Properties.LastModified
  72. // Check if the blob was last modified before the file was modified, indicating that the
  73. // file is the most recent version of the blob
  74. if blobModTime.Before(fileInfo.ModTime()) {
  75. log.Debugf("CloudCost: Azure: DownloadBlobToFile: file %s is more recent than correspondig blob %s", localFilePath, blobName)
  76. return nil
  77. }
  78. }
  79. // Create filepath
  80. dir := filepath.Dir(localFilePath)
  81. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  82. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create directory %w", err)
  83. }
  84. fp, err := os.Create(localFilePath)
  85. if err != nil {
  86. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create file %w", err)
  87. }
  88. defer fp.Close()
  89. // Download newest Azure Billing CSV to disk
  90. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieving blob: %v", blobName)
  91. filesize, err := client.DownloadFile(ctx, sc.Container, blobName, fp, nil)
  92. if err != nil {
  93. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to download %w", err)
  94. }
  95. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieved %v of size %dMB", blobName, filesize/1024/1024)
  96. return nil
  97. }