storagebillingparser.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package azure
  2. import (
  3. "context"
  4. "encoding/csv"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  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. // AzureStorageBillingParser accesses billing data stored in CSV files in Azure Storage
  18. type AzureStorageBillingParser struct {
  19. StorageConnection
  20. }
  21. func (asbp *AzureStorageBillingParser) Equals(config cloud.Config) bool {
  22. thatConfig, ok := config.(*AzureStorageBillingParser)
  23. if !ok {
  24. return false
  25. }
  26. return asbp.StorageConnection.Equals(&thatConfig.StorageConnection)
  27. }
  28. type AzureBillingResultFunc func(*BillingRowValues) error
  29. func (asbp *AzureStorageBillingParser) ParseBillingData(start, end time.Time, resultFn AzureBillingResultFunc) error {
  30. err := asbp.Validate()
  31. if err != nil {
  32. asbp.ConnectionStatus = cloud.InvalidConfiguration
  33. return err
  34. }
  35. serviceURL := fmt.Sprintf(asbp.StorageConnection.getBlobURLTemplate(), asbp.Account, "")
  36. client, err := asbp.Authorizer.GetBlobClient(serviceURL)
  37. if err != nil {
  38. asbp.ConnectionStatus = cloud.FailedConnection
  39. return err
  40. }
  41. ctx := context.Background()
  42. // Example blobNames: [ export/myExport/20240101-20240131/myExport_758a42af-0731-4edb-b498-1e523bb40f12.csv ]
  43. blobNames, err := asbp.getMostRecentBlobs(start, end, client, ctx)
  44. if err != nil {
  45. asbp.ConnectionStatus = cloud.FailedConnection
  46. return err
  47. }
  48. if len(blobNames) == 0 && asbp.ConnectionStatus != cloud.SuccessfulConnection {
  49. asbp.ConnectionStatus = cloud.MissingData
  50. return nil
  51. }
  52. for _, blobName := range blobNames {
  53. if env.IsAzureDownloadBillingDataToDisk() {
  54. localPath := filepath.Join(env.GetConfigPathWithDefault(env.DefaultConfigMountPath), "db", "cloudcost")
  55. localFilePath := filepath.Join(localPath, filepath.Base(blobName))
  56. if _, err := asbp.deleteFilesOlderThan7d(localPath); err != nil {
  57. log.Warnf("CloudCost: Azure: ParseBillingData: failed to remove the following stale files: %v", err)
  58. }
  59. err := asbp.DownloadBlobToFile(localFilePath, blobName, client, ctx)
  60. if err != nil {
  61. asbp.ConnectionStatus = cloud.FailedConnection
  62. return err
  63. }
  64. fp, err := os.Open(localFilePath)
  65. if err != nil {
  66. asbp.ConnectionStatus = cloud.FailedConnection
  67. return err
  68. }
  69. defer fp.Close()
  70. err = asbp.parseCSV(start, end, csv.NewReader(fp), resultFn)
  71. if err != nil {
  72. asbp.ConnectionStatus = cloud.ParseError
  73. return err
  74. }
  75. } else {
  76. streamReader, err2 := asbp.StreamBlob(blobName, client)
  77. if err2 != nil {
  78. asbp.ConnectionStatus = cloud.FailedConnection
  79. return err2
  80. }
  81. err2 = asbp.parseCSV(start, end, csv.NewReader(streamReader), resultFn)
  82. if err2 != nil {
  83. asbp.ConnectionStatus = cloud.ParseError
  84. return err2
  85. }
  86. }
  87. }
  88. asbp.ConnectionStatus = cloud.SuccessfulConnection
  89. return nil
  90. }
  91. func (asbp *AzureStorageBillingParser) parseCSV(start, end time.Time, reader *csv.Reader, resultFn AzureBillingResultFunc) error {
  92. headers, err := reader.Read()
  93. if err != nil {
  94. return err
  95. }
  96. abp, err := NewBillingParseSchema(headers)
  97. if err != nil {
  98. return err
  99. }
  100. for {
  101. var record, err = reader.Read()
  102. if err == io.EOF {
  103. break
  104. }
  105. if err != nil {
  106. return err
  107. }
  108. abv := abp.ParseRow(start, end, record)
  109. if abv == nil {
  110. continue
  111. }
  112. err = resultFn(abv)
  113. if err != nil {
  114. return err
  115. }
  116. }
  117. return nil
  118. }
  119. // getMostRecentBlobs returns a list of filepaths on the Azure Storage
  120. // Container. It uses the "Last Modified Time" of the file to determine which
  121. // has the latest month-to-date billing data.
  122. func (asbp *AzureStorageBillingParser) getMostRecentBlobs(start, end time.Time, client *azblob.Client, ctx context.Context) ([]string, error) {
  123. log.Infof("Azure Storage: retrieving most recent reports from: %v - %v", start, end)
  124. // Get list of month substrings for months contained in the start to end range
  125. monthStrs, err := asbp.getMonthStrings(start, end)
  126. if err != nil {
  127. return nil, err
  128. }
  129. mostRecentBlobs := make(map[string]container.BlobItem)
  130. pager := client.NewListBlobsFlatPager(asbp.Container, &azblob.ListBlobsFlatOptions{
  131. Include: container.ListBlobsInclude{Deleted: false, Versions: false},
  132. })
  133. for pager.More() {
  134. resp, err := pager.NextPage(ctx)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // Using the list of months strings find the most resent blob for each month in the range
  139. for _, blobInfo := range resp.Segment.BlobItems {
  140. if blobInfo.Name == nil {
  141. continue
  142. }
  143. // If Container Path configuration exists, check if it is in the blobs name
  144. if asbp.Path != "" && !strings.Contains(*blobInfo.Name, asbp.Path) {
  145. continue
  146. }
  147. for _, month := range monthStrs {
  148. if strings.Contains(*blobInfo.Name, month) {
  149. // check if blob is the newest seen for this month
  150. if prevBlob, ok := mostRecentBlobs[month]; ok {
  151. if prevBlob.Properties.CreationTime.After(*blobInfo.Properties.CreationTime) {
  152. continue
  153. }
  154. }
  155. mostRecentBlobs[month] = *blobInfo
  156. }
  157. }
  158. }
  159. }
  160. // convert blob names into blob urls and move from map into ordered list of blob names
  161. var blobNames []string
  162. for _, month := range monthStrs {
  163. if blob, ok := mostRecentBlobs[month]; ok {
  164. blobNames = append(blobNames, *blob.Name)
  165. }
  166. }
  167. return blobNames, nil
  168. }
  169. // getMonthStrings returns a list of month strings in the format
  170. // "YYYYMMDD-YYYYMMDD", where the dates are exactly the first and last day of
  171. // the month. It includes all month strings which would capture the start and
  172. // end parameters.
  173. // For example: ["20240201-20240229", "20240101-20240131", "20231201-20231231"]
  174. func (asbp *AzureStorageBillingParser) getMonthStrings(start, end time.Time) ([]string, error) {
  175. if start.After(end) {
  176. return []string{}, fmt.Errorf("start date must be before end date")
  177. }
  178. if end.After(time.Now()) {
  179. end = time.Now()
  180. }
  181. var monthStrs []string
  182. monthStr := asbp.timeToMonthString(start)
  183. endStr := asbp.timeToMonthString(end)
  184. monthStrs = append(monthStrs, monthStr)
  185. currMonth := start.AddDate(0, 0, -start.Day()+1)
  186. for monthStr != endStr {
  187. currMonth = currMonth.AddDate(0, 1, 0)
  188. monthStr = asbp.timeToMonthString(currMonth)
  189. monthStrs = append(monthStrs, monthStr)
  190. }
  191. return monthStrs, nil
  192. }
  193. func (asbp *AzureStorageBillingParser) timeToMonthString(input time.Time) string {
  194. format := "20060102"
  195. startOfMonth := input.AddDate(0, 0, -input.Day()+1)
  196. endOfMonth := input.AddDate(0, 1, -input.Day())
  197. return startOfMonth.Format(format) + "-" + endOfMonth.Format(format)
  198. }
  199. // deleteFilesOlderThan7d recursively walks the directory specified and deletes
  200. // files which have not been modified in the last 7 days. Returns a list of
  201. // files deleted.
  202. func (asbp *AzureStorageBillingParser) deleteFilesOlderThan7d(localPath string) ([]string, error) {
  203. duration := 7 * 24 * time.Hour
  204. cleaned := []string{}
  205. errs := []string{}
  206. if _, err := os.Stat(localPath); err != nil {
  207. return cleaned, nil // localPath does not exist
  208. }
  209. filepath.Walk(localPath, func(path string, info os.FileInfo, err error) error {
  210. if err != nil {
  211. errs = append(errs, err.Error())
  212. return err
  213. }
  214. if time.Since(info.ModTime()) > duration {
  215. err := os.Remove(path)
  216. if err != nil {
  217. errs = append(errs, err.Error())
  218. }
  219. cleaned = append(cleaned, path)
  220. }
  221. return nil
  222. })
  223. if len(errs) == 0 {
  224. return cleaned, nil
  225. } else {
  226. return cleaned, fmt.Errorf("deleteFilesOlderThan7d: %v", errs)
  227. }
  228. }