types.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package mqe
  2. import (
  3. "fmt"
  4. "strings"
  5. "regexp"
  6. "github.com/grafana/grafana/pkg/log"
  7. "github.com/grafana/grafana/pkg/tsdb"
  8. )
  9. type Metric struct {
  10. Metric string
  11. Alias string
  12. }
  13. type Query struct {
  14. Metrics []Metric
  15. Hosts []string
  16. Cluster []string
  17. AddClusterToAlias bool
  18. AddHostToAlias bool
  19. TimeRange *tsdb.TimeRange
  20. UseRawQuery bool
  21. RawQuery string
  22. }
  23. var (
  24. containsWildcardPattern *regexp.Regexp = regexp.MustCompile(`\*`)
  25. )
  26. func (q *Query) Build(availableSeries []string) ([]QueryToSend, error) {
  27. var queriesToSend []QueryToSend
  28. where := q.buildWhereClause()
  29. for _, v := range q.Metrics {
  30. if !containsWildcardPattern.Match([]byte(v.Metric)) {
  31. alias := ""
  32. if v.Alias != "" {
  33. alias = fmt.Sprintf(" {%s}", v.Alias)
  34. }
  35. rawQuery := fmt.Sprintf(
  36. "`%s`%s %s from %v to %v",
  37. v.Metric,
  38. alias,
  39. where,
  40. q.TimeRange.GetFromAsMsEpoch(),
  41. q.TimeRange.GetToAsMsEpoch())
  42. queriesToSend = append(queriesToSend, QueryToSend{
  43. RawQuery: rawQuery,
  44. QueryRef: q,
  45. })
  46. continue
  47. }
  48. m := strings.Replace(v.Metric, "*", ".*", -1)
  49. mp, err := regexp.Compile(m)
  50. if err != nil {
  51. log.Error2("failed to compile regex for ", "metric", m)
  52. continue
  53. }
  54. //TODO: this lookup should be cached
  55. for _, a := range availableSeries {
  56. if mp.Match([]byte(a)) {
  57. alias := ""
  58. if v.Alias != "" {
  59. alias = fmt.Sprintf(" {%s}", v.Alias)
  60. }
  61. rawQuery := fmt.Sprintf(
  62. "`%s`%s %s from %v to %v",
  63. a,
  64. alias,
  65. where,
  66. q.TimeRange.GetFromAsMsEpoch(),
  67. q.TimeRange.GetToAsMsEpoch())
  68. queriesToSend = append(queriesToSend, QueryToSend{
  69. RawQuery: rawQuery,
  70. QueryRef: q,
  71. })
  72. }
  73. }
  74. }
  75. return queriesToSend, nil
  76. }
  77. func (q *Query) buildWhereClause() string {
  78. hasApps := len(q.Cluster) > 0
  79. hasHosts := len(q.Hosts) > 0
  80. where := ""
  81. if hasHosts || hasApps {
  82. where += "where "
  83. }
  84. if hasApps {
  85. apps := strings.Join(q.Cluster, "', '")
  86. where += fmt.Sprintf("cluster in ('%s')", apps)
  87. }
  88. if hasHosts && hasApps {
  89. where += " and "
  90. }
  91. if hasHosts {
  92. hosts := strings.Join(q.Hosts, "', '")
  93. where += fmt.Sprintf("host in ('%s')", hosts)
  94. }
  95. return where
  96. }
  97. type TokenBody struct {
  98. Metrics []string
  99. }
  100. type TokenResponse struct {
  101. Success bool
  102. Body TokenBody
  103. }