searcher.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package plugin
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "os/exec"
  6. "github.com/hashicorp/go-hclog"
  7. "github.com/hashicorp/go-plugin"
  8. "github.com/sftpgo/sdk/plugin/eventsearcher"
  9. "github.com/drakkan/sftpgo/v2/logger"
  10. )
  11. type searcherPlugin struct {
  12. config Config
  13. searchear eventsearcher.Searcher
  14. client *plugin.Client
  15. }
  16. func newSearcherPlugin(config Config) (*searcherPlugin, error) {
  17. p := &searcherPlugin{
  18. config: config,
  19. }
  20. if err := p.initialize(); err != nil {
  21. logger.Warn(logSender, "", "unable to create events searcher plugin: %v, config %+v", err, config)
  22. return nil, err
  23. }
  24. return p, nil
  25. }
  26. func (p *searcherPlugin) exited() bool {
  27. return p.client.Exited()
  28. }
  29. func (p *searcherPlugin) cleanup() {
  30. p.client.Kill()
  31. }
  32. func (p *searcherPlugin) initialize() error {
  33. killProcess(p.config.Cmd)
  34. logger.Debug(logSender, "", "create new searcher plugin %#v", p.config.Cmd)
  35. var secureConfig *plugin.SecureConfig
  36. if p.config.SHA256Sum != "" {
  37. secureConfig.Checksum = []byte(p.config.SHA256Sum)
  38. secureConfig.Hash = sha256.New()
  39. }
  40. client := plugin.NewClient(&plugin.ClientConfig{
  41. HandshakeConfig: eventsearcher.Handshake,
  42. Plugins: eventsearcher.PluginMap,
  43. Cmd: exec.Command(p.config.Cmd, p.config.Args...),
  44. AllowedProtocols: []plugin.Protocol{
  45. plugin.ProtocolGRPC,
  46. },
  47. AutoMTLS: p.config.AutoMTLS,
  48. SecureConfig: secureConfig,
  49. Managed: false,
  50. Logger: &logger.HCLogAdapter{
  51. Logger: hclog.New(&hclog.LoggerOptions{
  52. Name: fmt.Sprintf("%v.%v", logSender, eventsearcher.PluginName),
  53. Level: pluginsLogLevel,
  54. DisableTime: true,
  55. }),
  56. },
  57. })
  58. rpcClient, err := client.Client()
  59. if err != nil {
  60. logger.Debug(logSender, "", "unable to get rpc client for plugin %#v: %v", p.config.Cmd, err)
  61. return err
  62. }
  63. raw, err := rpcClient.Dispense(eventsearcher.PluginName)
  64. if err != nil {
  65. logger.Debug(logSender, "", "unable to get plugin %v from rpc client for command %#v: %v",
  66. eventsearcher.PluginName, p.config.Cmd, err)
  67. return err
  68. }
  69. p.client = client
  70. p.searchear = raw.(eventsearcher.Searcher)
  71. return nil
  72. }