query.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package influxdb
  15. import (
  16. "fmt"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "yunion.io/x/pkg/utils"
  21. "yunion.io/x/onecloud/pkg/monitor/tsdb"
  22. )
  23. var (
  24. regexpOperatorPattern = regexp.MustCompile(`^\/.*\/$`)
  25. regexpMeasurementPattern = regexp.MustCompile(`^\/.*\/$`)
  26. )
  27. func (query *Query) Build(queryCtx *tsdb.TsdbQuery) (string, error) {
  28. var res string
  29. res = query.renderSelectors(queryCtx)
  30. res += query.renderMeasurement()
  31. res += query.renderWhereClause()
  32. res += query.renderTimeFilter(queryCtx)
  33. res += query.renderGroupBy(queryCtx)
  34. res += query.renderTz()
  35. calculator := tsdb.NewIntervalCalculator(&tsdb.IntervalOptions{})
  36. interval := calculator.Calculate(queryCtx.TimeRange, query.Interval)
  37. res = strings.Replace(res, "$timeFilter", query.renderTimeFilter(queryCtx), -1)
  38. res = strings.Replace(res, "$interval", interval.Text, -1)
  39. res = strings.Replace(res, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10), -1)
  40. res = strings.Replace(res, "$__interval", interval.Text, -1)
  41. return res, nil
  42. }
  43. func (query *Query) renderTags() []string {
  44. var res []string
  45. for i, tag := range query.Tags {
  46. str := ""
  47. if i > 0 {
  48. if tag.Condition == "" {
  49. str += "AND"
  50. } else {
  51. str += tag.Condition
  52. }
  53. str += " "
  54. }
  55. // If the operator is missing we fall back to sensible defaults
  56. if tag.Operator == "" {
  57. if regexpOperatorPattern.Match([]byte(tag.Value)) {
  58. tag.Operator = "=~"
  59. } else {
  60. tag.Operator = "="
  61. }
  62. }
  63. // quote value unless regex or number
  64. var textValue string
  65. if tag.Operator == "=~" || tag.Operator == "!~" {
  66. textValue = tag.Value
  67. } else if tag.Operator == "<" || tag.Operator == ">" {
  68. textValue = tag.Value
  69. } else {
  70. if utils.IsInStringArray(tag.Value, []string{"true", "false"}) {
  71. textValue = tag.Value
  72. } else {
  73. textValue = fmt.Sprintf("'%s'", strings.Replace(tag.Value, `\`, `\\`, -1))
  74. }
  75. }
  76. textValue = query.renderTagValue(textValue)
  77. res = append(res, fmt.Sprintf(`%s"%s" %s %s`, str, tag.Key, tag.Operator, textValue))
  78. }
  79. return res
  80. }
  81. func (query *Query) renderTagValue(val string) string {
  82. return strings.ReplaceAll(val, " ", "+")
  83. }
  84. func (query *Query) renderTimeFilter(queryCtx *tsdb.TsdbQuery) string {
  85. from := ""
  86. if strings.Contains(queryCtx.TimeRange.From, "now-") {
  87. from = "now() - " + strings.Replace(queryCtx.TimeRange.From, "now-", "", 1)
  88. } else {
  89. if _, ok := tsdb.TryParseUnixMsEpoch(queryCtx.TimeRange.From); ok {
  90. from = fmt.Sprintf("%sms", queryCtx.TimeRange.From)
  91. } else {
  92. from = "now() - " + queryCtx.TimeRange.From
  93. }
  94. }
  95. to := ""
  96. if queryCtx.TimeRange.To != "now" && queryCtx.TimeRange.To != "" {
  97. if _, ok := tsdb.TryParseUnixMsEpoch(queryCtx.TimeRange.To); ok {
  98. to = fmt.Sprintf(" and time < %sms", queryCtx.TimeRange.To)
  99. } else {
  100. to = " and time < now() - " + strings.Replace(queryCtx.TimeRange.To, "now-", "", 1)
  101. }
  102. }
  103. return fmt.Sprintf("time > %s%s", from, to)
  104. }
  105. func (query *Query) renderSelectors(queryCtx *tsdb.TsdbQuery) string {
  106. res := "SELECT "
  107. var selectors []string
  108. for _, sel := range query.Selects {
  109. stk := ""
  110. for _, s := range *sel {
  111. stk = s.Render(query, queryCtx, stk)
  112. }
  113. selectors = append(selectors, stk)
  114. }
  115. return res + strings.Join(selectors, ", ")
  116. }
  117. func (query *Query) renderMeasurement() string {
  118. var policy string
  119. if query.Policy == "" || query.Policy == "default" {
  120. policy = ""
  121. } else {
  122. policy = `"` + query.Policy + `".`
  123. }
  124. measurement := query.Measurement
  125. if !regexpMeasurementPattern.Match([]byte(measurement)) {
  126. measurement = fmt.Sprintf(`"%s"`, measurement)
  127. }
  128. return fmt.Sprintf(` FROM %s%s`, policy, measurement)
  129. }
  130. func (query *Query) renderWhereClause() string {
  131. res := " WHERE "
  132. conditions := query.renderTags()
  133. if len(conditions) > 0 {
  134. if len(conditions) > 1 {
  135. res += "(" + strings.Join(conditions, " ") + ")"
  136. } else {
  137. res += conditions[0]
  138. }
  139. res += " AND "
  140. }
  141. return res
  142. }
  143. func (query *Query) renderGroupBy(queryContext *tsdb.TsdbQuery) string {
  144. groupBy := ""
  145. for i, group := range query.GroupBy {
  146. if i == 0 {
  147. groupBy += " GROUP BY"
  148. }
  149. if i > 0 && utils.IsInStringArray(group.Type, []string{"field", "time", "tag"}) {
  150. groupBy += ", " //fill is so very special. fill is a creep, fill is a weirdo
  151. } else {
  152. groupBy += " "
  153. }
  154. groupBy += group.Render(query, queryContext, "")
  155. }
  156. return groupBy
  157. }
  158. func (query *Query) renderTz() string {
  159. tz := query.Tz
  160. if tz == "" {
  161. return ""
  162. }
  163. return fmt.Sprintf(" tz('%s')", tz)
  164. }