response_parser.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // wildcard as alias
  12. // add host to alias
  13. // add app to alias
  14. // regular alias
  15. func NewResponseParser() *MQEResponseParser {
  16. return &MQEResponseParser{
  17. log: log.New("tsdb.mqe"),
  18. }
  19. }
  20. type MQEResponse struct {
  21. Success bool `json:"success"`
  22. Name string `json:"name"`
  23. Body []MQEResponseSerie `json:"body"`
  24. }
  25. type ResponseTimeRange struct {
  26. Start int64 `json:"start"`
  27. End int64 `json:"end"`
  28. Resolution int64 `json:"Resolution"`
  29. }
  30. type MQEResponseSerie struct {
  31. Query string `json:"query"`
  32. Name string `json:"name"`
  33. Type string `json:"type"`
  34. Series []MQESerie `json:"series"`
  35. TimeRange ResponseTimeRange `json:"timerange"`
  36. }
  37. type MQESerie struct {
  38. Values []null.Float `json:"values"`
  39. Tagset map[string]string `json:"tagset"`
  40. }
  41. type MQEResponseParser struct {
  42. log log.Logger
  43. }
  44. func (parser *MQEResponseParser) Parse(res *http.Response) (*tsdb.QueryResult, error) {
  45. body, err := ioutil.ReadAll(res.Body)
  46. defer res.Body.Close()
  47. if err != nil {
  48. return nil, err
  49. }
  50. if res.StatusCode/100 != 2 {
  51. parser.log.Error("Request failed", "status code", res.StatusCode, "body", string(body))
  52. return nil, fmt.Errorf("Returned invalid statuscode")
  53. }
  54. var data *MQEResponse = &MQEResponse{}
  55. err = json.Unmarshal(body, data)
  56. if err != nil {
  57. parser.log.Info("Failed to unmarshal graphite response", "error", err, "status", res.Status, "body", string(body))
  58. return nil, err
  59. }
  60. if !data.Success {
  61. return nil, fmt.Errorf("MQE request failed.")
  62. }
  63. var series tsdb.TimeSeriesSlice
  64. for _, v := range data.Body {
  65. for _, k := range v.Series {
  66. serie := &tsdb.TimeSeries{
  67. Name: v.Name,
  68. }
  69. for i, value := range k.Values {
  70. timestamp := v.TimeRange.Start + int64(i)*v.TimeRange.Resolution
  71. serie.Points = append(serie.Points, tsdb.NewTimePoint(value, float64(timestamp)))
  72. }
  73. series = append(series, serie)
  74. }
  75. }
  76. return &tsdb.QueryResult{Series: series}, nil
  77. }