response_parser.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package mqe
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. null "gopkg.in/guregu/null.v3"
  7. "fmt"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/tsdb"
  10. )
  11. func NewResponseParser() *ResponseParser {
  12. return &ResponseParser{
  13. log: log.New("tsdb.mqe"),
  14. }
  15. }
  16. type MQEResponse struct {
  17. Success bool `json:"success"`
  18. Name string `json:"name"`
  19. Body []MQEResponseSerie `json:"body"`
  20. }
  21. type ResponseTimeRange struct {
  22. Start int64 `json:"start"`
  23. End int64 `json:"end"`
  24. Resolution int64 `json:"Resolution"`
  25. }
  26. type MQEResponseSerie struct {
  27. Query string `json:"query"`
  28. Name string `json:"name"`
  29. Type string `json:"type"`
  30. Series []MQESerie `json:"series"`
  31. TimeRange ResponseTimeRange `json:"timerange"`
  32. }
  33. type MQESerie struct {
  34. Values []null.Float `json:"values"`
  35. Tagset map[string]string `json:"tagset"`
  36. }
  37. type ResponseParser struct {
  38. log log.Logger
  39. }
  40. func (parser *ResponseParser) Parse(res *http.Response, queryRef *Query) (*tsdb.QueryResult, error) {
  41. body, err := ioutil.ReadAll(res.Body)
  42. defer res.Body.Close()
  43. if err != nil {
  44. return nil, err
  45. }
  46. if res.StatusCode/100 != 2 {
  47. parser.log.Error("Request failed", "status code", res.StatusCode, "body", string(body))
  48. return nil, fmt.Errorf("Returned invalid statuscode")
  49. }
  50. var data *MQEResponse = &MQEResponse{}
  51. err = json.Unmarshal(body, data)
  52. if err != nil {
  53. parser.log.Info("Failed to unmarshal response", "error", err, "status", res.Status, "body", string(body))
  54. return nil, err
  55. }
  56. if !data.Success {
  57. return nil, fmt.Errorf("Request failed.")
  58. }
  59. var series tsdb.TimeSeriesSlice
  60. for _, body := range data.Body {
  61. for _, mqeSerie := range body.Series {
  62. namePrefix := ""
  63. //append predefined tags to seriename
  64. for key, value := range mqeSerie.Tagset {
  65. if key == "app" && queryRef.AddAppToAlias {
  66. namePrefix += value + " "
  67. }
  68. if key == "host" && queryRef.AddHostToAlias {
  69. namePrefix += value + " "
  70. }
  71. }
  72. serie := &tsdb.TimeSeries{Name: namePrefix + body.Name}
  73. for i, value := range mqeSerie.Values {
  74. timestamp := body.TimeRange.Start + int64(i)*body.TimeRange.Resolution
  75. serie.Points = append(serie.Points, tsdb.NewTimePoint(value, float64(timestamp)))
  76. }
  77. series = append(series, serie)
  78. }
  79. }
  80. return &tsdb.QueryResult{Series: series}, nil
  81. }