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