athenaquerier.go 7.7 KB

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