athenaintegration.go 15 KB

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