athenaintegration.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. package aws
  2. import (
  3. "context"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/aws/aws-sdk-go-v2/service/athena/types"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/opencost"
  11. "github.com/opencost/opencost/pkg/cloud"
  12. )
  13. const LabelColumnPrefix = "resource_tags_user_"
  14. // athenaDateLayout is the default AWS date format
  15. const AthenaDateLayout = "2006-01-02 15:04:05.000"
  16. // Cost Columns
  17. const AthenaPricingColumn = "line_item_unblended_cost"
  18. // Amortized Cost Columns
  19. const AthenaRIPricingColumn = "reservation_effective_cost"
  20. const AthenaSPPricingColumn = "savings_plan_savings_plan_effective_cost"
  21. // Net Cost Columns
  22. const AthenaNetPricingColumn = "line_item_net_unblended_cost"
  23. var AthenaNetPricingCoalesce = fmt.Sprintf("COALESCE(%s, %s, 0)", AthenaNetPricingColumn, AthenaPricingColumn)
  24. // Amortized Net Cost Columns
  25. const AthenaNetRIPricingColumn = "reservation_net_effective_cost"
  26. var AthenaNetRIPricingCoalesce = fmt.Sprintf("COALESCE(%s, %s, 0)", AthenaNetRIPricingColumn, AthenaRIPricingColumn)
  27. const AthenaNetSPPricingColumn = "savings_plan_net_savings_plan_effective_cost"
  28. var AthenaNetSPPricingCoalesce = fmt.Sprintf("COALESCE(%s, %s, 0)", AthenaNetSPPricingColumn, AthenaSPPricingColumn)
  29. // athenaDateTruncColumn Aggregates line items from the hourly level to daily. "line_item_usage_start_date" is used because at
  30. // all time values 00:00-23:00 it will truncate to the correct date.
  31. const AthenaDateColumn = "line_item_usage_start_date"
  32. const AthenaDateTruncColumn = "DATE_TRUNC('day'," + AthenaDateColumn + ") as usage_date"
  33. const AthenaWhereDateFmt = `line_item_usage_start_date >= date '%s' AND line_item_usage_start_date < date '%s'`
  34. const AthenaWhereUsage = "(line_item_line_item_type = 'Usage' OR line_item_line_item_type = 'DiscountedUsage' OR line_item_line_item_type = 'SavingsPlanCoveredUsage' OR line_item_line_item_type = 'EdpDiscount' OR line_item_line_item_type = 'PrivateRateDiscount')"
  35. // AthenaQueryIndexes is a struct for holding the context of a query
  36. type AthenaQueryIndexes struct {
  37. Query string
  38. ColumnIndexes map[string]int
  39. TagColumns []string
  40. ListCostColumn string
  41. NetCostColumn string
  42. AmortizedNetCostColumn string
  43. AmortizedCostColumn string
  44. IsK8sColumn string
  45. }
  46. type AthenaIntegration struct {
  47. AthenaQuerier
  48. }
  49. // Query Athena for CUR data and build a new CloudCostSetRange containing the info
  50. func (ai *AthenaIntegration) GetCloudCost(start, end time.Time) (*opencost.CloudCostSetRange, error) {
  51. log.Infof("AthenaIntegration[%s]: GetCloudCost: %s", ai.Key(), opencost.NewWindow(&start, &end).String())
  52. // Query for all column names
  53. allColumns, err := ai.GetColumns()
  54. if err != nil {
  55. return nil, fmt.Errorf("GetCloudCost: error getting Athena columns: %w", err)
  56. }
  57. // List known, hard-coded columns to query
  58. groupByColumns := []string{
  59. AthenaDateTruncColumn,
  60. "line_item_resource_id",
  61. "bill_payer_account_id",
  62. "line_item_usage_account_id",
  63. "line_item_product_code",
  64. "line_item_usage_type",
  65. "product_region_code",
  66. "line_item_availability_zone",
  67. }
  68. // Create query indices
  69. aqi := AthenaQueryIndexes{}
  70. // Add is k8s column
  71. isK8sColumn := ai.GetIsKubernetesColumn(allColumns)
  72. groupByColumns = append(groupByColumns, isK8sColumn)
  73. aqi.IsK8sColumn = isK8sColumn
  74. // Determine which columns are user-defined tags and add those to the list
  75. // of columns to query.
  76. for column := range allColumns {
  77. if strings.HasPrefix(column, LabelColumnPrefix) {
  78. quotedTag := fmt.Sprintf(`"%s"`, column)
  79. groupByColumns = append(groupByColumns, quotedTag)
  80. aqi.TagColumns = append(aqi.TagColumns, quotedTag)
  81. }
  82. }
  83. var selectColumns []string
  84. // Duplicate GroupBy Columns into select columns
  85. selectColumns = append(selectColumns, groupByColumns...)
  86. // Clean Up group by columns
  87. ai.RemoveColumnAliases(groupByColumns)
  88. // Build list cost column and add it to the select columns
  89. listCostColumn := ai.GetListCostColumn()
  90. selectColumns = append(selectColumns, listCostColumn)
  91. aqi.ListCostColumn = listCostColumn
  92. // Build net cost column and add it to select columns
  93. netCostColumn := ai.GetNetCostColumn(allColumns)
  94. selectColumns = append(selectColumns, netCostColumn)
  95. aqi.NetCostColumn = netCostColumn
  96. // Build amortized net cost column and add it to select columns
  97. amortizedNetCostColumn := ai.GetAmortizedNetCostColumn(allColumns)
  98. selectColumns = append(selectColumns, amortizedNetCostColumn)
  99. aqi.AmortizedNetCostColumn = amortizedNetCostColumn
  100. // Build Amortized cost column and add it to select columns
  101. amortizedCostColumn := ai.GetAmortizedCostColumn(allColumns)
  102. selectColumns = append(selectColumns, amortizedCostColumn)
  103. aqi.AmortizedCostColumn = amortizedCostColumn
  104. // Build map of query columns to use for parsing query
  105. aqi.ColumnIndexes = map[string]int{}
  106. for i, column := range selectColumns {
  107. aqi.ColumnIndexes[column] = i
  108. }
  109. whereDate := fmt.Sprintf(AthenaWhereDateFmt, start.Format("2006-01-02"), end.Format("2006-01-02"))
  110. wherePartitions := ai.GetPartitionWhere(start, end)
  111. // Query for all line items with a resource_id or from AWS Marketplace, which did not end before
  112. // the range or start after it. This captures all costs with any amount of
  113. // overlap with the range, for which we will only extract the relevant costs
  114. whereConjuncts := []string{
  115. wherePartitions,
  116. whereDate,
  117. AthenaWhereUsage,
  118. }
  119. columnStr := strings.Join(selectColumns, ", ")
  120. whereClause := strings.Join(whereConjuncts, " AND ")
  121. groupByStr := strings.Join(groupByColumns, ", ")
  122. queryStr := `
  123. SELECT %s
  124. FROM "%s"
  125. WHERE %s
  126. GROUP BY %s
  127. `
  128. aqi.Query = fmt.Sprintf(queryStr, columnStr, ai.Table, whereClause, groupByStr)
  129. ccsr, err := opencost.NewCloudCostSetRange(start, end, opencost.AccumulateOptionDay, ai.Key())
  130. if err != nil {
  131. return nil, err
  132. }
  133. // Generate row handling function.
  134. rowHandler := func(row types.Row) {
  135. err2 := ai.RowToCloudCost(row, aqi, ccsr)
  136. if err2 != nil {
  137. log.Errorf("AthenaIntegration: GetCloudCost: error while parsing row: %s", err2.Error())
  138. }
  139. }
  140. log.Debugf("AthenaIntegration[%s]: GetCloudCost: querying: %s", ai.Key(), aqi.Query)
  141. // Query CUR data and fill out CCSR
  142. err = ai.Query(context.TODO(), aqi.Query, GetAthenaQueryFunc(rowHandler))
  143. if err != nil {
  144. return nil, err
  145. }
  146. ai.ConnectionStatus = ai.GetConnectionStatusFromResult(ccsr, ai.ConnectionStatus)
  147. return ccsr, nil
  148. }
  149. func (ai *AthenaIntegration) GetListCostColumn() string {
  150. var listCostBuilder strings.Builder
  151. listCostBuilder.WriteString("CASE line_item_line_item_type")
  152. listCostBuilder.WriteString(" WHEN 'EdpDiscount' THEN 0")
  153. listCostBuilder.WriteString(" WHEN 'PrivateRateDiscount' THEN 0")
  154. listCostBuilder.WriteString(" ELSE ")
  155. listCostBuilder.WriteString(AthenaPricingColumn)
  156. listCostBuilder.WriteString(" END")
  157. return fmt.Sprintf("SUM(%s) as list_cost", listCostBuilder.String())
  158. }
  159. func (ai *AthenaIntegration) GetNetCostColumn(allColumns map[string]bool) string {
  160. netCostColumn := ""
  161. if allColumns[AthenaNetPricingColumn] { // if Net pricing exists
  162. netCostColumn = AthenaNetPricingCoalesce
  163. } else { // Non-net for if there's no net pricing.
  164. netCostColumn = AthenaPricingColumn
  165. }
  166. return fmt.Sprintf("SUM(%s) as net_cost", netCostColumn)
  167. }
  168. func (ai *AthenaIntegration) GetAmortizedCostColumn(allColumns map[string]bool) string {
  169. amortizedCostCase := ai.GetAmortizedCostCase(allColumns)
  170. return fmt.Sprintf("SUM(%s) as amortized_cost", amortizedCostCase)
  171. }
  172. func (ai *AthenaIntegration) GetAmortizedNetCostColumn(allColumns map[string]bool) string {
  173. amortizedNetCostCase := ""
  174. if allColumns[AthenaNetPricingColumn] { // if Net pricing exists
  175. amortizedNetCostCase = ai.GetAmortizedNetCostCase(allColumns)
  176. } else { // Non-net for if there's no net pricing.
  177. amortizedNetCostCase = ai.GetAmortizedCostCase(allColumns)
  178. }
  179. return fmt.Sprintf("SUM(%s) as amortized_net_cost", amortizedNetCostCase)
  180. }
  181. func (ai *AthenaIntegration) GetAmortizedCostCase(allColumns map[string]bool) string {
  182. // Use unblended costs if Reserved Instances/Savings Plans aren't in use
  183. if !allColumns[AthenaRIPricingColumn] && !allColumns[AthenaSPPricingColumn] {
  184. return AthenaPricingColumn
  185. }
  186. var costBuilder strings.Builder
  187. costBuilder.WriteString("CASE line_item_line_item_type")
  188. if allColumns[AthenaRIPricingColumn] {
  189. costBuilder.WriteString(" WHEN 'DiscountedUsage' THEN ")
  190. costBuilder.WriteString(AthenaRIPricingColumn)
  191. }
  192. if allColumns[AthenaSPPricingColumn] {
  193. costBuilder.WriteString(" WHEN 'SavingsPlanCoveredUsage' THEN ")
  194. costBuilder.WriteString(AthenaSPPricingColumn)
  195. }
  196. costBuilder.WriteString(" ELSE ")
  197. costBuilder.WriteString(AthenaPricingColumn)
  198. costBuilder.WriteString(" END")
  199. return costBuilder.String()
  200. }
  201. func (ai *AthenaIntegration) GetAmortizedNetCostCase(allColumns map[string]bool) string {
  202. // Use net unblended costs if Reserved Instances/Savings Plans aren't in use
  203. if !allColumns[AthenaNetRIPricingColumn] && !allColumns[AthenaNetSPPricingColumn] {
  204. return AthenaNetPricingCoalesce
  205. }
  206. var costBuilder strings.Builder
  207. costBuilder.WriteString("CASE line_item_line_item_type")
  208. if allColumns[AthenaNetRIPricingColumn] {
  209. costBuilder.WriteString(" WHEN 'DiscountedUsage' THEN ")
  210. costBuilder.WriteString(AthenaNetRIPricingCoalesce)
  211. }
  212. if allColumns[AthenaNetSPPricingColumn] {
  213. costBuilder.WriteString(" WHEN 'SavingsPlanCoveredUsage' THEN ")
  214. costBuilder.WriteString(AthenaNetSPPricingCoalesce)
  215. }
  216. costBuilder.WriteString(" ELSE ")
  217. costBuilder.WriteString(AthenaNetPricingCoalesce)
  218. costBuilder.WriteString(" END")
  219. return costBuilder.String()
  220. }
  221. func (ai *AthenaIntegration) RemoveColumnAliases(columns []string) {
  222. for i, column := range columns {
  223. if strings.Contains(column, " as ") {
  224. columnValues := strings.Split(column, " as ")
  225. columns[i] = columnValues[0]
  226. }
  227. }
  228. }
  229. func (ai *AthenaIntegration) ConvertLabelToAWSTag(label string) string {
  230. // if the label already has the column prefix assume that it is in the correct format
  231. if strings.HasPrefix(label, LabelColumnPrefix) {
  232. return label
  233. }
  234. // replace characters with underscore
  235. tag := label
  236. tag = strings.ReplaceAll(tag, ".", "_")
  237. tag = strings.ReplaceAll(tag, "/", "_")
  238. tag = strings.ReplaceAll(tag, ":", "_")
  239. tag = strings.ReplaceAll(tag, "-", "_")
  240. // add prefix and return
  241. return LabelColumnPrefix + tag
  242. }
  243. // GetIsKubernetesColumn builds a column that determines if a row represents kubernetes spend
  244. func (ai *AthenaIntegration) GetIsKubernetesColumn(allColumns map[string]bool) string {
  245. disjuncts := []string{
  246. "line_item_product_code = 'AmazonEKS'", // EKS is always kubernetes
  247. }
  248. // tagColumns is a list of columns where the presence of a value indicates that a resource is part of a kubernetes cluster
  249. tagColumns := []string{
  250. "resource_tags_aws_eks_cluster_name",
  251. "resource_tags_user_eks_cluster_name",
  252. "resource_tags_user_alpha_eksctl_io_cluster_name",
  253. "resource_tags_user_kubernetes_io_service_name",
  254. "resource_tags_user_kubernetes_io_created_for_pvc_name",
  255. "resource_tags_user_kubernetes_io_created_for_pv_name",
  256. }
  257. for _, tagColumn := range tagColumns {
  258. // if tag column is present in the CUR check for it
  259. if _, ok := allColumns[tagColumn]; ok {
  260. disjunctStr := fmt.Sprintf("%s <> ''", tagColumn)
  261. disjuncts = append(disjuncts, disjunctStr)
  262. }
  263. }
  264. return fmt.Sprintf("(%s) as is_kubernetes", strings.Join(disjuncts, " OR "))
  265. }
  266. func (ai *AthenaIntegration) GetPartitionWhere(start, end time.Time) string {
  267. month := time.Date(start.Year(), start.Month(), 1, 0, 0, 0, 0, time.UTC)
  268. endMonth := time.Date(end.Year(), end.Month(), 1, 0, 0, 0, 0, time.UTC)
  269. var disjuncts []string
  270. for !month.After(endMonth) {
  271. disjuncts = append(disjuncts, fmt.Sprintf("(year = '%d' AND month = '%d')", month.Year(), month.Month()))
  272. month = month.AddDate(0, 1, 0)
  273. }
  274. str := fmt.Sprintf("(%s)", strings.Join(disjuncts, " OR "))
  275. return str
  276. }
  277. func (ai *AthenaIntegration) RowToCloudCost(row types.Row, aqi AthenaQueryIndexes, ccsr *opencost.CloudCostSetRange) error {
  278. if len(row.Data) < len(aqi.ColumnIndexes) {
  279. return fmt.Errorf("rowToCloudCost: row with fewer than %d columns (has only %d)", len(aqi.ColumnIndexes), len(row.Data))
  280. }
  281. // Iterate through the slice of tag columns, assigning
  282. // values to the column names, minus the tag prefix.
  283. labels := opencost.CloudCostLabels{}
  284. for _, tagColumnName := range aqi.TagColumns {
  285. // remove quotes
  286. labelName := strings.TrimPrefix(tagColumnName, `"`)
  287. labelName = strings.TrimSuffix(labelName, `"`)
  288. // remove prefix
  289. labelName = strings.TrimPrefix(labelName, LabelColumnPrefix)
  290. value := GetAthenaRowValue(row, aqi.ColumnIndexes, tagColumnName)
  291. if value != "" {
  292. labels[labelName] = value
  293. }
  294. }
  295. invoiceEntityID := GetAthenaRowValue(row, aqi.ColumnIndexes, "bill_payer_account_id")
  296. accountID := GetAthenaRowValue(row, aqi.ColumnIndexes, "line_item_usage_account_id")
  297. startStr := GetAthenaRowValue(row, aqi.ColumnIndexes, AthenaDateTruncColumn)
  298. providerID := GetAthenaRowValue(row, aqi.ColumnIndexes, "line_item_resource_id")
  299. productCode := GetAthenaRowValue(row, aqi.ColumnIndexes, "line_item_product_code")
  300. usageType := GetAthenaRowValue(row, aqi.ColumnIndexes, "line_item_usage_type")
  301. regionCode := GetAthenaRowValue(row, aqi.ColumnIndexes, "product_region_code")
  302. availabilityZone := GetAthenaRowValue(row, aqi.ColumnIndexes, "line_item_availability_zone")
  303. isK8s, _ := strconv.ParseBool(GetAthenaRowValue(row, aqi.ColumnIndexes, aqi.IsK8sColumn))
  304. k8sPct := 0.0
  305. if isK8s {
  306. k8sPct = 1.0
  307. }
  308. listCost, err := GetAthenaRowValueFloat(row, aqi.ColumnIndexes, aqi.ListCostColumn)
  309. if err != nil {
  310. return err
  311. }
  312. netCost, err := GetAthenaRowValueFloat(row, aqi.ColumnIndexes, aqi.NetCostColumn)
  313. if err != nil {
  314. return err
  315. }
  316. amortizedNetCost, err := GetAthenaRowValueFloat(row, aqi.ColumnIndexes, aqi.AmortizedNetCostColumn)
  317. if err != nil {
  318. return err
  319. }
  320. amortizedCost, err := GetAthenaRowValueFloat(row, aqi.ColumnIndexes, aqi.AmortizedCostColumn)
  321. if err != nil {
  322. return err
  323. }
  324. // Identify resource category in the CUR
  325. category := SelectAWSCategory(providerID, usageType, productCode)
  326. // Retrieve final stanza of product code for ProviderID
  327. if productCode == "AWSELB" || productCode == "AmazonFSx" {
  328. providerID = ParseARN(providerID)
  329. }
  330. if productCode == "AmazonEKS" && category == opencost.ComputeCategory {
  331. if strings.Contains(usageType, "CPU") {
  332. providerID = fmt.Sprintf("%s/CPU", providerID)
  333. } else if strings.Contains(usageType, "GB") {
  334. providerID = fmt.Sprintf("%s/RAM", providerID)
  335. }
  336. }
  337. properties := opencost.CloudCostProperties{
  338. ProviderID: providerID,
  339. Provider: opencost.AWSProvider,
  340. AccountID: accountID,
  341. AccountName: accountID,
  342. InvoiceEntityID: invoiceEntityID,
  343. InvoiceEntityName: invoiceEntityID,
  344. RegionID: regionCode,
  345. AvailabilityZone: availabilityZone,
  346. Service: productCode,
  347. Category: category,
  348. Labels: labels,
  349. }
  350. start, err := time.Parse(AthenaDateLayout, startStr)
  351. if err != nil {
  352. return fmt.Errorf("unable to parse %s: '%s'", AthenaDateTruncColumn, err.Error())
  353. }
  354. end := start.AddDate(0, 0, 1)
  355. cc := &opencost.CloudCost{
  356. Properties: &properties,
  357. Window: opencost.NewWindow(&start, &end),
  358. ListCost: opencost.CostMetric{
  359. Cost: listCost,
  360. KubernetesPercent: k8sPct,
  361. },
  362. NetCost: opencost.CostMetric{
  363. Cost: netCost,
  364. KubernetesPercent: k8sPct,
  365. },
  366. AmortizedNetCost: opencost.CostMetric{
  367. Cost: amortizedNetCost,
  368. KubernetesPercent: k8sPct,
  369. },
  370. AmortizedCost: opencost.CostMetric{
  371. Cost: amortizedCost,
  372. KubernetesPercent: k8sPct,
  373. },
  374. InvoicedCost: opencost.CostMetric{
  375. Cost: netCost, // We are using Net Cost for Invoiced Cost for now as it is the closest approximation
  376. KubernetesPercent: k8sPct,
  377. },
  378. }
  379. ccsr.LoadCloudCost(cc)
  380. return nil
  381. }
  382. func (ai *AthenaIntegration) GetConnectionStatusFromResult(result cloud.EmptyChecker, currentStatus cloud.ConnectionStatus) cloud.ConnectionStatus {
  383. if result.IsEmpty() && currentStatus != cloud.SuccessfulConnection {
  384. return cloud.MissingData
  385. }
  386. return cloud.SuccessfulConnection
  387. }