notifier.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package plugin
  15. import (
  16. "crypto/sha256"
  17. "fmt"
  18. "os/exec"
  19. "sync"
  20. "time"
  21. "github.com/hashicorp/go-hclog"
  22. "github.com/hashicorp/go-plugin"
  23. "github.com/sftpgo/sdk/plugin/notifier"
  24. "github.com/drakkan/sftpgo/v2/internal/logger"
  25. "github.com/drakkan/sftpgo/v2/internal/util"
  26. )
  27. // NotifierConfig defines configuration parameters for notifiers plugins
  28. type NotifierConfig struct {
  29. FsEvents []string `json:"fs_events" mapstructure:"fs_events"`
  30. ProviderEvents []string `json:"provider_events" mapstructure:"provider_events"`
  31. ProviderObjects []string `json:"provider_objects" mapstructure:"provider_objects"`
  32. RetryMaxTime int `json:"retry_max_time" mapstructure:"retry_max_time"`
  33. RetryQueueMaxSize int `json:"retry_queue_max_size" mapstructure:"retry_queue_max_size"`
  34. }
  35. func (c *NotifierConfig) hasActions() bool {
  36. if len(c.FsEvents) > 0 {
  37. return true
  38. }
  39. if len(c.ProviderEvents) > 0 && len(c.ProviderObjects) > 0 {
  40. return true
  41. }
  42. return false
  43. }
  44. type eventsQueue struct {
  45. sync.RWMutex
  46. fsEvents []*notifier.FsEvent
  47. providerEvents []*notifier.ProviderEvent
  48. }
  49. func (q *eventsQueue) addFsEvent(event *notifier.FsEvent) {
  50. q.Lock()
  51. defer q.Unlock()
  52. q.fsEvents = append(q.fsEvents, event)
  53. }
  54. func (q *eventsQueue) addProviderEvent(event *notifier.ProviderEvent) {
  55. q.Lock()
  56. defer q.Unlock()
  57. q.providerEvents = append(q.providerEvents, event)
  58. }
  59. func (q *eventsQueue) popFsEvent() *notifier.FsEvent {
  60. q.Lock()
  61. defer q.Unlock()
  62. if len(q.fsEvents) == 0 {
  63. return nil
  64. }
  65. truncLen := len(q.fsEvents) - 1
  66. ev := q.fsEvents[truncLen]
  67. q.fsEvents[truncLen] = nil
  68. q.fsEvents = q.fsEvents[:truncLen]
  69. return ev
  70. }
  71. func (q *eventsQueue) popProviderEvent() *notifier.ProviderEvent {
  72. q.Lock()
  73. defer q.Unlock()
  74. if len(q.providerEvents) == 0 {
  75. return nil
  76. }
  77. truncLen := len(q.providerEvents) - 1
  78. ev := q.providerEvents[truncLen]
  79. q.providerEvents[truncLen] = nil
  80. q.providerEvents = q.providerEvents[:truncLen]
  81. return ev
  82. }
  83. func (q *eventsQueue) getSize() int {
  84. q.RLock()
  85. defer q.RUnlock()
  86. return len(q.providerEvents) + len(q.fsEvents)
  87. }
  88. type notifierPlugin struct {
  89. config Config
  90. notifier notifier.Notifier
  91. client *plugin.Client
  92. queue *eventsQueue
  93. }
  94. func newNotifierPlugin(config Config) (*notifierPlugin, error) {
  95. p := &notifierPlugin{
  96. config: config,
  97. queue: &eventsQueue{},
  98. }
  99. if err := p.initialize(); err != nil {
  100. logger.Warn(logSender, "", "unable to create notifier plugin: %v, config %+v", err, config)
  101. return nil, err
  102. }
  103. return p, nil
  104. }
  105. func (p *notifierPlugin) exited() bool {
  106. return p.client.Exited()
  107. }
  108. func (p *notifierPlugin) cleanup() {
  109. p.client.Kill()
  110. }
  111. func (p *notifierPlugin) initialize() error {
  112. killProcess(p.config.Cmd)
  113. logger.Debug(logSender, "", "create new notifier plugin %#v", p.config.Cmd)
  114. if !p.config.NotifierOptions.hasActions() {
  115. return fmt.Errorf("no actions defined for the notifier plugin %#v", p.config.Cmd)
  116. }
  117. var secureConfig *plugin.SecureConfig
  118. if p.config.SHA256Sum != "" {
  119. secureConfig.Checksum = []byte(p.config.SHA256Sum)
  120. secureConfig.Hash = sha256.New()
  121. }
  122. client := plugin.NewClient(&plugin.ClientConfig{
  123. HandshakeConfig: notifier.Handshake,
  124. Plugins: notifier.PluginMap,
  125. Cmd: exec.Command(p.config.Cmd, p.config.Args...),
  126. AllowedProtocols: []plugin.Protocol{
  127. plugin.ProtocolGRPC,
  128. },
  129. AutoMTLS: p.config.AutoMTLS,
  130. SecureConfig: secureConfig,
  131. Managed: false,
  132. Logger: &logger.HCLogAdapter{
  133. Logger: hclog.New(&hclog.LoggerOptions{
  134. Name: fmt.Sprintf("%v.%v", logSender, notifier.PluginName),
  135. Level: pluginsLogLevel,
  136. DisableTime: true,
  137. }),
  138. },
  139. })
  140. rpcClient, err := client.Client()
  141. if err != nil {
  142. logger.Debug(logSender, "", "unable to get rpc client for plugin %#v: %v", p.config.Cmd, err)
  143. return err
  144. }
  145. raw, err := rpcClient.Dispense(notifier.PluginName)
  146. if err != nil {
  147. logger.Debug(logSender, "", "unable to get plugin %v from rpc client for command %#v: %v",
  148. notifier.PluginName, p.config.Cmd, err)
  149. return err
  150. }
  151. p.client = client
  152. p.notifier = raw.(notifier.Notifier)
  153. return nil
  154. }
  155. func (p *notifierPlugin) canQueueEvent(timestamp int64) bool {
  156. if p.config.NotifierOptions.RetryMaxTime == 0 {
  157. return false
  158. }
  159. if time.Now().After(time.Unix(0, timestamp).Add(time.Duration(p.config.NotifierOptions.RetryMaxTime) * time.Second)) {
  160. logger.Warn(logSender, "", "dropping too late event for plugin %v, event timestamp: %v",
  161. p.config.Cmd, time.Unix(0, timestamp))
  162. return false
  163. }
  164. if p.config.NotifierOptions.RetryQueueMaxSize > 0 {
  165. return p.queue.getSize() < p.config.NotifierOptions.RetryQueueMaxSize
  166. }
  167. return true
  168. }
  169. func (p *notifierPlugin) notifyFsAction(event *notifier.FsEvent) {
  170. if !util.Contains(p.config.NotifierOptions.FsEvents, event.Action) {
  171. return
  172. }
  173. go func() {
  174. Handler.addTask()
  175. defer Handler.removeTask()
  176. p.sendFsEvent(event)
  177. }()
  178. }
  179. func (p *notifierPlugin) notifyProviderAction(event *notifier.ProviderEvent, object Renderer) {
  180. if !util.Contains(p.config.NotifierOptions.ProviderEvents, event.Action) ||
  181. !util.Contains(p.config.NotifierOptions.ProviderObjects, event.ObjectType) {
  182. return
  183. }
  184. go func() {
  185. Handler.addTask()
  186. defer Handler.removeTask()
  187. objectAsJSON, err := object.RenderAsJSON(event.Action != "delete")
  188. if err != nil {
  189. logger.Warn(logSender, "", "unable to render user as json for action %v: %v", event.Action, err)
  190. return
  191. }
  192. event.ObjectData = objectAsJSON
  193. p.sendProviderEvent(event)
  194. }()
  195. }
  196. func (p *notifierPlugin) sendFsEvent(event *notifier.FsEvent) {
  197. if err := p.notifier.NotifyFsEvent(event); err != nil {
  198. logger.Warn(logSender, "", "unable to send fs action notification to plugin %v: %v", p.config.Cmd, err)
  199. if p.canQueueEvent(event.Timestamp) {
  200. p.queue.addFsEvent(event)
  201. }
  202. }
  203. }
  204. func (p *notifierPlugin) sendProviderEvent(event *notifier.ProviderEvent) {
  205. if err := p.notifier.NotifyProviderEvent(event); err != nil {
  206. logger.Warn(logSender, "", "unable to send user action notification to plugin %v: %v", p.config.Cmd, err)
  207. if p.canQueueEvent(event.Timestamp) {
  208. p.queue.addProviderEvent(event)
  209. }
  210. }
  211. }
  212. func (p *notifierPlugin) sendQueuedEvents() {
  213. queueSize := p.queue.getSize()
  214. if queueSize == 0 {
  215. return
  216. }
  217. logger.Debug(logSender, "", "check queued events for notifier %#v, events size: %v", p.config.Cmd, queueSize)
  218. fsEv := p.queue.popFsEvent()
  219. for fsEv != nil {
  220. go func(ev *notifier.FsEvent) {
  221. p.sendFsEvent(ev)
  222. }(fsEv)
  223. fsEv = p.queue.popFsEvent()
  224. }
  225. providerEv := p.queue.popProviderEvent()
  226. for providerEv != nil {
  227. go func(ev *notifier.ProviderEvent) {
  228. p.sendProviderEvent(ev)
  229. }(providerEv)
  230. providerEv = p.queue.popProviderEvent()
  231. }
  232. logger.Debug(logSender, "", "queued events sent for notifier %#v, new events size: %v", p.config.Cmd, p.queue.getSize())
  233. }