athenaquerier.go 8.7 KB

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