1
0

notifier.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Copyright (C) 2019-2023 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. "fmt"
  17. "os/exec"
  18. "sync"
  19. "time"
  20. "github.com/hashicorp/go-hclog"
  21. "github.com/hashicorp/go-plugin"
  22. "github.com/sftpgo/sdk/plugin/notifier"
  23. "github.com/drakkan/sftpgo/v2/internal/logger"
  24. "github.com/drakkan/sftpgo/v2/internal/util"
  25. )
  26. // NotifierConfig defines configuration parameters for notifiers plugins
  27. type NotifierConfig struct {
  28. FsEvents []string `json:"fs_events" mapstructure:"fs_events"`
  29. ProviderEvents []string `json:"provider_events" mapstructure:"provider_events"`
  30. ProviderObjects []string `json:"provider_objects" mapstructure:"provider_objects"`
  31. LogEvents []int `json:"log_events" mapstructure:"log_events"`
  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. logEvents []*notifier.LogEvent
  49. }
  50. func (q *eventsQueue) addFsEvent(event *notifier.FsEvent) {
  51. q.Lock()
  52. defer q.Unlock()
  53. q.fsEvents = append(q.fsEvents, event)
  54. }
  55. func (q *eventsQueue) addProviderEvent(event *notifier.ProviderEvent) {
  56. q.Lock()
  57. defer q.Unlock()
  58. q.providerEvents = append(q.providerEvents, event)
  59. }
  60. func (q *eventsQueue) addLogEvent(event *notifier.LogEvent) {
  61. q.Lock()
  62. defer q.Unlock()
  63. q.logEvents = append(q.logEvents, event)
  64. }
  65. func (q *eventsQueue) popFsEvent() *notifier.FsEvent {
  66. q.Lock()
  67. defer q.Unlock()
  68. if len(q.fsEvents) == 0 {
  69. return nil
  70. }
  71. truncLen := len(q.fsEvents) - 1
  72. ev := q.fsEvents[truncLen]
  73. q.fsEvents[truncLen] = nil
  74. q.fsEvents = q.fsEvents[:truncLen]
  75. return ev
  76. }
  77. func (q *eventsQueue) popProviderEvent() *notifier.ProviderEvent {
  78. q.Lock()
  79. defer q.Unlock()
  80. if len(q.providerEvents) == 0 {
  81. return nil
  82. }
  83. truncLen := len(q.providerEvents) - 1
  84. ev := q.providerEvents[truncLen]
  85. q.providerEvents[truncLen] = nil
  86. q.providerEvents = q.providerEvents[:truncLen]
  87. return ev
  88. }
  89. func (q *eventsQueue) popLogEvent() *notifier.LogEvent {
  90. q.Lock()
  91. defer q.Unlock()
  92. if len(q.logEvents) == 0 {
  93. return nil
  94. }
  95. truncLen := len(q.logEvents) - 1
  96. ev := q.logEvents[truncLen]
  97. q.logEvents[truncLen] = nil
  98. q.logEvents = q.logEvents[:truncLen]
  99. return ev
  100. }
  101. func (q *eventsQueue) getSize() int {
  102. q.RLock()
  103. defer q.RUnlock()
  104. return len(q.providerEvents) + len(q.fsEvents) + len(q.logEvents)
  105. }
  106. type notifierPlugin struct {
  107. config Config
  108. notifier notifier.Notifier
  109. client *plugin.Client
  110. queue *eventsQueue
  111. }
  112. func newNotifierPlugin(config Config) (*notifierPlugin, error) {
  113. p := &notifierPlugin{
  114. config: config,
  115. queue: &eventsQueue{},
  116. }
  117. if err := p.initialize(); err != nil {
  118. logger.Warn(logSender, "", "unable to create notifier plugin: %v, config %+v", err, config)
  119. return nil, err
  120. }
  121. return p, nil
  122. }
  123. func (p *notifierPlugin) exited() bool {
  124. return p.client.Exited()
  125. }
  126. func (p *notifierPlugin) cleanup() {
  127. p.client.Kill()
  128. }
  129. func (p *notifierPlugin) initialize() error {
  130. killProcess(p.config.Cmd)
  131. logger.Debug(logSender, "", "create new notifier plugin %q", p.config.Cmd)
  132. if !p.config.NotifierOptions.hasActions() {
  133. return fmt.Errorf("no actions defined for the notifier plugin %q", p.config.Cmd)
  134. }
  135. secureConfig, err := p.config.getSecureConfig()
  136. if err != nil {
  137. return err
  138. }
  139. client := plugin.NewClient(&plugin.ClientConfig{
  140. HandshakeConfig: notifier.Handshake,
  141. Plugins: notifier.PluginMap,
  142. Cmd: exec.Command(p.config.Cmd, p.config.Args...),
  143. AllowedProtocols: []plugin.Protocol{
  144. plugin.ProtocolGRPC,
  145. },
  146. AutoMTLS: p.config.AutoMTLS,
  147. SecureConfig: secureConfig,
  148. Managed: false,
  149. Logger: &logger.HCLogAdapter{
  150. Logger: hclog.New(&hclog.LoggerOptions{
  151. Name: fmt.Sprintf("%v.%v", logSender, notifier.PluginName),
  152. Level: pluginsLogLevel,
  153. DisableTime: true,
  154. }),
  155. },
  156. })
  157. rpcClient, err := client.Client()
  158. if err != nil {
  159. logger.Debug(logSender, "", "unable to get rpc client for plugin %q: %v", p.config.Cmd, err)
  160. return err
  161. }
  162. raw, err := rpcClient.Dispense(notifier.PluginName)
  163. if err != nil {
  164. logger.Debug(logSender, "", "unable to get plugin %v from rpc client for command %q: %v",
  165. notifier.PluginName, p.config.Cmd, err)
  166. return err
  167. }
  168. p.client = client
  169. p.notifier = raw.(notifier.Notifier)
  170. return nil
  171. }
  172. func (p *notifierPlugin) canQueueEvent(timestamp int64) bool {
  173. if p.config.NotifierOptions.RetryMaxTime == 0 {
  174. return false
  175. }
  176. if time.Now().After(time.Unix(0, timestamp).Add(time.Duration(p.config.NotifierOptions.RetryMaxTime) * time.Second)) {
  177. logger.Warn(logSender, "", "dropping too late event for plugin %v, event timestamp: %v",
  178. p.config.Cmd, time.Unix(0, timestamp))
  179. return false
  180. }
  181. if p.config.NotifierOptions.RetryQueueMaxSize > 0 {
  182. return p.queue.getSize() < p.config.NotifierOptions.RetryQueueMaxSize
  183. }
  184. return true
  185. }
  186. func (p *notifierPlugin) notifyFsAction(event *notifier.FsEvent) {
  187. if !util.Contains(p.config.NotifierOptions.FsEvents, event.Action) {
  188. return
  189. }
  190. go func() {
  191. Handler.addTask()
  192. defer Handler.removeTask()
  193. p.sendFsEvent(event)
  194. }()
  195. }
  196. func (p *notifierPlugin) notifyProviderAction(event *notifier.ProviderEvent, object Renderer) {
  197. if !util.Contains(p.config.NotifierOptions.ProviderEvents, event.Action) ||
  198. !util.Contains(p.config.NotifierOptions.ProviderObjects, event.ObjectType) {
  199. return
  200. }
  201. go func() {
  202. Handler.addTask()
  203. defer Handler.removeTask()
  204. objectAsJSON, err := object.RenderAsJSON(event.Action != "delete")
  205. if err != nil {
  206. logger.Warn(logSender, "", "unable to render user as json for action %v: %v", event.Action, err)
  207. return
  208. }
  209. event.ObjectData = objectAsJSON
  210. p.sendProviderEvent(event)
  211. }()
  212. }
  213. func (p *notifierPlugin) notifyLogEvent(event *notifier.LogEvent) {
  214. if !util.Contains(p.config.NotifierOptions.LogEvents, int(event.Event)) {
  215. return
  216. }
  217. go func() {
  218. Handler.addTask()
  219. defer Handler.removeTask()
  220. p.sendLogEvent(event)
  221. }()
  222. }
  223. func (p *notifierPlugin) sendFsEvent(event *notifier.FsEvent) {
  224. if err := p.notifier.NotifyFsEvent(event); err != nil {
  225. logger.Warn(logSender, "", "unable to send fs action notification to plugin %v: %v", p.config.Cmd, err)
  226. if p.canQueueEvent(event.Timestamp) {
  227. p.queue.addFsEvent(event)
  228. }
  229. }
  230. }
  231. func (p *notifierPlugin) sendProviderEvent(event *notifier.ProviderEvent) {
  232. if err := p.notifier.NotifyProviderEvent(event); err != nil {
  233. logger.Warn(logSender, "", "unable to send user action notification to plugin %v: %v", p.config.Cmd, err)
  234. if p.canQueueEvent(event.Timestamp) {
  235. p.queue.addProviderEvent(event)
  236. }
  237. }
  238. }
  239. func (p *notifierPlugin) sendLogEvent(event *notifier.LogEvent) {
  240. if err := p.notifier.NotifyLogEvent(event); err != nil {
  241. logger.Warn(logSender, "", "unable to send log event to plugin %v: %v", p.config.Cmd, err)
  242. if p.canQueueEvent(event.Timestamp) {
  243. p.queue.addLogEvent(event)
  244. }
  245. }
  246. }
  247. func (p *notifierPlugin) sendQueuedEvents() {
  248. queueSize := p.queue.getSize()
  249. if queueSize == 0 {
  250. return
  251. }
  252. logger.Debug(logSender, "", "check queued events for notifier %q, events size: %v", p.config.Cmd, queueSize)
  253. fsEv := p.queue.popFsEvent()
  254. for fsEv != nil {
  255. go func(ev *notifier.FsEvent) {
  256. p.sendFsEvent(ev)
  257. }(fsEv)
  258. fsEv = p.queue.popFsEvent()
  259. }
  260. providerEv := p.queue.popProviderEvent()
  261. for providerEv != nil {
  262. go func(ev *notifier.ProviderEvent) {
  263. p.sendProviderEvent(ev)
  264. }(providerEv)
  265. providerEv = p.queue.popProviderEvent()
  266. }
  267. logEv := p.queue.popLogEvent()
  268. for logEv != nil {
  269. go func(ev *notifier.LogEvent) {
  270. p.sendLogEvent(ev)
  271. }(logEv)
  272. logEv = p.queue.popLogEvent()
  273. }
  274. logger.Debug(logSender, "", "queued events sent for notifier %q, new events size: %v", p.config.Cmd, p.queue.getSize())
  275. }