2
0

athenaquerier.go 8.4 KB

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