types.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 MQEMetric struct {
  10. Metric string
  11. Alias string
  12. }
  13. type MQEQuery struct {
  14. Metrics []MQEMetric
  15. Hosts []string
  16. Apps []string
  17. AddAppToAlias 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 *MQEQuery) Build(availableSeries []string) ([]string, error) {
  27. var metrics []MQEMetric
  28. for _, v := range q.Metrics {
  29. if !containsWildcardPattern.Match([]byte(v.Metric)) {
  30. metrics = append(metrics, v)
  31. continue
  32. }
  33. m := strings.Replace(v.Metric, "*", ".*", -1)
  34. mp, err := regexp.Compile(m)
  35. if err != nil {
  36. log.Error2("failed to compile regex for ", "metric", m)
  37. continue
  38. }
  39. //TODO: this lookup should be cached
  40. for _, a := range availableSeries {
  41. if mp.Match([]byte(a)) {
  42. metrics = append(metrics, MQEMetric{
  43. Metric: a,
  44. Alias: v.Alias,
  45. })
  46. }
  47. }
  48. }
  49. var queries []string
  50. where := q.buildWhereClause()
  51. for _, metric := range metrics {
  52. alias := ""
  53. if metric.Alias != "" {
  54. alias = fmt.Sprintf(" {%s}", metric.Alias)
  55. }
  56. queries = append(queries,
  57. fmt.Sprintf(
  58. "`%s`%s %s from %v to %v",
  59. metric.Metric,
  60. alias,
  61. where,
  62. q.TimeRange.GetFromAsMsEpoch(),
  63. q.TimeRange.GetToAsMsEpoch()))
  64. }
  65. return queries, nil
  66. }
  67. func (q *MQEQuery) buildWhereClause() string {
  68. hasApps := len(q.Apps) > 0
  69. hasHosts := len(q.Hosts) > 0
  70. where := ""
  71. if hasHosts || hasApps {
  72. where += "where "
  73. }
  74. if hasApps {
  75. apps := strings.Join(q.Apps, "', '")
  76. where += fmt.Sprintf("app in ('%s')", apps)
  77. }
  78. if hasHosts && hasApps {
  79. where += " and "
  80. }
  81. if hasHosts {
  82. hosts := strings.Join(q.Hosts, "', '")
  83. where += fmt.Sprintf("host in ('%s')", hosts)
  84. }
  85. return where
  86. }
  87. type TokenBody struct {
  88. Metrics []string
  89. }
  90. type TokenResponse struct {
  91. Success bool
  92. Body TokenBody
  93. }