datasource_plugin.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package plugins
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "github.com/grafana/grafana/pkg/log"
  14. "github.com/grafana/grafana/pkg/models"
  15. "github.com/grafana/grafana/pkg/plugins/datasource/wrapper"
  16. "github.com/grafana/grafana/pkg/tsdb"
  17. "github.com/grafana/grafana_plugin_model/go/datasource"
  18. plugin "github.com/hashicorp/go-plugin"
  19. )
  20. type DataSourcePlugin struct {
  21. FrontendPluginBase
  22. Annotations bool `json:"annotations"`
  23. Metrics bool `json:"metrics"`
  24. Alerting bool `json:"alerting"`
  25. QueryOptions map[string]bool `json:"queryOptions,omitempty"`
  26. BuiltIn bool `json:"builtIn,omitempty"`
  27. Mixed bool `json:"mixed,omitempty"`
  28. HasQueryHelp bool `json:"hasQueryHelp,omitempty"`
  29. Routes []*AppPluginRoute `json:"routes"`
  30. Backend bool `json:"backend,omitempty"`
  31. Executable string `json:"executable,omitempty"`
  32. log log.Logger
  33. client *plugin.Client
  34. }
  35. func (p *DataSourcePlugin) Load(decoder *json.Decoder, pluginDir string) error {
  36. if err := decoder.Decode(&p); err != nil {
  37. return err
  38. }
  39. if err := p.registerPlugin(pluginDir); err != nil {
  40. return err
  41. }
  42. // look for help markdown
  43. helpPath := filepath.Join(p.PluginDir, "QUERY_HELP.md")
  44. if _, err := os.Stat(helpPath); os.IsNotExist(err) {
  45. helpPath = filepath.Join(p.PluginDir, "query_help.md")
  46. }
  47. if _, err := os.Stat(helpPath); err == nil {
  48. p.HasQueryHelp = true
  49. }
  50. DataSources[p.Id] = p
  51. return nil
  52. }
  53. var handshakeConfig = plugin.HandshakeConfig{
  54. ProtocolVersion: 1,
  55. MagicCookieKey: "grafana_plugin_type",
  56. MagicCookieValue: "datasource",
  57. }
  58. func composeBinaryName(executable, os, arch string) string {
  59. var extension string
  60. os = strings.ToLower(os)
  61. if os == "windows" {
  62. extension = ".exe"
  63. }
  64. return fmt.Sprintf("%s_%s_%s%s", executable, os, strings.ToLower(arch), extension)
  65. }
  66. func (p *DataSourcePlugin) startBackendPlugin(ctx context.Context, log log.Logger) error {
  67. p.log = log.New("plugin-id", p.Id)
  68. err := p.spawnSubProcess()
  69. if err == nil {
  70. go p.restartKilledProcess(ctx)
  71. }
  72. return err
  73. }
  74. func (p *DataSourcePlugin) spawnSubProcess() error {
  75. cmd := composeBinaryName(p.Executable, runtime.GOOS, runtime.GOARCH)
  76. fullpath := path.Join(p.PluginDir, cmd)
  77. p.client = plugin.NewClient(&plugin.ClientConfig{
  78. HandshakeConfig: handshakeConfig,
  79. Plugins: map[string]plugin.Plugin{p.Id: &datasource.DatasourcePluginImpl{}},
  80. Cmd: exec.Command(fullpath),
  81. AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
  82. Logger: LogWrapper{Logger: p.log},
  83. })
  84. rpcClient, err := p.client.Client()
  85. if err != nil {
  86. return err
  87. }
  88. raw, err := rpcClient.Dispense(p.Id)
  89. if err != nil {
  90. return err
  91. }
  92. plugin := raw.(datasource.DatasourcePlugin)
  93. tsdb.RegisterTsdbQueryEndpoint(p.Id, func(dsInfo *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  94. return wrapper.NewDatasourcePluginWrapper(p.log, plugin), nil
  95. })
  96. return nil
  97. }
  98. func (p *DataSourcePlugin) restartKilledProcess(ctx context.Context) error {
  99. ticker := time.NewTicker(time.Second * 1)
  100. for {
  101. select {
  102. case <-ctx.Done():
  103. return ctx.Err()
  104. case <-ticker.C:
  105. if p.client.Exited() {
  106. err := p.spawnSubProcess()
  107. p.log.Debug("Spawning new sub process", "name", p.Name, "id", p.Id)
  108. if err != nil {
  109. p.log.Error("Failed to spawn subprocess")
  110. }
  111. }
  112. }
  113. }
  114. }
  115. func (p *DataSourcePlugin) Kill() {
  116. if p.client != nil {
  117. p.log.Debug("Killing subprocess ", "name", p.Name)
  118. p.client.Kill()
  119. }
  120. }