notifier.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package csplugin
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/crowdsecurity/crowdsec/pkg/protobufs"
  6. plugin "github.com/hashicorp/go-plugin"
  7. "google.golang.org/grpc"
  8. )
  9. type Notifier interface {
  10. Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error)
  11. Configure(ctx context.Context, cfg *protobufs.Config) (*protobufs.Empty, error)
  12. }
  13. type NotifierPlugin struct {
  14. plugin.Plugin
  15. Impl Notifier
  16. }
  17. type GRPCClient struct{ client protobufs.NotifierClient }
  18. func (m *GRPCClient) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) {
  19. done := make(chan error)
  20. go func() {
  21. _, err := m.client.Notify(
  22. context.Background(), &protobufs.Notification{Text: notification.Text, Name: notification.Name},
  23. )
  24. done <- err
  25. }()
  26. select {
  27. case err := <-done:
  28. return &protobufs.Empty{}, err
  29. case <-ctx.Done():
  30. return &protobufs.Empty{}, fmt.Errorf("timeout exceeded")
  31. }
  32. }
  33. func (m *GRPCClient) Configure(ctx context.Context, config *protobufs.Config) (*protobufs.Empty, error) {
  34. _, err := m.client.Configure(
  35. context.Background(), config,
  36. )
  37. return &protobufs.Empty{}, err
  38. }
  39. type GRPCServer struct {
  40. Impl Notifier
  41. }
  42. func (p *NotifierPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error {
  43. protobufs.RegisterNotifierServer(s, p.Impl)
  44. return nil
  45. }
  46. func (p *NotifierPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
  47. return &GRPCClient{client: protobufs.NewNotifierClient(c)}, nil
  48. }