grpc.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package notifier
  2. import (
  3. "context"
  4. "time"
  5. "google.golang.org/protobuf/types/known/emptypb"
  6. "google.golang.org/protobuf/types/known/timestamppb"
  7. "github.com/drakkan/sftpgo/v2/sdk/plugin/notifier/proto"
  8. )
  9. const (
  10. rpcTimeout = 20 * time.Second
  11. )
  12. // GRPCClient is an implementation of Notifier interface that talks over RPC.
  13. type GRPCClient struct {
  14. client proto.NotifierClient
  15. }
  16. // NotifyFsEvent implements the Notifier interface
  17. func (c *GRPCClient) NotifyFsEvent(timestamp time.Time, action, username, fsPath, fsTargetPath, sshCmd, protocol string, fileSize int64, status int) error {
  18. ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
  19. defer cancel()
  20. _, err := c.client.SendFsEvent(ctx, &proto.FsEvent{
  21. Timestamp: timestamppb.New(timestamp),
  22. Action: action,
  23. Username: username,
  24. FsPath: fsPath,
  25. FsTargetPath: fsTargetPath,
  26. SshCmd: sshCmd,
  27. FileSize: fileSize,
  28. Protocol: protocol,
  29. Status: int32(status),
  30. })
  31. return err
  32. }
  33. // NotifyUserEvent implements the Notifier interface
  34. func (c *GRPCClient) NotifyUserEvent(timestamp time.Time, action string, user []byte) error {
  35. ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
  36. defer cancel()
  37. _, err := c.client.SendUserEvent(ctx, &proto.UserEvent{
  38. Timestamp: timestamppb.New(timestamp),
  39. Action: action,
  40. User: user,
  41. })
  42. return err
  43. }
  44. // GRPCServer defines the gRPC server that GRPCClient talks to.
  45. type GRPCServer struct {
  46. Impl Notifier
  47. }
  48. // SendFsEvent implements the serve side fs notify method
  49. func (s *GRPCServer) SendFsEvent(ctx context.Context, req *proto.FsEvent) (*emptypb.Empty, error) {
  50. err := s.Impl.NotifyFsEvent(req.Timestamp.AsTime(), req.Action, req.Username, req.FsPath, req.FsTargetPath, req.SshCmd,
  51. req.Protocol, req.FileSize, int(req.Status))
  52. return &emptypb.Empty{}, err
  53. }
  54. // SendUserEvent implements the serve side user notify method
  55. func (s *GRPCServer) SendUserEvent(ctx context.Context, req *proto.UserEvent) (*emptypb.Empty, error) {
  56. err := s.Impl.NotifyUserEvent(req.Timestamp.AsTime(), req.Action, req.User)
  57. return &emptypb.Empty{}, err
  58. }