grpc.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, ip,
  18. virtualPath, virtualTargetPath string, fileSize int64, status int,
  19. ) error {
  20. ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
  21. defer cancel()
  22. _, err := c.client.SendFsEvent(ctx, &proto.FsEvent{
  23. Timestamp: timestamppb.New(timestamp),
  24. Action: action,
  25. Username: username,
  26. FsPath: fsPath,
  27. FsTargetPath: fsTargetPath,
  28. SshCmd: sshCmd,
  29. FileSize: fileSize,
  30. Protocol: protocol,
  31. Ip: ip,
  32. Status: int32(status),
  33. VirtualPath: virtualPath,
  34. VirtualTargetPath: virtualTargetPath,
  35. })
  36. return err
  37. }
  38. // NotifyProviderEvent implements the Notifier interface
  39. func (c *GRPCClient) NotifyProviderEvent(timestamp time.Time, action, username, objectType, objectName, ip string, object []byte) error {
  40. ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
  41. defer cancel()
  42. _, err := c.client.SendProviderEvent(ctx, &proto.ProviderEvent{
  43. Timestamp: timestamppb.New(timestamp),
  44. Action: action,
  45. ObjectType: objectType,
  46. Username: username,
  47. Ip: ip,
  48. ObjectName: objectName,
  49. ObjectData: object,
  50. })
  51. return err
  52. }
  53. // GRPCServer defines the gRPC server that GRPCClient talks to.
  54. type GRPCServer struct {
  55. Impl Notifier
  56. }
  57. // SendFsEvent implements the serve side fs notify method
  58. func (s *GRPCServer) SendFsEvent(ctx context.Context, req *proto.FsEvent) (*emptypb.Empty, error) {
  59. err := s.Impl.NotifyFsEvent(req.Timestamp.AsTime(), req.Action, req.Username, req.FsPath, req.FsTargetPath, req.SshCmd,
  60. req.Protocol, req.Ip, req.VirtualPath, req.VirtualTargetPath, req.FileSize, int(req.Status))
  61. return &emptypb.Empty{}, err
  62. }
  63. // SendProviderEvent implements the serve side provider event notify method
  64. func (s *GRPCServer) SendProviderEvent(ctx context.Context, req *proto.ProviderEvent) (*emptypb.Empty, error) {
  65. err := s.Impl.NotifyProviderEvent(req.Timestamp.AsTime(), req.Action, req.Username, req.ObjectType, req.ObjectName,
  66. req.Ip, req.ObjectData)
  67. return &emptypb.Empty{}, err
  68. }