storagebillingparser.go 5.0 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-storage-blob-go/azblob"
  11. "github.com/opencost/opencost/pkg/cloud"
  12. cloudconfig "github.com/opencost/opencost/pkg/cloud/config"
  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 cloudconfig.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. containerURL, err := asbp.getContainer()
  34. if err != nil {
  35. asbp.ConnectionStatus = cloud.FailedConnection
  36. return err
  37. }
  38. ctx := context.Background()
  39. blobNames, err := asbp.getMostRecentBlobs(start, end, containerURL, 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, containerURL, ctx)
  50. if err2 != nil {
  51. asbp.ConnectionStatus = cloud.FailedConnection
  52. return err
  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, containerURL *azblob.ContainerURL, 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]azblob.BlobItemInternal)
  99. for marker := (azblob.Marker{}); marker.NotDone(); {
  100. // Get a result segment starting with the blob indicated by the current Marker.
  101. listBlob, err := containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{})
  102. if err != nil {
  103. return nil, err
  104. }
  105. // ListBlobs returns the start of the next segment; you MUST use this to get
  106. // the next segment (after processing the current result segment).
  107. marker = listBlob.NextMarker
  108. // Using the list of months strings find the most resent blob for each month in the range
  109. for _, blobInfo := range listBlob.Segment.BlobItems {
  110. for _, month := range monthStrs {
  111. if strings.Contains(blobInfo.Name, month) {
  112. // If Container Path configuration exists, check if it is in the blobs name
  113. if asbp.Path != "" && !strings.Contains(blobInfo.Name, asbp.Path) {
  114. continue
  115. }
  116. if prevBlob, ok := mostResentBlobs[month]; ok {
  117. if prevBlob.Properties.CreationTime.After(*blobInfo.Properties.CreationTime) {
  118. continue
  119. }
  120. }
  121. mostResentBlobs[month] = blobInfo
  122. }
  123. }
  124. }
  125. }
  126. // convert blob names into blob urls and move from map into ordered list of blob names
  127. var blobNames []string
  128. for _, month := range monthStrs {
  129. if blob, ok := mostResentBlobs[month]; ok {
  130. blobNames = append(blobNames, blob.Name)
  131. }
  132. }
  133. return blobNames, nil
  134. }
  135. func (asbp *AzureStorageBillingParser) getMonthStrings(start, end time.Time) ([]string, error) {
  136. if start.After(end) {
  137. return []string{}, fmt.Errorf("start date must be before end date")
  138. }
  139. if end.After(time.Now()) {
  140. end = time.Now()
  141. }
  142. var monthStrs []string
  143. monthStr := asbp.timeToMonthString(start)
  144. endStr := asbp.timeToMonthString(end)
  145. monthStrs = append(monthStrs, monthStr)
  146. currMonth := start.AddDate(0, 0, -start.Day()+1)
  147. for monthStr != endStr {
  148. currMonth = currMonth.AddDate(0, 1, 0)
  149. monthStr = asbp.timeToMonthString(currMonth)
  150. monthStrs = append(monthStrs, monthStr)
  151. }
  152. return monthStrs, nil
  153. }
  154. func (asbp *AzureStorageBillingParser) timeToMonthString(input time.Time) string {
  155. format := "20060102"
  156. startOfMonth := input.AddDate(0, 0, -input.Day()+1)
  157. endOfMonth := input.AddDate(0, 1, -input.Day())
  158. return startOfMonth.Format(format) + "-" + endOfMonth.Format(format)
  159. }