storageconnection.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package azure
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
  12. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
  13. "github.com/opencost/opencost/core/pkg/log"
  14. "github.com/opencost/opencost/pkg/cloud"
  15. "github.com/opencost/opencost/pkg/env"
  16. )
  17. // StorageConnection provides access to Azure Storage
  18. type StorageConnection struct {
  19. StorageConfiguration
  20. lock sync.Mutex
  21. ConnectionStatus cloud.ConnectionStatus
  22. }
  23. func (sc *StorageConnection) GetStatus() cloud.ConnectionStatus {
  24. // initialize status if it has not done so; this can happen if the integration is inactive
  25. if sc.ConnectionStatus.String() == "" {
  26. sc.ConnectionStatus = cloud.InitialStatus
  27. }
  28. return sc.ConnectionStatus
  29. }
  30. func (sc *StorageConnection) Equals(config cloud.Config) bool {
  31. thatConfig, ok := config.(*StorageConnection)
  32. if !ok {
  33. return false
  34. }
  35. return sc.StorageConfiguration.Equals(&thatConfig.StorageConfiguration)
  36. }
  37. // getBlobURLTemplate returns the correct BlobUrl for whichever Cloud storage account is specified by the AzureCloud configuration
  38. // defaults to the Public Cloud template
  39. func (sc *StorageConnection) getBlobURLTemplate() string {
  40. // Use gov cloud blob url if gov is detected in AzureCloud
  41. if strings.Contains(strings.ToLower(sc.Cloud), "gov") {
  42. return "https://%s.blob.core.usgovcloudapi.net/%s"
  43. } else if strings.Contains(strings.ToLower(sc.Cloud), "china") {
  44. // Use China cloud blob url if china is detected in AzureCloud
  45. return "https://%s.blob.core.chinacloudapi.cn/%s"
  46. }
  47. // default to Public Cloud template
  48. return "https://%s.blob.core.windows.net/%s"
  49. }
  50. // DownloadBlob downloads the Azure Billing CSV into a byte slice
  51. func (sc *StorageConnection) DownloadBlob(blobName string, client *azblob.Client, ctx context.Context) ([]byte, error) {
  52. log.Infof("Azure Storage: retrieving blob: %v", blobName)
  53. downloadResponse, err := client.DownloadStream(ctx, sc.Container, blobName, nil)
  54. if err != nil {
  55. return nil, fmt.Errorf("Azure: DownloadBlob: failed to download %w", err)
  56. }
  57. // NOTE: automatically retries are performed if the connection fails
  58. retryReader := downloadResponse.NewRetryReader(ctx, &azblob.RetryReaderOptions{})
  59. defer retryReader.Close()
  60. // read the body into a buffer
  61. downloadedData := bytes.Buffer{}
  62. _, err = downloadedData.ReadFrom(retryReader)
  63. if err != nil {
  64. return nil, fmt.Errorf("Azure: DownloadBlob: failed to read downloaded data %w", err)
  65. }
  66. return downloadedData.Bytes(), nil
  67. }
  68. // StreamBlob returns an io.Reader for the given blob which uses a re-usable double buffer approach to stream directly
  69. // from blob storage.
  70. func (sc *StorageConnection) StreamBlob(blobName string, client *azblob.Client) (*StreamReader, error) {
  71. return NewStreamReader(client, sc.Container, blobName)
  72. }
  73. // DownloadBlobToFile downloads the Azure Billing CSV to a local file
  74. func (sc *StorageConnection) DownloadBlobToFile(localFilePath string, blob container.BlobItem, client *azblob.Client, ctx context.Context) error {
  75. // Lock to prevent accessing a file which may not be fully downloaded
  76. sc.lock.Lock()
  77. defer sc.lock.Unlock()
  78. blobName := *blob.Name
  79. // Check if file already exists
  80. if fileInfo, err := os.Stat(localFilePath); err == nil {
  81. blobModTime := *blob.Properties.LastModified
  82. // Check if the blob was last modified before the file was modified, indicating that the
  83. // file is the most recent version of the blob
  84. if blobModTime.Before(fileInfo.ModTime()) {
  85. log.Debugf("CloudCost: Azure: DownloadBlobToFile: file %s is more recent than correspondig blob %s", localFilePath, blobName)
  86. return nil
  87. }
  88. }
  89. // Create filepath
  90. dir := filepath.Dir(localFilePath)
  91. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  92. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create directory %w", err)
  93. }
  94. fp, err := os.Create(localFilePath)
  95. if err != nil {
  96. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to create file %w", err)
  97. }
  98. defer fp.Close()
  99. // Download newest Azure Billing CSV to disk
  100. // Time out to prevent deadlock on download
  101. timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Minute)
  102. defer cancel()
  103. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieving blob: %v", blobName)
  104. filesize, err := client.DownloadFile(timeoutCtx, sc.Container, blobName, fp, nil)
  105. if err != nil {
  106. // Clean up file from failed download
  107. err2 := os.Remove(localFilePath)
  108. if err2 != nil {
  109. log.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to remove file %s after failed download %s", localFilePath, err2.Error())
  110. }
  111. return fmt.Errorf("CloudCost: Azure: DownloadBlobToFile: failed to download %w", err)
  112. }
  113. log.Infof("CloudCost: Azure: DownloadBlobToFile: retrieved %v of size %dMB", blobName, filesize/1024/1024)
  114. return nil
  115. }
  116. // deleteFilesOlderThanRetention recursively walks the directory specified and deletes
  117. // files which have not been modified in the last N days. Returns a list of
  118. // files deleted.
  119. // Retention period is determined by the CLOUD_COST_PV_RETENTION environment variable, which defaults to 2 days.
  120. func (sc *StorageConnection) deleteFilesOlderThanRetention(localPath string) ([]string, error) {
  121. sc.lock.Lock()
  122. defer sc.lock.Unlock()
  123. duration := time.Duration(env.GetCloudCostPvRetention()) * 24 * time.Hour
  124. cleaned := []string{}
  125. errs := []string{}
  126. if _, err := os.Stat(localPath); err != nil {
  127. return cleaned, nil // localPath does not exist
  128. }
  129. filepath.Walk(localPath, func(path string, info os.FileInfo, err error) error {
  130. if err != nil {
  131. errs = append(errs, err.Error())
  132. return err
  133. }
  134. if time.Since(info.ModTime()) > duration {
  135. err := os.Remove(path)
  136. if err != nil {
  137. errs = append(errs, err.Error())
  138. }
  139. cleaned = append(cleaned, path)
  140. }
  141. return nil
  142. })
  143. if len(errs) == 0 {
  144. return cleaned, nil
  145. } else {
  146. return cleaned, fmt.Errorf("deleteFilesOlderThanRetention: %v", errs)
  147. }
  148. }