athenaquerier.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. if err != nil {
  90. return fmt.Errorf("QueryAthenaPaginated: GetAthenaClient error: %s", err.Error())
  91. }
  92. // Query Athena
  93. startQueryExecutionOutput, err := cli.StartQueryExecution(ctx, startQueryExecutionInput)
  94. if err != nil {
  95. return fmt.Errorf("QueryAthenaPaginated: start query error: %s", err.Error())
  96. }
  97. err = waitForQueryToComplete(ctx, cli, startQueryExecutionOutput.QueryExecutionId)
  98. if err != nil {
  99. return fmt.Errorf("QueryAthenaPaginated: query execution error: %s", err.Error())
  100. }
  101. queryResultsInput := &athena.GetQueryResultsInput{
  102. QueryExecutionId: startQueryExecutionOutput.QueryExecutionId,
  103. }
  104. getQueryResultsPaginator := athena.NewGetQueryResultsPaginator(cli, queryResultsInput)
  105. for getQueryResultsPaginator.HasMorePages() {
  106. pg, err := getQueryResultsPaginator.NextPage(ctx)
  107. if err != nil {
  108. log.Errorf("queryAthenaPaginated: NextPage error: %s", err.Error())
  109. continue
  110. }
  111. fn(pg)
  112. }
  113. return nil
  114. }
  115. func waitForQueryToComplete(ctx context.Context, client *athena.Client, queryExecutionID *string) error {
  116. inp := &athena.GetQueryExecutionInput{
  117. QueryExecutionId: queryExecutionID,
  118. }
  119. isQueryStillRunning := true
  120. for isQueryStillRunning {
  121. qe, err := client.GetQueryExecution(ctx, inp)
  122. if err != nil {
  123. return err
  124. }
  125. if qe.QueryExecution.Status.State == "SUCCEEDED" {
  126. isQueryStillRunning = false
  127. continue
  128. }
  129. if qe.QueryExecution.Status.State != "RUNNING" && qe.QueryExecution.Status.State != "QUEUED" {
  130. return fmt.Errorf("no query results available for query %s", *queryExecutionID)
  131. }
  132. time.Sleep(2 * time.Second)
  133. }
  134. return nil
  135. }
  136. // GetAthenaRowValue retrieve value from athena row based on column names and used stringutil.Bank() to prevent duplicate
  137. // allocation of strings
  138. func GetAthenaRowValue(row types.Row, queryColumnIndexes map[string]int, columnName string) string {
  139. columnIndex, ok := queryColumnIndexes[columnName]
  140. if !ok {
  141. return ""
  142. }
  143. valuePointer := row.Data[columnIndex].VarCharValue
  144. if valuePointer == nil {
  145. return ""
  146. }
  147. return stringutil.Bank(*valuePointer)
  148. }
  149. // getAthenaRowValueFloat retrieve value from athena row based on column names and convert to float if possible
  150. func GetAthenaRowValueFloat(row types.Row, queryColumnIndexes map[string]int, columnName string) (float64, error) {
  151. columnIndex, ok := queryColumnIndexes[columnName]
  152. if !ok {
  153. return 0.0, fmt.Errorf("getAthenaRowValueFloat: missing column index: %s", columnName)
  154. }
  155. valuePointer := row.Data[columnIndex].VarCharValue
  156. if valuePointer == nil {
  157. return 0.0, fmt.Errorf("getAthenaRowValueFloat: nil field")
  158. }
  159. cost, err := strconv.ParseFloat(*valuePointer, 64)
  160. if err != nil {
  161. return cost, fmt.Errorf("getAthenaRowValueFloat: failed to parse %s: '%s': %s", columnName, *valuePointer, err.Error())
  162. }
  163. return cost, nil
  164. }
  165. func SelectAWSCategory(providerID, usageType, service string) string {
  166. // Network has the highest priority and is based on the usage type ending in "Bytes"
  167. if strings.HasSuffix(usageType, "Bytes") {
  168. return kubecost.NetworkCategory
  169. }
  170. // The node and volume conditions are mutually exclusive.
  171. // Provider ID has prefix "i-"
  172. if strings.HasPrefix(providerID, "i-") {
  173. return kubecost.ComputeCategory
  174. }
  175. // Provider ID has prefix "vol-"
  176. if strings.HasPrefix(providerID, "vol-") {
  177. return kubecost.StorageCategory
  178. }
  179. // Default categories based on service
  180. switch strings.ToUpper(service) {
  181. case "AWSELB", "AWSGLUE", "AMAZONROUTE53":
  182. return kubecost.NetworkCategory
  183. case "AMAZONEC2", "AWSLAMBDA", "AMAZONELASTICACHE":
  184. return kubecost.ComputeCategory
  185. case "AMAZONEKS":
  186. // Check if line item is a fargate pod
  187. if strings.Contains(providerID, ":pod/") {
  188. return kubecost.ComputeCategory
  189. }
  190. return kubecost.ManagementCategory
  191. case "AMAZONS3", "AMAZONATHENA", "AMAZONRDS", "AMAZONDYNAMODB", "AWSSECRETSMANAGER", "AMAZONFSX":
  192. return kubecost.StorageCategory
  193. default:
  194. return kubecost.OtherCategory
  195. }
  196. }
  197. var parseARNRx = regexp.MustCompile("^.+\\/(.+)?") // Capture "a406f7761142e4ef58a8f2ba478d2db2" from "arn:aws:elasticloadbalancing:us-east-1:297945954695:loadbalancer/a406f7761142e4ef58a8f2ba478d2db2"
  198. func ParseARN(id string) string {
  199. match := parseARNRx.FindStringSubmatch(id)
  200. if len(match) == 0 {
  201. if id != "" {
  202. log.DedupedInfof(10, "aws.parseARN: failed to parse %s", id)
  203. }
  204. return id
  205. }
  206. return match[len(match)-1]
  207. }
  208. func GetAthenaQueryFunc(fn func(types.Row)) func(*athena.GetQueryResultsOutput) bool {
  209. pageNum := 0
  210. processItemQueryResults := func(page *athena.GetQueryResultsOutput) bool {
  211. if page == nil {
  212. log.Errorf("AthenaQuerier: Athena page is nil")
  213. return false
  214. } else if page.ResultSet == nil {
  215. log.Errorf("AthenaQuerier: Athena page.ResultSet is nil")
  216. return false
  217. }
  218. rows := page.ResultSet.Rows
  219. if pageNum == 0 {
  220. rows = page.ResultSet.Rows[1:len(page.ResultSet.Rows)]
  221. }
  222. for _, row := range rows {
  223. fn(row)
  224. }
  225. pageNum++
  226. return true
  227. }
  228. return processItemQueryResults
  229. }