athenaquerier.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package aws
  2. import (
  3. "context"
  4. "fmt"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/opencost/opencost/pkg/cloud"
  10. cloudconfig "github.com/opencost/opencost/pkg/cloud/config"
  11. "github.com/aws/aws-sdk-go-v2/aws"
  12. "github.com/aws/aws-sdk-go-v2/service/athena"
  13. "github.com/aws/aws-sdk-go-v2/service/athena/types"
  14. "github.com/opencost/opencost/pkg/kubecost"
  15. "github.com/opencost/opencost/pkg/log"
  16. "github.com/opencost/opencost/pkg/util/stringutil"
  17. )
  18. type AthenaQuerier struct {
  19. AthenaConfiguration
  20. ConnectionStatus cloud.ConnectionStatus
  21. }
  22. func (aq *AthenaQuerier) GetStatus() cloud.ConnectionStatus {
  23. return aq.ConnectionStatus
  24. }
  25. func (aq *AthenaQuerier) Equals(config cloudconfig.Config) bool {
  26. thatConfig, ok := config.(*AthenaQuerier)
  27. if !ok {
  28. return false
  29. }
  30. return aq.AthenaConfiguration.Equals(&thatConfig.AthenaConfiguration)
  31. }
  32. // GetColumns returns a list of the names of all columns in the configured
  33. // Athena table
  34. func (aq *AthenaQuerier) GetColumns() (map[string]bool, error) {
  35. columnSet := map[string]bool{}
  36. // This Query is supported by Athena tables and views
  37. q := `SELECT column_name FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s'`
  38. query := fmt.Sprintf(q, aq.Database, aq.Table)
  39. athenaErr := aq.Query(context.TODO(), query, GetAthenaQueryFunc(func(row types.Row) {
  40. columnSet[*row.Data[0].VarCharValue] = true
  41. }))
  42. if athenaErr != nil {
  43. return columnSet, athenaErr
  44. }
  45. if len(columnSet) == 0 {
  46. log.Infof("No columns retrieved from Athena")
  47. }
  48. return columnSet, nil
  49. }
  50. func (aq *AthenaQuerier) Query(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  51. err := aq.Validate()
  52. if err != nil {
  53. aq.ConnectionStatus = cloud.InvalidConfiguration
  54. return err
  55. }
  56. log.Debugf("AthenaQuerier[%s]: Performing Query: %s", aq.Key(), query)
  57. err = aq.queryAthenaPaginated(ctx, query, fn)
  58. if err != nil {
  59. aq.ConnectionStatus = cloud.FailedConnection
  60. return err
  61. }
  62. return nil
  63. }
  64. func (aq *AthenaQuerier) GetAthenaClient() (*athena.Client, error) {
  65. cfg, err := aq.Authorizer.CreateAWSConfig(aq.Region)
  66. if err != nil {
  67. return nil, err
  68. }
  69. cli := athena.NewFromConfig(cfg)
  70. return cli, nil
  71. }
  72. // QueryAthenaPaginated executes athena query and processes results. An error from this method indicates a
  73. // FAILED_CONNECTION CloudConnectionStatus and should immediately stop the caller to maintain the correct CloudConnectionStatus
  74. func (aq *AthenaQuerier) queryAthenaPaginated(ctx context.Context, query string, fn func(*athena.GetQueryResultsOutput) bool) error {
  75. queryExecutionCtx := &types.QueryExecutionContext{
  76. Database: aws.String(aq.Database),
  77. }
  78. if aq.Catalog != "" {
  79. queryExecutionCtx.Catalog = aws.String(aq.Catalog)
  80. }
  81. resultConfiguration := &types.ResultConfiguration{
  82. OutputLocation: aws.String(aq.Bucket),
  83. }
  84. startQueryExecutionInput := &athena.StartQueryExecutionInput{
  85. QueryString: aws.String(query),
  86. QueryExecutionContext: queryExecutionCtx,
  87. ResultConfiguration: resultConfiguration,
  88. }
  89. // Only set if there is a value, the default input is nil
  90. if aq.Workgroup != "" {
  91. startQueryExecutionInput.WorkGroup = aws.String(aq.Workgroup)
  92. }
  93. // Create Athena Client
  94. cli, err := aq.GetAthenaClient()
  95. if err != nil {
  96. return fmt.Errorf("QueryAthenaPaginated: GetAthenaClient error: %s", err.Error())
  97. }
  98. // Query Athena
  99. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  100. if err != nil {
  101. return fmt.Errorf("QueryAthenaPaginated: start query error: %s", err.Error())
  102. }
  103. err = waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  104. if err != nil {
  105. return fmt.Errorf("QueryAthenaPaginated: query execution error: %s", err.Error())
  106. }
  107. queryResultsInput := &athena.GetQueryResultsInput{
  108. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  109. }
  110. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  111. for getQueryResultsPaginator.HasMorePages() {
  112. pg, err := getQueryResultsPaginator.NextPage(ctx)
  113. if err != nil {
  114. log.Errorf("queryAthenaPaginated: NextPage error: %s", err.Error())
  115. continue
  116. }
  117. fn(pg)
  118. }
  119. return nil
  120. }
  121. func waitForQueryToComplete(ctx context.Context, client *athena.Client, queryExecutionID *string) error {
  122. inp := &athena.GetQueryExecutionInput{
  123. QueryExecutionId: queryExecutionID,
  124. }
  125. isQueryStillRunning := true
  126. for isQueryStillRunning {
  127. qe, err := client.GetQueryExecution(ctx, inp)
  128. if err != nil {
  129. return err
  130. }
  131. if qe.QueryExecution.Status.State == "SUCCEEDED" {
  132. isQueryStillRunning = false
  133. continue
  134. }
  135. if qe.QueryExecution.Status.State != "RUNNING" && qe.QueryExecution.Status.State != "QUEUED" {
  136. return fmt.Errorf("no query results available for query %s", *queryExecutionID)
  137. }
  138. time.Sleep(2 * time.Second)
  139. }
  140. return nil
  141. }
  142. // GetAthenaRowValue retrieve value from athena row based on column names and used stringutil.Bank() to prevent duplicate
  143. // allocation of strings
  144. func GetAthenaRowValue(row types.Row, queryColumnIndexes map[string]int, columnName string) string {
  145. columnIndex, ok := queryColumnIndexes[columnName]
  146. if !ok {
  147. return ""
  148. }
  149. valuePointer := row.Data[columnIndex].VarCharValue
  150. if valuePointer == nil {
  151. return ""
  152. }
  153. return stringutil.Bank(*valuePointer)
  154. }
  155. // getAthenaRowValueFloat retrieve value from athena row based on column names and convert to float if possible
  156. func GetAthenaRowValueFloat(row types.Row, queryColumnIndexes map[string]int, columnName string) (float64, error) {
  157. columnIndex, ok := queryColumnIndexes[columnName]
  158. if !ok {
  159. return 0.0, fmt.Errorf("getAthenaRowValueFloat: missing column index: %s", columnName)
  160. }
  161. valuePointer := row.Data[columnIndex].VarCharValue
  162. if valuePointer == nil {
  163. return 0.0, fmt.Errorf("getAthenaRowValueFloat: nil field")
  164. }
  165. cost, err := strconv.ParseFloat(*valuePointer, 64)
  166. if err != nil {
  167. return cost, fmt.Errorf("getAthenaRowValueFloat: failed to parse %s: '%s': %s", columnName, *valuePointer, err.Error())
  168. }
  169. return cost, nil
  170. }
  171. func SelectAWSCategory(providerID, usageType, service string) string {
  172. // Network has the highest priority and is based on the usage type ending in "Bytes"
  173. if strings.HasSuffix(usageType, "Bytes") {
  174. return kubecost.NetworkCategory
  175. }
  176. // The node and volume conditions are mutually exclusive.
  177. // Provider ID has prefix "i-"
  178. if strings.HasPrefix(providerID, "i-") {
  179. return kubecost.ComputeCategory
  180. }
  181. // Provider ID has prefix "vol-"
  182. if strings.HasPrefix(providerID, "vol-") {
  183. return kubecost.StorageCategory
  184. }
  185. // Default categories based on service
  186. switch strings.ToUpper(service) {
  187. case "AWSELB", "AWSGLUE", "AMAZONROUTE53":
  188. return kubecost.NetworkCategory
  189. case "AMAZONEC2", "AWSLAMBDA", "AMAZONELASTICACHE":
  190. return kubecost.ComputeCategory
  191. case "AMAZONEKS":
  192. // Check if line item is a fargate pod
  193. if strings.Contains(providerID, ":pod/") {
  194. return kubecost.ComputeCategory
  195. }
  196. return kubecost.ManagementCategory
  197. case "AMAZONS3", "AMAZONATHENA", "AMAZONRDS", "AMAZONDYNAMODB", "AWSSECRETSMANAGER", "AMAZONFSX":
  198. return kubecost.StorageCategory
  199. default:
  200. return kubecost.OtherCategory
  201. }
  202. }
  203. var parseARNRx = regexp.MustCompile("^.+\\/(.+)?") // Capture "a406f7761142e4ef58a8f2ba478d2db2" from "arn:aws:elasticloadbalancing:us-east-1:297945954695:loadbalancer/a406f7761142e4ef58a8f2ba478d2db2"
  204. func ParseARN(id string) string {
  205. match := parseARNRx.FindStringSubmatch(id)
  206. if len(match) == 0 {
  207. if id != "" {
  208. log.DedupedInfof(10, "aws.parseARN: failed to parse %s", id)
  209. }
  210. return id
  211. }
  212. return match[len(match)-1]
  213. }
  214. func GetAthenaQueryFunc(fn func(types.Row)) func(*athena.GetQueryResultsOutput) bool {
  215. pageNum := 0
  216. processItemQueryResults := func(page *athena.GetQueryResultsOutput) bool {
  217. if page == nil {
  218. log.Errorf("AthenaQuerier: Athena page is nil")
  219. return false
  220. } else if page.ResultSet == nil {
  221. log.Errorf("AthenaQuerier: Athena page.ResultSet is nil")
  222. return false
  223. }
  224. rows := page.ResultSet.Rows
  225. if pageNum == 0 {
  226. rows = page.ResultSet.Rows[1:len(page.ResultSet.Rows)]
  227. }
  228. for _, row := range rows {
  229. fn(row)
  230. }
  231. pageNum++
  232. return true
  233. }
  234. return processItemQueryResults
  235. }