datasource_plugin.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package plugins
  2. import (
  3. "encoding/json"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "path/filepath"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/models"
  10. "github.com/grafana/grafana/pkg/plugins/backend"
  11. "github.com/grafana/grafana/pkg/tsdb"
  12. shared "github.com/grafana/grafana/pkg/tsdb/models/proxy"
  13. plugin "github.com/hashicorp/go-plugin"
  14. )
  15. type DataSourcePlugin struct {
  16. FrontendPluginBase
  17. Annotations bool `json:"annotations"`
  18. Metrics bool `json:"metrics"`
  19. Alerting bool `json:"alerting"`
  20. QueryOptions map[string]bool `json:"queryOptions,omitempty"`
  21. BuiltIn bool `json:"builtIn,omitempty"`
  22. Mixed bool `json:"mixed,omitempty"`
  23. HasQueryHelp bool `json:"hasQueryHelp,omitempty"`
  24. Routes []*AppPluginRoute `json:"routes"`
  25. Backend bool `json:"backend,omitempty"`
  26. Executable string `json:"executable,omitempty"`
  27. log log.Logger
  28. client *plugin.Client
  29. }
  30. func (p *DataSourcePlugin) Load(decoder *json.Decoder, pluginDir string) error {
  31. if err := decoder.Decode(&p); err != nil {
  32. return err
  33. }
  34. if err := p.registerPlugin(pluginDir); err != nil {
  35. return err
  36. }
  37. // look for help markdown
  38. helpPath := filepath.Join(p.PluginDir, "QUERY_HELP.md")
  39. if _, err := os.Stat(helpPath); os.IsNotExist(err) {
  40. helpPath = filepath.Join(p.PluginDir, "query_help.md")
  41. }
  42. if _, err := os.Stat(helpPath); err == nil {
  43. p.HasQueryHelp = true
  44. }
  45. DataSources[p.Id] = p
  46. return nil
  47. }
  48. func (p *DataSourcePlugin) initBackendPlugin(log log.Logger) error {
  49. p.log = log.New("plugin-id", p.Id)
  50. p.client = plugin.NewClient(&plugin.ClientConfig{
  51. HandshakeConfig: handshakeConfig,
  52. Plugins: map[string]plugin.Plugin{p.Id: &shared.TsdbPluginImpl{}},
  53. Cmd: exec.Command(path.Join(p.PluginDir, p.Executable)),
  54. AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
  55. Logger: backend.LogWrapper{Logger: p.log},
  56. })
  57. rpcClient, err := p.client.Client()
  58. if err != nil {
  59. return err
  60. }
  61. raw, err := rpcClient.Dispense(p.Id)
  62. if err != nil {
  63. return err
  64. }
  65. plugin := raw.(shared.TsdbPlugin)
  66. tsdb.RegisterTsdbQueryEndpoint(p.Id, func(dsInfo *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  67. return &shared.TsdbWrapper{TsdbPlugin: plugin}, nil
  68. })
  69. return nil
  70. }
  71. func (p *DataSourcePlugin) Kill() {
  72. p.client.Kill()
  73. }