storageconnection.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. } else if strings.Contains(strings.ToLower(sc.Cloud), "china") {
  40. // Use China cloud blob url if china is detected in AzureCloud
  41. return "https://%s.blob.core.chinacloudapi.cn/%s"
  42. }
  43. // default to Public Cloud template
  44. return "https://%s.blob.core.windows.net/%s"
  45. }
  46. // DownloadBlob downloads the Azure Billing CSV into a byte slice
  47. func (sc *StorageConnection) DownloadBlob(blobName string, client *azblob.Client, ctx context.Context) ([]byte, error) {
  48. log.Infof("Azure Storage: retrieving blob: %v", blobName)
  49. downloadResponse, err := client.DownloadStream(ctx, sc.Container, blobName, nil)
  50. if err != nil {
  51. return nil, fmt.Errorf("Azure: DownloadBlob: failed to download %w", err)
  52. }
  53. // NOTE: automatically retries are performed if the connection fails
  54. retryReader := downloadResponse.NewRetryReader(ctx, &azblob.RetryReaderOptions{})
  55. defer retryReader.Close()
  56. // read the body into a buffer
  57. downloadedData := bytes.Buffer{}
  58. _, err = downloadedData.ReadFrom(retryReader)
  59. if err != nil {
  60. return nil, fmt.Errorf("Azure: DownloadBlob: failed to read downloaded data %w", err)
  61. }
  62. return downloadedData.Bytes(), nil
  63. }
  64. // StreamBlob returns an io.Reader for the given blob which uses a re-usable double buffer approach to stream directly
  65. // from blob storage.
  66. func (sc *StorageConnection) StreamBlob(blobName string, client *azblob.Client) (*StreamReader, error) {
  67. return NewStreamReader(client, sc.Container, blobName)
  68. }
  69. // DownloadBlobToFile downloads the Azure Billing CSV to a local file
  70. func (sc *StorageConnection) DownloadBlobToFile(localFilePath string, blob container.BlobItem, client *azblob.Client, ctx context.Context) error {
  71. blobName := *blob.Name
  72. // Check if file already exists
  73. if fileInfo, err := os.Stat(localFilePath); err == nil {
  74. blobModTime := *blob.Properties.LastModified
  75. // Check if the blob was last modified before the file was modified, indicating that the
  76. // file is the most recent version of the blob
  77. if blobModTime.Before(fileInfo.ModTime()) {
  78. log.Debugf("CloudCost: Azure: DownloadBlobToFile: file %s is more recent than correspondig blob %s", localFilePath, blobName)
  79. return nil
  80. }
  81. }
  82. // Create filepath
  83. dir := filepath.Dir(localFilePath)
  84. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  85. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create directory %w", err)
  86. }
  87. fp, err := os.Create(localFilePath)
  88. if err != nil {
  89. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create file %w", err)
  90. }
  91. defer fp.Close()
  92. // Download newest Azure Billing CSV to disk
  93. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieving blob: %v", blobName)
  94. filesize, err := client.DownloadFile(ctx, sc.Container, blobName, fp, nil)
  95. if err != nil {
  96. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to download %w", err)
  97. }
  98. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieved %v of size %dMB", blobName, filesize/1024/1024)
  99. return nil
  100. }