grpc.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, sessionID 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. SessionId: sessionID,
  35. })
  36. return err
  37. }
  38. // NotifyProviderEvent implements the Notifier interface
  39. func (c *GRPCClient) NotifyProviderEvent(timestamp int64, 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: 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, req.Action, req.Username, req.FsPath, req.FsTargetPath, req.SshCmd,
  60. req.Protocol, req.Ip, req.VirtualPath, req.VirtualTargetPath, req.SessionId, 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, req.Action, req.Username, req.ObjectType, req.ObjectName,
  66. req.Ip, req.ObjectData)
  67. return &emptypb.Empty{}, err
  68. }