backend_datasource.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package plugins
  2. import (
  3. "context"
  4. "encoding/json"
  5. "os/exec"
  6. "path"
  7. "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/plugins/backend"
  9. "github.com/grafana/grafana/pkg/tsdb"
  10. "github.com/grafana/grafana/pkg/log"
  11. proto "github.com/grafana/grafana/pkg/tsdb/models"
  12. shared "github.com/grafana/grafana/pkg/tsdb/models/proxy"
  13. plugin "github.com/hashicorp/go-plugin"
  14. )
  15. type BackendDatasource struct {
  16. *PluginBase
  17. Executable string
  18. client *plugin.Client
  19. }
  20. type Killable interface {
  21. Kill()
  22. }
  23. type NoopKiller struct{}
  24. func (nk NoopKiller) Kill() {}
  25. func (p *BackendDatasource) initBackendPlugin() (Killable, error) {
  26. logger := log.New("grafana.plugins")
  27. p.client = plugin.NewClient(&plugin.ClientConfig{
  28. HandshakeConfig: plugin.HandshakeConfig{
  29. ProtocolVersion: 1,
  30. MagicCookieKey: "BASIC_PLUGIN",
  31. MagicCookieValue: "hello",
  32. },
  33. Plugins: map[string]plugin.Plugin{p.Id: &shared.TsdbPluginImpl{}},
  34. Cmd: exec.Command("sh", "-c", path.Join(p.PluginDir, p.Executable)),
  35. AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
  36. Logger: backend.LogWrapper{Logger: logger},
  37. })
  38. rpcClient, err := p.client.Client()
  39. if err != nil {
  40. return NoopKiller{}, err
  41. }
  42. raw, err := rpcClient.Dispense(p.Id)
  43. if err != nil {
  44. return NoopKiller{}, err
  45. }
  46. plugin := raw.(shared.TsdbPlugin)
  47. response, err := plugin.Query(context.Background(), &proto.TsdbQuery{})
  48. if err != nil {
  49. logger.Error("Response from plugin. ", "response", response)
  50. } else {
  51. logger.Info("Response from plugin. ", "response", response)
  52. }
  53. tsdb.RegisterTsdbQueryEndpoint(p.Id, func(dsInfo *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  54. return &shared.TsdbWrapper{TsdbPlugin: plugin}, nil
  55. })
  56. return p.client, nil
  57. }
  58. func (p *BackendDatasource) Kill() {
  59. p.client.Kill()
  60. }
  61. func (p *BackendDatasource) Load(decoder *json.Decoder, pluginDir string) error {
  62. if err := decoder.Decode(&p); err != nil {
  63. return err
  64. }
  65. if err := p.registerPlugin(pluginDir); err != nil {
  66. return err
  67. }
  68. BackendDatasources[p.Id] = p
  69. return nil
  70. }