athenaquerier.go 8.1 KB

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