influxdb.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. "bytes"
  17. "context"
  18. "encoding/json"
  19. "net/http"
  20. "net/url"
  21. "path"
  22. "strings"
  23. "golang.org/x/net/context/ctxhttp"
  24. "moul.io/http2curl/v2"
  25. "yunion.io/x/log"
  26. "yunion.io/x/pkg/errors"
  27. "yunion.io/x/onecloud/pkg/apis/monitor"
  28. mod "yunion.io/x/onecloud/pkg/mcclient/modules/monitor"
  29. "yunion.io/x/onecloud/pkg/monitor/tsdb"
  30. )
  31. const (
  32. ErrInfluxdbInvalidResponse = errors.Error("Influxdb invalid status")
  33. )
  34. func init() {
  35. tsdb.RegisterTsdbQueryEndpoint(monitor.DataSourceTypeInfluxdb, NewInfluxdbExecutor)
  36. }
  37. type InfluxdbExecutor struct {
  38. QueryParser *InfluxdbQueryParser
  39. ResponseParser *ResponseParser
  40. }
  41. func NewInfluxdbExecutor(datasource *tsdb.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  42. return &InfluxdbExecutor{
  43. QueryParser: &InfluxdbQueryParser{},
  44. ResponseParser: &ResponseParser{},
  45. }, nil
  46. }
  47. func (e *InfluxdbExecutor) GetRawQuery(dsInfo *tsdb.DataSource, tsdbQuery *tsdb.TsdbQuery) (string, []*Query, error) {
  48. querys := make([]*tsdb.Query, len(tsdbQuery.Queries)+1)
  49. influxQ := make([]*Query, 0)
  50. copy(querys, tsdbQuery.Queries)
  51. var buffer bytes.Buffer
  52. var rawQuery string
  53. for i := 0; i < len(querys); i++ {
  54. query, err := e.getQuery(dsInfo, querys, tsdbQuery)
  55. if err != nil {
  56. return "", nil, errors.Wrap(err, "getQuery")
  57. }
  58. influxQ = append(influxQ, query)
  59. rawQuery, err := query.Build(tsdbQuery)
  60. if err != nil {
  61. return "", nil, errors.Wrap(err, "query.Build")
  62. }
  63. buffer.WriteString(rawQuery + ";")
  64. if len(querys) > 0 {
  65. querys = querys[1:]
  66. }
  67. }
  68. rawQuery = buffer.String()
  69. spitCount := strings.Count(rawQuery, ";")
  70. rawQuery = strings.Replace(rawQuery, ";", "", spitCount)
  71. //query, err := e.getQuery(dsInfo, tsdbQuery.Queries, tsdbQuery)
  72. //if err != nil {
  73. // return nil, err
  74. //}
  75. //
  76. //rawQuery, err := query.Build(tsdbQuery)
  77. //if err != nil {
  78. // return nil, err
  79. //}
  80. return rawQuery, influxQ, nil
  81. }
  82. func (e *InfluxdbExecutor) Query(ctx context.Context, dsInfo *tsdb.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  83. rawQuery, influxQ, err := e.GetRawQuery(dsInfo, tsdbQuery)
  84. if err != nil {
  85. return nil, errors.Wrap(err, "GetRawQuery")
  86. }
  87. db := dsInfo.Database
  88. if db == "" {
  89. db = tsdbQuery.Queries[0].Database
  90. }
  91. dsInfo.Database = db
  92. req, err := e.createRequest(dsInfo, rawQuery)
  93. if err != nil {
  94. return nil, err
  95. }
  96. httpClient, err := dsInfo.GetHttpClient()
  97. if err != nil {
  98. return nil, err
  99. }
  100. resp, err := ctxhttp.Do(ctx, httpClient, req)
  101. if err != nil {
  102. return nil, err
  103. }
  104. defer resp.Body.Close()
  105. if resp.StatusCode/100 != 2 {
  106. // TODO: convert status code err
  107. return nil, errors.Wrapf(ErrInfluxdbInvalidResponse, "status code: %v", resp.Status)
  108. }
  109. var response Response
  110. dec := json.NewDecoder(resp.Body)
  111. dec.UseNumber()
  112. if err := dec.Decode(&response); err != nil {
  113. return nil, err
  114. }
  115. if response.Err != nil {
  116. return nil, response.Err
  117. }
  118. result := &tsdb.Response{
  119. Results: make(map[string]*tsdb.QueryResult),
  120. }
  121. for i, query := range tsdbQuery.Queries {
  122. ret := e.ResponseParser.Parse(&response, influxQ[i])
  123. ret.Meta = monitor.QueryResultMeta{
  124. RawQuery: rawQuery,
  125. }
  126. result.Results[query.RefId] = ret
  127. }
  128. //ret := e.ResponseParser.Parse(&response, query)
  129. //ret.Meta = tsdb.QueryResultMeta{
  130. // RawQuery: rawQuery,
  131. //}
  132. //result.Results["A"] = ret
  133. return result, nil
  134. }
  135. func (e *InfluxdbExecutor) getQuery(dsInfo *tsdb.DataSource, queries []*tsdb.Query, context *tsdb.TsdbQuery) (*Query, error) {
  136. // The model supports multiple queries, but right now this is only used from
  137. // alerting so we only need to support batch executing 1 query at a time.
  138. if len(queries) > 0 {
  139. query, err := e.QueryParser.Parse(queries[0], dsInfo)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return query, nil
  144. }
  145. return nil, errors.Error("query request contains no queries")
  146. }
  147. func (e *InfluxdbExecutor) createRequest(dsInfo *tsdb.DataSource, query string) (*http.Request, error) {
  148. u, _ := url.Parse(dsInfo.Url)
  149. u.Path = path.Join(u.Path, "query")
  150. req, err := func() (*http.Request, error) {
  151. // use POST mode
  152. bodyValues := url.Values{}
  153. bodyValues.Add("q", query)
  154. body := bodyValues.Encode()
  155. return http.NewRequest(http.MethodPost, u.String(), strings.NewReader(body))
  156. }()
  157. if err != nil {
  158. return nil, err
  159. }
  160. req.Header.Set("User-Agent", "OneCloud Monitor")
  161. params := req.URL.Query()
  162. params.Set("db", dsInfo.Database)
  163. params.Set("epoch", "ms")
  164. req.Header.Set("Content-type", "application/x-www-form-urlencoded")
  165. req.URL.RawQuery = params.Encode()
  166. /*if dsInfo.BasicAuth {
  167. req.SetBasicAuth(dsinfo.BasicAuthUser, dsInfo.DecryptedBasicAuthPassword())
  168. }
  169. if !dsInfo.BasicAuth && dsInfo.User != "" {
  170. req.SetBasicAuth(dsInfo.User, dsInfo.DecryptedPassword())
  171. }*/
  172. curlCmd, _ := http2curl.GetCurlCommand(req)
  173. log.Debugf("Influxdb raw query: %q from db %s, curl: %s", query, dsInfo.Database, curlCmd)
  174. return req, nil
  175. }
  176. func (e *InfluxdbExecutor) FilterMeasurement(
  177. ctx context.Context,
  178. ds *tsdb.DataSource,
  179. from, to string,
  180. ms *monitor.InfluxMeasurement,
  181. tagFilter *monitor.MetricQueryTag,
  182. ) (*monitor.InfluxMeasurement, error) {
  183. retMs := new(monitor.InfluxMeasurement)
  184. q := mod.NewAlertQuery(ms.Database, ms.Measurement).From(from).To(to)
  185. q.Selects().Select("*").LAST()
  186. if tagFilter != nil {
  187. q.Where().AddTag(tagFilter)
  188. }
  189. tq := q.ToTsdbQuery()
  190. resp, err := e.Query(ctx, ds, tq)
  191. if err != nil {
  192. return nil, errors.Wrap(err, "influxdb.Query")
  193. }
  194. ss := resp.Results[""].Series
  195. //log.Infof("=====get ss: %s", jsonutils.Marshal(ss).PrettyString())
  196. // parse fields
  197. retFields := make([]string, 0)
  198. for _, s := range ss {
  199. cols := s.Columns
  200. for _, col := range cols {
  201. if !strings.Contains(col, "last") {
  202. continue
  203. }
  204. retFields = append(retFields, strings.Replace(col, "last_", "", 1))
  205. }
  206. }
  207. retMs.FieldKey = retFields
  208. if len(retMs.FieldKey) != 0 {
  209. retMs.Measurement = ms.Measurement
  210. retMs.Database = ms.Database
  211. retMs.ResType = ms.ResType
  212. }
  213. return retMs, nil
  214. }
  215. func FillSelectWithMean(query *monitor.AlertQuery) *monitor.AlertQuery {
  216. for i, sel := range query.Model.Selects {
  217. if len(sel) > 1 {
  218. continue
  219. }
  220. sel = append(sel, monitor.MetricQueryPart{
  221. Type: "mean",
  222. Params: []string{},
  223. })
  224. query.Model.Selects[i] = sel
  225. }
  226. return query
  227. }
  228. func (e *InfluxdbExecutor) FillSelect(query *monitor.AlertQuery, isAlert bool) *monitor.AlertQuery {
  229. return FillSelectWithMean(query)
  230. }
  231. func FillGroupByWithWildChar(query *monitor.AlertQuery, inputQuery *monitor.MetricQueryInput, tagId string) *monitor.AlertQuery {
  232. if len(tagId) == 0 || (len(inputQuery.Slimit) != 0 && len(inputQuery.Soffset) != 0) {
  233. tagId = "*"
  234. }
  235. if tagId != "" {
  236. query.Model.GroupBy = append(query.Model.GroupBy,
  237. monitor.MetricQueryPart{
  238. Type: "field",
  239. Params: []string{tagId},
  240. })
  241. }
  242. return query
  243. }
  244. func (e *InfluxdbExecutor) FillGroupBy(query *monitor.AlertQuery, inputQuery *monitor.MetricQueryInput, tagId string, isAlert bool) *monitor.AlertQuery {
  245. return FillGroupByWithWildChar(query, inputQuery, tagId)
  246. }