grpc.go 2.4 KB

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