datasource_plugin_wrapper.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package tsdb
  2. import (
  3. "github.com/golang/protobuf/ptypes"
  4. "github.com/grafana/grafana/pkg/components/null"
  5. "github.com/grafana/grafana/pkg/models"
  6. "github.com/grafana/grafana/pkg/tsdb"
  7. proto "github.com/grafana/grafana/pkg/tsdb/models"
  8. "golang.org/x/net/context"
  9. )
  10. type DatasourcePluginWrapper struct {
  11. TsdbPlugin
  12. }
  13. func (tw *DatasourcePluginWrapper) Query(ctx context.Context, ds *models.DataSource, query *tsdb.TsdbQuery) (*tsdb.Response, error) {
  14. jsonData, err := ds.JsonData.MarshalJSON()
  15. if err != nil {
  16. return nil, err
  17. }
  18. now, err := ptypes.TimestampProto(query.TimeRange.Now)
  19. if err != nil {
  20. return nil, err
  21. }
  22. pbQuery := &proto.TsdbQuery{
  23. Datasource: &proto.DatasourceInfo{
  24. Access: string(ds.Access),
  25. BasicAuth: ds.BasicAuth,
  26. BasicAuthUser: ds.BasicAuthUser,
  27. BasicAuthPassword: ds.BasicAuthPassword,
  28. JsonData: string(jsonData),
  29. Name: ds.Name,
  30. Type: ds.Type,
  31. Url: ds.Url,
  32. Id: ds.Id,
  33. OrgId: ds.OrgId,
  34. },
  35. Timerange: &proto.Timerange{
  36. From: query.TimeRange.From,
  37. To: query.TimeRange.To,
  38. Now: now,
  39. },
  40. Queries: []*proto.Query{},
  41. }
  42. for _, q := range query.Queries {
  43. modelJson, _ := q.Model.MarshalJSON()
  44. pbQuery.Queries = append(pbQuery.Queries, &proto.Query{
  45. ModelJson: string(modelJson),
  46. IntervalMs: q.IntervalMs,
  47. RefId: q.RefId,
  48. MaxDataPoints: q.MaxDataPoints,
  49. })
  50. }
  51. pbres, err := tw.TsdbPlugin.Query(ctx, pbQuery)
  52. if err != nil {
  53. return nil, err
  54. }
  55. res := &tsdb.Response{
  56. Message: pbres.Message,
  57. Results: map[string]*tsdb.QueryResult{},
  58. }
  59. for _, r := range pbres.Results {
  60. res.Results[r.RefId] = &tsdb.QueryResult{
  61. RefId: r.RefId,
  62. Series: []*tsdb.TimeSeries{},
  63. }
  64. for _, s := range r.Series {
  65. points := tsdb.TimeSeriesPoints{}
  66. for _, p := range s.Points {
  67. po := tsdb.NewTimePoint(null.FloatFrom(p.Value), float64(p.Timestamp))
  68. points = append(points, po)
  69. }
  70. res.Results[r.RefId].Series = append(res.Results[r.RefId].Series, &tsdb.TimeSeries{
  71. Name: s.Name,
  72. Tags: s.Tags,
  73. Points: points,
  74. })
  75. }
  76. }
  77. return res, nil
  78. }