2
0

storagebillingparser.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package azure
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/csv"
  6. "fmt"
  7. "io"
  8. "strings"
  9. "time"
  10. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
  11. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
  12. "github.com/opencost/opencost/pkg/cloud"
  13. "github.com/opencost/opencost/pkg/log"
  14. )
  15. // AzureStorageBillingParser accesses billing data stored in CSV files in Azure Storage
  16. type AzureStorageBillingParser struct {
  17. StorageConnection
  18. }
  19. func (asbp *AzureStorageBillingParser) Equals(config cloud.Config) bool {
  20. thatConfig, ok := config.(*AzureStorageBillingParser)
  21. if !ok {
  22. return false
  23. }
  24. return asbp.StorageConnection.Equals(&thatConfig.StorageConnection)
  25. }
  26. type AzureBillingResultFunc func(*BillingRowValues) error
  27. func (asbp *AzureStorageBillingParser) ParseBillingData(start, end time.Time, resultFn AzureBillingResultFunc) error {
  28. err := asbp.Validate()
  29. if err != nil {
  30. asbp.ConnectionStatus = cloud.InvalidConfiguration
  31. return err
  32. }
  33. client, err := asbp.Authorizer.GetBlobClient(asbp.StorageConnection.getBlobURLTemplate())
  34. if err != nil {
  35. asbp.ConnectionStatus = cloud.FailedConnection
  36. return err
  37. }
  38. ctx := context.Background()
  39. blobNames, err := asbp.getMostRecentBlobs(start, end, client, ctx)
  40. if err != nil {
  41. asbp.ConnectionStatus = cloud.FailedConnection
  42. return err
  43. }
  44. if len(blobNames) == 0 && asbp.ConnectionStatus != cloud.SuccessfulConnection {
  45. asbp.ConnectionStatus = cloud.MissingData
  46. return nil
  47. }
  48. for _, blobName := range blobNames {
  49. blobBytes, err2 := asbp.DownloadBlob(blobName, client, ctx)
  50. if err2 != nil {
  51. asbp.ConnectionStatus = cloud.FailedConnection
  52. return err2
  53. }
  54. err2 = asbp.parseCSV(start, end, csv.NewReader(bytes.NewReader(blobBytes)), resultFn)
  55. if err2 != nil {
  56. asbp.ConnectionStatus = cloud.ParseError
  57. return err2
  58. }
  59. }
  60. asbp.ConnectionStatus = cloud.SuccessfulConnection
  61. return nil
  62. }
  63. func (asbp *AzureStorageBillingParser) parseCSV(start, end time.Time, reader *csv.Reader, resultFn AzureBillingResultFunc) error {
  64. headers, err := reader.Read()
  65. if err != nil {
  66. return err
  67. }
  68. abp, err := NewBillingParseSchema(headers)
  69. if err != nil {
  70. return err
  71. }
  72. for {
  73. var record, err = reader.Read()
  74. if err == io.EOF {
  75. break
  76. }
  77. if err != nil {
  78. return err
  79. }
  80. abv := abp.ParseRow(start, end, record)
  81. if abv == nil {
  82. continue
  83. }
  84. err = resultFn(abv)
  85. if err != nil {
  86. return err
  87. }
  88. }
  89. return nil
  90. }
  91. func (asbp *AzureStorageBillingParser) getMostRecentBlobs(start, end time.Time, client *azblob.Client, ctx context.Context) ([]string, error) {
  92. log.Infof("Azure Storage: retrieving most recent reports from: %v - %v", start, end)
  93. // Get list of month substrings for months contained in the start to end range
  94. monthStrs, err := asbp.getMonthStrings(start, end)
  95. if err != nil {
  96. return nil, err
  97. }
  98. mostResentBlobs := make(map[string]container.BlobItem)
  99. pager := client.NewListBlobsFlatPager(asbp.Container, &azblob.ListBlobsFlatOptions{
  100. Include: container.ListBlobsInclude{Deleted: false, Versions: false},
  101. })
  102. for pager.More() {
  103. resp, err := pager.NextPage(ctx)
  104. if err != nil {
  105. return nil, err
  106. }
  107. // Using the list of months strings find the most resent blob for each month in the range
  108. for _, blobInfo := range resp.Segment.BlobItems {
  109. for _, month := range monthStrs {
  110. if strings.Contains(*blobInfo.Name, month) {
  111. // If Container Path configuration exists, check if it is in the blobs name
  112. if asbp.Path != "" && !strings.Contains(*blobInfo.Name, asbp.Path) {
  113. continue
  114. }
  115. if prevBlob, ok := mostResentBlobs[month]; ok {
  116. if prevBlob.Properties.CreationTime.After(*blobInfo.Properties.CreationTime) {
  117. continue
  118. }
  119. }
  120. mostResentBlobs[month] = *blobInfo
  121. }
  122. }
  123. }
  124. }
  125. // convert blob names into blob urls and move from map into ordered list of blob names
  126. var blobNames []string
  127. for _, month := range monthStrs {
  128. if blob, ok := mostResentBlobs[month]; ok {
  129. blobNames = append(blobNames, *blob.Name)
  130. }
  131. }
  132. return blobNames, nil
  133. }
  134. func (asbp *AzureStorageBillingParser) getMonthStrings(start, end time.Time) ([]string, error) {
  135. if start.After(end) {
  136. return []string{}, fmt.Errorf("start date must be before end date")
  137. }
  138. if end.After(time.Now()) {
  139. end = time.Now()
  140. }
  141. var monthStrs []string
  142. monthStr := asbp.timeToMonthString(start)
  143. endStr := asbp.timeToMonthString(end)
  144. monthStrs = append(monthStrs, monthStr)
  145. currMonth := start.AddDate(0, 0, -start.Day()+1)
  146. for monthStr != endStr {
  147. currMonth = currMonth.AddDate(0, 1, 0)
  148. monthStr = asbp.timeToMonthString(currMonth)
  149. monthStrs = append(monthStrs, monthStr)
  150. }
  151. return monthStrs, nil
  152. }
  153. func (asbp *AzureStorageBillingParser) timeToMonthString(input time.Time) string {
  154. format := "20060102"
  155. startOfMonth := input.AddDate(0, 0, -input.Day()+1)
  156. endOfMonth := input.AddDate(0, 1, -input.Day())
  157. return startOfMonth.Format(format) + "-" + endOfMonth.Format(format)
  158. }